text
stringlengths 2
95.7k
| meta
dict |
|---|---|
the
of
and
to
a
in
for
is
on
that
by
this
with
i
you
it
not
or
be
are
from
at
as
your
all
have
new
more
an
was
we
will
home
can
us
about
if
page
my
has
search
free
but
our
one
other
do
no
information
time
they
site
he
up
may
what
which
their
news
out
use
any
there
see
only
so
his
when
contact
here
business
who
web
also
now
help
get
pm
view
online
c
e
first
am
been
would
how
were
me
s
services
some
these
click
its
like
service
x
than
find
price
date
back
top
people
had
list
name
just
over
year
day
into
email
two
n
world
re
next
used
go
b
work
last
most
products
music
buy
data
make
them
should
product
system
post
her
city
t
add
policy
number
such
please
available
copyright
support
message
after
best
software
then
jan
good
video
well
d
where
info
rights
public
books
high
through
m
each
links
she
review
years
order
very
privacy
book
items
company
r
read
group
need
many
user
said
de
does
set
under
general
january
mail
full
map
reviews
program
life
know
way
days
management
p
part
could
great
real
f
item
international
center
must
travel
comments
made
development
report
off
member
details
line
terms
before
did
send
right
type
because
local
those
using
results
office
national
take
posted
internet
address
within
area
want
phone
shipping
reserved
subject
between
l
long
based
w
code
show
o
even
check
special
prices
website
index
being
much
sign
file
link
open
today
case
project
same
pages
version
section
own
found
sports
house
related
both
g
county
photo
members
power
while
care
network
down
computer
systems
three
total
place
end
following
download
h
him
without
per
access
think
resources
current
posts
big
media
control
history
pictures
size
art
personal
since
including
guide
shop
directory
board
location
change
white
text
small
rating
rate
during
return
v
shopping
account
times
sites
level
digital
profile
previous
form
events
old
main
call
hours
image
department
title
description
non
k
y
another
why
shall
still
money
quality
every
listing
content
country
private
little
visit
save
tools
low
reply
customer
december
compare
movies
include
value
article
card
provide
j
food
source
author
different
press
u
learn
sale
around
print
job
process
too
point
join
science
categories
advanced
west
sales
look
english
left
team
box
select
photos
thread
week
category
note
live
large
gallery
table
register
however
june
october
november
really
start
series
model
industry
plan
provided
yes
required
second
hot
cost
forums
march
la
september
better
say
questions
july
going
test
friend
come
dec
application
cart
staff
articles
feedback
again
play
looking
issues
april
never
users
complete
street
topic
comment
things
standard
person
below
mobile
less
got
blog
party
payment
login
let
offers
legal
above
recent
side
act
problem
give
social
q
august
quote
language
story
sell
options
experience
create
key
body
important
field
few
east
ii
age
example
additional
password
z
|
{
"pile_set_name": "Github"
}
|
במדבר פרק א
א וַיְדַבֵּר יְהוָה אֶל-מֹשֶׁה בְּמִדְבַּר סִינַי, בְּאֹהֶל מוֹעֵד: בְּאֶחָד לַחֹדֶשׁ הַשֵּׁנִי בַּשָּׁנָה הַשֵּׁנִית, לְצֵאתָם מֵאֶרֶץ מִצְרַיִם--לֵאמֹר. ב שְׂאוּ, אֶת-רֹאשׁ כָּל-עֲדַת בְּנֵי-יִשְׂרָאֵל, לְמִשְׁפְּחֹתָם, לְבֵית אֲבֹתָם--בְּמִסְפַּר שֵׁמוֹת, כָּל-זָכָר לְגֻלְגְּלֹתָם. ג מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה, כָּל-יֹצֵא צָבָא בְּיִשְׂרָאֵל--תִּפְקְדוּ אֹתָם לְצִבְאֹתָם, אַתָּה וְאַהֲרֹן. ד וְאִתְּכֶם יִהְיוּ, אִישׁ אִישׁ לַמַּטֶּה--אִישׁ רֹאשׁ לְבֵית-אֲבֹתָיו, הוּא. ה וְאֵלֶּה שְׁמוֹת הָאֲנָשִׁים, אֲשֶׁר יַעַמְדוּ אִתְּכֶם: לִרְאוּבֵן, אֱלִיצוּר בֶּן-שְׁדֵיאוּר. ו לְשִׁמְעוֹן, שְׁלֻמִיאֵל בֶּן-צוּרִישַׁדָּי. ז לִיהוּדָה, נַחְשׁוֹן בֶּן-עַמִּינָדָב. ח לְיִשָּׂשכָר, נְתַנְאֵל בֶּן-צוּעָר. ט לִזְבוּלֻן, אֱלִיאָב בֶּן-חֵלֹן. י לִבְנֵי יוֹסֵף--לְאֶפְרַיִם, אֱלִישָׁמָע בֶּן-עַמִּיהוּד; לִמְנַשֶּׁה, גַּמְלִיאֵל בֶּן-פְּדָהצוּר. יא לְבִנְיָמִן, אֲבִידָן בֶּן-גִּדְעֹנִי. יב לְדָן, אֲחִיעֶזֶר בֶּן-עַמִּישַׁדָּי. יג לְאָשֵׁר, פַּגְעִיאֵל בֶּן-עָכְרָן. יד לְגָד, אֶלְיָסָף בֶּן-דְּעוּאֵל. טו לְנַפְתָּלִי, אֲחִירַע בֶּן-עֵינָן. טז אֵלֶּה קריאי (קְרוּאֵי) הָעֵדָה, נְשִׂיאֵי מַטּוֹת אֲבוֹתָם: רָאשֵׁי אַלְפֵי יִשְׂרָאֵל, הֵם. יז וַיִּקַּח מֹשֶׁה, וְאַהֲרֹן, אֵת הָאֲנָשִׁים הָאֵלֶּה, אֲשֶׁר נִקְּבוּ בְּשֵׁמֹת. יח וְאֵת כָּל-הָעֵדָה הִקְהִילוּ, בְּאֶחָד לַחֹדֶשׁ הַשֵּׁנִי, וַיִּתְיַלְדוּ עַל-מִשְׁפְּחֹתָם, לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמוֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--לְגֻלְגְּלֹתָם. יט כַּאֲשֶׁר צִוָּה יְהוָה, אֶת-מֹשֶׁה; וַיִּפְקְדֵם, בְּמִדְבַּר סִינָי. {ס}
כ וַיִּהְיוּ בְנֵי-רְאוּבֵן בְּכֹר יִשְׂרָאֵל, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמוֹת, לְגֻלְגְּלֹתָם--כָּל-זָכָר מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה, כֹּל יֹצֵא צָבָא. כא פְּקֻדֵיהֶם, לְמַטֵּה רְאוּבֵן--שִׁשָּׁה וְאַרְבָּעִים אֶלֶף, וַחֲמֵשׁ מֵאוֹת. {פ}
כב לִבְנֵי שִׁמְעוֹן, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: פְּקֻדָיו, בְּמִסְפַּר שֵׁמוֹת לְגֻלְגְּלֹתָם--כָּל-זָכָר מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה, כֹּל יֹצֵא צָבָא. כג פְּקֻדֵיהֶם, לְמַטֵּה שִׁמְעוֹן--תִּשְׁעָה וַחֲמִשִּׁים אֶלֶף, וּשְׁלֹשׁ מֵאוֹת. {פ}
כד לִבְנֵי גָד, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמוֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. כה פְּקֻדֵיהֶם, לְמַטֵּה גָד--חֲמִשָּׁה וְאַרְבָּעִים אֶלֶף, וְשֵׁשׁ מֵאוֹת וַחֲמִשִּׁים. {פ}
כו לִבְנֵי יְהוּדָה, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. כז פְּקֻדֵיהֶם, לְמַטֵּה יְהוּדָה--אַרְבָּעָה וְשִׁבְעִים אֶלֶף, וְשֵׁשׁ מֵאוֹת. {פ}
כח לִבְנֵי יִשָּׂשכָר, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. כט פְּקֻדֵיהֶם, לְמַטֵּה יִשָּׂשכָר--אַרְבָּעָה וַחֲמִשִּׁים אֶלֶף, וְאַרְבַּע מֵאוֹת. {פ}
ל לִבְנֵי זְבוּלֻן, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. לא פְּקֻדֵיהֶם, לְמַטֵּה זְבוּלֻן--שִׁבְעָה וַחֲמִשִּׁים אֶלֶף, וְאַרְבַּע מֵאוֹת. {פ}
לב לִבְנֵי יוֹסֵף לִבְנֵי אֶפְרַיִם, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. לג פְּקֻדֵיהֶם, לְמַטֵּה אֶפְרָיִם--אַרְבָּעִים אֶלֶף, וַחֲמֵשׁ מֵאוֹת. {פ}
לד לִבְנֵי מְנַשֶּׁה, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמוֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. לה פְּקֻדֵיהֶם, לְמַטֵּה מְנַשֶּׁה--שְׁנַיִם וּשְׁלֹשִׁים אֶלֶף, וּמָאתָיִם. {פ}
לו לִבְנֵי בִנְיָמִן, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. לז פְּקֻדֵיהֶם, לְמַטֵּה בִנְיָמִן--חֲמִשָּׁה וּשְׁלֹשִׁים אֶלֶף, וְאַרְבַּע מֵאוֹת. {פ}
לח לִבְנֵי דָן, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. לט פְּקֻדֵיהֶם, לְמַטֵּה דָן--שְׁנַיִם וְשִׁשִּׁים אֶלֶף, וּשְׁבַע מֵאוֹת. {פ}
מ לִבְנֵי אָשֵׁר, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. מא פְּקֻדֵיהֶם, לְמַטֵּה אָשֵׁר--אֶחָד וְאַרְבָּעִים אֶלֶף, וַחֲמֵשׁ מֵאוֹת. {פ}
מב בְּנֵי נַפְתָּלִי, תּוֹלְדֹתָם לְמִשְׁפְּחֹתָם לְבֵית אֲבֹתָם: בְּמִסְפַּר שֵׁמֹת, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה--כֹּל, יֹצֵא צָבָא. מג פְּקֻדֵיהֶם, לְמַטֵּה נַפְתָּלִי--שְׁלֹשָׁה וַחֲמִשִּׁים אֶלֶף, וְאַרְבַּע מֵאוֹת. {פ}
מד אֵלֶּה הַפְּקֻדִים אֲשֶׁר פָּקַד מֹשֶׁה וְאַהֲרֹן, וּנְשִׂיאֵי יִשְׂרָאֵל--שְׁנֵים עָשָׂר, אִישׁ: אִישׁ-אֶחָד לְבֵית-אֲבֹתָיו, הָיוּ. מה וַיִּהְיוּ כָּל-פְּקוּדֵי בְנֵי-יִשְׂרָאֵל, לְבֵית אֲבֹתָם, מִבֶּן עֶשְׂרִים שָׁנָה וָמַעְלָה, כָּל-יֹצֵא צָבָא בְּיִשְׂרָאֵל. מו וַיִּהְיוּ, כָּל-הַפְּקֻדִים--שֵׁשׁ-מֵאוֹת אֶלֶף, וּשְׁלֹשֶׁת אֲלָפִים; וַחֲמֵשׁ מֵאוֹת, וַחֲמִשִּׁים. מז וְהַלְוִיִּם, לְמַטֵּה אֲבֹתָם--לֹא הָתְפָּקְדוּ, בְּתוֹכָם. {פ}
מח וַיְדַבֵּר יְהוָה, אֶל-מֹשֶׁה לֵּאמֹר. מט אַךְ אֶת-מַטֵּה לֵוִי לֹא תִפְקֹד, וְאֶת-רֹאשָׁם לֹא תִשָּׂא, בְּתוֹךְ, בְּנֵי יִשְׂרָאֵל. נ וְאַתָּה הַפְקֵד אֶת-הַלְוִיִּם עַל-מִשְׁכַּן הָעֵדֻת וְעַל כָּל-כֵּלָיו, וְעַל כָּל-אֲשֶׁר-לוֹ--הֵמָּה יִשְׂאוּ אֶת-הַמִּשְׁכָּן וְאֶת-כָּל-כֵּלָיו, וְהֵם יְשָׁרְתֻהוּ; וְסָבִיב לַמִּשְׁכָּן, יַחֲנוּ. נא וּבִנְסֹעַ הַמִּשְׁכָּן, יוֹרִידוּ אֹתוֹ הַלְוִיִּם, וּבַחֲנֹת הַמִּשְׁכָּן, יָקִימוּ אֹתוֹ הַלְוִיִּם; וְהַזָּר הַקָּרֵב, יוּמָת. נב וְחָנוּ, בְּנֵי יִשְׂרָאֵל, אִישׁ עַל-מַחֲנֵהוּ וְאִישׁ עַל-דִּגְלוֹ, לְצִבְאֹתָם. נג וְהַלְוִיִּם יַחֲנוּ סָבִיב, לְמִשְׁכַּן הָעֵדֻת, וְלֹא-יִהְיֶה קֶצֶף, עַל-עֲדַת בְּנֵי יִשְׂרָאֵל; וְשָׁמְרוּ, הַלְוִיִּם, אֶת-מִשְׁמֶרֶת, מִשְׁכַּן הָעֵדוּת. נד וַיַּעֲשׂוּ, בְּנֵי יִשְׂרָאֵל: כְּכֹל אֲשֶׁר צִוָּה יְהוָה, אֶת-מֹשֶׁה--כֵּן עָשׂוּ. {פ}
|
{
"pile_set_name": "Github"
}
|
# Подозреваете ошибку в компиляторе? Проверьте получше свой код!
(В оригинале - Check Your Code First before Looking to Blame Others)
Все разработчики часто склонны не верить, что ошибка в их коде, обвиняя вместо этого, например, компилятор.
Однако в реальности то, что ошибка на самом деле в компиляторе, интерпретаторе, операционной системе, сервере приложений, базе данных, менеджере памяти или еще где-нибудь среди системного ПО, весьма маловероятно. Да, такие ошибки тоже есть, однако случаются они гораздо реже, чем бы нам хотелось.
Один раз я сталкнулся с реальной ошибкой компилятора, неправильно оптимизировавшего цикл, однако я обвинял компилятор и операционку гораздо чаще. Я убил очень много времени на попытки доказать наличие ошибок в системе, и все лишь для того, чтобы в конце испытать неловкость, найдя ошибку в своем коде.
Если инструмент широко распространен и используется множеством людей в различных ситуациях, то причин сомневаться в его качестве очень мало. Конечно, если инструмент еще в стадии раннего релиза, используется лишь несколькими людьми в мире, имеет версию 0.1 или же относится к редко скачиваемому open source, то основания для подозрений могут быть гораздо более весомыми. То же самое справедливо и для альфа-версий известных коммерческих продуктов.
Взяв за основу то, что ошибки в компиляторах – очень большая редкость, вы сможете гораздо эффективнее тратить свое время на поиски ошибок у себя вместо попыток доказать, что виноват компилятор. Применяйте все обычные практики отладки: изолируйте проблему, отслеживайте вызовы, окружайте ее тестами, проверяйте соглашение о вызовах, общие библиотеки и версии, расскажите о проблеме кому-нибудь еще, проверьте переполнение и повреждение стека, запустите код на разных машинах и с разными конфигурациями сборки (debug и release).
Если кто-то заявляет о проблеме, которую вы не можете воспроизвести, то пойдите и посмотрите, как это у него получается. Возможно, он делает что-то, что вы не учли, или делает это каким-то другим способом.
Моим правилом стало то, что если я сталкиваюсь с ошибкой, которую не могу найти, и у меня появляются мысли, что ошибка в компиляторе, то самое время поискать повреждения стека. Особенно если добавление отладочного кода приводит к исчезновении ошибки.
Проблемы в многозадачных системах – еще один тип ошибок, способный увеличить количество седых волос у вас и бросить тень подозрения на компилятор или ОС. Все рекомендации поддерживать код простым становятся в разы актуальнее, когда вы работаете с многозадачной системой. Отладка и модульное тестирование практически не способны отлавливать такие ошибки, поэтому простота кода выходит на первое место.
Так что перед тем, как обвинить компилятор, вспомните правило Шерлока Холмса: «После того, как вы исключили невозможное, то все, что осталось, независимо от того, насколько невероятным оно выглядит, является истиной», и отдавайте предпочтение именно ему, а не правилу Дирка Джентли «Посл того, как вы исключили невероятное, все, что осталось, независимо от того, насколько невозможным оно выглядит, является истиной».
Автор оригинала - [Allan Kelly](http://programmer.97things.oreilly.com/wiki/index.php/Allan_Kelly)
|
{
"pile_set_name": "Github"
}
|
# Использование конструкторов с параметрами при объявлении структуры (NestedConstructorsInStructureDeclaration)
Тип | Поддерживаются<br>языки | Важность | Включена<br>по умолчанию | Время на<br>исправление (мин) | Тэги
:-: | :-: | :-: | :-: | :-: | :-:
`Дефект кода` | `BSL`<br>`OS` | `Незначительный` | `Да` | `10` | `badpractice`<br>`brainoverload`
<!-- Блоки выше заполняются автоматически, не трогать -->
## Описание диагностики
Не рекомендуется в конструкторе структуры использовать конструкторы других объектов, если эти конструкторы принимают параметры. В частности в конструкторе одной структуры не рекомендуется создавать другие структуры с объявлением значений свойств.
## Примеры
Неправильно
```bsl
НоменклатураСервер.ЗаполнитьСлужебныеРеквизитыПоНоменклатуреВКоллекции(
Объект.Товары,
Новый Структура(
"ЗаполнитьПризнакХарактеристикиИспользуются,
|ЗаполнитьПризнакТипНоменклатуры, ЗаполнитьПризнакВариантОформленияПродажи",
Новый Структура("Номенклатура", "ХарактеристикиИспользуются"),
Новый Структура("Номенклатура", "ТипНоменклатуры"),
Новый Структура("Номенклатура", "ВариантОформленияПродажи")
)
);
```
Правильно
```bsl
ПараметрыЗаполненияРеквизитов = Новый Структура;
ПараметрыЗаполненияРеквизитов.Вставить("ЗаполнитьПризнакХарактеристикиИспользуются",
Новый Структура("Номенклатура", "ХарактеристикиИспользуются"));
ПараметрыЗаполненияРеквизитов.Вставить("ЗаполнитьПризнакТипНоменклатуры",
Новый Структура("Номенклатура", "ТипНоменклатуры"));
НоменклатураСервер.ЗаполнитьСлужебныеРеквизитыПоНоменклатуреВКоллекции(Объект.Товары,
ПараметрыЗаполненияРеквизитов);
```
## Сниппеты
<!-- Блоки ниже заполняются автоматически, не трогать -->
### Экранирование кода
```bsl
// BSLLS:NestedConstructorsInStructureDeclaration-off
// BSLLS:NestedConstructorsInStructureDeclaration-on
```
### Параметр конфигурационного файла
```json
"NestedConstructorsInStructureDeclaration": false
```
|
{
"pile_set_name": "Github"
}
|
# Загрузчик пользовательских настроек
## Загрузка глобальных переменных из внешнего файла
Чтобы не зашивать в тесты все плавающие пользовательские переменные, такие как имена баз, строки подключения, логины, пароли и др., имеется возможность забирать эти переменные из внешнего файла или внешнего key-value хранилища по http протоколу (поддерживается `Consul`). Это может быть особенно полезно, когда над фичами работает команда, и у каждого участника существуют свои настройки подключения к базам.
Чтобы воспользоваться этой функциональностью для файлового режима, нужно выполнить следующее:
1. В своем каталоге проекта создать файл `user_settings.json` следующего формата:
```json
{
"userSettings": [
{
"user": "USERNAME_1",
"settings": {
"ИМЯ_ПЕРЕМЕННОЙ_1": "ЗНАЧЕНИЕ_ПЕРЕМЕННОЙ_1",
"ИМЯ_ПЕРЕМЕННОЙ_2": "ЗНАЧЕНИЕ_ПЕРЕМЕННОЙ_2",
}
},
{
"user": "USERNAME_2",
"settings": {
"ИМЯ_ПЕРЕМЕННОЙ_1": "ЗНАЧЕНИЕ_ПЕРЕМЕННОЙ_1",
"ИМЯ_ПЕРЕМЕННОЙ_2": "ЗНАЧЕНИЕ_ПЕРЕМЕННОЙ_2",
}
}
]
}
```
2. В свойства user поставить доменное (локальное) имя пользователя, для которого должны применяться настройки. Именно по этому свойству будет определяться, какие пользовательские настройки нужно загружать.
3. В свойстве settings прописать конкретные настройки для каждого пользователя. Состав настроек необязательно должен совпадать между пользователями, для какого-то пользователя настройки могут отсутствовать.
4. Открыть обработку `bddRunner` из корня `Vanessa.ADD` - файл `user_settings.json` подтянется автоматически из каталога, в котором находится `Vanessa.ADD` (поле `Каталог инструментов` на вкладке `Сервис`). Если такого файла нет, то загрузка не выполняется. Имеется возможность указать свой каталог загрузки настроек, он подчиняется свойству `Каталог проекта` на вкладке `Сервис`.
Если файл найден, то на основании текущего имени пользователя компьютера или домена (которое определяется через WShell скрипт), ищутся настройки текущего пользователя и загружаются только они. Если настройки не найдены, то выводится предупреждающее сообщение.
Чтобы воспользоваться этой функциональностью для `Consul`-a нужно:
1. Развернуть единый сервер консула и установить агентов консула на каждой машине, на которой запускается `Vanessa.ADD`.
2. На вкладке `Сервис` в `Vanessa.ADD` указать `Поставщик пользовательских настроек` равным `CONSUL`, а в поле `Адрес пользовательских настроек` указать полный url к настройкам на сервере. Url должен содержать путь, доступный через REST интерфейс консула, например http://127.0.0.1:8500/v1/kv/ivanov
|
{
"pile_set_name": "Github"
}
|
QUERY
{{.Query}}
{{with .Alert}}{{.}}
{{end}}{{/* .Alert */}}{{/*
---------------------------------------
*/}}{{with .Alt}}DID YOU MEAN
{{range .Alts}} {{.}}
{{end}}
{{end}}{{/* .Alt */}}{{/*
---------------------------------------
*/}}{{with .Pak}}PACKAGE {{$.Query}}
{{range .}} {{pkgLink .Pak.Path}}
{{end}}
{{end}}{{/* .Pak */}}{{/*
---------------------------------------
*/}}{{range $key, $val := .Idents}}{{if $val}}{{$key.Name}}
{{range $val}} {{.Path}}.{{.Name}}
{{end}}
{{end}}{{end}}{{/* .Idents */}}{{/*
---------------------------------------
*/}}{{with .Hit}}{{with .Decls}}PACKAGE-LEVEL DECLARATIONS
{{range .}}package {{.Pak.Name}}
{{range $file := .Files}}{{range .Groups}}{{range .}} {{srcLink $file.File.Path}}:{{infoLine .}}{{end}}
{{end}}{{end}}{{/* .Files */}}
{{end}}{{end}}{{/* .Decls */}}{{/*
---------------------------------------
*/}}{{with .Others}}LOCAL DECLARATIONS AND USES
{{range .}}package {{.Pak.Name}}
{{range $file := .Files}}{{range .Groups}}{{range .}} {{srcLink $file.File.Path}}:{{infoLine .}}
{{end}}{{end}}{{end}}{{/* .Files */}}
{{end}}{{end}}{{/* .Others */}}{{end}}{{/* .Hit */}}{{/*
---------------------------------------
*/}}{{if .Textual}}{{if .Complete}}{{.Found}} TEXTUAL OCCURRENCES{{else}}MORE THAN {{.Found}} TEXTUAL OCCURRENCES{{end}}
{{range .Textual}}{{len .Lines}} {{srcLink .Filename}}
{{end}}{{if not .Complete}}... ...
{{end}}{{end}}
|
{
"pile_set_name": "Github"
}
|
# [Глава 2](../index.md#Глава-2-Построение-абстракций-с-помощью-данных)
### Упражнение 2.7
Лиза постулирует существование абстрактного объекта, называемого «интервал», у которого есть два конца: верхняя и нижняя границы. Кроме того, она предполагает, что имея два конца интервала, мы можем сконструировать его при помощи конструктора `make-interval`. Сначала Лиза пишет процедуру сложения двух интервалов. Она рассуждает так: минимальное возможное значение суммы равно сумме нижних границ интервалов, а максимальное возможное значение сумме верхних границ интервалов.
```clojure
(defn add-interval
[a b]
(make-interval (+ (lower-bound a)
(lower-bound b))
(+ (upper-bound a)
(upper-bound b))))
```
Кроме того, она вычисляет произведение двух интервалов путем нахождения минимума и максимума произведений концов интервалов и использования в качестве границ интервала-результата. (`min` и `max` — примитивы, которые находят минимум и максимум при любом количестве аргументов.)
```clojure
(defn mul-interval [a b]
(let [p1 (* (lower-bound a) (lower-bound b))
p2 (* (lower-bound a) (upper-bound b))
p3 (* (upper-bound a) (lower-bound b))
p4 (* (upper-bound a) (upper-bound b))]
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
```
При делении двух интервалов Лиза умножает первый из них на интервал, обратный второму. Заметим, что границами обратного интервала являются числа, обратные верхнейи нижней границе исходного интервала, именно в таком порядке.
```clojure
(defn div-interval
[a b]
(mul-interval a
(make-interval (/ 1.0 (upper-bound b))
(/ 1.0 (lower-bound b)))))
```
Программа Лизы неполна, поскольку она не определила, как реализуется абстракция интервала. Вот определение конструктора интервала:
```clojure
(defn make-interval
[a b]
(vector a b))
```
Завершите реализацию, определив селекторы `upper-bound` и `lower-bound`.
#### Решение
[Code](../../src/sicp/chapter02/2_07.clj) | [Test](../../test/sicp/chapter02/2_07_test.clj)
|
{
"pile_set_name": "Github"
}
|
---
title: "Урок 0"
description: "Подготовка рабочего места в Windows и Linux. Virtual Environment (venv). Ответы на вопросы"
type: docs
BookToC: true
weight: 1
---
## Предисловие
Весь текст ниже появился как попытка дать универсальный ответ на те вопросы, которые дорогие читатели присылали и продолжают присылать раз за разом. Здесь не будет кода, связанного с ботами напрямую, а лишь советы по организации процесса написания. И, конечно же, не нужно воспринимать это как истину в последней инстанции, напротив, выбирайте те инструменты и подходы к разработке, которые лично вам кажутся удобными. Важная деталь: текст написан в конце 2019 года. Достаточно вступительных слов, поехали!
Предположим, вы уже немного знаете язык Python 3 (забудьте про Python 2.7, он мёртв), умеете писать простенькие программы и хотите взяться за разработку ботов. Где это делать? В чём писать код? Как правило, у большинства начинающих программистов основной операционкой используется Microsoft Windows. С неё и начнём, но сперва…
## Virtual environment
Вы когда-нибудь пользовались VirtualBox? Например, чтобы «пощупать» другие операционные системы или просто установить какой-нибудь подозрительный софт. [Python Virtual environment](https://docs.python.org/3/library/venv.html) (далее — venv) чем-то напоминает «виртуалку». При его использовании создаётся копия выбранного интерпретатора Питон, а все устанавливаемые модули хранятся изолированно от общесистемных, тем самым, упрощается их обновление, удаление или изменение. Часто venv позволяет избежать ошибок, связанных с обратной совместимостью некоторых библиотек, а также обойтись без конфликтов с системными модулями.
Работа с venv будет подробнее описана ниже в разделе Linux, но использовать его мы будем везде.
## Windows
Первым делом, разумеется, нужно скачать сам интерпретатор Python. На момент написания этого текста актуальной версией является [Python 3.8.1](https://www.python.org/downloads/release/python-381). В качестве каталога установки я рекомендую использовать что-то простое, вроде C:\Python38.
Где писать код — личное дело каждого, конечно, но я всё же рекомендую использовать специальную среду разработки под названием PyCharm Community Edition. Бесплатной версии (та самая Community) более чем достаточно.
После установки и первичной настройки выберите пункт File -> New Project. Укажите имя вашего первого проекта, а ниже укажите «New environment using virtualenv», ниже в качестве интерпретатора путь к python.exe каталога с Питоном (например, C:\Python38\python.exe).
{{% img2 src="/images/l0_1.jpg" caption="Создание нового проекта в PyCharm" %}}
После запуска откройте вкладку Terminal в левом нижнем углу и установите библиотеку pytelegrambotapi (не telebot!). Для любителей тыкать мышкой есть более запутанный вариант: File -> Settings -> Project {имя проекта} -> Project Interpreter -> кнопка «+» в правой части экрана.
{{% img2 src="/images/l0_2.png" caption="Установка библиотеки через терминал в PyCharm" %}}
Прекрасно, теперь начинайте творить! Создайте первый файл с исходником, нажав правой кнопкой мышки по имени проекта в списке файлов, затем New и Python File.
{{% img2 src="/images/l0_3.png" caption="Создание нового файла кода в PyCharm" %}}
Запустить код можно, выбрав сверху пункт Run, затем снова Run…, но с многоточием, и затем выбрав созданный ранее файл.
### Как залить файлы на сервер?
Для копирования файлов на удалённый сервер (обычно там стоит Linux), я использую замечательную бесплатную программу [WinSCP](https://winscp.net/eng/download.php), причём в ней присутствует режим автоматической синхронизации файлов, чтобы при любом изменении в локальном каталоге обновлялось содержимое на удалённой машине, избавляя вас от необходимости копировать всё вручную.
{{% img2 src="/images/l0_4.png" caption="Скриншот программы WinSCP" %}}
При помощи WinSCP можно даже просто подключиться к серверу и подправить файл «на лету», не забудьте только потом перезапустить бота!
## Linux
Если Linux у вас используется вместо Windows, то работа с PyCharm будет точно такой же, поэтому второй раз писать не имеет смысла. Далее рассмотрен процесс запуска в терминале на удалённом сервере.
Прекрасно, вы написали бота и хотите где-то его запустить. Например, арендовали сервер у Scaleway/DigitalOcean/AWS/etc. Запустили сервер, подключились к нему по SSH, а там чёрный экран и терминальная Linux-сессия. Во-первых, давайте посмотрим, какой интерпретатор у нас выбран по умолчанию, введя команду `python3`.
Хорошим правилом будет иметь на сервере ровно ту же версию Python, что и на своей локальной машине, во избежание различных неприятностей. Если версия на сервере ниже 3.7 и/или ниже той, что установлена локально, лучше всего будет установить её отдельно. Очень рекомендую [вот эту статью](https://tecadmin.net/install-python-3-7-on-ubuntu-linuxmint/), по которой я для себя написал простой [скрипт](https://gist.github.com/MasterGroosha/f46e24ec8dd5c0ce5cd872a479a19c96) для автоматизации рутинных действий.
Итак, интерпретатор установлен, теперь пора создать каталог, куда положим файлы бота. Выполните по очереди следующие команды:
```bash
mkdir mybot
cd mybot
python3.7 -m venv venv
source venv/bin/activate
pip install pytelegrambotapi
deactivate
```
В результате должно получиться примерно то же самое, что на скриншоте ниже, с той лишь разницей, что я прервал процесс установки библиотеки для читабельности. Обратите внимание, что после подгрузки файла venv/bin/activate, перед названием пользователя и текущего каталога появится приписка (venv), означающая, что мы «вошли» в виртуальное окружение и устанавливаем библиотеки именно в него.
{{% img2 src="/images/l0_5.jpg" caption="Создание venv в Linux-терминале" %}}
Что произошло выше? Во-первых, мы создали каталог с названием mybot и перешли в него. Во-вторых, мы использовали Python версии 3.7 (в вашем случае это может быть не так), чтобы создать виртуальное окружение в подкаталоге venv. В-третьих, мы «активировали» venv и выполнили в нём нужную нам команду. Внутри venv команды pip и python точно знают, к какому именно интерпретатору они относятся, поэтому путаницы вроде «я установил библиотеку для Python 3.5, а запускаю из-под Python 3.7» попросту не будет. Наконец, в-четвёртых, мы деактивировали venv, поскольку он напрямую нам больше не нужен.
Чтобы сделать жизнь ещё приятнее, давайте настроим автозагрузку бота, чтобы при возникновении ошибок или при перезапуске сервера он вновь запускался, избавляя нас от необходимости постоянно проверять всё вручную. Для этого мы воспользуемся подсистемой инициализации systemd, которая всё больше распространена в современных Linux-дистрибутивах. Прежде, чем описать службу systemd, откройте главный файл с ботом, в котором прописан его запуск и добавьте в качестве первой строки следующий код:
`#!venv/bin/python`
Сохраните файл, закройте его и выполните команду `chmod +x имяфайласботом.py`, чтобы сделать его исполняемым.
Теперь создайте файл mybot.service, и скопируйте туда следующий текст:
```systemd
[Unit]
Description=MY BOT
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/user/mybot
ExecStart=/home/user/mybot/bot.py
KillMode=process
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
```
Отредактируйте поля `Description`, `WorkingDirectory` и `ExecStart`, сохраните и закройте файл. Далее скопируйте его в каталог `/etc/systemd/system`, введя свой пароль при необходимости (если сидите не из-под рута, что правильно, то ваш юзер должен иметь возможность выполнять команды от имени sudo). Затем выполните следующие команды для включения автозагрузки и запуска бота (опять-таки, требуются права суперпользователя):
```bash
systemctl enable mybot.service
systemctl restart mybot
```
Наконец, проверьте состояние вашего бота командой `systemctl status mybot`. Его статус должен быть `Active (running)` зелёного цвета (если поддерживается разноцветный режим).
{{% img2 src="/images/l0_6.png" caption="Проверка статуса бота через systemd" %}}
### Как редактировать файлы на сервере?
Если что-то нужно подправить небольшое, то неплохим вариантом остаётся старое доброе подключение по SSH и использование редакторов вроде micro, nano или даже vim с emacs. Но если вдруг у вас в качестве локальной машины применяется Linux, то крайне рекомендую редактор Visual Studio Code (https://code.visualstudio.com) с дополнением Remote-SSH. В этом случае, вы сможете прямо в VS Code открывать каталоги на сервере и редактировать файлы в удобном окружении и с подсветкой синтаксиса. К сожалению, насколько мне известно, расширение Remote-SSH не работает в Windows, но впоследствии этот недочёт будет устранён.
## Ответы на часто задаваемые вопросы (FAQ)
**Хочу научиться писать ботов. С чего мне начать?**
Прежде всего, пожалуйста, изучите хотя бы немного сам язык Python. Он довольно простой, но перед созданием ботов стоит понять азы. Конкретнее: переменные, циклы, функции, классы, обработка исключений, работа с файлами и файловой системой.
**Можно ли писать ботов на телефоне?**
Да кто ж вам запретит-то? Но лучше от этого никому не будет, поверьте. Будет трудно, неудобно и контрпродуктивно. Используйте нормальный компьютер.
**[pyTelegramBotAPI] Ошибка AttributeError: module 'telebot' has no attribute 'TeleBot'!**
На 99% уверен, что вы установили библиотеку telebot вместо pytelegrambotapi. С учётом всего вышесказанного проще создать новое окружение venv, перенести туда нужные файлы и установить именно pytelegrambotapi, при этом в исходниках должно остаться import telebot.
**Как мне держать бота запущеным в Windows?**
Запустите бота в PyCharm, не закрывайте приложение и не выключайте комп. Почти шутка. По-моему, Windows — не самая лучшая операционка для подобных вещей, проще арендовать сервер у европейских провайдеров, заодно не будет геморроя с варварами из Российского Консорциума Неадекватов.
**Библиотека pyTelegramBotAPI не поддерживает новые фичи Bot API!**
К сожалению, упомянутая библиотека в 2019 году развивалась гораздо медленнее, чем хотелось. Если вы уже чувствуете себя уверенным ботописателем, подумайте о переходе на альтернативы вроде [aiogram](https://github.com/aiogram/aiogram).
В завершение хочется напомнить, что если у вас возникли замечания, предложения или вопросы, вы всегда можете [открыть issue на Github](https://github.com/MasterGroosha/telegram-tutorial/issues) или прийти к нам в [чатик](https://t.me/joinchat/ABtnIE7H7Q3TRRh8n8uNww).
{{< btn_right relref="/docs/pytelegrambotapi/lesson_01" >}}Урок №1{{< /btn_right >}}
|
{
"pile_set_name": "Github"
}
|
Вы просыпаетесь в комнате со стенами из зефира.
Пол покрыт шоколадной глазурью
Солнце светит и вы видите в окне цветы, цветущие в саду.
Тихая музыка в джазовом стиле слышна, наверно она знакомая?
Да, это Small Mouse Big Band притаился в Вашей подмышечной впадине и наигрывает "Караван".
От звука тромбона Вам становится щекотно.
Нащупав наконец, головой, недопитый ящик водки, вы пытаетесь открыть глаза.
Это была всего лишь банка с вишневым компотом.
И тут вы вспоминаете своего знакомого, с которым пресеклись две недели назад. Именно он порекомендовал вам компанию,
которая может превратить вашу квартиру в шоколадный торт. Толстый слой зефира на стенах.
Слой шоколада на полу и заварного крема на потолке. Кровать из песочного теста. Подушки из свежего бисквита.
Да, служащие компании постарались на славу!
Будет не стыдно перед знакомыми за такой дом!
Вчера вы хотели только прилечь на кровать, но накопившаяся усталость дала о себе знать и вы проспали 9 часов.
Наступил день и теперь вы, полностью отдохнувший, готовы осуществить то, ради чего вы все это затеяли.
Взмахнув руками, вы наконец-то начинаете полет.
Ваши действия:
[Вы летите на Зов Ктулху](cthulhu/cthulhu.md)
[Пригласить профессора Воробьева](invite-proffesor/invite-proffesor.md)
[Попросите девушку ущепнуть вас](girlfriend-pinch-you/girlfriend-pinch-you.md)
[Пойти поплавать](go-to-swim/go-to-swim.md)
[Начать танцевать Лезгинку](dance_lezginka/dance.md)
[Смешать водку с пивом](vodka/vodka.md)
[Импортозаместить тромбон на гусли](gusli/gusli.md)
[Ненавижу зефир... Прочь из этой ужасной комнаты!](flowers/flowers.md)
[Открыть окно](window/window.md)
[Задернуть занавеску](draw-curtain/drawing-curtain.md)
[Поразмышляете о причинах вашей неожиданной смерти и природе сознания.](thinking-about/thinking.md)
[Начнёте есть стены.](eating-walls/eating-marshmallows.md)
[Разведёте костер.](light-fire/fire.md)
[Включите вести недели](vesti-nedeli/vesti.md)
[Попытаетесь проснуться.](awaken/awaken.md)
[Вернётесь ко сну.](sleep/zefir.md)
[Пойдёте варить кофе.](awaken/stand-up/coffee/coffee.md)
[Позвоните в ЖЭК.](buildings-dep/buildings-dep.md)
[Закроете глаза.](close-eyes/close-eyes.md)
[Откроете зефирный магазин.](shop/shop.md)
[Пойдёте в сад.](garden/garden.md)
[Позовёте друзей.](invite-friends/invite.md)
[Позвоните маме.](call-mom/call-mom.md)
[Позвоните охотникам за привидениями.](call-ghostbusters/ghostbusters.md)
[Поставите запятую после "цветы".] (comma/comma.md)
[Начинайте танцевать от радости.](dance/dance.md)
[Вспомните интересную шутку](Holms-Watson/Holmes-Watson.md)
[Откроете дверь, в нее настойчиво стучат.](rat-rat/rat-rat.md)
[Поздравлю деда.](grandad/grandad.md)
[Попробую отщипнуть кусочек зефирной стены.](nip-off/nip-off.md)
[Почесать в подмышечной впадине.](scratch/scratch.md)
[Пойду в другую комнату](next_room/next_room.md)
[Поговорю с соседями](speak_to_neighbor/speak_to_neighbor.md)
[Внезапно безумно начну просить сломать меня] (break-me-completelly/break-me.md)
[Зевну, откушу кусок зефира и снова усну...](dream/dream.md)
[Завоюю мир, в котором проснулся](conquer/lead.md)
[Отхлебну и закушу](kompot/kompot.md)
[Открою Instagram](instagram/instagram.md)
[Бросить "уделанную" футболку Slayer в стирку и отправиться на заутреннюю молитву](prayer/morning_prayer.md)
[Почувствуете ужасный голод] (hunger/feel-hunger.md)
[Начнёте медитировать](meditate/meditate.md)
[Решите программировать] (programming/to-program.md)
[Отправитесь путешествовать](travelling/go-to-travel.md)
[Буду клеить](glue/index.md)
[Включите музыку](music/turn_music.md)
[Наделаю селфи](selfie/make_selfie.md)
[Зайти на двач](2ch/2ch.md)
[Стану вегетарианцем](vegetarian/vegetarian.md)
[Открою сайт спутник.ру](sputnik/sputnik.md)
|
{
"pile_set_name": "Github"
}
|
\section{Асимметричные протоколы}\label{section-protocols-asymmetric}
\selectlanguage{russian}
Асимметричные протоколы, или же протоколы, основанные на криптосистемах с открытыми ключами, позволяют ослабить требования к предварительному этапу протоколов. Вместо общего секретного ключа, который должны иметь две стороны (либо каждая из сторон и доверенный центр), в рассматриваемых ниже протоколах стороны должны предварительно обменяться открытыми ключами (между собой либо с доверенным центром). Такой предварительный обмен может проходить по открытому каналу связи, в предположении, что криптоаналитик не может повлиять на содержимое канала связи на данном этапе.
В данном разделе рассмотрены только такие протоколы, которые не описывают и не ограничивают используемые математические операции, а позволяют использовать любые надёжные криптографические примитивы из симметричной и асимметричной криптографии. При анализе надёжности таких протоколов криптостойкость используемых <<примитивных>> алгоритмов не учитывается.
\input{denning-sacco}
\input{dass}
\input{woo-lam}
|
{
"pile_set_name": "Github"
}
|
# Бинарный поиск
## Введение
Бинарный поиск является одним из базовых алгоритмов поиска и часто встречается на собеседованиях.
В отличии от обычного линейного перебора, работает быстрее, но работает только с отсортированными данными.
## Алгоритм
Алгоритм состоит в том, чтобы взять серединный элемент массива, сравнить его с искомым, и, в зависимости от того, меньше он искомого или больше,
искать в левой или правой части соответственно.
Это продолжается до тех пор, пока искомый элемент не будет найден, либо пока массив не закончится.

Таким образом нам понадобится число операций равное тому, сколько раз нам нужно поделить массив размером `N` пополам.
Отсюда и временная сложность алгоритма двоичного поиска: `O(log(n))`.
Из описания алгоритма понятно, что он работает **только** с отсортированными массивами.
## Реализация
Реализовать алгоритм бинарного поиска можно как итеративно, так и рекурсивно.
Рекурсивно:
```java
public class BinarySearch {
public static int search(final int[] arr, final int element) {
if (arr.length == 0) {
return -1;
}
return search(arr, element, 0, arr.length - 1);
}
private static int search(final int[] arr, final int element, final int left, final int right) {
if (left > right) {
return -1;
}
final int mid = (left + right) / 2;
if (arr[mid] == element) {
return mid;
} else if (arr[mid] > element) {
return search(arr, element, left, mid - 1);
} else {
return search(arr, element, mid + 1, right);
}
}
}
```
Итеративно:
```java
public class BinarySearch {
public static int searchIter(final int[] arr, final int key) {
if (arr.length == 0) {
return -1;
}
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
left = mid + 1;
} else if (arr[mid] > key) {
right = mid - 1;
}
}
return -1;
}
}
```
## Производительность
Временная сложность: `O(log(n))`.
## Заключение
Алгоритм бинарного поиска используется во многих библиотеках и используется с отсортированными структурами данных, в частности, в `Java` уже есть его реализация, досутпная в `java.util.Arrays` через метод `binarySearch`.
|
{
"pile_set_name": "Github"
}
|
---
id: 5900f4771000cf542c50ff8a
challengeType: 5
title: 'Problem 267: Billionaire'
forumTopicId: 301916
localeTitle: 'Проблема 267: Миллиардер'
---
## Description
<section id='description'>
Вам предоставляется уникальная инвестиционная возможность. Начиная с 1 фунта капитала, вы можете выбрать фиксированную пропорцию, f, вашего капитала, чтобы делать ставку на честную монету, чтобы бросить несколько раз за 1000 бросков. Ваше возвращение удваивает вашу ставку для голов, и вы теряете свою ставку за хвосты. Например, если f = 1/4, для первого броска вы ставите £ 0,25, а если голова поднимается, вы выигрываете £ 0,5, а затем получаете £ 1.5. Затем вы ставите £ 0,375, и если второй бросок - это хвосты, у вас есть £ 1.125. Выбрав f, чтобы максимизировать ваши шансы иметь по меньшей мере 1 000 000 000 фунтов стерлингов после 1000 флип, какова вероятность того, что вы станете миллиардером? Все вычисления считаются точными (без округления), но дайте ответ округленным до 12 цифр за десятичной точкой в форме 0.abcdefghijkl.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler267()</code> should return 0.999992836187.
testString: assert.strictEqual(euler267(), 0.999992836187);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler267() {
// Good luck!
return true;
}
euler267();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
|
{
"pile_set_name": "Github"
}
|
# Макеты и CLI
Разработка в Electron разнообразна - нет "одного истинного пути" для разработки, сборки, упаковки или выпуска приложения. Дополнительные особенности для Electron, как для сборки, так и для времени выполнения, обычно можно найти в [npm](https://www.npmjs.com/search?q=electron) в отдельных пакетах, что позволяет разработчикам как создать приложение, так и построить конвейер, в котором они нуждаются.
Этот уровень модульности и расширяемости гарантирует, что все разработчики, работающие с Electron, как большие, так и малые по размеру группы, никогда не ограничены тем, что они могут или не могут делать в любое время в течение своего жизненного цикла разработки. Тем не менее, для многих разработчиков один из управляемых сообществом шаблонов или инструментов командной строки может значительно упростить компиляцию, упаковку и выпуск приложения.
## Макеты против CLI
Шаблон является только отправной точкой - это, так сказать, холст, из которого вы создаете свое приложение. Они обычно приходят в виде репозитория, который вы можете клонировать и настраивать ваш контент.
С другой стороны, инструмент командной строки продолжает поддерживать вас на протяжении всей разработки и выпуска. Они более полезны и поддерживаемы, но обеспечивают соблюдение рекомендаций о том, как ваш код должен быть структурирован и построен. *Специально для новичков - использование командной строки будет весьма полезно*.
## electron-forge
"Полноценный инструмент для создания современных приложений Electron". Electron Forge объединяет существующие (и хорошо поддерживаемые) инструменты сборки в единый пакет, чтобы каждый мог прямо сейчас заняться разработкой в Electron.
Forge поставляется с [готовым к использованию шаблонои](https://electronforge.io/templates), используя Webpack в качестве бандлера. Он включает в себя пример конфигурации typescript и предоставляет два конфигурационных файла, которые позволяют легко настраивать. Он использует те же основные модули, которые используются большим сообществом Electron (например, [`electron-packager`](https://github.com/electron/electron-packager)). Изменения, вносимые заказчиками Electron (например, Slack), также приносят пользу пользователям Forge.
Вы можете найти больше информации и документации на [electronforge.io](https://electronforge.io/).
## electron-builder
"Полноценное решение для упаковки и создания готового к использованию приложения Electron", которое фокусируется на интегрированном опыте. [`electron-builder`](https://github.com/electron-userland/electron-builder) добавляет одну единственную зависимость, ориентированную на простоту, и управляет всеми дополнительными требованиями изнутри.
`electron-builder` заменяет функции и модули, используемые майнтейнерами Electron (такими как автообновление) с пользовательскими. Они, как правило, более тесно интегрированы, но будут иметь меньше общего с популярными приложениями Electron, такими как Atom, Visual Studio Code или Slack.
Вы можете найти дополнительную информацию и документацию в [репозитории](https://github.com/electron-userland/electron-builder).
## electron-react-boilerplate
Если вам не нужны какие-либо инструменты, а только плоский шаблон, из которого можно собрать приложение, вам стоит взглянуть на [`electron-react-boilerplate`](https://github.com/chentsulin/electron-react-boilerplate). Он довольно популярен в сообществе и использует встроенный `electron-builder`.
## Другие инструменты и макеты
Список [«Awesome Electron»](https://github.com/sindresorhus/awesome-electron#boilerplates) предоставляет большой выбор инструментов и шаблонов. Если вы обнаружите, что длина списка вас пугает, не забывайте, что можно добавлять инструменты по ходу работы.
|
{
"pile_set_name": "Github"
}
|
# V8: за кулисами (Мартовское издание. Запуск I+TF и декларативный JavaScript)
*Перевод статьи [Benedikt Meurer](http://benediktmeurer.de) [V8: Behind the Scenes (March Edition feat. I+TF launch and Declarative JavaScript)](http://benediktmeurer.de/2017/04/03/v8-behind-the-scenes-march-edition/). Опубликовано с разрешения автора.*
Я снова опаздываю c мартовским изданием, так что это может превратиться в некую традицию. В прошлом месяце было довольно интересно: мы наконец включили Ignition и TurboFan по умолчанию для Chrome M59. Потребовалось две попытки, но, похоже, теперь всё прижилось. В целом все прошло на удивление хорошо, несмотря на сложность и влияние этого изменения. Как сказал мой site director (*прим. пер.: к сожалению не удалось найти адекватный перевод этой должности на русский*): [«Переход с Crankshaft на TurboFan в Chrome был похож на смену движка болида F1 на скорости 250 км/ч»](https://twitter.com/holfelder/status/842473381832409093).

[https://twitter.com/bmeurer/status/839337377671839744](https://twitter.com/bmeurer/status/839337377671839744)
Обратите внимание, что с этим переключением мы также удалили параметр enable-v8-future из chrome://flags и вместо него добавили выключатель disable-v8-ignition-turbo для новой конфигурации в Chrome M59. У этого выключателя есть три возможные настройки: Default, Disabled и Enabled. Если вы оставите его в Default, есть определенная вероятность, что вы получите старый конвейер компилятора даже на канале Canary или Dev из-за A/B тестирования. Установите для него значение «Отключено», чтобы быть уверенными, что вы получили новый конвейер, или установите его во «Включено», чтобы снова использовать Crankshaft и Full-Codegen.

Включение новой конфигурации по умолчанию выявило несколько проблем, которые не были известны ранее, поэтому я был очень занят, помогая с их решением. Но, насколько я могу судить, сейчас все выглядит очень многообещающе.
В конце прошлого месяца я выступил с презентацией [TurboFan: новая архитектура генерации кода для V8](https://docs.google.com/presentation/d/1_eLlVzcj94_G4r9j9d_Lj5HRKFnq6jgpuPJtnmIBs88) на Мюнхенской встрече Node.js User Group, рассказав немного о вещах, которые изменятся с новым конвейером. Самое главное, что включение нового конвейера значительно уменьшает общую сложность V8 и упрощает его перенос на новые архитектуры, а что ещё более важно с точки зрения пользователя, полностью исключает необходимость беспокоиться о так называемых *убийцах оптимизации*, поскольку TurboFan способен обрабатывать каждую конструкцию языка. Это не означает, что внезапно использование странной языковой конструкции, такой как `with`, становится невероятно быстрым, но это означает, что присутствие одного из этих *убийц оптимизации* больше не отключает оптимизирующий компилятор для этой конкретной функции.

Источник: [TurboFan: A new code generation architecture for V8](https://docs.google.com/presentation/d/1_eLlVzcj94_G4r9j9d_Lj5HRKFnq6jgpuPJtnmIBs88/edit#slide=id.g2134da681e_0_672), MNUG March '07 Meetup, [@bmeurer](https://twitter.com/bmeurer).
Вероятно, наиболее важными изменениями являются полностью оптимизируемые: операторы try-catch/try-finally, генераторы и асинхронные функции, и, конечно, теперь вы можете использовать let и const, не рискуя попасть в печально известный ["Unsupported phi use of const or let variable"](https://github.com/vhf/v8-bailout-reasons/issues/12).
Одно интересное и несколько неожиданное продолжение дискуссии, вызванное рекомендациями по оптимизации производительности, которые я назвал *декларативным JavaScript* в своём докладе:

[https://twitter.com/michaelhaeu/status/845003383153025024](https://twitter.com/michaelhaeu/status/845003383153025024)
*Мало того, что декларативный код легче читать, он также создает красивый байт-код и, следовательно, он быстрее. Спасибо [@bmeurer](https://twitter.com/bmeurer) [@munichnug](https://twitter.com/munichnug)*
Прежде всего, кажется, что некоторые люди сбиты с толку терминологией. Похоже, что использование понятий «явный против неявного» вместо «декларативный против неясного» для многих более понятно, поэтому просто представьте эти термины, когда смотрите на слайд выше. Однако главным спорным вопросом было то, имеет ли смысл использовать этот совет или предположить, что движок оптимизирует все это под капотом.
Имея бесконечные ресурсы, V8 мог бы генерировать улучшенный код и для правого слайда (и Crankshaft использовал это в прошлом), где он проверяет переменную в условии на то, что она является `undefined` или `Object`, и деоптимизирует во всех других случаях. Это уменьшает число проверок в оптимизированном коде. Однако этот подход имеет свою цену: он может деоптимизировать оптимизированный код, как только вводятся новые значения, а движку необходимо отслеживать, какие значения были видны для `obj` в базовом случае, что требует времени и памяти.
Но реальность такова: V8 не имеет бесконечных ресурсов. Фактически, когда все больше и больше бюджетных Android устройств заходит в мобильный интернет и все меньше и меньше трафика приходится на мобильные устройства или настольные компьютеры высокого класса, кажется, что в будущем у V8 (и Chrome) будет ещё меньше ресурсов. Снижение накладных расходов и менее агрессивная оптимизация помогли за последние два года значительно улучшить опыт работы на мобильных устройствах.
Иногда я слышу, как разработчики говорят, что эти проблемы при запуске не имеют значения для Node.js, и проблемы прогрева V8 не должны влиять на то, что они называют *серверной производительностью*, но затем я слышу, как они жалуются, что TypeScript, UglifyJS, Webpack, Babel и т.д. работают слишком медленно. Эти библиотеки также запускаются на V8 и также сильно страдают от накладных расходов во время прогрева или слишком агрессивной оптимизации, приводящей к частым деоптимизациям. Я видел много доказательств того, что уменьшение чрезмерной оптимизации помогло значительно уменьшить серверные нагрузки, как, например, измеряется в Node.js бенчмарке AcmeAir.

Производительность улучшилась более чем на 45%, в основном за счет снижения оверхэда в V8. Эти измерения были выполнены на типичных клиентских рабочих нагрузках. Для типичных рабочих нагрузок на стороне сервера результат не так уж сильно отличается.
И ещё один важный аспект, который легко забывается: V8 – не единственный JavaScript движок, о котором вам следует беспокоиться. Он, безусловно, очень доминирует из-за его использования в Chrome, Node.js, Android и Opera, но ограничивать себя одним движком и производить оптимизации только для него (или надеяться на то, что некоторые оптимизации появятся в V8) – это, безусловно, не путь к успеху.
Говоря о примере выше, вопросы о том, оптимизирует ли движок [ToBoolean](https://tc39.github.io/ecma262/#sec-toboolean) или нет, и, в частности, какая обратная связь отслеживается и расходуется относительно входящих значений, являются и должны оставаться неважными. Если вы можете написать свой горячий код таким образом, чтобы его можно было оптимизировать независимо от определенных спекулятивных оптимизаций, вы должны одобрить этот способ. Например, когда у вас есть значение `obj`, которое может быть `undefined` или объектом, рассмотрите возможность исключения неопределенности через явное условие:
```js
if (obj !== undefined) {
// …
}
```
или даже лучше:
```js
if (obj !== void 0) {
// …
}
```
Это так же поможет вам понять ваш собственный код через два года, так как из этого
```js
if (obj) {
// …
}
```
не ясно, что всё что вы хотели сделать – избежать `undefined` для `obj`.
Это особенно полезно иметь в виду при использовании `||` и `&&` в JavaScript. Например, я видел разработчиков, использующих `||` для реализации параметров по умолчанию, например:
```js
function foo(a, b) {
a = a || "value";
b = b || 4;
// …
}
```
Когда я спросил, является ли пустая строка допустимым значением для `a` или является ли `0` допустимым значением для `b`, они были весьма удивлены, заметив, что таким образом они ошибочно отфильтровали допустимые входные данные. Так что не делайте этого! Вместо этого используйте функцию ES2015:
```js
function foo(a = "value", b = 4) {
// …
}
```
Эта конструкция заменяет только значения `undefined` значениями по умолчанию, что является нормальным. Есть также [интересный аспект производительности](https://github.com/developit/preact/pull/610) при использовании `&&` и `||` в JavaScript. Я посмотрю, смогу ли я написать серию статей о *явном JavaScript* с удалением особого внимания аспектам производительности с точки зрения виртуальных машин, которые могут помочь пролить некоторый свет на эту тему.
Мой обычный дисклеймер: я не фронтенд инженер. У меня иные приоритеты, чем у вас (возможно), и у вас могут быть веские причины игнорировать любые советы, которые я здесь даю. Это совершенно нормально. Также будьте осторожны с переоптимизацией!
- - - -
*Читайте нас на [Медиуме](https://medium.com/devschacht), контрибьютьте на [Гитхабе](https://github.com/devSchacht), общайтесь в [группе Телеграма](https://t.me/devSchacht), следите в [Твиттере](https://twitter.com/DevSchacht) и [канале Телеграма](https://t.me/devSchachtChannel), рекомендуйте в [VK](https://vk.com/devschacht) и [Facebook](https://www.facebook.com/devSchacht). Скоро подъедет подкаст, не теряйтесь.*
[Статья на Medium](https://medium.com/devschacht/v8-behind-the-scenes-march-edition-5c53ed2c0467)
|
{
"pile_set_name": "Github"
}
|
# Совместимость типов на основе вида типизации
Каждый раз при присваивании значения компилятор подвергает его проверке на совместимость с ожидаемым типом. Компилятор словно секюрити стоящий на фейсконтроле ночного клуба решает пропускать или нет то, или иное значение. Подобные решения принимаются на основании правил, которые зависят не только клуба (языка программирования), но также вида проводимых мероприятий. Понять логику на которую опирается компилятор при определении совместимости нам поможет текущая и следующая глава. Но сначала давайте выведем правило самой совместимости.
## Совместимость типов (Types Compatibility)
_Совместимость типов_ — это совокупность правил, на основе которых программа, анализируя два типа, принимает решение о возможности одного типа заменить другой таким образом, чтобы замена не нарушила выполнение программы. Простыми словами, совместимость типов — это механизм, по которому происходит сопоставление типов.
Существует несколько основных механизмов и выбор конкретного зависит от случая, при котором возникает потребность сопоставления типов данных. Один из таких механизмов состоит из совокупности правил составляющих такое понятие, как типизация. Из существующего множества правил можно выделить несколько групп, которые образуют три вида типизации — _номинативную_, _структурную_ и _утиную_.
Чтобы различия между ними были более очевидными, все они будут рассматриваться на одном примере, диаграмма которого показана ниже.

## Номинативная Типизация (nominative typing)
_Номинативная типизация_ (nominative typing) устанавливает совместимость типов основываясь на идентификаторах типов (ссылках). Простыми словами, при проверке на совместимость компилятор проверяет иерархию типов на признаки наследования и реализацию интерфейсов. То есть, тип `B` будет совместим с типом `A` только тогда, когда он является его предком (`extends`). Кроме того, тип `B` будет совместим с интерфейсом `IA` только в том случае, если он или один из его предков реализует его явно (`implements`).

Как можно понять по изображению выше, при проверке на совместимость типа `Bird` с типом `Animal` компилятор обходит дерево в поисках наличия ссылки на тип `Animal` и обнаружив её, приходит к выводу, что типы совместимы. Тот же самый процесс требуется для установления совместимости типа `Bird` с типом интерфейса `INameable`. Полная картина совместимости изображена на диаграмме ниже.

Номинативная типизация присуща исключительно статически типизированным языкам.
К языкам с номинативной типизацией относятся _Java_, _C#_ и другие.
## Структурная Типизация (structural typing)
_Структурная типизация_ — это принцип, определяющий совместимость типов основываясь не на иерархии наследования или явной реализации интерфейсов, а на их описании.

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

Структурная типизация присуща исключительно языкам с явной типизацией (глава [“Экскурс в типизацию - Сильная и слабая типизация”](../007.(Экскурс%20в%20типизацию)%20Сильная%20и%20слабая%20типизация)).
К языкам со структурной типизацией относятся _TypeScript_, _Scala_ и им подобные.
## Утиная Типизация (Duck typing)
_Утиная типизация_, как и в случае со структурной типизацией — это принцип, определяющий совместимость типов основываясь не на иерархии наследования или явной реализации интерфейсов, а на их описании. Утиная типизация ничем не отличается от структурной, за исключением того, что присуща лишь языкам с _динамическим связыванием_ (динамическая типизация).
Термин «Утиная типизация» произошёл от английского выражения _duck test_, который в оригинале звучит как -
_Если это выглядит как утка, плавает как утка и крякает как утка, то это, вероятно, и есть утка_.
Так как утиная типизация не отличается от структурной, то в качестве примеров совместимости можно воспользоваться диаграммой из предыдущего раздела, посвященного структурной типизации.
К языкам с утиной типизацией относятся _Python_, _JavaScript_ и другие.
|
{
"pile_set_name": "Github"
}
|
module["exports"] = {
"descriptor": [
"Lead",
"Senior",
"Direct",
"Corporate",
"Dynamic",
"Future",
"Product",
"National",
"Regional",
"District",
"Central",
"Global",
"Customer",
"Investor",
"Dynamic",
"International",
"Legacy",
"Forward",
"Internal",
"Human",
"Chief",
"Principal"
],
"level": [
"Solutions",
"Program",
"Brand",
"Security",
"Research",
"Marketing",
"Directives",
"Implementation",
"Integration",
"Functionality",
"Response",
"Paradigm",
"Tactics",
"Identity",
"Markets",
"Group",
"Division",
"Applications",
"Optimization",
"Operations",
"Infrastructure",
"Intranet",
"Communications",
"Web",
"Branding",
"Quality",
"Assurance",
"Mobility",
"Accounts",
"Data",
"Creative",
"Configuration",
"Accountability",
"Interactions",
"Factors",
"Usability",
"Metrics"
],
"job": [
"Supervisor",
"Associate",
"Executive",
"Liaison",
"Officer",
"Manager",
"Engineer",
"Specialist",
"Director",
"Coordinator",
"Administrator",
"Architect",
"Analyst",
"Designer",
"Planner",
"Orchestrator",
"Technician",
"Developer",
"Producer",
"Consultant",
"Assistant",
"Facilitator",
"Agent",
"Representative",
"Strategist"
]
};
|
{
"pile_set_name": "Github"
}
|
# Пакт про участь - Кодекс поведінки
## Наші зобовʼязання
В інтересах зміцнення відкритого і дружнього середовища, ми, як учасники та
супроводжувачі, зобовʼязуємось приймати участь в розбудові нашого проекту та
спільноти навколо нього, уникаючи будь-яких образ та притискань в залежності
від віку, статури, особливих потреб, етнічної та гендерної приналежності,
самовираження, досвіду, національності, зовнішнього вигляду, раси, сексуальної
самоідентифікації та орієнтації.
## Наші стандарти
Приклади поведінки, які сприяють створенню сприятливих умов:
* Використання доброзичливої та зрозумілої мови
* Повага до різних точок зору та досвіду
* Ввічливе сприйняття конструктивної критики
* Зосередження уваги на тому, що краще для спільноти
* Демонстрація співпереживання по відношенню до інших членів спільноти
Приклади неприпустимої поведінки до інших учасників:
* Використання виразів і зображень сексуального характеру, небажана увага
сексуального характеру чи вислови
* Тролінг, образливі/принизливі коментарі або персональні чи політичні
випади
* Публічні чи приватні домагання
* Оприлюднення приватної інформації інших осіб, наприклад поштової чи
електронної адреси, без явної на те згоди
* Інша поведінка, яка обґрунтовано може вважатись недоречною в професійному оточенні
## Наші обовʼязки
Супроводжувачі проекту несуть відповідальність за розʼяснення стандартів
прийнятної поведінки, і від них очікується належне і справедливе
виправлення у відповідь на будь-які випадки неприйнятної поведінки.
Супроводжувачі проекту несуть відповідальність та мають право вилучати,
змінювати або відхиляти коментарі, коміти, код, зміни у вікі, записи
та інший вклад в проект, що не відповідає Кодексу поведінки, чи блокувати
тимчасово або назавжди будь-якого учасника за його поведінку, якщо вони
вважають такі дії недоцільними, загрозливими, образливими або шкідливими.
## Сфера застосування
Цей Кодекс поведінки застосовується як в середині проекту, так і публічно,
коли особа представляє проект або його спільноту. Приклади представлення
проекту або його спільноти включають використання офіційної адреси
електронної пошти, публікації в соцальних мережах від імені проекта, або виступи
на онлайн чи оффлайн подіях в якості представника проекту. Способи
представництва можуть бути уточнені супроводжувачами проекта.
## Правозастосування
Про випадки образливого або іншого неприпустимого поводження можна повідомити,
надіславши листа до команди проекта за адресою [INSERT EMAIL ADDRESS]. Всі скарги
будуть розглянуті та перевірені, що призведе до реакції, що вважається
необхідною і доцільною відповідно до обставин. Команда проекту зобовʼязується
зберігати конфеденційність позивача. Інші деталі щодо правозастосування можуть
оприлюднюватись окремо.
Супроводжувачі проекту, які не дотримуються або порушують Кодекс поведінки,
можуть зіткнутися з тимчасовими або постійними наслідками, які визначені членами
керівництва проекту.
## Посилання
Цей Кодекс поведінки заснований на [Пакті про участь][homepage], версії 1.4,
що знаходиться за адресою https://www.contributor-covenant.org/uk/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
|
{
"pile_set_name": "Github"
}
|
т
табак
Красавице, которая нюхала
Возможно ль? вместо роз, Амуром
насажденных,
Тюльпанов, гордо наклоненных,
Душистых ландышей, ясминов и лилей,
Которых ты всегда любила
И прежде всякий день носила
На мраморной груди твоей--
Возможно ль, милая Климена?
Какая странная во вкусе перемена! . .
Ты любишь обонять не утренний цветок,
А вредную траву зелену,
Искусством превращену
В пушистый порошок!
Пускай уже седой профессор Геттингена,
На старой кафедре согнувшися дугой,
Вперив в латинщину глубокий разум свой,
Раскашлявшись, табак толченый
Пихает в длинный нос иссохшею рукой.
Пускай младой драгун усатый
Поутру, сидя у окна,
Стаканы сушит все до дна,
С остатком утреннего сна
Из трубки пенковой дым гонит сероватый.
Пускай красавица шестидесяти лет,
У граций в отпуску, и у любви в отставке
У коей держится вся прелесть на подставке,
У коей без морщин на теле места нет,
Чаек в прикуску попивает,
И с верным табаком печали забывает,
Злословит, молится, зевает.
А ты, прелестная! . . но если уж табак
Так нравится тебе--о пыл воображенья!
Ах! если, превращенный в прах,
И в табакерке, в заточеньи,
Я в персты нежные твои попасться мог,
Тогда б в сердечном восхищеньи
Рассыпался на грудь под шалевый платок
И даже, может быть. . о сладость
вожделенья
...До тайных прелестей, которых сам
Эрот
Запрятал за леса и горы,
Чтоб не могли нескромны взоры
Открыть вместилище божественных
красот.
Но что! мечта, мечта пустая.
Не будет этого никак.
Судьба завистливая злая!
Ах, отчего я не табак! . .
End of the Project Gutenberg EBook of Krasavitse, Kotoraya Niuhala Tabak, by
Aleksandr Sergeevich Pushkin
|
{
"pile_set_name": "Github"
}
|
# July 24, 2018 Meeting Notes
-----
Waldemar Horwat (WH), Mark Miller (MM), Till Schneidereit (TST), Michael Ficarra (MF), Michael Saboff (MLS), James Burke (JRB), Maxim Aleksa (MAA), Brian Terlson (BT), Shu-yu Guo (SYG), Rex Jaeschke (RJE), Yehuda Katz (YK), Andrew Paprocki (API), Chip Morningstar (CM), Mariko Kosaka (MKA), Jordan Harband (JHD), Patrick Soquet (PST), Sam Goto (SGO), Dave Herman (DH), Brendan Eich (BE), Pieter Ouwerkerk (POK), Leo Balter (LBR), Limin Zhu (LZU), Aki Rose (AKI), Ross Kirsling (RKG), Shane Carr (SFC), Kevin Smith (KS), Ron Buckton (RBN), Jean-Francois Paradis (JFP), Peter Hoddie (PHE), Godfrey Chan (GCN), Domenic Denicola (DD), István Sebestyén (IS), Bradley Farias (BFS), Adam Klein (AK), Gus Caplan (GCL), Felipe Balbontín (FBN), Daniel Rosenwasser (DRR), Jonathan Keslin (JKN), Christopher Blappert (CBT), Dean Tribble (DT), Richard Gibson (RGN), Lin Clark (LCK), Allen Wirfs-Brock (AWB), Maggie Pint (MPT), Timothy Gu (TGU), Sebastian Markbåge (SM), Dustin Savery (DSY), Mike Murry (MMY), Alex Vincent (AVT) John-David Dalton (JDD)
Remote:
Rick Waldron (RW), Daniel Ehrenberg (DE), Caridy Patiño (CP), Justin Ridgewell (JRL), Brian Warner (BWR), Yulia Startsev (YSV), Jason Williams (JWS), Ron Buckton (RBN), Ross Kirsling (RKG)
-----
## Agenda
- [Agenda](https://github.com/tc39/agendas/blob/master/2018/07.md)
## Opening, welcome and roll call
RJE: (housekeeping)
RJE: Firstly, we have four new voting members. Agoric Systems (SPC), npm (SME), Stripe (OM), and Igalia (SME). Today we'll break at 5pm, and open it up to new members until we're kicked out of the room. We have a CoC, which we follow for our operations in addition to the general TC39/ECMA rules.
BT: (Talking about logistics) We have a queue app. To talk about a certain agenda item, hit the new tab in the queue app and add a new topic. Rex will prompt you when it's your turn to speak. Join the IRC channels (`#tc39` for public discussions and `#tc39-delegates` for backchannel discussions, message BT for access to this).
DE: A reminder: to contribute to TC39, you must be a member of a delegate company or sign our IP agreement. If you are a non-member and didn't sign this form, you must attend as an observer (and not contribute).
## Adoption of Agenda
RJE: Item 9 deferred to Wednesday morning for Maya to attend. Could someone please ping Maya. For Item 10, I propose 2:00pm today. (Approved). Could Brian or Maggie ping him on that? I propose Yulia presents on Wednesday at 10:00am.
YSV: I have two presentations, one 10-minute long presentation and one 20-minute long presentation?
RJE: That could conflict with Dynamic Modules which needs to be presented at 10:30am on Wednesday. How about 10:45am?
YSV: That works.
RJE: Peter Hoddie—you're flexible? (Yes.) DE, does anytime Wednesday work for Decorators? (Yes.) MLS, does Thursday morning work?
MM: Where did the report on the security review end up (Item 9)?
RJE: This was slightly de-prioritized in favor of proposals.
MM: The reason why I proposed to present for an hour was because there's flexibility in the schedule. I'd much rather present for 30 minutes than not at all, however.
#### Conclusion/Resolution
- Agenda Adopted
## Approval of the minutes from last meeting
RJE: Approval?
#### Conclusion/Resolution
- Minutes Approved
## Dates for next meetings
RJE: September 25-27, 2018 at PayPal in New York
AKI: Next meeting will be hosted at PayPal in Lower Manhattan. Logistics will be posted as soon as I have them. While I'm talking, I also have a quick CoC update: everyone is expected to uphold the code of conduct, which is [on GitHub](https://tc39.github.io/code-of-conduct/). This explains our expectations as well as how to handle things when they go wrong. Separately, I have stickers for TC39, please let me know if you want one (and didn't already take one at JSConf EU).
## Report from the Ecma Secretariat
(István Sebestyén)
- [slides](https://github.com/tc39/Reflector/files/2215322/tc39-2018-037_R1.pdf)
IS: (Presenting slides)
IS: Still need to improve that quality of the PDF conversion of the ECMAScript spec. It's not good right now.
IS: OSC didn't properly respond to clarification requests for the General Assembly.
IS: Update on ECMA Fellows: this is a category suggested by this committee, and it was approved by the General Assembly. A couple of rules: must be proposed by the Technical Committee and will get this status for life, once approved by the GA.
RJE: We should add to the agenda some time to discuss the status of TC39's chairmanship.
WH: Can you clarify what's the issue with the TC39 chairmanship?
IS: We must elect a chair for 2019. It's July, we have a meeting in September, then in November we must hold our election for the 2019 chair. It can be the same person or a different person.
BFS: Do we need to do anything to proceed with the "Submission of JavaScript (ECMAScript Standardization)" to the 5th World Internet Conference in Wuzhen, China?
IS: No, I will submit it on the committee's behalf.
## Project Editors' Reports
### ECMA-262
(Brian Terlson)
BT: A couple of new additions in ES2019: 1) ECMAScript is now a superset of JSON. 2) The catch binding is now optional. Other than that, a few bugfixes, and a few remaining things will be filed in needs-consensus PRs.
### ECMA-402
(Dan Ehrenberg)
DE: I was elected the Interim Editor, and worked in partnership with Mozilla (thanks for the support!). This is JS' built-in internationalization library. Intl has a separate specification also developed by TC39, we meet monthly in a 2-hour phone call to discuss details, but we'd love to hear more from application developers. Please contact me for an invitation to the call.
DE: In terms of PRs, we have:
1. a request to permit unknown fields, which is useful in the Chinese calendar. When locale data suggests something else should be presented that's unexpected, the PR suggests that we return a type "unknown".
2. `Intl.RelativeTimeFormat`: given a number and a unit, it will format the number and wrap it in something that indicates the unit. If the number ends up breaking into multiple parts, we have `formatToParts` to break apart the number. Please take a look at these, and if you have any concerns, we'll be happy to revisit them.
3. `Intl.Locale`: if you give an empty string for the calendar, we now throw a RangeError. We also now use the modern form of canonicalization.
4. `Intl.ListFormat` implementation is now in V8. Given a list of items, we can automatically insert "and" or "or".
5. `Intl.Segmenter` (Stage 3): Segmenter can segment a sentence into its constituent words. Being developed in conjunction with W3C's internationalization WG. Implementation almost complete in V8.
RJE: Questions for DE? (None). Thank you DE!
### ECMA-404
...
### Test262
(Leo Balter)
LBR: Some updates since the last meeting. (Reads slide about Git diff; quite a few changes to Test262). We refactored several tests for Atomics and reviewed repeatedly these changes. Thanks to Rick Waldron and André Bargull for their efforts on this. We're ready to rename Atomics.wake to Atomics.notify (we will discuss this more). We have coverage for Symbol.prototype.description. We also updated RegExp Unicode property escape tests for Unicode 11. We now have tests for `export *` as namespace from `foo` syntaxDynamic Imports. We've had our first implementation-contributed where bots will check for updates and verify Test262 coverage, starting with JavaScriptCore; initial curation is in progress here, though it requires a lot of manual work. Lastly, we have a new Test262 harness in C++!
## Atomics.notify()
(Leo Balter)
- [slides](https://docs.google.com/presentation/d/1iiGJyVwy6YM3p8T0hfaDuj4fQ4tT0b4Oz24OzzCetAg/)
LBR: Some engines have already renamed Atomics.wake to Atomics.notify. ChakraCore, V8, Moddable XS among others. Node.js has introduced an experimental worker API that has cautious aliasing. Unfortunately, UnrealEngine repository requires a developer account, which we don't have.
LBR: So, can we have consensus for this to land?
AK: Didn't this already have consensus?
DE: I support this landing.
AK: It's weird that we have to reaffirm consensus. V8 was under the impression this already had consensus.
RW: (follow up) This was not to "reaffirm". We did not have consensus at first presentation. We were told to complete a set of tasks and then we'd have consensus. This was supposed to be a status report.
#### Conclusion/Resolution
- Consensus
## ArrayBuffer.prototype.transfer()
(Domenic Denicola, DD)
- [proposal](https://github.com/domenic/proposal-arraybuffer-transfer)
DD: Long history of sitting at Stage 0. Reintroducing. Binary data has potential for race conditions. (See example in proposal.) Not obvious for debugging. Node.js in particular directly reads the buffer from another thread w/o locking. The defensive way to write this code is to write a copy, and this is what many APIs do on the web. The idiomatic way to do this in JS is to slice it. However, this adds time and space consumption to every time you use an array buffer, and that's very sad. Detaching and transferring ("neutering") is a built-in solution. Already used widely in the web platform. Detaching means it is no longer a usable handle for that memory. So no one who had original access to the array buffer can use it. Concretely, if we added this to JS, we would add a new method `transfer()` you would get a new ArrayBuffer object where the backing memory is the same as the old one, but the old one is now detached, so any attempts to access the memory at the old one will throw an exception (or return undefined, in implementations). The transferred one (lexically scoped and private to the current function) has a reference to the memory area but is fully functional. (Points to example using transfer()). This doesn't have to copy or detach, and makes the operation fast. You can transfer without having to save the result anywhere. Any thoughts?
BFS: There's a visible cost in Node.js with copying all the time, so this is great for us with module loaders!
JKN: Similar to move semantics. Syntax that the data is taken from them? Non-obvious to the caller.
DD: Not sure if we can have those guarantees for callers in JavaScript. Since they're mutable, there's no idiomatic way I can conceive of.
WH: What did you mean by "protecting data from other threads"? `transfer` is (rightfully) not done for SharedArrayBuffer, so what does "threads" refer to here?
DD: Basically, this is a particular bad pattern where people compromise safety for performance. `fs.writeFile()` in Node will write concurrently from memory. But this isn't thread safe, because they don't want to take that cost.
WH: Isn't such lack of thread safety an issue anyway?
DD: This is unsafe if you don't know this happens.
WH: What happens if the other thread is using the data, but the original thread transfers it?
DD: Transferring has no effect on the data itself; the other thread will continue to refer to the now transferred buffer.
MM: I dispute that Node.js is allowed by the JS spec to mutate this memory in another thread. There is a computational model that the spec is very clear on. This is not mutable state shared across agents! If this is the same agent, then there cannot be concurrent modifications.
DD: You're right, but Node.js doesn't write to the ArrayBuffer.
MM: If it's reading from another thread, then it's the same problem. The notion of an ownership transfer can still be useful (separate from the concurrency issue). I was surprised when WH pointed out the difference with SharedArrayBuffer, as ownership transfer is useful there as well.
DD: I have an FAQ that says for SharedArrayBuffer, this is not applicable. For SharedArrayBuffer, there's no concept of detaching, for example.
MM: I think it's natural if this proposal is to be promoted to think about this as a missing feature for SharedArrayBuffer.
DD: For example, you could have a transfer method on SharedArrayBuffer that returns a normal ArrayBuffer? That's very cool.
MM: You have insisted in the past that object-granularity security is impossible. The points you are making here assume object-granularity is meaningful, and that proposals (such as this) should indeed proceed assuming that it is possible, practical, and attractive.
DD: We can take that offline.
SYG: I like the proposal, but this can happen for any JavaScript object. Why only ArrayBuffer?
DD: This is an 80-20% tradeoff. The idea of detached already exists.
SYG: I think people don't actually try to serialize large object graphs and transfer them.
DD: People might. This is exposing a primitive that all engines already have. Let's scope this proposal to that.
DH: This talks about concurrency. This method alone doesn't give capability to do concurrency, right?
DD: No.
DH: What you're doing here is exposing the pure primitive of transfer itself. This is not going to solve concurrency problems.
DD: I shouldn't have put anything about threads in the proposal.
JHD: You can already do transfer ArrayBuffers using post message?
DD: Already possible in the web platform (structured cloning). Only indirectly, by posting to yourself or by storing in the History API (but this doesn't allow transferring, so nevermind). No way to do this synchronously, however. Existing methods are merely work-arounds. I would like to add this as a primitive.
BFS: In Node.js, we don't have these APIs, and I would like them.
DD: I've wrote a Spec for this and I would like to go for Stage 2.
DE: I want to point out a related proposal in HTML that exposes structured serialization/deserialization for the Web, that has the capability to transfer ArrayBuffer. You can just call this structuredClone method and it can do most of the same things (and more). If we advance this to Stage 2, we just should know that there's multiple ways to do this, and that we're proceeding with this because it's a simpler/more memorable way.
DD: High-level vs. low-level distinction. Structured cloning is high-level and opinionated: Maps and Sets serialization, for example. Transfer is low-level.
DE: My second point: transferring ownership of Array buffers is something we should be making more idiomatic. WASM is doing this. It seems good to establish a pattern of transferring ownership, but it's admittedly a complicated topic. In Rust, this is a core thing in the language, so tacking it on to JavaScript is difficult, but it would be very useful.
BFS: Do we need a way to prevent transferring? Can't use frozen, maybe as an add-on proposal for later.
DD: I agree, I think it is an interesting area to explore. There are a lot more primitives we can add in this space about transferring and ownership.
YK: First of all, I've used this idiom in the web platform, and I think it's great to add better workarounds. As a person who writes a lot of Rust code, I think the ownership transfer idiom is a good one, and I'm not concerned that the style would leak into your other code that doesn't use this idiom. Rust has something very similar – I would be happy to see it in JavaScript.
LBR: I like the proposal, from Test262, it's great to have the observable points of ArrayBuffers from ECMAScript tools. Is the second part of the proposal (realloc) also going for Stage 2?
DD: More realistically, that will probably spin out into a separate proposal.
WH: I like this, but I'm a bit confused about the thread question from earlier. Also, I just wanted to find out if anyone out there is upset that SharedArrayBuffers will not have `transfer`. If we add `transfer` to ArrayBuffer, it's likely that we'll face pressure in the future to add this method to SharedArrayBuffer as well, and I'm wondering what we'll do about that.
DD: MM gave an idea: spin ArrayBuffer from a SharedArrayBuffer. We can explore that in the future.
WH: For the record, my position is not to add `transfer` to SharedArrayBuffer for obvious reasons.
#### Conclusion/Resolution
- Stage 2 acceptance
### Secondary Proposal for ArrayBuffer.prototype.transfer()
(Domenic Denicola, DD)
- [proposal](https://github.com/domenic/proposal-arraybuffer-transfer)
DD: Secondary proposal, trimming while avoiding copies. If we introduce a new function `realloc` where we transfer a subset of bytes. Think of this as an alternative to Slice. I call it realloc in honor of the C/POSIX standard library method with the same name.
TST: Can you speak more about how the internal feedback made you split this out from the transfer proposal?
DD: For transfer, it's meant to be a guarantee—we'll definitely reuse this memory. For `realloc`, it's not as clear. Do we want to transfer ownership or are we concerned with saving memory?
TST: If you know about transfer, the discovery of that method is much easier, than realloc. This is much harder to reason about needing/use cases.
DD: Original version was more ambitious, could trim start as well as end. Feedback: will probably have to copy for an implementation. Realloc is more explicit about its connection to the lower-level primitive.
BFS: You say the main use case is trimming, but are you also allowing realloc to get a larger size?
DD: I believe so? But it contradicts a lot of my arguments for it...
??: In Moddable XS, For the memory allocation in ArrayBuffers, we can create larger allocations pretty trivially.
GCL: Wondering how this parallels with TypedArray's subarray().
DD: subarray is different. Will add to FAQ.
MM: WASM has a concept similar to ArrayBuffer, but it is growable while maintaining the same identity. If realloc is "change in place" and maintains identity, then this would fix the mismatch between JavaScript and WASM.
DD: Will look into that, and split realloc into a separate proposal.
#### Conclusion/Resolution
- Split into a separate proposal
## Report on Realms shim Security Review
(Mark Miller, MM)
slides in pdf, slides in keynote with light animations
(The following notes omit almost everything said in the actual presentation)
MM: First some terminology: the mandated objects that must exist before code starts running are called primordials. Of those primordials, most are replaceable with initialization code. Some object are reachable by syntax. We call everything that's reachable by syntax "undeniables." Today, platforms already support multiple realms (in the browser, iframes; in Node, vm.createContext). (Points to examples in slides).
BE: Does Carol's compartment (example in slides) get frozen?
MM: Carol's compartment does not get frozen in deepFreeze.
MM: How do we implement this in browsers today? The shim must intercept all attempts to access a free variable (generally looked up in the global lexical scope or on the global object), and we want without parsing or rewriting, to evaluate the code as is.
WH: Early on in the talk you said you wanted to avoid parsing. How does this avoid parsing when you use `eval`?
MM: We wanted to avoid a parser written in JavaScript (parsing at the user level).
#### Conclusion/Resolution
- ?
## Intl.DateTimeFormat.prototype.formatRange
(Felipe Balbontín, FB)
- [slides](https://docs.google.com/presentation/d/e/2PACX-1vQXuKpkf-kHF4Ue-35PAez79EL2bTU-s3dGbQvj0zwOzbqnF1zJJif_RT8wV9v8VkI4agEzvBPbKOoi/pub)
FBN: It's common for websites to show date ranges or intervals—for example for travel dates or a graph range. How do we display this in a friendly way? We can format the two date strings and concatenate them. But we can do this more concisely, if for example the two dates have repeated aspects, like months and years. Another issue is that different locales have different rules for the way they write date ranges. We propose two additional methods: `formatRange` and `formatRangeToParts`. `formatRange` returns a string, and `formatRangeToParts` returns an array of objects, where each object is a different part of the date interval. To give you an example of how to use this API, we instantiate the range with a locale and several options. Why add this to the platform as opposed to loading a library? Formatting date ranges requires a non-trivial amount of raw compiled data.
WH: How much flexibility do you have in deciding where the dash goes? Do you always share the parts of the dates that don't change, or can you duplicate them? Seeing a date range such as `1/2-3/4/2014` would be confusing, whereas `1/2/2014-3/4/2014` would be clearer.
FBN: Everything is based on that locale, and how that locale formats ranges by default.
#### Conclusion/Resolution
- Stage 2 acceptance
## Explicit Resource Management
(Ron Buckton, RBN)
- [proposal](https://github.com/rbuckton/proposal-using-statement#readme)
- [slides](https://docs.google.com/presentation/d/1OmkXFMizf5iYME9ClERZ3C1dwUAhh7-r2YMD-rTzY-Y/)
RBN: (Reading slides). The proposal that we are presenting today is this `using` keyword, which requires a cover grammar to work correctly. There are two basic mechanisms to manage these resources. The first example has an expression that is guaranteed to be cleaned up at the end of the block. The second example lets you use variables declared in `using` head within the block. The resources in the head of the block are disposed at the end of the block. If the declaration in the head of the using block is null or undefined, we just ignore it for simplicity. Some challenges with `using`, we must use a cover grammar to disambiguate with CallExpression, though we could use `try () {}` (without a catch or finally).
. We'll need to have some follow-up implementations here. We have an initial implementation for testing
MM: When you're reading code, including code inside generators, async functions, and async generator functions, it's easy to find by visual inspection the possible interleaving points. So you could reason about what happens before the executing code vs. after the code resumes from an interleaving point. Wouldn't the end of the dispose block would be a hidden interleaving point?
RBN: It's possible, but the transparency of the interleaving point is effectively the same as an async generator.
MM: The issue you're raising with regard to "yield" in an async generator, was controversial. The resolution recognized that "yield" in a generator was already an interleaving point, in that control could resume after the yield point at an arbitrary later time. It remains the case in JavaScript that *all* interleaving points are marked with either the keywords "await" or "yield" in all contexts. It must remain the case that a trivial visual inspection is able to reliably find all interleaving points in control flow.
TST: This is consistent with Python, and I think it makes sense to support this. On slide 5, you say this solves the footgun of releaseLock. How?
RBN: It doesn't especially avoid the footgun, but if somewhere within the code to getReader and releaseLock, you have an exception, if there's a common syntax/pattern here, it's easier to drum into users these good habits.
TST: If releaseLock throws, how do you get an exception from that? Do you swallow the exception and then throw it?
RBN: (Shows slide 18). When the end of the block hits, you effectively have two try/finally blocks. You have effectively a stack of resources allocated, then you need to clean up these resources in reverse order.
TST: But I don't understand how you would handle exceptions.
RBN: You should use a try/catch in that case.
DH: I think there's a missed opportunity to make sure to do all the disposals and offer a composite exception. I'm happy to take this to GitHub.
WH: I'm OK with this feature. I'm not OK with the `using` syntax, because it creates cover grammars on top of cover grammars. The `try` syntax, on the other hand, is fine. It also matches with what Java's try-with-resources statement does.
WH: Note, however, that Java made a conscious decision to reverse which exception gets thrown if both the block and the finalizer throw. Unlike regular `try` blocks, try-with-resources blocks will ignore the finalizer's exception and throw the original exception instead.
RBN: We should use the regular `try` block semantics to be consistent with `try` blocks if we use the `try` syntax.
WH: There are no existing expectations for this feature. On the other hand, using identical syntax to Java's but with reversed semantics would be very confusing to anyone who knows both languages, making it hard to remember which one is which.
BFS: I'm not super comfortable with the cover grammar. I'd like to see a contextual grammar.
SYG: Given that we already have an iterator protocol, I'm concerned we'll have multiple protocols that are all in play.
RBN: `for...of` in ECMAScript is a combination of two different patterns, an iteration pattern and a disposal pattern. I would not want to find a way to wrap every resource I create in a for...of—this is an over-complication.
MF: We'll still have two disposal protocols and the difference between them is very questionable. Could you list the concrete benefits to this?
RBN: I would not want to have to wrap every stream I have in a for...of. This is a single pattern for dealing with resource disposal, and it makes a lot of sense.
DH: I would really like to see us not add new statement forms. New statement bodies are OK, expression forms too, but statement forms are not. We don't have to have that conversation now, but I'd like to add to the record that we should avoid unless absolutely necessary adding statement forms.
?: I am uneasy about advancing this to stage 1 because this functionality may already be in the language.
JLH: Just want to clarify that any hesitations to add this to the language should be discussed before proceeding to Stage 2. Moving to Stage 1 just means we will spend more time as a committee exploring this feature.
#### Conclusion/Resolution
- Stage 1 acceptance
## Management/infrastructure tasks; invited expert policy; meeting planning
(Daniel Ehrenberg, DE)
- [slides](https://docs.google.com/presentation/d/1eTBTMZzylhZR4v7Hgfd3UJYwLBgQZgX8q8fGvsvcNDE/edit#slide=id.p)
DE: Each PR should be from someone who is either part of a member organization or a signatory of the contributor IP agreement. This is a great task for a bot! We would love it if someone would help build a bot to enforce this. Archival of materials is also very important. We need an archive of GitHub, our Wiki, various old bug-trackers. We need more collaborators. Please get in touch with me, Thomas, or Keith. Next, we need to improve our delegate database and our Doodles. It's important to get this right—for keeping in touch, for following up with proposals, and for planning reasons. I think we could use a database of all the delegates and help is much needed to get this done.
DH: For archival things, this is a tricky topic. I've tried and failed to do this before. David Scott's mission in life is to archive things, maybe we could contract him?
DE: Currently, we're relying on internet archive. The servers that hosted this information have gone missing. It would be very useful to get in touch with whomever ran these servers, because the Internet Archive wiki is incomplete.
DE: Management: Rex is the interim chair. Neither Leo nor I wants to be chair. We need candidates by September so we can vote in November. I would encourage you all to think about management. If you'd be interested in participating in the facilitation group, that would be great. One of the other roles in management is the Editor group.
JHD: We meet once a week, we go over open PRs and issues and decide whether something is ready to merge or not, and comment our decision publically. Anyone in this room should also feel totally welcome to comment and review.
BT: If anyone wants to attend our meetings, please let us know and we will forward the invite.
DE: Then there's the code of conduct committee.
AKI: CoC committee gets together every other week on Thursdays at 1:30 EST. We review any comments or complaints we receive and decide how to respond as a group. There hasn't been a lot; we're pretty good as a group. When something does come up though, we're very thoughtful about how to proceed. If you want to help in any way, please let us know.
DE: Website and How we work group, we're trying to improve explaining to the public what TC39 is. As you can see there's a lot of ways to get involved and to help out. This is a cry for help. Please help!
DE: Moving on, let's talk about the invited expert policy. In TC39, members can invite guests, and there haven't been too many issues here. Babel has been an interesting case study. For the past several meetings, Babel's presence has been very helpful. I've gone to the ECMA Executive Committee to discuss this, and they are aware that Babel has been attending. For some organizations like Babel, which are critical stakeholders but wouldn't be able to join Ecma traditionally, we want to propose something to Ecma ExeCom to discuss policy considerations to enable stakeholders like Babel to attend TC39.
## TC53 introduction for TC39
(Peter Hoddie, PHE)
- [slides](https://www.icloud.com/keynote/0gW-7doOkHuxIMDRi0P9XpDng#tc53_to_tc39)
PHE: This is a brief intro to TC53, which was just formed this year. The charter has three components 1) building JS applications on wearable devices, 2) interchange formats for sensor data and 3) communication from device-to-device and to cloud. The goal is not to create a new version of the JavaScript language, to create a new platform, a new IOT protocol. So why then? Wearables are becoming more independent from other devices. An open standard we believe will enable silicon manufacturers a platform to rally behind, but the whole web runtime is a bit too heavy so we need something smaller in scope for them to use. Outside members are definitely welcome to attend meetings at this point. TC53 builds off the work of TC39 and therefore welcomes participation from TC39 members, particularly to ensure consistent JS APIs.
DH: Why wearables as opposed to small IoT devices?
PHE: I suspect that maybe eventually TC53 will extend to all small devices. One of the more important things that this committee is concerned about is energy, about which wearables have particular concerns.
LBR: Bocoup is excited to host. It will not be at the cave, but our nice office. (Laughs)
## Update on `do`-expressions
(Dave Herman, DH)
DH: This is a status update, no advancement. I've been working with Chris Krycho on this proposal. We want to bring the current state up to you and see if you have strong opinions. The goal of do-expressions is a syntactic form for statements but then to get a value out from the other side. The killer feature of this is the local scoping that doesn't pollute the larger context. (Shows example). Do-expressions respect the Tennent's Correspondence Principle (TCP) -- you're trying to have as few new special cases introduced by the new feature as possible. This means we aren't changing the meaning of this, or return. So in this example, we can return from the outer function, you can! Static Semantics: if you observe that do-expressions are allowing statements to appear in new syntactic positions are there positions where do { $stmt } can have unexpected results? Most cases are uninteresting, but `return`, `var`, `break` and `continue`.
MM: Feedback: I'm split between the two options for return. The argument for disallow, is that anytime it is not clear what semantics user will assume, no matter what we choose, some users will be surprised. The least damaging form of surprise is a static error. Even if you don't know why you got the error, you do something else until your code is both accepted and seems to work. All other forms of surprise may result in the program at runtime doing something different from what the programmer intended, in ways that the programmer did not catch during development.
DH: The difference is that throw is not scoped.
MM: #2 is perfectly defensible, but how much of a surprise is it?
DH: I just want to get feedback as we go along, instead of batching it up at the end. I really just want to get feedback and bring up the edge cases people care the most about. (Shows examples of `var` and `break`/`continue`). I think we should not allow breaking in loop header.
WH: What does `do {continue}` do in the first expression of a for-loop header, for which the loop hasn't started yet?
```js
lab: for (let x = do {continue lab;}, y = 17; x; ++x} ...
```
BFS: What do you mean when you say disallow? ARe you disallowing do-expressions in this context or the grammar constructs within the do-expression?
DH: We're changing the scoping. Break to a label that's not in scope is disallowed. Returning could be disallowed.
MM: You didn't mention sloppy/strict. I beg you to allow do-expressions only in strict mode. In sloppy mode, you would have to support all sorts of difficult semantics of nested function declarations, which seems difficult and pointless.
DH: I wouldn't feel that it would be necessary to only do this in strict mode.
MLS: If we're talking footguns, this has a lot of bullets in it. These questionable constructs must be early errors not dynamic errors.
DH: I knew if I went through these difficult edge cases, I would get trolled, but if we over-focus on these ridiculous edge cases, the feature seems more complicated than it is, but I think a lot of these cases are ambiguous enough that people tend to shy away from them. I think this is a lot of very strong indication that people want this, so I wouldn't want some hard cases prevent us from seeing those powerful use cases.
YK: I want to agree with Mark for a couple of reasons. In general, this feature isn't as scary as other features; you're writing code in your own scope, so I don't think syntax errors make this worse. They would help users avoid footguns.
WH: I agree that option 1 is off the table for default values in function headers. Initially I was leaning towards option 2, but because of how we treat variable references in function headers — they do not see the braced scope of the function — I'm now much more persuaded to go with option 3 (disallow). I would not want to allow `var` there either.
DH: I agree.
MM: One further point in favor of the disallow option: Of these choices, disallow is the only early choice that we can change our mind about later.
#### Conclusion/Resolution
- ?
## New name for global
(Jordan Harband, JHD)
- [slides](https://github.com/tc39/proposal-global/issues/20)
JHD: A new name for global, since `global` is not web-compatible. Instead of burning bridges, I reached out to a couple of browser vendors to get a list of what names would be possible. I got some data back from Edge, global itself is used quite a lot. `globals` is also quite used, **redacted** is used pretty infrequently, so it's also my next favorite option.
?? How did you determine what names to search?
JHD: We took a long list and narrowed it down to satisfy Edge's requests.
SYG: Do you want the name to be stricken from the notes too, until browsers try it?
JHD: I fully expect people to troll us.
Kevin: Do you think standard modules have some bearing on this?
JHD: I do not.
JHD: The average use-case I imagine is not a casual developer using it. So I think if the name is long and ugly, that's OK.
YK: I agree with Domenic's "this" perspective. I also don't like a camelCase name.
BE: Has anyone thought of `function.global` or `eval.this` or something else?
MM: No! (Laughs). The global object must NEVER be accessible from syntax. We MUST be able to intercept it.
BE: Or `yagni`(\*) to indicate people shouldn't use it.
(\*) "You Ain't Gonna Need It"
JHD: I think **redacted** is good for it being pretty obvious, but obscure enough that you won't accidentally using it without knowing what you're doing.
MM: I will be objecting.
JHD: To the choice of the name or the concept of a global identifier?
MM: Both.
Diego: Has there been any debate about adding some non-alpha numeric names? Like `__global__`?
JHD: That seems much uglier, and we'd have to pull metrics about it all over again. Plus, we use `__` for proto, so there's a high chance it's being used in webcode already.
BE: Are you looking for an identifier or a deniable special form?
JHD: It has to be deniable.
#### Conclusion/Resolution
- No name picked yet
## Object.fromEntries to stage 3
(Jordan Harband, JHD)
- [slides](https://github.com/tc39/proposal-object-from-entries/issues/19)
JHD: Very small changes here, I am hoping I can still achieve stage 3 today. Are there any questions or comments?
#### Conclusion/Resolution
- Stage 3 acceptance
## User testing (e.g. usability or learnability): call for resources
(Shu-yu Guo, SYG)
SYG: We've talked in the past about doing some user-testing for language ergonomics. I can offer resources at Bloomberg London and New York for user testing. What we don't have is people qualified to design user tests (especially programming tasks) and would need very specific studies.
BT: I think what you're saying, that usability studies would be great. But I'd also encourage us to challenge what rigorous scientific approaches we can take without having to go into a lab. We can develop a bunch of hypotheses about how users will appreciate a particular feature. We don't need to necessarily go into a lab to test those. Any of us in this room could choose to be very data-driven, but you may not need to do that.
SYG: I'm saying let's not do anecdotal studies, and pushing for more scientific approaches. Though I'm not equipped to do that, necessarily.
BT: There's a wide spectrum between no data collection, throwing up a poll on Twitter, and doing a usability lab. I think there's plenty of opportunity for our committee to do informal interviews with users. With a light discussion guide, we could get some very valuable data from users.
DH: I think I've seen people confuse science for design. I.e. do you prefer A or B, we sampled 50% and choose the more popular one. But that could be a poorly sampled or designed study, so I would want to caution us away from invalidating the kinds of reasons that aren't "data-driven" but are backed with a tremendous amount of expertise.
SYG: We do design, but sometimes things get stuck without a leading opinion. I think user-testing could help for this.
TST: I think we aren't equipped as a group to design studies like this.
SYG: I agree, which is why I'm asking if companies could be willing to lend resources for such studies.
BT: There are definitely techniques you can do to validate program design (including APIs), so potentially the same could be done with language design. There's a huge space between doing nothing and some research, to try to be more rigorous in getting user input.
TST: My only concern is that in language design, we could find a suboptimal outcome because of how complicated and subtle language design is. I imagine there is scientific literature about this, and I would encourage us to consult the literature first.
WH: I'm a bit leery about this because of what happened to a similar area. There's been scientific research on what kinds of headlines people click on. Using science to optimize them produced rather unpleasant results.
YK: I think it's a great idea to survey users and see what kinds of findings we can get. In an environment where everyone agrees that we're not doing rigorous things, there's nothing about our environment that forces people to do this carefully or correctly.
SYG: My premise is that we are not experts in designing experiments like this.
YK: There's an anecdotal structure where using these results can get you useful answers. I think if we treat experiments like this, that would be very helpful.
DRR: So at Microsoft we speak to a lot of customers and try to find their pain-points. I was very skeptical of process, but I've found that occasionally, you do find answers to something else entirely, and you may find trends which are very helpful. So, I think that's one of the key values, there's a lot of anecdotal evidence where you can say definitively, but you can use it for motivation and put it into concrete terms to help people determine users' pain-points.
SYG: I think this was a good discussion.
|
{
"pile_set_name": "Github"
}
|
# MinEspSDK (meSDK)
Minimalist SDK on ESP8266ex v2.0.0
---
A complete set of Wi-Fi and [LwIP](http://savannah.nongnu.org/projects/lwip/) functions.<br>
Имеет полный набор функций работы с WiFi и UDP/TCP (LwIP ver1.4.0).<br>
Данная сборка не содержит espconn и SSL.<br>
Проектируется для работы с датчиками и будет содержать расширения для быстрого<br>
старта после deep-sleep с возможностями управления дальнейшей загрузки SDK или<br>
опроса датчиков и нового перехода в режим deep-sleep.<br>
В целях экономии питания, время от просыпания после deep-sleep до старта опроса<br>
датчиков и для принятия решения повторного засыпания или загрузки полного SDK<br>
для коммуникации и передачи накопленных данных будет составлять 30..40 мс.<br>
В текщей версии, при стандартных настройках по умолчанию, после события подачи<br>
питания, reset или deep-sleep соединение по TCP при фиксированном ip модуля в<br>
режиме STATION к модулю в режиме SOFTAP устанавливается примерно не более чем<br>
через 540 мс. Основное время занимает инициализации SDK в части WiFi.<br>
Далее полудуплексный трафик TCP составляет более 1-го Мегабайта в секунду.<br>
From [Espressif SDK](http://bbs.espressif.com/) ver 2.0.0 used only:<br>
libpp.a, libwpa.a, libcrypto.a, libnet80211.a, parts libphy.a, user_interface.o<br>
Из [Espressif SDK](http://bbs.espressif.com/) ver 2.0.0 используются только описанные части.<br>
Остальные части даны с исходными кодами.<br>
LwIP based on [Open source LWIP for ESP_IOT_SDK_V1.5.2](http://bbs.espressif.com/viewtopic.php?f=46&t=1221).<br>
Supported options 48 kbytes IRAM.<br>
Supported '[Rapid Loader](https://github.com/pvvx/Rapid_Loader/)' and Flash 512 кbytes - 16 Mbytes.<br>
Поддержка расширенной памяти IRAM в 48 килобайт (опция USE_MAX_IRAM 48),<br>
Flash от 512 килобайт до 16 Мегабайт и ускоряющего загрузку SDK 'лоадера'.<br>
Free IRAM : 12 or 28 kbytes (option USE_MAX_IRAM) <br>
Free Heap : 55 kbytes<br>
Total Free RAM : 83 kbytes<br>
Options programming Flash:<br>
SPI_SPEED: 40MHz or 80MHz.<br>
SPI_MODE: QIO only.<br>
FLASH_SIZE: Always set the size to 512 KB flash.<br>
Automatic determination of the real size of the flash.<br>
При заливке прошивки в модуль всегда устанавливайте размер Flash в 512 килобайт.<br>
Реальный размер Flash определяется автоматически во время старта SDK.<br>
Для компиляции SDK используется [Unofficial Developer Kit](http://esp8266.ru/forum/forums/devkit/).<br>
В Eclipse заданы 3 опции Manage Configurations:<br>
1. AutoMake (собрать проект для прошивки, используются установки в Eclipse)<br>
2. CreateLib (собрать библиотеку libsdk.a, используются установки в Eclipse)<br>
3. Default (собрать проект для прошивки, используя makefile)<br>
Полный комплект для сборки проекта с помощью SDK библиотеки:<br>
libsdk.a + [libmicroc.a](https://github.com/anakod/esp_microc) и include<br>
|
{
"pile_set_name": "Github"
}
|
ограничения по брой и продължителност, които да се определи ще има
Свърлик достигаща до села Дражевци, на десет версти зад Ниш.
антибактериалното средство, които потискат чувствителните бактерии. Тя
В запазения архив на П. Шафарик се откриват записани сведения отнасящи
бактерии. Тяхното терапевтично повлияване често е невъзможно с
посвещава параграф 12, също разглеждащ въпросът за географското му
екосистемите с участието на патогенни и непатогенни бактерии, което
11. Условие за участие. Формулират се в зависимост от взетите
или в града, от където са мнозинството участници. Избраната база се
в Прага биват отпечатани първо и второ издание на "Славянски
той не само усвоява до съвършенство сръбския език, събира и обработва
"заразяват" чувствителните бактериални клетки и да ги превръщат в
на което поп Рашко отговаря, че няма да се противопоставя на
вместо език е употребил думата "реч", и то при всички славянски
гентамицина са резистентни 30-35% от
Физическия институт при БАН, където работи до пенсионирането
чудак, такъв остава Рашко Зайков в спомените на близките си;
главна, ако не единствена, причина за резистентността към модерните
глас се оказва решаващ. Акад. Бонев казва: "На аерогарата в
563-602.
където географските названия - едни турцизирани, други турски, трети
протеини (ПСП).
е хромозомна, а когато принадлежат на
професор - едно закъсняло, но заслужено признание.
на място се отчита възможността да се осигури подходяща база по вид,
със
563-602.
Анализът на механизмите на резистентност през последното десетилетие
инфекциозни болести, което мотивира тяхното изключително широко
подражават и импровизират или да се доверяват на недобросъвестни или
5. Цветообрание на старославянската книжнина в България. Събрано и на
своят крупен научен труд "История на славянския език и литература по
старославянската книжнина. На този въпрос той е посветил цял един
на баща си и хуква към някаква пропаст. Едва успяват да го
решения в т. 1., 3., 4., 5.
увеличаване относителния дял на резистентните към него бактериални
молекулите на аминогликозидите ги инактивират, и т.н. (2) Използване
време на Освободителната война с руските войски. Като
Бесарабия, 50,000 в Унгария по точно в Банат, така че около 3,500,000
резервира предварително.
език през 1849 г. тази забележителна студия бива преведена на
В посочените граници на българската реч, П. Шафарик се е опитал да
Генетични и биохимични механизми на резистентността. Инфекциозна
563-602.
Следване и работа в Германия (1922-1928)
съставна част на клетъчните им стени. Процесът са катализира от
"признаци", а писмен език е означил като "наречи", в руския превод
Разпространение на резистентните бактерии. Всяко антимикробно вещество
антибактериалното средство. Така, при откриването на пеницина 8% от
отделни страни, региони, болници и пр., което се обяснява преди всички
на място се отчита възможността да се осигури подходяща база по вид,
с различията в степента и начините на използване на антимикробните
да ни чакат да умрем, та да могат да постъпят на местата
във втория етап се поставят допълнителни изисквания (преработка на
Разцвет
се касае за ограничаване достъпа на антимикробното вещество до мястото
Зайков, един много способен български физик, с който си
Много важно е още в първия стадий на организирането на срещата да се
Интересен и неизвестен факт от биографията на Рашко Зайков е
неопитни фирми.
привлечени дарители.
като физик-теоретик за него не се намира, вероятно поради
Западните Родопи, Доспат и Неврокопска, както и мохамеданите от
Между чудачествата е и невероятната работоспособност. Можел
една жива легенда.
След напускането на гр. Иена, за кратко време Шаферик се отбива в
1843.
руския превод "обем" (9, с.31). По отношение на езиковите
култура. Българко историческо дружество. Секция "Етнография". С.,1978,
спрат. "Попречихте ми да изчисля за колко секунди ще стигна
със
пептидогликана, полимер с жизнено важно значение за бактериите като
на което поп Рашко отговаря, че няма да се противопоставя на
главна, ако не единствена, причина за резистентността към модерните
с когото съвместно обсъждат теоретични проблеми. Но работа
финансови средства понякога се издават само кратки или
(Павел Йозеф Шафарик, Р.С.), който доказа на света какъв е бил
Пенка ЛАЗАРОВА
своя син - единствен от класа. Но на свободолюбивия Рашко не
страни, където контролирано се използват антимикробните лекарства,
ни".
съставна част на клетъчните им стени. Процесът са катализира от
За научните приноси на проф. Рашко Зайков можете да
славянски езици са естествена предпоставка още през 1826 г. да напише
Павел Йозеф Шафарик, починал на 26 май 1861 г. в Прага. В некролога за
Македония и България, П. Шафарик започнал да подготвя още в Нови Сад
направи реалистична план-сметка като се преценява какви такси ще са
дискусии, постъри, "кръгли маси", демонстрации и т.н.) и съответните
механизмите на тяхната устойчивост. Автор е на много публикации по
професор в сръбската православна гимназия от 1819 до 1833 г. Престоят
|
{
"pile_set_name": "Github"
}
|
form=词
tags=
风月溪堂,
也曾是、东州行客。
长记得、相逢一笑,
*愁都雪。
又对青山谈世事,
老怀未减元龙节。
恨霜蹄、蹴踏短辕间,
论监铁。
官里事,
何曾歇。
公等志,
吾能说。
尽纵横鞭算,
玉壶冰洁。
烂醉春风能几度,
桃花未了杨花坼。
甚一城、相望半年过,
长如别。
冠剑梁园,
又去作、庞眉书客。
休自叹、功名几许,
一家风雪。
春色似嫌莺燕老,
秋霜历试松筠节。
爱赵生、游刃簿书闲,
昆刀铁。
都会地,
繁华歇。
形胜在,
犹堪说。
更诸君表里,
玉辉冰洁。
水陆若论都漕计,
夷门忍使黄流坼。
好相须、着力障狂澜,
休伤别。
雷动云横,
惊飙鹜、北城西下。
人共骇、赤丸夜语,
电光飞射。
将领未承诸葛令,
橐*已在汾阳胯。
笑书生、思握玉鳞符,
从公驾。
铃索静,
云麾亚。
追往事,
何多暇。
道一篇乐府,
翰林情话。
日月低回黄阁梦,
风云惨淡凌烟画。
尽花边、高*卧麒麟,
终潇洒。
秣马膏车,
又去作、天涯*客。
明见得、水云深处,
万花如雪。
绿暗江城多洞府,
红烧烛影翻双节。
被晓风、吹散枕中春,
檐间铁。
尘世事,
无穷歇。
吾最爱,
沧浪说。
恐灵均泽畔,
只成孤洁。
心事比量无少恶,
前途何必论*坼。
倘祥金、陶铸遇良工,
从区别。
书剑梁园,
忆曾是、青*游客。
宫苑废、三山依约,
绿云红雪。
好在西溪王老子,
留连醉尽花时节。
记尊前、金缕唱新声,
忘筝铁。
襟韵合,
曾衰歇。
消客气,
歆情说。
尽暮年心事,
风霜孤洁。
一片黄流翻晚照,
回惊吴楚东南坼。
偶追思、往事叹余生,
长年别。
一柱华峰,
绿翠似、芙蓉金削。
孤负却、画船春水,
一尊同酌。
寒食清明都几日,
征鞍遽作西归客。
漫春风、墙燕语留人,
高城隔。
春草碧,
杨花白。
妆点就,
行轩色。
道不应霜翮,
能舒长策。
三尺青萍风义在,
看君冠盖长安陌。
对夕阳、淡处最关情,
河梁别。
柱石中朝,
人道是、汉家真相。
试看取、凤池高步,
佩声清音。
世祖功臣三十六,
第动合在云台上。
欲暂分、霖雨霈秦川,
从时望。
睿思远,
谁能□。
空健倒,
骊驹唱。
抚一方何似,
际天寅亮。
肘后不知金印重,
玉堂正要吾军张。
向五云深处望三台,
光千丈。
柱石中朝,
还不减、汾阳劝考。
人尽道、今年相府,
南衙春早。
肘后不知金印大,
书中渐觉群众疑少。
问南枝、消息几多春,
调羹了。
宝窦暖,
香云*。
睛云霁,
西山晓。
见一星声入江淮渺。
愿神尖、长对寿眉青,
以上王恽作品《满江红》共8首
|
{
"pile_set_name": "Github"
}
|
{
"FAQ": "ЧаПи",
"termsAndAgreement": "By clicking the button below, you are indicating that you have read and agree to the <a href='/static/terms'>Terms of Service</a> and <a href='/static/privacy'>Privacy Policy</a>.",
"accept1Terms": "Натискаючи кнопку внизу, я приймаю",
"accept2Terms": "та",
"alexandraQuote": "Couldn't NOT talk about [Habitica] during my speech in Madrid. Must-have tool for freelancers who still need a boss.",
"althaireQuote": "Мати квест постійно - дійсно мотивує мене виконувати всі мої щоденні та звичайні завдання. Моя набільша мотвація - не дати \"впасти\" моїй групі.",
"andeeliaoQuote": "Надзвичайний продукт, тільки-но почала користуватись декілька днів тому та вже більш усвідомлено та продуктивно ставлюся до свого часу!",
"autumnesquirrelQuote": "Я менше прокрастиную на роботі та вдома. А також оплачую рахунки вчасно.",
"businessSample1": "Підтвердити 1 сторінку Інвентаря",
"businessSample2": "20 хвилин обробки інформації",
"businessSample3": "Відсортувати та обробити Вхідну пошту",
"businessSample4": "Підготувати 1 документ для Клієнта",
"businessSample5": "Подзвонити Клієнтам/Відкласти дзвінки",
"businessText": "Використовуйте Habitica для вашого бізнесу",
"choreSample1": " Покласти брудний одяг у кошик для брудної білизни",
"choreSample2": "20 хвилин роботи по дому",
"choreSample3": "Вимити посуд",
"choreSample4": "Прибрати у одній кімнаті",
"choreSample5": "Випрати та висушити купу одягу",
"chores": "Робота по дому",
"clearBrowserData": "Очистити історію браузера",
"communityBug": "Повідомити про баґ",
"communityExtensions": "<a href='http://habitica.fandom.com/wiki/Extensions,_Add-Ons,_and_Customizations' target='_blank'>Доповнення та розширення</a>",
"communityFacebook": "Facebook",
"communityFeature": "Активація особливості",
"communityForum": "<a target='_blank' href='http://habitica.fandom.com/wiki/Special:Forum'>Форум</a>",
"communityKickstarter": "Kickstarter",
"communityReddit": "Reddit",
"companyAbout": "Як це пряцює",
"companyBlog": "Блоґ",
"devBlog": "Блог розробника",
"companyContribute": "Contribute",
"companyDonate": "Пожертвувати",
"companyPrivacy": "Політика конфіденційности",
"companyTerms": "Умови",
"companyVideos": "Видива",
"contribUse": "Habitica contributors use",
"dragonsilverQuote": "Скільки систем відстежування часу та завдань я спробував за останні десятиліття... [Habitica] це єдина з них що фактично допомагає мені здійснити мої плани, а не просто скласти список завдань.",
"dreimQuote": "When I discovered [Habitica] last summer, I had just failed about half of my exams. Thanks to the Dailies... I was able to organize and discipline myself, and I actually passed all my exams with really good grades a month ago.",
"elmiQuote": "Кожен ранок я прагну встати щоб заробити трохи золота!",
"forgotPassword": "Забули пароль?",
"emailNewPass": "Email a Password Reset Link",
"forgotPasswordSteps": "Введіть електронну пошту на яку ви реєстрували ваш аккаунт.",
"sendLink": "Відправити посилання",
"evagantzQuote": "My very first dentist appointment where the hygienist was actually excited about my flossing habits. Thanks [Habitica]!",
"examplesHeading": "Гравці користуються сайтом Habitica щоб керувати ...",
"featureAchievementByline": "Зробили щось надзвичайне? Отримайте значок та хизуйтесь ним!",
"featureAchievementHeading": "Значки досягнень",
"featureEquipByline": "Buy limited edition equipment, potions, and other virtual goodies in our Market with your task rewards!",
"featureEquipHeading": "Equipment and extras",
"featurePetByline": "Eggs and items drop when you complete your tasks. Be as productive as possible to collect pets and mounts!",
"featurePetHeading": "Улюбленці та скакуни",
"featureSocialByline": "Join common-interest groups with like-minded people. Create Challenges to compete against other users.",
"featureSocialHeading": "Social play",
"featuredIn": "Featured in",
"featuresHeading": "We also feature...",
"footerDevs": "Розробники",
"footerCommunity": "Спільнота",
"footerCompany": "Компанія",
"footerMobile": "Мобільник",
"footerSocial": "Громада",
"forgotPass": "Забули пароль",
"frabjabulousQuote": "[Habitica] is the reason I got a killer, high-paying job... and even more miraculous, I'm now a daily flosser!",
"free": "Приєднайся безкоштовно",
"gamifyButton": "Gamify your life today!",
"goalSample1": "Грати на піаніно 1 годину",
"goalSample2": "Work on article for publication",
"goalSample3": "Work on blog post",
"goalSample4": "Урок японської мови на Duolingo",
"goalSample5": "Прочитати інформативну Статтю",
"goals": "Цілі",
"guidanceForBlacksmiths": "Guidance for Blacksmiths",
"wellness": "Здоров'я",
"healthSample1": "Drink Water/Soda",
"healthSample2": "Жувати гумку/палити",
"healthSample3": "Скористатись сходами/ліфтом",
"healthSample4": "Їсти здорову/шкідливу їжу",
"healthSample5": "Break a Sweat for 1 hr",
"history": "Історія",
"infhQuote": "[Habitica] has really helped me impart structure to my life in graduate school.",
"invalidEmail": "A valid email address is required in order to perform a password reset.",
"irishfeet123Quote": "I've had horrible habits with clearing my place completely after meals and leaving cups all over the place. [Habitica] has cured that!",
"kazuiQuote": "Before [Habitica], I was stuck with my thesis, as well as dissatisfied with my personal discipline regarding housework and things like learning vocabulary and studying Go theory. It turns out breaking down these tasks into smaller manageable checklists is quite the thing to keep me motivated and constantly working.",
"landingend": "Вам і цього замало?",
"landingend2": "See a more detailed list of [our features](/static/overview). Are you looking for a more private approach? Check out our [administrative packages](/static/plans), which are perfect for families, teachers, support groups, and businesses.",
"landingp1": "The problem with most productivity apps on the market is that they provide no incentive to continue using them. Habitica fixes this by making habit building fun! By rewarding you for your successes and penalizing you for slip-ups, Habitica provides external motivation for completing your day-to-day activities.",
"landingp2": "Whenever you reinforce a positive habit, complete a daily task, or take care of an old to-do, Habitica immediately rewards you with Experience points and Gold. As you gain experience, you can level up, increasing your Stats and unlocking more features, like classes and pets. Gold can be spent on in-game items that change your experience or personalized rewards you've created for motivation. When even the smallest successes provide you with an immediate reward, you're less likely to procrastinate.",
"landingp2header": "Миттєві нагороди",
"landingp3": "Whenever you indulge in a bad habit or fail to complete one of your daily tasks, you lose health. If your health drops too low, you lose some of the progress you've made. By providing immediate consequences, Habitica can help break bad habits and procrastination cycles before they cause real-world problems.",
"landingp3header": "Наслідки",
"landingp4": "With an active community, Habitica provides the accountability you need to stay on task. With the party system, you can bring in a group of your closest friends to cheer you on. The guild system allows you to find people with similar interests or obstacles, so you can share your goals and swap tips on how to tackle your problems. In Habitica, the community means that you have both the support and the accountability you need to succeed.",
"landingp4header": "Відповідальність",
"leadText": "Habitica is a free habit building and productivity app that treats your real life like a game. With in-game rewards and punishments to motivate you and a strong social network to inspire you, Habitica can help you achieve your goals to become healthy, hard-working, and happy.",
"login": "Увійти",
"loginAndReg": "Увійти / Зареєструватися",
"loginFacebookAlt": "Увійти через Facebook",
"loginGoogleAlt": "Увійти через Google",
"logout": "Вийти",
"marketing1Header": "Improve Your Habits by Playing a Game",
"marketing1Lead1Title": "Your Life, the Role Playing Game",
"marketing1Lead1": "Habitica — це відеогра, з допомогою якої ви можете поліпшити свої звички у реальному житті. Вона „ігрофікує“ ваше життя, перетворюючи всі ваші завдання (звички, щоденні справи та обов'язки) на маленьких потвор, яких вам потрібно побороти. Чим ліпше вам це вдаватиметься, тим більше ви просуватиметеся грою. Кожна ваша помилка у реальному житті відкидатиме назад вашого персонажа у грі.",
"marketing1Lead2Title": "Отримуйте файнички",
"marketing1Lead2": "Improve your habits to build up your avatar. Show off the sweet gear you've earned!",
"marketing1Lead3Title": "Знаходьте випадкові призи",
"marketing1Lead3": "For some, it's the gamble that motivates them: a system called \"stochastic rewards.\" Habitica accommodates all reinforcement and punishment styles: positive, negative, predictable, and random.",
"marketing2Header": "Змагайтеся з друзями. Долучайтеся до груп за уподобаннями",
"marketing2Lead1Title": "Social Productivity",
"marketing2Lead1": "While you can play Habitica solo, the lights really turn on when you start collaborating, competing, and holding each other accountable. The most effective part of any self-improvement program is social accountability, and what better an environment for accountability and competition than a video game?",
"marketing2Lead2Title": "Fight Monsters",
"marketing2Lead2": "What's a Role Playing Game without battles? Fight monsters with your party. Monsters are \"super accountability mode\" - a day you miss the gym is a day the monster hurts *everyone!*",
"marketing2Lead3Title": "Випробовуйте одне одного",
"marketing2Lead3": "Challenges let you compete with friends and strangers. Whoever does the best at the end of a challenge wins special prizes.",
"marketing3Header": "Додатки та розширення",
"marketing3Lead1": "The **iPhone & Android** apps let you take care of business on the go. We realize that logging into the website to click buttons can be a drag.",
"marketing3Lead2Title": "Інтеграції",
"marketing3Lead2": "Other **3rd Party Tools** tie Habitica into various aspects of your life. Our API provides easy integration for things like the [Chrome Extension](https://chrome.google.com/webstore/detail/habitica/pidkmpibnnnhneohdgjclfdjpijggmjj?hl=en-US), for which you lose points when browsing unproductive websites, and gain points when on productive ones. [See more here](http://habitica.fandom.com/wiki/Extensions,_Add-Ons,_and_Customizations).",
"marketing4Header": "Organizational Use",
"marketing4Lead1": "Education is one of the best sectors for gamification. We all know how glued to phones and games students are these days; harness that power! Pit your students against each other in friendly competition. Reward good behavior with rare prizes. Watch their grades and behavior soar.",
"marketing4Lead1Title": "Впровадження ігор в освіту",
"marketing4Lead2": "Health care costs are on the rise, and something's gotta give. Hundreds of programs are built to reduce costs and improve wellness. We believe Habitica can pave a substantial path towards healthy lifestyles.",
"marketing4Lead2Title": "Gamification In Health and Wellness",
"marketing4Lead3-1": "Хочеш перетворити своє життя у гру?",
"marketing4Lead3-2": "Interested in running a group in education, wellness, and more?",
"marketing4Lead3-3": "Хочеш дізнтися більше?",
"marketing4Lead3Title": "Перетвори у гру будь-що",
"mobileAndroid": "Android",
"mobileIOS": "iOS",
"motivate": "Мотивуйте себе та свою команду!",
"motivate1": "Motivate yourself to do anything.",
"motivate2": "Get Organized. Get Motivated. Get Gold.",
"oldNews": "Новини",
"newsArchive": "News archive on Wikia (multilingual)",
"passConfirm": "Підтвердіть пароль",
"setNewPass": "Set New Password",
"passMan": "In case you are using a password manager (like 1Password) and have problems logging in, try typing your username and password manually.",
"password": "Пароль",
"playButton": "Грати",
"playButtonFull": "Enter Habitica",
"presskit": "Press Kit",
"presskitDownload": "Завантажуй всі зображення:",
"presskitText": "Thanks for your interest in Habitica! The following images can be used for articles or videos about Habitica. For more information, please contact us at <%= pressEnquiryEmail %>.",
"pkQuestion1": "What inspired Habitica? How did it start?",
"pkAnswer1": "If you’ve ever invested time in leveling up a character in a game, it’s hard not to wonder how great your life would be if you put all of that effort into improving your real-life self instead of your avatar. We starting building Habitica to address that question. <br /> Habitica officially launched with a Kickstarter in 2013, and the idea really took off. Since then, it’s grown into a huge project, supported by our awesome open-source volunteers and our generous users.",
"pkQuestion2": "Why does Habitica work?",
"pkAnswer2": "Forming a new habit is hard because people really need that obvious, instant reward. For example, it’s tough to start flossing, because even though our dentist tells us that it's healthier in the long run, in the immediate moment it just makes your gums hurt. <br /> Habitica's gamification adds a sense of instant gratification to everyday objectives by rewarding a tough task with experience, gold… and maybe even a random prize, like a dragon egg! This helps keep people motivated even when the task itself doesn't have an intrinsic reward, and we've seen people turn their lives around as a result. You can check out success stories here: https://habitversary.tumblr.com",
"pkQuestion3": "Why did you add social features?",
"pkAnswer3": "Social pressure is a huge motivating factor for a lot of people, so we knew that we wanted to have a strong community that would hold each other accountable for their goals and cheer for their successes. Luckily, one of the things that multiplayer video games do best is foster a sense of community among their users! Habitica’s community structure borrows from these types of games; you can form a small Party of close friends, but you can also join a larger, shared-interest groups known as a Guild. Although some users choose to play solo, most decide to form a support network that encourages social accountability through features such as Quests, where Party members pool their productivity to battle monsters together.",
"pkQuestion4": "Why does skipping tasks remove your avatar’s health?",
"pkAnswer4": "If you skip one of your daily goals, your avatar will lose health the following day. This serves as an important motivating factor to encourage people to follow through with their goals because people really hate hurting their little avatar! Plus, the social accountability is critical for a lot of people: if you’re fighting a monster with your friends, skipping your tasks hurts their avatars, too.",
"pkQuestion5": "What distinguishes Habitica from other gamification programs?",
"pkAnswer5": "One of the ways that Habitica has been most successful at using gamification is that we've put a lot of effort into thinking about the game aspects to ensure that they are actually fun. We've also included many social components, because we feel that some of the most motivating games let you play with friends, and because research has shown that it's easier to form habits when you have accountability to other people.",
"pkQuestion6": "Who is the typical user of Habitica?",
"pkAnswer6": "Lots of different people use Habitica! More than half of our users are ages 18 to 34, but we have grandparents using the site with their young grandkids and every age in-between. Often families will join a party and battle monsters together. <br /> Many of our users have a background in games, but surprisingly, when we ran a survey a while back, 40% of our users identified as non-gamers! So it looks like our method can be effective for anyone who wants productivity and wellness to feel more fun.",
"pkQuestion7": "Why does Habitica use pixel art?",
"pkAnswer7": "Habitica uses pixel art for several reasons. In addition to the fun nostalgia factor, pixel art is very approachable to our volunteer artists who want to chip in. It's much easier to keep our pixel art consistent even when lots of different artists contribute, and it lets us quickly generate a ton of new content!",
"pkQuestion8": "How has Habitica affected people's real lives?",
"pkAnswer8": "You can find lots of testimonials for how Habitica has helped people here: https://habitversary.tumblr.com",
"pkMoreQuestions": "Do you have a question that’s not on this list? Send an email to admin@habitica.com!",
"pkVideo": "Відео",
"pkPromo": "Promos",
"pkLogo": "Логотипи",
"pkBoss": "Боси",
"pkSamples": "Sample Screens",
"pkWebsite": "Веб-сайт",
"pkiOS": "iOS",
"pkAndroid": "Android",
"privacy": "Політику Конфіденційности",
"psst": "Агов",
"punishByline": "Break bad habits and procrastination cycles with immediate consequences.",
"punishHeading1": "Miss a daily goal?",
"punishHeading2": "Lose health!",
"questByline1": "Playing with your friends keeps you accountable for your tasks.",
"questByline2": "Issue each other Challenges to complete a goal together!",
"questHeading1": "Battle monsters with your friends!",
"questHeading2": "If you slack off, they all get hurt!",
"register": "Зареєструватися",
"rewardByline1": "Spend gold on virtual and real-life rewards.",
"rewardByline2": "Instant rewards keep you motivated!",
"rewardHeading": "Complete a task to earn gold!",
"sampleDailies": "Sample Dailies",
"sampleHabits": "Прості звички",
"sampleToDo": "Sample To-Dos",
"school": "School",
"schoolSample1": "Finish 1 Assignment",
"schoolSample2": "Study 1 hour",
"schoolSample3": "Meet with Study Group",
"schoolSample4": "Notes for 1 Chapter",
"schoolSample5": "Прочитати 1 розділ",
"sixteenBitFilQuote": "I'm getting my jobs and tasks done in record time thanks to [Habitica]. I'm just always so eager to reach my next level-up!",
"skysailorQuote": "My party and our quests keep me engaged in the game, which keeps me motivated to get things done and change my life in positive ways",
"socialTitle": "Habitica — Гра твого життя",
"supermouse35Quote": "I'm exercising more and I haven't forgotten to take my meds for months! Thanks, Habit. :D",
"sync": "Синхронізуватися",
"tasks": "Завдання",
"teamSample1": "Outline Meeting Itinerary for Tuesday",
"teamSample2": "Brainstorm Growth Hacking",
"teamSample3": "Discuss this week's KPIs",
"teams": "Команди",
"terms": "Умови користування",
"testimonialHeading": "Що кажуть люди...",
"tumblr": "Tumblr",
"localStorageTryFirst": "If you are experiencing problems with Habitica, click the button below to clear local storage and most cookies for this website (other websites will not be affected). You will need to log in again after doing this, so first be sure that you know your log-in details, which can be found at Settings -> <%= linkStart %>Site<%= linkEnd %>.",
"localStorageTryNext": "If the problem persists, please <%= linkStart %>Report a Bug<%= linkEnd %> if you haven't already.",
"localStorageClearing": "Clearing Data",
"localStorageClearingExplanation": "Habitica's stored data is being cleared from your browser. You will be logged out and redirected to the home page. Please wait.",
"localStorageClear": "Clear Data",
"localStorageClearExplanation": "This button will clear local storage and most cookies, and log you out.",
"tutorials": "Навчання",
"unlockByline1": "Achieve your goals and level up.",
"unlockByline2": "Unlock new motivational tools, such as pet collecting, random rewards, spell-casting, and more!",
"unlockHeadline": "As you stay productive, you unlock new content!",
"useUUID": "Використати UUID / API Token (для користувачів Facebook )",
"username": "Логін",
"emailOrUsername": "Логін або E-mail (чутливо до регістру)",
"watchVideos": "Переглядай відео",
"work": "Work",
"zelahQuote": "With [Habitica], I can be persuaded to go to bed on time by the thought of gaining points for an early night or losing health for a late one!",
"reportAccountProblems": "Report Account Problems",
"reportCommunityIssues": "Report Community Issues",
"subscriptionPaymentIssues": "Subscription and Payment Issues",
"generalQuestionsSite": "General Questions about the Site",
"businessInquiries": "Business/Marketing Inquiries",
"merchandiseInquiries": "Physical Merchandise (T-Shirts, Stickers) Inquiries",
"marketingInquiries": "Marketing/Social Media Inquiries",
"tweet": "Tweet",
"apps": "Додатки",
"checkOutMobileApps": "Check out our mobile apps!",
"imagine1": "Imagine if improving your life were as fun as playing a game.",
"alreadyHaveAccount": "В мене вже є обліковий запис!",
"getStartedNow": "Get Started Now!",
"altAttrNavLogo": "Habitica home",
"altAttrLifehacker": "Lifehacker",
"altAttrNewYorkTimes": "The New York Times",
"altAttrMakeUseOf": "MakeUseOf",
"altAttrForbes": "Forbes",
"altAttrCnet": "CNet",
"altAttrFastCompany": "Fast Company",
"altAttrKickstarter": "Kickstarter",
"altAttrDiscover": "Discover Magazine",
"altAttrFrabjabulous": "Frabjabulous: ",
"altAttrAlexandraSo": "_AlexandraSo_: ",
"altAttrEvaGantz": "EvaGantz: ",
"altAttrSupermouse35": "supermouse35: ",
"altAttrAlthaire": "Althaire: ",
"altAttrInfH": "InfH: ",
"altAttrDreiM": "Drei-M: ",
"altAttrKazui": "Kazui: ",
"altAttrAutumnesquirrel": "autumnesquirrel: ",
"altAttrIrishfeet123": "irishfeet123: ",
"altAttrElmi": "Elmi: ",
"altAttr16bitFil": "16bitFil: ",
"altAttrZelahMeyer": "Zelah Meyer: ",
"altAttrSkysailor": "skysailor: ",
"altAttrIonic": "Ionic",
"altAttrWebstorm": "WebStorm",
"altAttrGithub": "GitHub",
"altAttrTrello": "Trello",
"altAttrSlack": "Slack",
"missingAuthHeaders": "Missing authentication headers.",
"missingAuthParams": "Missing authentication parameters.",
"missingUsernameEmail": "Missing username or email.",
"missingEmail": "Missing email.",
"missingUsername": "Missing username.",
"missingPassword": "Missing password.",
"missingNewPassword": "Missing new password.",
"invalidEmailDomain": "You cannot register with emails with the following domains: <%= domains %>",
"wrongPassword": "Wrong password.",
"incorrectDeletePhrase": "Please type <%= magicWord %> in all caps to delete your account.",
"notAnEmail": "Email-адреса не дійсна.",
"emailTaken": "Email-адреса уже використовується інших обліковим записом.",
"newEmailRequired": "Missing new email address.",
"usernameTime": "It's time to set your username!",
"usernameInfo": "Login names are now unique usernames that will be visible beside your display name and used for invitations, chat @mentions, and messaging.<br><br>If you'd like to learn more about this change, <a href='http://habitica.fandom.com/wiki/Player_Names' target='_blank'>visit our wiki</a>.",
"usernameTOSRequirements": "Usernames must conform to our <a href='/static/terms' target='_blank'>Terms of Service</a> and <a href='/static/community-guidelines' target='_blank'>Community Guidelines</a>. If you didn’t previously set a login name, your username was auto-generated.",
"usernameTaken": "Логін вже зайнято.",
"passwordConfirmationMatch": "Пароль та підтвердження паролю не співпадають.",
"invalidLoginCredentials": "Incorrect username and/or email and/or password.",
"passwordResetPage": "Скинути пароль",
"passwordReset": "If we have your email on file, instructions for setting a new password have been sent to your email.",
"passwordResetEmailSubject": "Скидання паролю до Habitica",
"passwordResetEmailText": "If you requested a password reset for <%= username %> on Habitica, head to <%= passwordResetLink %> to set a new one. The link will expire after 24 hours. If you haven't requested a password reset, please ignore this email.",
"passwordResetEmailHtml": "If you requested a password reset for <strong><%= username %></strong> on Habitica, <a href=\"<%= passwordResetLink %>\">click here</a> to set a new one. The link will expire after 24 hours.<br/><br>If you haven't requested a password reset, please ignore this email.",
"invalidLoginCredentialsLong": "Uh-oh - your email address / username or password is incorrect.\n- Make sure they are typed correctly. Your username and password are case-sensitive.\n- You may have signed up with Facebook or Google-sign-in, not email so double-check by trying them.\n- If you forgot your password, click \"Forgot Password\".",
"invalidCredentials": "There is no account that uses those credentials.",
"accountSuspended": "This account, User ID \"<%= userId %>\", has been blocked for breaking the [Community Guidelines](https://habitica.com/static/community-guidelines) or [Terms of Service](https://habitica.com/static/terms). For details or to ask to be unblocked, please email our Community Manager at <%= communityManagerEmail %> or ask your parent or guardian to email them. Please copy your User ID into the email and include your username.",
"accountSuspendedTitle": "Account has been suspended",
"unsupportedNetwork": "This network is not currently supported.",
"cantDetachSocial": "Account lacks another authentication method; can't detach this authentication method.",
"onlySocialAttachLocal": "Local authentication can be added to only a social account.",
"invalidReqParams": "Invalid request parameters.",
"memberIdRequired": "\"member\" must be a valid UUID.",
"heroIdRequired": "\"heroId\" must be a valid UUID.",
"cannotFulfillReq": "Your request cannot be fulfilled. Email admin@habitica.com if this error persists.",
"modelNotFound": "This model does not exist.",
"signUpWithSocial": "Зареєструватись через <%= social %>",
"loginWithSocial": "Увійти через <%= social %>",
"confirmPassword": "Підтвердіть пароль",
"usernameLimitations": "Username must be 1 to 20 characters, containing only letters a to z, numbers 0 to 9, hyphens, or underscores, and cannot include any inappropriate terms.",
"usernamePlaceholder": "e.g., HabitRabbit",
"emailPlaceholder": "типу, rabbit@example.com",
"passwordPlaceholder": "типу, ******************",
"confirmPasswordPlaceholder": "Переконайтесь що це той самий пароль!",
"joinHabitica": "Приєднатися до Habitica",
"alreadyHaveAccountLogin": "Already have a Habitica account? <strong>Log in.</strong>",
"dontHaveAccountSignup": "Don’t have a Habitica account? <strong>Sign up.</strong>",
"motivateYourself": "Motivate yourself to achieve your goals.",
"timeToGetThingsDone": "It's time to have fun when you get things done! Join over <%= userCountInMillions %> million Habiticans and improve your life one task at a time.",
"singUpForFree": "Зареєструйтесь безкоштовно",
"or": "АБО",
"gamifyYourLife": "Gamify Your Life",
"aboutHabitica": "Habitica is a free habit-building and productivity app that treats your real life like a game. With in-game rewards and punishments to motivate you and a strong social network to inspire you, Habitica can help you achieve your goals to become healthy, hard-working, and happy.",
"trackYourGoals": "Track Your Habits and Goals",
"trackYourGoalsDesc": "Stay accountable by tracking and managing your Habits, Daily goals, and To-Do list with Habitica’s easy-to-use mobile apps and web interface.",
"earnRewards": "Earn Rewards for Your Goals",
"earnRewardsDesc": "Check off tasks to level up your Avatar and unlock in-game features such as battle armor, mysterious pets, magic skills, and even quests!",
"battleMonsters": "Battle Monsters with Friends",
"battleMonstersDesc": "Fight monsters with other Habiticans! Use the Gold that you earn to buy in-game or custom rewards, like watching an episode of your favorite TV show.",
"playersUseToImprove": "Players Use Habitica to Improve",
"healthAndFitness": "Здоров'я та фітнес",
"healthAndFitnessDesc": "Never motivated to floss? Can't seem to get to the gym? Habitica finally makes it fun to get healthy.",
"schoolAndWork": "Школа та Робота",
"schoolAndWorkDesc": "Whether you're preparing a report for your teacher or your boss, it's easy to keep track of your progress as you tackle your toughest tasks.",
"muchmuchMore": "And much, much more!",
"muchmuchMoreDesc": "Our fully customizable task list means that you can shape Habitica to fit your personal goals. Work on creative projects, emphasize self-care, or pursue a different dream -- it's all up to you.",
"levelUpAnywhere": "Level Up Anywhere",
"levelUpAnywhereDesc": "Our mobile apps make it simple to keep track of your tasks on-the-go. Accomplish your goals with a single tap, no matter where you are.",
"joinMany": "Приєднайтеся до 2,000,000 людей, які отримають задоволеня досягаючи своїх цілей!",
"joinToday": "Приєднайтеся до Habitica сьогодні",
"signup": "Зареєструватися",
"getStarted": "Get Started!",
"mobileApps": "Мобільні додатки",
"learnMore": "Learn More"
}
|
{
"pile_set_name": "Github"
}
|
---
id: 5900f3db1000cf542c50feec
challengeType: 5
title: 'Problem 109: Darts'
forumTopicId: 301733
localeTitle: 'Задача 109: Дартс'
---
## Description
<section id='description'>
В игре дартс игрок бросает три дротика на целевую доску, которая разделена на двадцать одинаковых размеров, пронумерованных от одного до двадцати. <p> Оценка дротика определяется количеством области, в которую попадает дротик. Дарт, вылетающий за пределы красного / зеленого внешнего кольца, имеет нулевое значение. Черные и кремовые области внутри этого кольца представляют собой одиночные баллы. Тем не менее, красное / зеленое внешнее кольцо и среднее кольцо оценивают двойные и высокие частоты соответственно. В центре доски расположены два концентрических круга, называемых бычьей областью или бычьим глазом. Внешний бык стоит 25 очков, а внутренний бык - в два раза, стоит 50 очков. Существует множество вариаций правил, но в самой популярной игре игроки начнут со счетом 301 или 501, и первым игроком, который снизит свою общую сумму до нуля, станет победителем. Тем не менее, нормально играть в систему «удваивает», а это означает, что игрок должен приземлить двойную (в том числе двойную бычьи глаза в центре доски) на свой последний дротик, чтобы выиграть; любой другой дротик, который уменьшил бы их общее количество до одного или ниже, означает, что оценка для этого набора из трех дротиков является «бюстом». Когда игрок может закончить свой текущий счет, он называется «проверка», а самая высокая проверка - 170: T20 T20 D25 (два тройных 20-х и двойной бык). Есть ровно одиннадцать различных способов проверки на счет 6: </p><p> D3 </p><p> D1 D2 </p><p> S2 D2 </p><p> D2 D1 </p><p> S4 D1 </p><p> S1 S1 D2 S1 T1 D1 S1 S3 D1 D1 D1 D1 D1 S2 D1 S2 S2 D1 </p><p> Обратите внимание, что D1 D2 считается отличным от D2 D1, поскольку они заканчиваются в разных двухместных. Однако комбинация S1 T1 D1 считается такой же, как T1 S1 D1. Кроме того, мы не будем включать пропуски при рассмотрении комбинаций; например, D3 совпадает с 0 D3 и 0 0 D3. Невероятно 42336 различных способов проверки в целом. Сколько различных способов может пройти проверка игрока со счетом менее 100? </p>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler109()</code> should return 38182.
testString: assert.strictEqual(euler109(), 38182);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler109() {
// Good luck!
return true;
}
euler109();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
|
{
"pile_set_name": "Github"
}
|
/*========================================================================
Copyright (C) 1996-2002 by Jorn Lind-Nielsen
All rights reserved
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, reproduce, prepare derivative
works, distribute, and display this software and its documentation
for any purpose, provided that (1) the above copyright notice and
the following two paragraphs appear in all copies of the source code
and (2) redistributions, including without limitation binaries,
reproduce these notices in the supporting documentation. Substantial
modifications to this software may be copyrighted by their authors
and need not follow the licensing terms described here, provided
that the new terms are clearly indicated in all files where they apply.
IN NO EVENT SHALL JORN LIND-NIELSEN, OR DISTRIBUTORS OF THIS
SOFTWARE 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 THE AUTHORS OR ANY OF THE
ABOVE PARTIES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
JORN LIND-NIELSEN SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.
========================================================================*/
/*************************************************************************
$Header: /cvsroot/buddy/buddy/src/bdd.h,v 1.1.1.1 2004/06/25 13:22:09 haimcohen Exp $
FILE: bdd.h
DESCR: C,C++ User interface for the BDD package
AUTH: Jorn Lind
DATE: (C) feb 1997
*************************************************************************/
#ifndef _BDD_H
#define _BDD_H
/* Allow this headerfile to define C++ constructs if requested */
#ifdef __cplusplus
#define CPLUSPLUS
#endif
#include <stdio.h>
/*=== Defined operators for apply calls ================================*/
#define bddop_and 0
#define bddop_xor 1
#define bddop_or 2
#define bddop_nand 3
#define bddop_nor 4
#define bddop_imp 5
#define bddop_biimp 6
#define bddop_diff 7
#define bddop_less 8
#define bddop_invimp 9
/* Should *not* be used in bdd_apply calls !!! */
#define bddop_not 10
#define bddop_simplify 11
/*=== User BDD types ===================================================*/
typedef int BDD;
#ifndef CPLUSPLUS
typedef BDD bdd;
#endif /* CPLUSPLUS */
typedef struct s_bddPair
{
BDD *result;
int last;
int id;
struct s_bddPair *next;
} bddPair;
/*=== Status information ===============================================*/
/*
NAME {* bddStat *}
SECTION {* kernel *}
SHORT {* Status information about the bdd package *}
PROTO {* typedef struct s_bddStat
{
long int produced;
int nodenum;
int maxnodenum;
int freenodes;
int minfreenodes;
int varnum;
int cachesize;
int gbcnum;
} bddStat; *}
DESCR {* The fields are \\[\baselineskip] \begin{tabular}{lp{10cm}}
{\tt produced} & total number of new nodes ever produced \\
{\tt nodenum} & currently allocated number of bdd nodes \\
{\tt maxnodenum} & user defined maximum number of bdd nodes \\
{\tt freenodes} & number of currently free nodes \\
{\tt minfreenodes} & minimum number of nodes that should be left after a
garbage collection. \\
{\tt varnum} & number of defined bdd variables \\
{\tt cachesize} & number of entries in the internal caches \\
{\tt gbcnum} & number of garbage collections done until now
\end{tabular} *}
ALSO {* bdd\_stats *}
*/
typedef struct s_bddStat
{
long int produced;
int nodenum;
int maxnodenum;
int freenodes;
int minfreenodes;
int varnum;
int cachesize;
int gbcnum;
} bddStat;
/*
NAME {* bddGbcStat *}
SECTION {* kernel *}
SHORT {* Status information about garbage collections *}
PROTO {* typedef struct s_bddGbcStat
{
int nodes;
int freenodes;
long time;
long sumtime;
int num;
} bddGbcStat; *}
DESCR {* The fields are \\[\baselineskip] \begin{tabular}{ll}
{\tt nodes} & Total number of allocated nodes in the nodetable \\
{\tt freenodes} & Number of free nodes in the nodetable \\
{\tt time} & Time used for garbage collection this time \\
{\tt sumtime} & Total time used for garbage collection \\
{\tt num} & number of garbage collections done until now
\end{tabular} *}
ALSO {* bdd\_gbc\_hook *}
*/
typedef struct s_bddGbcStat
{
int nodes;
int freenodes;
long time;
long sumtime;
int num;
} bddGbcStat;
/*
NAME {* bddCacheStat *}
SECTION {* kernel *}
SHORT {* Status information about cache usage *}
PROTO {* typedef struct s_bddCacheStat
{
long unsigned int uniqueAccess;
long unsigned int uniqueChain;
long unsigned int uniqueHit;
long unsigned int uniqueMiss;
long unsigned int opHit;
long unsigned int opMiss;
long unsigned int swapCount;
} bddCacheStat; *}
DESCR {* The fields are \\[\baselineskip] \begin{tabular}{ll}
{\bf Name} & {\bf Number of } \\
uniqueAccess & accesses to the unique node table \\
uniqueChain & iterations through the cache chains in the unique node table\\
uniqueHit & entries actually found in the the unique node table \\
uniqueMiss & entries not found in the the unique node table \\
opHit & entries found in the operator caches \\
opMiss & entries not found in the operator caches \\
swapCount & number of variable swaps in reordering \\
\end{tabular} *}
ALSO {* bdd\_cachestats *}
*/
typedef struct s_bddCacheStat
{
long unsigned int uniqueAccess;
long unsigned int uniqueChain;
long unsigned int uniqueHit;
long unsigned int uniqueMiss;
long unsigned int opHit;
long unsigned int opMiss;
long unsigned int swapCount;
} bddCacheStat;
/*=== BDD interface prototypes =========================================*/
/*
NAME {* bdd\_relprod *}
SECTION {* operator *}
SHORT {* relational product *}
PROTO {* #define bdd_relprod(a,b,var) bdd_appex(a,b,bddop_and,var) *}
DESCR {* Calculates the relational product of {\tt a} and {\tt b} as
{\tt a AND b} with the variables in {\tt var} quantified out
afterwards. *}
RETURN {* The relational product or {\tt bddfalse} on errors. *}
ALSO {* bdd\_appex *}
*/
#define bdd_relprod(a,b,var) bdd_appex((a),(b),bddop_and,(var))
/* In file "kernel.c" */
#ifdef CPLUSPLUS
extern "C" {
#endif
typedef void (*bddinthandler)(int);
typedef void (*bddgbchandler)(int,bddGbcStat*);
typedef void (*bdd2inthandler)(int,int);
typedef int (*bddsizehandler)(void);
typedef void (*bddfilehandler)(FILE *, int);
typedef void (*bddallsathandler)(char*, int);
extern bddinthandler bdd_error_hook(bddinthandler);
extern bddgbchandler bdd_gbc_hook(bddgbchandler);
extern bdd2inthandler bdd_resize_hook(bdd2inthandler);
extern bddinthandler bdd_reorder_hook(bddinthandler);
extern bddfilehandler bdd_file_hook(bddfilehandler);
extern int bdd_init(int, int);
extern void bdd_done(void);
extern int bdd_setvarnum(int);
extern int bdd_extvarnum(int);
extern int bdd_isrunning(void);
extern int bdd_setmaxnodenum(int);
extern int bdd_setmaxincrease(int);
extern int bdd_setminfreenodes(int);
extern double bdd_setincreasefactor(double);
extern int bdd_getnodenum(void);
extern int bdd_setallocnum(int);
extern int bdd_getallocnum(void);
extern char* bdd_versionstr(void);
extern int bdd_versionnum(void);
extern void bdd_stats(bddStat *);
extern void bdd_cachestats(bddCacheStat *);
extern void bdd_fprintstat(FILE *);
extern void bdd_printstat(void);
extern void bdd_default_gbchandler(int, bddGbcStat *);
extern void bdd_default_errhandler(int);
extern const char *bdd_errstring(int);
extern void bdd_clear_error(void);
#ifndef CPLUSPLUS
extern BDD bdd_true(void);
extern BDD bdd_false(void);
#endif
extern int bdd_varnum(void);
extern BDD bdd_ithvar(int);
extern BDD bdd_nithvar(int);
extern int bdd_var(BDD);
extern BDD bdd_low(BDD);
extern BDD bdd_high(BDD);
extern int bdd_varlevel(int);
extern BDD bdd_addref(BDD);
extern BDD bdd_delref(BDD);
extern void bdd_gbc(void);
extern int bdd_duplicatevar(int);
extern int bdd_scanset(BDD, int**, int*);
extern BDD bdd_makeset(int *, int);
extern bddPair* bdd_newpair(void);
extern int bdd_setpair(bddPair*, int, int);
extern int bdd_setpairs(bddPair*, int*, int*, int);
extern int bdd_setbddpair(bddPair*, int, BDD);
extern int bdd_setbddpairs(bddPair*, int*, BDD*, int);
extern void bdd_resetpair(bddPair *);
extern void bdd_freepair(bddPair*);
/* In bddop.c */
extern int bdd_setcacheratio(int);
extern BDD bdd_buildcube(int, int, BDD *);
extern BDD bdd_ibuildcube(int, int, int *);
extern BDD bdd_not(BDD);
extern BDD bdd_apply(BDD, BDD, int);
extern BDD bdd_and(BDD, BDD);
extern BDD bdd_or(BDD, BDD);
extern BDD bdd_xor(BDD, BDD);
extern BDD bdd_imp(BDD, BDD);
extern BDD bdd_biimp(BDD, BDD);
extern BDD bdd_ite(BDD, BDD, BDD);
extern BDD bdd_restrict(BDD, BDD);
extern BDD bdd_constrain(BDD, BDD);
extern BDD bdd_replace(BDD, bddPair*);
extern BDD bdd_compose(BDD, BDD, BDD);
extern BDD bdd_veccompose(BDD, bddPair*);
extern BDD bdd_simplify(BDD, BDD);
extern BDD bdd_exist(BDD, BDD);
extern BDD bdd_forall(BDD, BDD);
extern BDD bdd_unique(BDD, BDD);
extern BDD bdd_appex(BDD, BDD, int, BDD);
extern BDD bdd_appall(BDD, BDD, int, BDD);
extern BDD bdd_appuni(BDD, BDD, int, BDD);
extern BDD bdd_support(BDD);
extern BDD bdd_satone(BDD);
extern BDD bdd_satoneset(BDD, BDD, BDD);
extern BDD bdd_fullsatone(BDD);
extern void bdd_allsat(BDD r, bddallsathandler handler);
extern double bdd_satcount(BDD);
extern double bdd_satcountset(BDD, BDD);
extern double bdd_satcountln(BDD);
extern double bdd_satcountlnset(BDD, BDD);
extern int bdd_nodecount(BDD);
extern int bdd_anodecount(BDD *, int);
extern int* bdd_varprofile(BDD);
extern double bdd_pathcount(BDD);
/* In file "bddio.c" */
extern void bdd_printall(void);
extern void bdd_fprintall(FILE *);
extern void bdd_fprinttable(FILE *, BDD);
extern void bdd_printtable(BDD);
extern void bdd_fprintset(FILE *, BDD);
extern void bdd_printset(BDD);
extern int bdd_fnprintdot(char *, BDD);
extern void bdd_fprintdot(FILE *, BDD);
extern void bdd_printdot(BDD);
extern int bdd_fnsave(char *, BDD);
extern int bdd_save(FILE *, BDD);
extern int bdd_fnload(char *, BDD *);
extern int bdd_load(FILE *ifile, BDD *);
/* In file reorder.c */
extern int bdd_swapvar(int v1, int v2);
extern void bdd_default_reohandler(int);
extern void bdd_reorder(int);
extern int bdd_reorder_gain(void);
extern bddsizehandler bdd_reorder_probe(bddsizehandler);
extern void bdd_clrvarblocks(void);
extern int bdd_addvarblock(BDD, int);
extern int bdd_intaddvarblock(int, int, int);
extern void bdd_varblockall(void);
extern bddfilehandler bdd_blockfile_hook(bddfilehandler);
extern int bdd_autoreorder(int);
extern int bdd_autoreorder_times(int, int);
extern int bdd_var2level(int);
extern int bdd_level2var(int);
extern int bdd_getreorder_times(void);
extern int bdd_getreorder_method(void);
extern void bdd_enable_reorder(void);
extern void bdd_disable_reorder(void);
extern int bdd_reorder_verbose(int);
extern void bdd_setvarorder(int *);
extern void bdd_printorder(void);
extern void bdd_fprintorder(FILE *);
#ifdef CPLUSPLUS
}
#endif
/*=== BDD constants ====================================================*/
#ifndef CPLUSPLUS
extern const BDD bddfalse;
extern const BDD bddtrue;
#endif /* CPLUSPLUS */
/*=== Reordering algorithms ============================================*/
#define BDD_REORDER_NONE 0
#define BDD_REORDER_WIN2 1
#define BDD_REORDER_WIN2ITE 2
#define BDD_REORDER_SIFT 3
#define BDD_REORDER_SIFTITE 4
#define BDD_REORDER_WIN3 5
#define BDD_REORDER_WIN3ITE 6
#define BDD_REORDER_RANDOM 7
#define BDD_REORDER_FREE 0
#define BDD_REORDER_FIXED 1
/*=== Error codes ======================================================*/
#define BDD_MEMORY (-1) /* Out of memory */
#define BDD_VAR (-2) /* Unknown variable */
#define BDD_RANGE (-3) /* Variable value out of range (not in domain) */
#define BDD_DEREF (-4) /* Removing external reference to unknown node */
#define BDD_RUNNING (-5) /* Called bdd_init() twice whithout bdd_done() */
#define BDD_FILE (-6) /* Some file operation failed */
#define BDD_FORMAT (-7) /* Incorrect file format */
#define BDD_ORDER (-8) /* Vars. not in order for vector based functions */
#define BDD_BREAK (-9) /* User called break */
#define BDD_VARNUM (-10) /* Different number of vars. for vector pair */
#define BDD_NODES (-11) /* Tried to set max. number of nodes to be fewer */
/* than there already has been allocated */
#define BDD_OP (-12) /* Unknown operator */
#define BDD_VARSET (-13) /* Illegal variable set */
#define BDD_VARBLK (-14) /* Bad variable block operation */
#define BDD_DECVNUM (-15) /* Trying to decrease the number of variables */
#define BDD_REPLACE (-16) /* Replacing to already existing variables */
#define BDD_NODENUM (-17) /* Number of nodes reached user defined maximum */
#define BDD_ILLBDD (-18) /* Illegal bdd argument */
#define BDD_SIZE (-19) /* Illegal size argument */
#define BVEC_SIZE (-20) /* Mismatch in bitvector size */
#define BVEC_SHIFT (-21) /* Illegal shift-left/right parameter */
#define BVEC_DIVZERO (-22) /* Division by zero */
#define BDD_ERRNUM 24
#include "trace.h"
/*************************************************************************
If this file is included from a C++ compiler then the following
classes, wrappers and hacks are supplied.
*************************************************************************/
#ifdef CPLUSPLUS
#include <iostream>
/*=== User BDD class ===================================================*/
class bvec;
class bdd
{
public:
bdd(void) { root=0; }
bdd(const bdd &r) { bdd_addref(root=r.root); }
~bdd(void) { bdd_delref(root); }
int id(void) const;
bdd operator=(const bdd &r);
bdd operator&(const bdd &r) const;
bdd operator&=(const bdd &r);
bdd operator^(const bdd &r) const;
bdd operator^=(const bdd &r);
bdd operator|(const bdd &r) const;
bdd operator|=(const bdd &r);
bdd operator!(void) const;
bdd operator>>(const bdd &r) const;
bdd operator>>=(const bdd &r);
bdd operator-(const bdd &r) const;
bdd operator-=(const bdd &r);
bdd operator>(const bdd &r) const;
bdd operator<(const bdd &r) const;
bdd operator<<(const bdd &r) const;
bdd operator<<=(const bdd &r);
int operator==(const bdd &r) const;
int operator!=(const bdd &r) const;
private:
BDD root;
bdd(BDD r) { bdd_addref(root=r); }
bdd operator=(BDD r);
friend int bdd_init(int, int);
friend int bdd_setvarnum(int);
friend bdd bdd_true(void);
friend bdd bdd_false(void);
friend bdd bdd_ithvarpp(int);
friend bdd bdd_nithvarpp(int);
friend int bdd_var(const bdd &);
friend bdd bdd_low(const bdd &);
friend bdd bdd_high(const bdd &);
friend int bdd_scanset(const bdd &, int *&, int &);
friend bdd bdd_makesetpp(int *, int);
friend int bdd_setbddpair(bddPair*, int, const bdd &);
friend int bdd_setbddpairs(bddPair*, int*, const bdd *, int);
friend bdd bdd_buildcube(int, int, const bdd *);
friend bdd bdd_ibuildcubepp(int, int, int *);
friend bdd bdd_not(const bdd &);
friend bdd bdd_simplify(const bdd &, const bdd &);
friend bdd bdd_apply(const bdd &, const bdd &, int);
friend bdd bdd_and(const bdd &, const bdd &);
friend bdd bdd_or(const bdd &, const bdd &);
friend bdd bdd_xor(const bdd &, const bdd &);
friend bdd bdd_imp(const bdd &, const bdd &);
friend bdd bdd_biimp(const bdd &, const bdd &);
friend bdd bdd_ite(const bdd &, const bdd &, const bdd &);
friend bdd bdd_restrict(const bdd &, const bdd &);
friend bdd bdd_constrain(const bdd &, const bdd &);
friend bdd bdd_exist(const bdd &, const bdd &);
friend bdd bdd_forall(const bdd &, const bdd &);
friend bdd bdd_unique(const bdd &, const bdd &);
friend bdd bdd_appex(const bdd &, const bdd &, int, const bdd &);
friend bdd bdd_appall(const bdd &, const bdd &, int, const bdd &);
friend bdd bdd_appuni(const bdd &, const bdd &, int, const bdd &);
friend bdd bdd_replace(const bdd &, bddPair*);
friend bdd bdd_compose(const bdd &, const bdd &, int);
friend bdd bdd_veccompose(const bdd &, bddPair*);
friend bdd bdd_support(const bdd &);
friend bdd bdd_satone(const bdd &);
friend bdd bdd_satoneset(const bdd &, const bdd &, const bdd &);
friend bdd bdd_fullsatone(const bdd &);
friend void bdd_allsat(const bdd &r, bddallsathandler handler);
friend double bdd_satcount(const bdd &);
friend double bdd_satcountset(const bdd &, const bdd &);
friend double bdd_satcountln(const bdd &);
friend double bdd_satcountlnset(const bdd &, const bdd &);
friend int bdd_nodecount(const bdd &);
friend int bdd_anodecountpp(const bdd *, int);
friend int* bdd_varprofile(const bdd &);
friend double bdd_pathcount(const bdd &);
friend void bdd_fprinttable(FILE *, const bdd &);
friend void bdd_printtable(const bdd &);
friend void bdd_fprintset(FILE *, const bdd &);
friend void bdd_printset(const bdd &);
friend void bdd_printdot(const bdd &);
friend int bdd_fnprintdot(char*, const bdd &);
friend void bdd_fprintdot(FILE*, const bdd &);
friend std::ostream &operator<<(std::ostream &, const bdd &);
friend int bdd_fnsave(char*, const bdd &);
friend int bdd_save(FILE*, const bdd &);
friend int bdd_fnload(char*, bdd &);
friend int bdd_load(FILE*, bdd &);
friend bdd fdd_ithvarpp(int, int);
friend bdd fdd_ithsetpp(int);
friend bdd fdd_domainpp(int);
friend int fdd_scanvar(const bdd &, int);
friend int* fdd_scanallvar(const bdd &);
friend bdd fdd_equalspp(int, int);
friend void fdd_printset(const bdd &);
friend void fdd_fprintset(FILE*, const bdd &);
friend bdd fdd_makesetpp(int*, int);
friend int fdd_scanset(const bdd &, int *&, int &);
friend int bdd_addvarblock(const bdd &, int);
friend class bvec;
friend bvec bvec_ite(const bdd& a, const bvec& b, const bvec& c);
friend bvec bvec_shlfixed(const bvec &e, int pos, const bdd &c);
friend bvec bvec_shl(const bvec &left, const bvec &right, const bdd &c);
friend bvec bvec_shrfixed(const bvec &e, int pos, const bdd &c);
friend bvec bvec_shr(const bvec &left, const bvec &right, const bdd &c);
friend bdd bvec_lth(const bvec &left, const bvec &right);
friend bdd bvec_lte(const bvec &left, const bvec &right);
friend bdd bvec_gth(const bvec &left, const bvec &right);
friend bdd bvec_gte(const bvec &left, const bvec &right);
friend bdd bvec_equ(const bvec &left, const bvec &right);
friend bdd bvec_neq(const bvec &left, const bvec &right);
};
/*=== BDD constants ====================================================*/
extern const bdd bddfalsepp;
extern const bdd bddtruepp;
#define bddtrue bddtruepp
#define bddfalse bddfalsepp
/*=== C++ interface ====================================================*/
extern int bdd_cpp_init(int, int);
inline void bdd_stats(bddStat& s)
{ bdd_stats(&s); }
inline bdd bdd_ithvarpp(int v)
{ return bdd_ithvar(v); }
inline bdd bdd_nithvarpp(int v)
{ return bdd_nithvar(v); }
inline int bdd_var(const bdd &r)
{ return bdd_var(r.root); }
inline bdd bdd_low(const bdd &r)
{ return bdd_low(r.root); }
inline bdd bdd_high(const bdd &r)
{ return bdd_high(r.root); }
inline int bdd_scanset(const bdd &r, int *&v, int &n)
{ return bdd_scanset(r.root, &v, &n); }
inline bdd bdd_makesetpp(int *v, int n)
{ return bdd(bdd_makeset(v,n)); }
inline int bdd_setbddpair(bddPair *p, int ov, const bdd &nv)
{ return bdd_setbddpair(p,ov,nv.root); }
/* In bddop.c */
inline bdd bdd_replace(const bdd &r, bddPair *p)
{ return bdd_replace(r.root, p); }
inline bdd bdd_compose(const bdd &f, const bdd &g, int v)
{ return bdd_compose(f.root, g.root, v); }
inline bdd bdd_veccompose(const bdd &f, bddPair *p)
{ return bdd_veccompose(f.root, p); }
inline bdd bdd_restrict(const bdd &r, const bdd &var)
{ return bdd_restrict(r.root, var.root); }
inline bdd bdd_constrain(const bdd &f, const bdd &c)
{ return bdd_constrain(f.root, c.root); }
inline bdd bdd_simplify(const bdd &d, const bdd &b)
{ return bdd_simplify(d.root, b.root); }
inline bdd bdd_ibuildcubepp(int v, int w, int *a)
{ return bdd_ibuildcube(v,w,a); }
inline bdd bdd_not(const bdd &r)
{ return bdd_not(r.root); }
inline bdd bdd_apply(const bdd &l, const bdd &r, int op)
{ return bdd_apply(l.root, r.root, op); }
inline bdd bdd_and(const bdd &l, const bdd &r)
{ return bdd_apply(l.root, r.root, bddop_and); }
inline bdd bdd_or(const bdd &l, const bdd &r)
{ return bdd_apply(l.root, r.root, bddop_or); }
inline bdd bdd_xor(const bdd &l, const bdd &r)
{ return bdd_apply(l.root, r.root, bddop_xor); }
inline bdd bdd_imp(const bdd &l, const bdd &r)
{ return bdd_apply(l.root, r.root, bddop_imp); }
inline bdd bdd_biimp(const bdd &l, const bdd &r)
{ return bdd_apply(l.root, r.root, bddop_biimp); }
inline bdd bdd_ite(const bdd &f, const bdd &g, const bdd &h)
{ return bdd_ite(f.root, g.root, h.root); }
inline bdd bdd_exist(const bdd &r, const bdd &var)
{ return bdd_exist(r.root, var.root); }
inline bdd bdd_forall(const bdd &r, const bdd &var)
{ return bdd_forall(r.root, var.root); }
inline bdd bdd_unique(const bdd &r, const bdd &var)
{ return bdd_unique(r.root, var.root); }
inline bdd bdd_appex(const bdd &l, const bdd &r, int op, const bdd &var)
{ return bdd_appex(l.root, r.root, op, var.root); }
inline bdd bdd_appall(const bdd &l, const bdd &r, int op, const bdd &var)
{ return bdd_appall(l.root, r.root, op, var.root); }
inline bdd bdd_appuni(const bdd &l, const bdd &r, int op, const bdd &var)
{ return bdd_appuni(l.root, r.root, op, var.root); }
inline bdd bdd_support(const bdd &r)
{ return bdd_support(r.root); }
inline bdd bdd_satone(const bdd &r)
{ return bdd_satone(r.root); }
inline bdd bdd_satoneset(const bdd &r, const bdd &var, const bdd &pol)
{ return bdd_satoneset(r.root, var.root, pol.root); }
inline bdd bdd_fullsatone(const bdd &r)
{ return bdd_fullsatone(r.root); }
inline void bdd_allsat(const bdd &r, bddallsathandler handler)
{ bdd_allsat(r.root, handler); }
inline double bdd_satcount(const bdd &r)
{ return bdd_satcount(r.root); }
inline double bdd_satcountset(const bdd &r, const bdd &varset)
{ return bdd_satcountset(r.root, varset.root); }
inline double bdd_satcountln(const bdd &r)
{ return bdd_satcountln(r.root); }
inline double bdd_satcountlnset(const bdd &r, const bdd &varset)
{ return bdd_satcountlnset(r.root, varset.root); }
inline int bdd_nodecount(const bdd &r)
{ return bdd_nodecount(r.root); }
inline int* bdd_varprofile(const bdd &r)
{ return bdd_varprofile(r.root); }
inline double bdd_pathcount(const bdd &r)
{ return bdd_pathcount(r.root); }
/* I/O extensions */
inline void bdd_fprinttable(FILE *file, const bdd &r)
{ bdd_fprinttable(file, r.root); }
inline void bdd_printtable(const bdd &r)
{ bdd_printtable(r.root); }
inline void bdd_fprintset(FILE *file, const bdd &r)
{ bdd_fprintset(file, r.root); }
inline void bdd_printset(const bdd &r)
{ bdd_printset(r.root); }
inline void bdd_printdot(const bdd &r)
{ bdd_printdot(r.root); }
inline void bdd_fprintdot(FILE* ofile, const bdd &r)
{ bdd_fprintdot(ofile, r.root); }
inline int bdd_fnprintdot(char* fname, const bdd &r)
{ return bdd_fnprintdot(fname, r.root); }
inline int bdd_fnsave(char *fname, const bdd &r)
{ return bdd_fnsave(fname, r.root); }
inline int bdd_save(FILE *ofile, const bdd &r)
{ return bdd_save(ofile, r.root); }
inline int bdd_fnload(char *fname, bdd &r)
{ int lr,e; e=bdd_fnload(fname, &lr); r=bdd(lr); return e; }
inline int bdd_load(FILE *ifile, bdd &r)
{ int lr,e; e=bdd_load(ifile, &lr); r=bdd(lr); return e; }
inline int bdd_addvarblock(const bdd &v, int f)
{ return bdd_addvarblock(v.root, f); }
/* Hack to allow for overloading */
#define bdd_init bdd_cpp_init
#define bdd_ithvar bdd_ithvarpp
#define bdd_nithvar bdd_nithvarpp
#define bdd_makeset bdd_makesetpp
#define bdd_ibuildcube bdd_ibuildcubepp
#define bdd_anodecount bdd_anodecountpp
/*=== Inline C++ functions =============================================*/
inline int bdd::id(void) const
{ return root; }
inline bdd bdd::operator&(const bdd &r) const
{ return bdd_apply(*this,r,bddop_and); }
inline bdd bdd::operator&=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_and)); }
inline bdd bdd::operator^(const bdd &r) const
{ return bdd_apply(*this,r,bddop_xor); }
inline bdd bdd::operator^=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_xor)); }
inline bdd bdd::operator|(const bdd &r) const
{ return bdd_apply(*this,r,bddop_or); }
inline bdd bdd::operator|=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_or)); }
inline bdd bdd::operator!(void) const
{ return bdd_not(*this);}
inline bdd bdd::operator>>(const bdd &r) const
{ return bdd_apply(*this,r,bddop_imp); }
inline bdd bdd::operator>>=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_imp)); }
inline bdd bdd::operator-(const bdd &r) const
{ return bdd_apply(*this,r,bddop_diff); }
inline bdd bdd::operator-=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_diff)); }
inline bdd bdd::operator>(const bdd &r) const
{ return bdd_apply(*this,r,bddop_diff); }
inline bdd bdd::operator<(const bdd &r) const
{ return bdd_apply(*this,r,bddop_less); }
inline bdd bdd::operator<<(const bdd &r) const
{ return bdd_apply(*this,r,bddop_invimp); }
inline bdd bdd::operator<<=(const bdd &r)
{ return (*this=bdd_apply(*this,r,bddop_invimp)); }
inline int bdd::operator==(const bdd &r) const
{ return r.root==root; }
inline int bdd::operator!=(const bdd &r) const
{ return r.root!=root; }
inline bdd bdd_true(void)
{ return 1; }
inline bdd bdd_false(void)
{ return 0; }
/*=== Iostream printing ================================================*/
class bdd_ioformat
{
public:
bdd_ioformat(int f) { format=f; }
private:
bdd_ioformat(void) { }
int format;
static int curformat;
friend std::ostream &operator<<(std::ostream &, const bdd_ioformat &);
friend std::ostream &operator<<(std::ostream &, const bdd &);
};
std::ostream &operator<<(std::ostream &, const bdd &);
std::ostream &operator<<(std::ostream &, const bdd_ioformat &);
extern bdd_ioformat bddset;
extern bdd_ioformat bddtable;
extern bdd_ioformat bdddot;
extern bdd_ioformat bddall;
extern bdd_ioformat fddset;
extern int trace_enable;
typedef void (*bddstrmhandler)(std::ostream &, int);
extern bddstrmhandler bdd_strm_hook(bddstrmhandler);
#endif /* CPLUSPLUS */
#endif /* _BDD_H */
/* EOF */
|
{
"pile_set_name": "Github"
}
|
[](https://travis-ci.org/NYTimes/Store)
# Store
Store — это легкая в использовании библиотека для реактивной загрузки данных под Android.
### Проблемы:
+ Современные Android-приложения нуждаются в удобном и всегда доступном представлении данных.
+ Пользователи ожидают, что загрузка данных не будет мешать их взаимодействию с приложением.
И от социальных, и от новостных, и от business-to-business приложений, пользователи ожидают бесшовного взаимодействия как при подключении к сети, так и в автономном режиме.
+ В международном роуминге большой объем загружаемых данных может привести к астрономическим счетам за связь.
Store представляет собой класс, который упрощает загрузку, парсинг, хранение и извлечение данных в вашем приложении.
Store похож на паттерн «репозиторий» [[https://msdn.microsoft.com/en-us/library/ff649690.aspx](https://msdn.microsoft.com/en-us/library/ff649690.aspx)], в дополнение предоставляя реактивный API, реализованный с помощью RxJava, который придерживается однонаправленного потока данных.
Store обеспечивает уровень абстракции между элементами UI и операциями с данными.
### Обзор
Store отвечает за управление загрузкой конкретного запроса данных.
Когда вы создаёте новую реализацию Store, вы предоставляете ему `Fetcher` — функцию, которая определяет, как будет происходить загрузка данных из сети.
Также вы можете настроить, как Store будет кэшировать данные в памяти и на диске, а так же то, как будет происходить их парсинг.
Store возвращает данные в виде `Observable`, обеспечивая удобную работу с потоками.
Созданный Store управляет логикой обработки потока данных, позволяя элементам пользовательского интерфейса использовать наиболее подходящий их источник, и гарантирует, что новейшие данные будут доступны для последующего использования в автономном режиме.
Store может использовать классы для промежуточной обработки данных (парсинг и кэширование), идущие в комплекте, или же использовать ваши собственные реализации.
Store использует RxJava и «склеивание» множественных запросов, чтобы минимизировать количество обращений к источнику данных в сети и кэшу на диске.
Используя Store, с помощью двух уровней кэширования (память и диск), вы исключите ситуации, когда один и тот же сетевой запрос будет выполняться избыточное количество раз.
### Полностью сконфигурированный Store
Для начала рассмотрим, как выглядит полностью сконфигурированный Store.
Затем последуют более простые примеры, демонстрирующие каждую деталь в отдельности.
```java
Store<ArticleAsset, Integer> articleStore = StoreBuilder.<Integer, BufferedSource, ArticleAsset>parsedWithKey()
.fetcher(articleId -> api.getArticleAsBufferedSource(articleId)) //OkHttp responseBody.source()
.persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()),pathResolver))
.parser(GsonParserFactory.createSourceParser(gson, ArticleAsset.Article.class))
.open();
```
Используя указанную выше конфигурацию вы получите:
+ Кэш в памяти, использующийся при смене конфигурации (например, при повороте экрана)
+ Кэш на диске для использования в автономном режиме
+ Парсинг через потоковый API, чтобы ограничить использование памяти
+ Многофункциональный API для запроса данных: получение кэшированных/новых данных или подписка на их будущие обновления.
А теперь более подробно:
### Создание Store
Для создания Store используется паттерн builder (строитель).
Единственный обязательный параметр — это `.Fetcher<ReturnType,KeyType>`, который содержит единственный метод `fetch(key)`, возвращающий `Observable<ReturnType>`.
``` java
Store<ArticleAsset, Integer> store = StoreBuilder.<ArticleAsset,Integer>key()
.fetcher(articleId -> api.getArticle(articleId)) //OkHttp responseBody.source()
.open();
```
Store использует типизированные ключи в качестве идентификаторов для данных.
Ключом может быть любой объект-значение (value object), который должным образом реализует методы `toString()`, `equals()` и `hashCode()`.
При вызове вашей `Fetcher`-функции, ей будет передан конкретный экземпляр ключа.
Аналогичным образом, ключ будет использоваться в качестве основного идентификатора в кэше (убедитесь, что ваш ключ правильно реализует `hashCode()`!)
### Наша реализация ключа — BarCode
Для удобства мы включили в библиотеку нашу собственную реализацию ключа, называемую BarCode (штрихкод).
Barcode имеет два поля: ключ `String key` и тип `String type`.
``` java
BarCode barcode = new BarCode("Article", "42");
```
При использовании BarCode в качестве ключа, удобно использовать соответсвующий метод StoreBuilder:
``` java
Store<ArticleAsset, Integer> store = StoreBuilder.<ArticleAsset>barcode()
.fetcher(articleBarcode -> api.getAsset(articleBarcode.getKey(),articleBarcode.getType()))
.open();
```
### Публичный интерфейс: Get, Fetch, Stream, GetRefreshing
```java
Observable<Article> article = store.get(barCode);
```
В первый раз, когда вы подпишитесь на `store.get(barCode)`, ответ будет сохранён в кэше в памяти.
Все последующие вызовы `store.get(barCode)` с тем же ключом будут возвращать кэшированную версию данных, минимизируя ненужные запросы.
Это позволяет предотвратить загрузку свежих данных из сети (или другого внешнего источника), чтобы уменьшить расход трафика и экономить заряд батареи.
Хороший пример использования: пересоздание пользовательского интерфейса (activity или fragment) после поворота устройства — будут загружены кэшированные данные из Store.
Использование Store поможет вам избежать необходимости реализовывать эту логику на уровне представления.
Поток данных, которым управляет Store, на данный момент будет выглядеть следующим образом:

По умолчанию, 100 элементов будут сохранены в памяти на 24 часа.
Вы можете передать свой экземпляр Guava Cache, чтобы переопределить стандартную политику.
### Запрос свежих данных
В качестве альтернативы, вы можете вызвать `store.fetch(barCode)`, чтобы получить `Observable`, игнорируя кэш в памяти (и кэш на диске, если он используется).
Получение свежих данных выглядит следующим образом: `store.fetch()`

В приложении The New York Times фоновое обновление, выполняемое ночью, использует `fetch()`, чтобы во время обычного использования приложения вызов `store.get()` не приводил к сетевым запросам.
Другой хороший пример использования `fetch()` — обработка жеста pull-to-refresh, когда пользователь сам запрашивает обновление данных.
Методы `fetch()` и `get()` порождают одно значение и затем вызывают `onCompleted()` или выбрасывают исключение в случае ошибки.
### Поток
Для обновлений в реальном времени вы также можете вызвать метод `store.stream()`, который возвращает `Observable`, который порождает событие при сохранении нового объекта в Store.
Вы можете рассматривать этот поток как шину событий (Event Bus), позволяющую узнавать, когда происходят новые удачные обращения к сети для определённого Store.
Вы можете использовать оператор RxJava `filter()`, чтобы подписаться только на определенные события.
### Получение обновляющихся данных
Существует еще один специальный способ подписаться на Store: `getRefreshing(key)`.
`getRefreshing()` подпишется на `get()`, который возвращает один результат, но в отличие от `get()`, `getRefreshing()` останется подписанным.
Каждый раз после вызова `store.clear(key)` все подписчики `getRefreshing(key)` подпишутся заново и принудительно создадут новый сетевой запрос данных.
### Оптимизация запросов
Store предлагает дополнительные механизмы для предотвращения дублирующихся запросов одних и тех же данных.
Если некий запрос выполняется в течение минуты после предыдущего точно такого же запроса, возвращается тот же ответ.
Это полезно в ситуациях, когда вашему приложению во время запуска требуется сделать много асинхронных вызовов для одних и тех же данных или когда пользователь интенсивно запрашивает обновление данных.
Например, новостное приложение The New York Times при запуске вызывает `ConfigStore.get()` из 12 разных мест.
Первый из запросов выполняется, а остальные ожидают поступления данных.
Мы увидели значительное сокращение объема использованных данных приложением после реализации этой логики.
### Добавление парсера
Поскольку данные из сети редко поступают в нужном формате, Store может делегировать их обработку парсеру с помощью `StoreBuilder.<BarCode, BufferedSource, Article>parsedWithKey()`
```java
Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
.fetcher(articleId -> api.getArticle(articleId))
.parser(source -> {
try (InputStreamReader reader = new InputStreamReader(source.inputStream())) {
return gson.fromJson(reader, Article.class);
} catch (IOException e) {
throw new RuntimeException(e);
}
})
.open();
```
Теперь обновленный поток данных будет выглядеть следующим образом:
`store.get()` -> 
### Промежуточная обработка данных — GsonSourceParser
Отдельный артефакт предоставляет парсеры, использующие Gson, которые могут быть полезны, если `Fethcer` возвращает Reader, BufferedSource или String:
- GsonReaderParser
- GsonSourceParser
- GsonStringParser
Они доступны через класс фабрики (GsonParserFactory).
Наш пример можно переписать так:
```java
Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
.fetcher(articleId -> api.getArticle(articleId))
.parser(GsonParserFactory.createSourceParser(gson, Article.class))
.open();
```
В некоторых случаях вам может потребоваться проанализировать JSONArray верхнего уровня, в этом случае вы можете передать TypeToken.
```java
Store<List<Article>,Integer> store = StoreBuilder.<Integer, BufferedSource, List<Article>>parsedWithKey()
.fetcher(articleId -> api.getArticles())
.parser(GsonParserFactory.createSourceParser(gson, new TypeToken<List<Article>>() {}))
.open();
```
Также существуют артефакты парсеров для Moshi и Jackson!
### Кэширование на диске
Можно включить кэширование данных на диске, используя экземпляр класса `Persister` при создании Store.
Всякий раз после выполнения сетевого запроса Store будет сохранять данные на диск, а затем считывать их.
Поток данных будет выглядеть так:
`store.get()` -> 
Идеальным вариантом будет, если данные будут передаваться из сети на диск с использованием BufferedSource или Reader в качестве типа данных (а не String).
```java
Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
.fetcher(articleId -> api.getArticles())
.persister(new Persister<BufferedSource>() {
@Override
public Observable<BufferedSource> read(Integer key) {
if (dataIsCached) {
return Observable.fromCallable(() -> userImplementedCache.get(key));
} else {
return Observable.empty();
}
}
@Override
public Observable<Boolean> write(BarCode barCode, BufferedSource source) {
userImplementedCache.save(key, source);
return Observable.just(true);
}
})
.parser(GsonParserFactory.createSourceParser(gson, Article.class))
.open();
```
Stores не заботятся о том, как вы сохраняете или извлекаете данные с диска.
В результате вы можете использовать Store с хранилищем объектов или любой базой данных (Realm, SQLite, CouchDB, Firebase etc).
Единственное требование заключается в том, что данные должны быть одного и того же типа при сохранении/получении, что и возвращаемое функцией Fetcher значение.
Теоретически, ничто не мешает вам реализовать свою версию класса `Persister`, который будет использовать для кэширования данных только память устройства.
В таком случае в памяти будут храниться не один а два уровня кэша: первый с оригинальными данными, а второй с распарсенными, что позволит делиться кэшем `Persister` между разными экземплярами Store
**Примечание**: При использовании парсера и кэша на диске, парсер будет вызван ПОСЛЕ получения данных с диска, а не между успешным сетевым вызовом и сохранением на диск.
Это позволяет классу `Persister` работать непосредственно с сетевым потоком.
При использовании SQLite мы рекомендуем библиотеку SqlBrite.
Если вы не используете SqlBrite, вы можете создать `Observable` с помощью `Observable.fromCallable(() -> getDBValue())`
### Промежуточный слой — SourcePersister и FileSystem
Мы установили, что наибольшей скорости сохранения можно добиться, выполняя потоковое сохранение данных из сети.
Поэтому мы включили отдельную библиотеку, предлагающую реактивную файловую систему, использующую `BufferedSource` из библиотеки Okio.
Также артефакт этот включает в себя `FileSystemPersister`, реализующий дисковый кэш для Store и прекрасно работающий с `GsonSourceParser`.
При использовании `FileSystemPersister` нужно передать ему реализацию `PathResolver`, определяющую пути к элементам кэша в файловой системе.
Вернемся к первому примеру:
```java
Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey()
.fetcher(articleId -> api.getArticles(articleId))
.persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()),pathResolver))
.parser(GsonParserFactory.createSourceParser(gson, String.class))
.open();
```
Как уже упоминалось, это то, как мы работаем с сетевыми операциями в The New York Times.
Используя конфигурацию, указанную выше, вы получаете:
+ Кэширование в памяти с помощью Guava Cache
+ Кэширование на диске с помощью FileSystem (вы можете переиспользовать одну и ту же файловую систему для всех Store)
+ Парсинг данных из `BufferedSource` в `<T>` (Класс Article в нашем примере) с помошью Gson
+ Оптимизация запросов
+ Возможность использовать кэшированные данные или запросить свежие (методы `get()` и `fresh()`)
+ Возможность подписаться на все новые элементы, полученные из сети (метод `stream()`)
+ Возможность получить уведомление об очистке кэша, а также переподписаться после этого (метод `getRefreshing()`). Полезно, если нужно выполнить запрос типа POST, после чего другой обновить экран)
Мы рекомендуем использовать эту конфигурацию для большинства хранилищ Store.
Благодаря передаче данных из сети на диск и с диска в парсер в формате потока байтов, `SourcePersister` потребляет малое количество памяти.
Это позволяет нам загружать десятки ответов в формате json размером более 1mb и не беспокоиться об исключениях OutOfMemory на устройствах с малым объемом памяти.
Как упоминалось выше, использование Store позволяет нам делать такие вещи, как вызов `configStore.get()` множествно раз асинхронно, прежде чем наша MainActivity закончит загрузку, не блокируя основной поток и не загружая сеть.
### RecordProvider
Если вы хотите, чтобы ваш Store знал об устаревании данных на диске, ваш `Persister` должер реализовывать интерфейс `RecordProvider`.
После этого, вы можете настроить работу Store одним из двух способов:
```java
store = StoreBuilder.<BufferedSource>barcode()
.fetcher(fetcher)
.persister(persister)
.refreshOnStale()
.open();
```
`refreshOnStale` инвалидирует дисковый кэш, каждый раз когда данные устареют.
Пользователь получит устаревшие данные.
Или же:
```java
store = StoreBuilder.<BufferedSource>barcode()
.fetcher(fetcher)
.persister(persister)
.networkBeforeStale()
.open();
```
`networkBeforeStale` — Store попытается использовать сетевой источник, если данные устарели.
Если сетевой источник данных выбрасывает исключение или возвращает пустой ответ, Store будет использовать устаревшие данные.
### Создание подклассов Store
Можно отнаследоваться от класса реализации Store (`RealStore<T>`):
```java
public class SampleStore extends RealStore<String, BarCode> {
public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) {
super(fetcher, persister);
}
}
```
Это может быть полезно, если вы хотите внедрить зависимость Store или добавить несколько вспомогательных методов:
```java
public class SampleStore extends RealStore<String, BarCode> {
@Inject
public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) {
super(fetcher, persister);
}
}
```
### Артефакты
Примечание: релизы синхронизированы с состоянием ветки master (а не develop).
+ **Cache** Кэш, извлеченный из библиотеки Guava (чтобы сократить количество методов)
```groovy
implementation 'com.nytimes.android:cache:CurrentVersion'
```
+ **Store** Содержит только классы Store, зависит от RxJava и артефакта кэша
```groovy
implementation 'com.nytimes.android:store:CurrentVersion'
```
+ **Middleware** Парсеры Gson (не стесняйтесь создавать новые и предлагать PR)
```groovy
implementation 'com.nytimes.android:middleware:CurrentVersion'
```
+ **Middleware-Jackson** Парсеры Jackson (не стесняйтесь создавать новые и предлагать PR)
```groovy
implementation 'com.nytimes.android:middleware-jackson:CurrentVersion'
```
+ **Middleware-Moshi** Парсеры Moshi (не стесняйтесь создавать новые и предлагать PR)
```groovy
implementation 'com.nytimes.android:middleware-moshi:CurrentVersion'
```
+ **File System** библиотека, использующая Okio Source/Sink + Middleware для сохранения потока данных из сети в файловую систему
```groovy
implementation 'com.nytimes.android:filesystem:CurrentVersion'
```
### Пример проекта
Директория app содержит тестовое приложение, демонстрирующее использование Store.
Кроме того, вики этого репозитория содержит некоторые рецепты для распространенных сценариев использования:
+ Простой пример: Retrofit + Store
+ Сложный пример: BufferedSource и Retrofit (или OkHTTP) + кэш на диске с FileSystem + GsonSourceParser
|
{
"pile_set_name": "Github"
}
|
# Developers
Morten O. Alver
Nizar N. Batada
Michel Baylac
Guillaume Gardey
Cyrille d'Haese
Raik Nagel
Christopher Oezbek
Ellen Reitmayr
Michael Spiegel
Ulrik Stervbo
Dominik Waßenhoven
Joerg K. Wegner
Michael Wrighton
Egon Willighagen
Jörg Zieren
# Contributions from
Kolja Brix
Frédéric Darboux
Fabrice Dessaint
Nathan Dunn
Brian Van Essen
Alexis Gallagher
Sascha Hunold
Bernd Kalbfuss
Martin Kähmer
Christian Kopf
Alex Montgomery
John Relph
Moritz Ringler
Rudolf Seemann
Mike Smoot
Ulrich Stärk
Martin Stolle
Matthias Stuermer
David Weitzman
Seb Wills
# Thanks to
Samin Muhammad Ridwanul Karim
Stefan Robert
|
{
"pile_set_name": "Github"
}
|
entertainment 台 媒 预 测 周 冬 雨 金 马 奖 封 后 , 大 气 的 倪 妮 却 佳 作 难 出
food 农 村 就 是 好 , 能 吃 到 纯 天 然 无 添 加 的 野 生 蜂 蜜 , 营 养 又 健 康
fashion 1 4 款 知 性 美 装 , 时 尚 惊 艳 搁 浅 的 阳 光 轻 熟 的 优 雅
history 火 焰 喷 射 器 1 0 0 0 度 火 焰 烧 死 鬼 子 4 连 拍
society 1 8 岁 青 年 砍 死 8 8 岁 老 兵
fashion 醋 洗 脸 的 正 确 方 法 洗 对 了 不 仅 美 容 肌 肤 还 能 收 缩 毛 孔
game 大 家 都 说 说 除 了 这 1 0 个 英 雄 , L O L 还 有 哪 些 英 雄 可 以 单 挑 男 爵
sports 王 仕 鹏 退 役 担 任 N B A 总 决 赛 现 场 解 说 嘉 宾
regimen 天 天 吃 “ 洋 快 餐 ” , 5 岁 女 童 患 上 肝 炎
food 汤 里 的 蛋 花 怎 样 才 能 如 花 朵 般 漂 亮 , 注 意 这 一 点 即 可 !
tech 英 退 休 人 士 把 谷 歌 当 活 人 以 礼 貌 搜 索 请 求 征 服 整 个 互 联 网
discovery N A S A 探 测 器 拍 摄 地 球 、 火 星 和 冥 王 星 合 影
society 当 骗 子 遇 上 撒 贝 宁 ! 几 句 话 过 后 骗 子 赔 礼 道 歉 . . . . .
history 红 军 长 征 在 中 国 革 命 史 上 的 地 位
world 实 拍 神 秘 之 国 , 带 你 走 进 真 实 的 朝 鲜
tech 逼 格 爆 表 ! 古 文 版 2 0 1 6 网 络 热 词 : 燃 尽 洪 荒 之 力
story 因 为 一 样 东 西 这 个 后 娘 竟 然 给 孩 子 磕 头
game L O L : 皮 肤 对 操 作 没 影 响 ? 细 数 那 些 有 加 成 效 果 的 皮 肤
fashion 冬 天 想 穿 裙 子 又 怕 冷 ? 学 了 这 些 搭 配 就 能 好 看 又 温 暖 !
entertainment 贾 建 军 少 林 三 光 剑 视 频
food 再 也 不 用 出 去 吃 羊 肉 串 , 自 己 做 又 卫 生 又 健 康
regimen 男 人 多 吃 这 几 道 菜 , 效 果 胜 “ 伟 哥 ”
baby 宝 贝 厨 房 丨 肉 类 辅 食 第 一 步 宝 宝 的 生 长 发 育 每 天 都 离 不 开 它 !
travel 近 8 0 亿 的 顶 级 豪 华 邮 轮 上 到 底 有 什 么 ?
sports 厄 齐 尔 心 中 最 想 签 约 的 三 个 人
food 东 北 的 粘 豆 包 啊 , 想 死 你 们 了 !
military 强 军 足 音
sports 奥 运 赛 场 上 , 被 喷 子 痛 批 的 十 大 知 名 运 动 员
game 老 玩 家 分 享 对 2 0 1 6 L P L 夏 季 赛 R N G 的 分 析
military 揭 秘 : 关 于 战 争 的 五 大 真 相 , 不 要 再 被 影 视 所 欺 骗 了 !
food 小 丫 厨 房 : 夏 天 怎 么 吃 辣 不 长 痘 ? 告 诉 你 火 锅 鸡 、 香 辣 鱼 的 正 确 做 法
travel 中 国 首 个 内 陆 城 市 群 上 的 9 座 城 市 , 看 看 有 你 的 家 乡 吗
fashion 李 小 璐 做 榜 样 接 亲 吻 脚 大 流 行 新 娘 玉 足 怎 样 才 有 好 味 道 ?
game 黄 金 吊 打 钻 石 ? L O L 最 强 刷 钱 毒 瘤 打 法 诞 生
history 奇 事 ! 上 万 只 青 蛙 拦 路 告 状 , 竟 然 牵 扯 出 一 桩 命 案
baby 奶 奶 , 你 为 什 么 不 让 我 用 尿 不 湿
game L O L 当 5 个 大 发 明 家 炮 台 围 住 泉 水 的 时 候 : 这 是 真 虐 泉 !
essay 文 友 忠 告 暖 人 心 : 人 到 中 年 “ 不 交 五 友 ”
travel 这 一 年 , 我 们 去 日 本
food 好 吃 早 饭 近 似 吃 补 药
fashion 夏 天 太 热 , 唇 膏 化 了 如 何 办 ?
society 厂 里 面 的 9 0 后 打 工 妹 , 辛 苦 来 之 不 易
history 罕 见 老 照 片 展 示 美 国 大 萧 条 时 期 景 象
world 美 国 总 统 奥 巴 马 , 是 童 心 未 泯 的 温 情 奥 大 大 , 还 是 个 超 级 老 顽 童
finance 脱 欧 公 投 前 一 天 抛 售 英 镑 这 一 次 索 罗 斯 也 被 “ 打 败 ” 了 . . .
history 翻 越 长 征 路 上 第 一 座 大 山
world 朝 鲜 批 奥 巴 马 涉 朝 言 论 , 称 只 要 核 威 胁 存 在 将 继 续 强 化 核 武 力 量
game 《 巫 师 3 : 狂 猎 》 不 良 因 素 解 析 攻 略
travel 在 郑 州 有 个 地 方 , 时 光 仿 佛 在 那 儿 停 下 脚 步
history 它 号 称 “ 天 下 第 一 团 ” , 走 出 过 1 4 位 共 和 国 将 军 以 及 一 位 著 名 作 家
car 煤 老 板 去 黄 江 买 车 , 以 为 占 了 便 宜 没 想 被 坑 了 1 0 0 多 万
society “ 试 管 婴 儿 之 母 ” 张 丽 珠 遗 体 告 别 仪 式 8 日 举 行
sports 东 京 奥 运 会 , 中 国 女 排 卫 冕 的 几 率 有 多 大 ?
travel 成 都 我 们 永 远 依 恋 的 城 市
tech 雷 布 斯 除 了 小 米 还 有 这 些 秘 密 , 你 知 道 吗 ?
world “ 仲 裁 庭 损 害 国 际 法 体 系 公 正 性 ” — — 访 武 汉 大 学 中 国 边 界 与 海 洋 研 究 院 首 席 专 家 易 显 河
entertainment 上 海 观 众 和 欧 洲 三 大 影 展 之 间 的 距 离 : 零 时 差
essay 关 系 好 , 一 切 便 好
baby 刚 出 生 不 到 1 小 时 的 白 鲸 宝 宝 被 冲 上 岸 , 被 救 后 对 恩 人 露 出 微 笑
tech 赚 足 眼 球 , 诺 基 亚 五 边 形 W i n 1 0 M o b i l e 概 念 手 机 : 棱 镜
essay 2 4 句 经 典 语 录 : 穷 三 年 可 以 怨 命 , 穷 十 年 就 得 自 省
food 这 道 菜 真 下 饭 ! 做 法 简 单 , 防 辐 射 、 抗 衰 老 , 关 键 还 便 宜
entertainment 《 继 承 者 们 》 要 拍 中 国 版 , 众 角 色 你 期 待 谁 来 演 ?
game D N F 暴 走 改 版 后 怎 么 样 D N F 暴 走 改 版 红 眼 变 弱 了 吗
entertainment 郑 佩 佩 自 曝 与 李 小 龙 的 过 去 他 是 个 “ 疯 子 ”
baby 女 性 只 有 8 4 次 最 佳 受 孕 机 会
travel 月 初 一 个 人 去 了 日 本 . .
military 不 为 人 知 的 8 0 万 苏 联 女 兵 ! 最 后 一 张 很 美 !
tech 网 络 商 家 提 供 小 米 5 运 存 升 级 服 务 : 3 G B 秒 变 6 G B
history 宋 太 祖 、 宋 太 宗 凌 辱 亡 国 皇 后 , 徽 钦 二 帝 后 宫 被 金 人 凌 辱
history 人 有 三 面 最 “ 难 吃 ” ! 黑 帮 大 佬 杜 月 笙 论 江 湖 规 矩 ! 一 生 只 怕 这 一 人
game 来 了 ! 索 尼 P S 4 独 占 大 作 《 战 神 4 》 正 式 公 布
discovery 延 时 视 频 显 示 珊 瑚 如 何 “ 驱 逐 ” 共 生 藻 类
car 传 祺 G A 8 和 东 风 A 9 谁 才 是 自 主 “ 豪 车 ” 大 佬
fashion 娶 老 婆 就 要 娶 这 种 ! 蒋 欣 这 样 微 胖 的 女 人 好 看 又 实 用
sports 黄 山 姑 娘 吕 秀 芝 勇 夺 奥 运 铜 牌 数 百 父 老 彻 夜 为 她 加 油
military [ 每 日 军 图 ] 土 豪 补 仓 ! 沙 特 再 次 购 买 上 百 辆 美 国 M 1 A 2 主 战 坦 克
military 美 军 这 款 武 器 号 称 能 让 半 个 中 国 陷 入 黑 暗 , 解 放 军 少 将 : 我 们 也 有
world 邓 小 平 与 日 本 天 皇 的 历 史 性 会 谈 , 对 中 日 两 国 都 具 有 深 远 的 意 义 啊 !
baby 为 什 么 有 人 上 个 厕 所 都 能 生 出 孩 子 ?
fashion 欣 宜 举 行 首 次 个 唱 十 万 颗 宝 仕 奥 莎 仿 水 晶 闪 耀 全 场
food 小 两 口 上 周 的 晚 餐
society 在 北 京 就 要 守 规 矩
entertainment 知 情 人 曝 翰 爽 分 手 内 幕 : 郑 爽 想 结 婚 却 被 一 直 拖 着
military 中 国 反 舰 导 弹 世 界 第 一 远 远 超 过 美 国 但 为 何 却 还 不 如 俄 罗 斯 ?
entertainment 他 除 了 是 《 我 歌 》 音 乐 总 监 , 还 曾 组 乐 队 玩 摇 滚 , 是 黄 家 驹 旧 日 知 己
baby 长 鹅 口 疮 的 孩 子 怎 么 照 顾 ? 不 要 再 说 拿 他 没 办 法 了 !
discovery 微 重 力 不 需 使 用 肌 肉 , 太 空 人 返 回 地 球 后 脊 椎 旁 肌 肉 萎 缩 约 1 9 %
regimen 这 6 种 人 将 来 会 得 老 年 痴 呆 ! 预 防 老 年 痴 呆 症 , 这 些 办 法 被 全 世 界 公 认
society 2 0 1 6 年 上 海 即 将 发 生 哪 些 大 事 件 。 。 。 。
car 北 汽 自 主 品 牌 亏 损 3 3 . 4 1 亿 额 外 促 销 成 主 因
car 在 那 山 的 那 边 海 的 那 边 , 有 一 群 自 由 侠
history 一 个 小 城 就 屠 杀 了 4 0 0 0 苏 军 战 俘 , 希 特 勒 死 神 战 队 的 崛 起 与 覆 灭
baby 给 孩 子 洗 澡 时 , 这 些 部 位 再 脏 也 不 要 碰 !
essay 好 久 不 见 , 你 还 好 么
baby 被 娃 误 伤 的 9 种 痛 , 数 一 数 你 中 了 几 枪 ?
food 初 秋 的 小 炖 品 放 冰 糖 就 比 较 滋 润 , 放 红 糖 就 补 血 又 不 燥 热
game 佩 服 佩 服 ! 羊 驼 D e f t 单 排 重 回 韩 服 最 强 王 者 第 一 名 !
game 三 个 时 代 的 标 志 炉 石 传 说 三 大 远 古 毒 瘤 卡 组
discovery 2 0 世 纪 最 伟 大 科 学 发 现 — — 魔 术 般 的 超 导 材 料 !
|
{
"pile_set_name": "Github"
}
|
* Покращено кнопки та статус оновлення
* Перероблено налаштування, нові елементи керування використанням даних
* Покращено роботу АКБ на Android 5.0+
* Поділитися пунктом меню сховища
* Вимкніть звіти про збої в налаштуваннях
* Можливість перегляду історії, коли ввімкнено ведення журналу
* Можна натиснути на список небажаних функцій, додано NoSourceSince
* Підтримка Android 4.0+
* Вдосконалено налаштування версій F-Droid
* Можна надсилати дані зневадження версій+UUID під час завантажень
|
{
"pile_set_name": "Github"
}
|
menu:
docs: Документация
api: API
news: Новости
plugins: Плагины
themes: Темы
about: About
search: Поиск
index:
get_started: Начнём
theme_intro: Choose from a huge library of spectacular, feature-packed and customizable themes. Create your own using any compatible template engines.
theme_link: Explore themes
page:
contents: Содержание
back_to_top: Наверх
improve: Предложить улучшение
prev: Пред
next: След
last_updated: "Последнее обновление: %s"
sidebar:
docs:
getting_started: Начало работы
overview: Обзор
setup: Установка
configuration: Конфигурация
commands: Команды
migration: Миграция
basic_usage: Основы
writing: Написание
front_matter: Шапка файла
tag_plugins: Плагины тегов
asset_folders: Папки с материалами
data_files: Файлы с данными
server: Сервер
generating: Генерация
deployment: Публикация
github_pages: GitHub Pages
gitlab_pages: GitLab Pages
one_command_deployment: Размещение одной командой
customization: Кастомизация
permalinks: Постоянные ссылки
themes: Темы
structure: Структура
templates: Шаблоны
variables: Переменные
helpers: Помощники
internationalization: Интернационализация (i18n)
syntax_highlight: Syntax Highlight
plugins: Плагины
miscellaneous: Разное
troubleshooting: Решение проблем
contributing: Содействие
api:
core: Ядро
overview: Обзор
events: События
locals: Переменные
router: Маршруты
box: Модуль
rendering: Рендеринг
posts: Посты
scaffolds: Заготовки
themes: Темы
extensions: Расширения
console: Консоль
deployer: Инструмент размещения
filter: Фильтр
generator: Генератор
helper: Помошник
injector: Injector
migrator: Мигратор
processor: Обработчик
renderer: Рендер
tag: Тег
|
{
"pile_set_name": "Github"
}
|
# Использование с React
Для начала стоит подчеркнуть, что Redux не имеет отношения к React. Вы можете создавать Redux-приложения c помощью React, Angular, Ember, jQuery или обычного JavaScript.
И все-таки, Redux работает особенно хорошо с такими фреймворками, как [React](http://facebook.github.io/react/) и [Deku](https://github.com/dekujs/deku), потому что они позволяют вам описать UI как функцию состояния, и, кроме того, Redux умеет менять состояние (state) приложения в ответ на произошедшие экшены (actions).
Мы будем использовать React для создания нашего простого приложения todo и рассмотрим основы использования React с Redux.
> **Примечание**: смотрите **официальную документацию React-Redux на https://react-redux.js.org** для полного руководства о том, как использовать Redux и React вместе.
## Установка React Redux
[React bindings](https://github.com/reactjs/react-redux) не включены в redux по умолчанию. Вам нужно установить их явно:
```
npm install --save react-redux
```
Если вы не используете npm, то можете взять последнюю UMD-сборку из unpkg ([development](https://unpkg.com/react-redux@latest/dist/react-redux.js) или [production](https://unpkg.com/react-redux@latest/dist/react-redux.min.js)). Добавив UMD-сборку на страницу при помощи тега `<script>`, вы получите глобальный `window.ReactRedux`.
## Презентационные компоненты и компоненты-контейнеры (Presentational and Container Components)
React байндинг для Redux отделяют _презентационные_ компоненты от _компонент-контейнеров_ Такой подход может облегчить понимание вашего приложения и упростить повторное использование компонентов. Вот краткое изложение различий между презентационными и контейнерными компонентами (но если вы незнакомы, мы рекомендуем вам также прочитать [оригинальную статью Дэна Абрамова, описывающую концепцию презентационных и контейнерных компонентов](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)):
<table>
<thead>
<tr>
<th></th>
<th scope="col" style="text-align:left" width="36%">Компоненты-представления</th>
<th scope="col" style="text-align:left" width="41%">Компоненты-контейнеры</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" style="text-align:right">Назначение</th>
<td>Как выглядит (разметка, стили)</td>
<td>Как работает (загрузка данных, обновление состояния)</td>
</tr>
<tr>
<th scope="row" style="text-align:right">Знают о Redux</th>
<td>Нет</th>
<td>Да</th>
</tr>
<tr>
<th scope="row" style="text-align:right">Читают данные</th>
<td>Читают данные из props</td>
<td>Подписываются на Redux-состояние</td>
</tr>
<tr>
<th scope="row" style="text-align:right">Изменяют данные</th>
<td>Вызывают колбеки из props</td>
<td>Отправляют Redux-экшены</td>
</tr>
<tr>
<th scope="row" style="text-align:right">Написаны</th>
<td>Руками</td>
<td>Обычно генерируются React Redux</td>
</tr>
</tbody>
</table>
Большинство компонентов, которые мы напишем, будут представлениями, но чтобы соединить их с Redux-состоянием, нам потребуется сгенерировать несколько контейнеров. Это и дальнейшее описание не означает, что компоненты-контейнеры должны быть расположены ближе к вершине дерева компонентов. Если компонент-контейнер становится слишком сложным, т.е. он имеет сильную вложенность презентационных компонентов, с бесчисленным количеством обратных вызовов, передающихся вниз, используйте еще один контейнер в дереве компонентов, как отмечено в [FAQ](../faq/ReactRedux.md#react-multiple-components).
Технически, вы можете написать контейнеры вручную, используя [`store.subscribe()`](../api/Store.md#subscribe). Мы не советуем вам это делать, потому что React Redux производит много оптимизаций производительности, которые было бы трудно написать руками. По этой причине, вместо того чтобы писать контейнеры, мы генерируем их, воспользовавшись функцией [`connect()`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options), предоставленной React Redux, об этом ниже.
## Проектирование иерархии компонентов
Помните, как мы [спроектировали структуру корневого объекта состояния](Reducers.md)? В этот раз мы спроектируем иерархию UI-компонентов, которая будет соответствовать этой структуре. С такого рода задачей Вы можете столкнуться, разрабатывая и не Redux-приложение. [Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html) — великолепное руководство, которое поясняет весь процесс решения этой задачи.
Наш бриф довольно прост. Мы хотим показать список дел (todo). По клику мы должны зачеркнуть дело, что будет означать, что оно выполнено. Также мы хотим показать поле ввода, с помощью которого пользователь сможет добавить новое дело в список. В футере должны быть переключатели, с помощью которых мы будем показывать все дела, только завершенные, только не завершенные.
### Разработка презентационных компонентов
Из этого брифа получаются следующие представления и их props:
* **`TodoList`** — список, показывающий видимые todos.
- `todos: Array` — массив todo-объектов, имеющих форму `{ id, text, completed }`.
- `onTodoClick(id: number)` — колбек, который будет вызван при клике на todo.
* **`Todo`** — отдельный todo.
- `text: string` — текст для отображения.
- `completed: boolean` — должен ли todo показываться зачеркнутым.
- `onClick()` — колбек, который будет вызван при клике на todo.
* **`Link`** — ссылка с колбеком.
- `onClick()` — колбек, который будет вызван при клике на ссылку.
* **`Footer`** — область, где мы позволим пользователю менять текущую видимость todos.
* **`App`** — корневой компонент, который рендерит все остальное.
Они описывают *вид*, но не знают *откуда* приходят данные или *как* изменить их. Они только рендерят то, что им дают. Если вы мигрируете с Redux на что-нибудь другое, вы сможете оставить эти компоненты точно такими же. Они не зависят от Redux.
### Проектирование компонент-контейнеров
Нам также потребуются некоторые контейнеры, чтобы соединить представления с Redux. Например, представлению `TodoList` требуется контейнер `VisibleTodoList`, который подписывается на Redux-стор и знает, как применять текущий фильтр видимости. Чтобы изменить фильтр видимости, мы предоставим представлению `FilterLink`, контейнер, который рендерит `Link`, а тот, в свою очередь, отправляет соответствующий экшен при клике:
* **`VisibleTodoList`** — фильтрует todos согласно текущему фильтру видимости и рендерит `TodoList`.
* **`FilterLink`** — получает текущий фильтр видимости и рендерит `Link`.
- `filter: string` — текущий фильтр видимости.
### Проектирование других компонент
Иногда трудно сказать, каким должен быть компонент — представлением или контейнером. Например, иногда форма и функция действительно соединены вместе, как в случае с этим миниатюрным компонентом:
* **`AddTodo`** — инпут с кнопкой "Добавить"
Технически, мы могли бы разделить его на два компонента, но это может быть слишком рано на данном этапе. Вполне допустимо смешивать представление и логику, когда компонент очень маленький. Как только он вырастет, станет более понятно как разделить его, так что мы пока оставим его смешанным.
## Реализуем компоненты
Давайте напишем компоненты! Мы начнем с представлений, так что пока нам не нужно думать о привязке к Redux.
### Компоненты-представления
Это все обычные React-компоненты, поэтому мы не будем изучать их детально. Мы пишем функциональные stateless-компоненты, пока нам не потребуются локальное состояние или lifecycle-методы. Это не значит, что представления *должны быть* функциями, просто так легче. Если/когда вам потребуется добавить локальное состояние, lifecycle-методы или оптимизацию производительности, вы сможете конвертировать их в классы.
#### `components/Todo.js`
```js
import React from 'react'
import PropTypes from 'prop-types'
const Todo = ({ onClick, completed, text }) => (
<li
onClick={onClick}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
)
Todo.propTypes = {
onClick: PropTypes.func.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}
export default Todo
```
#### `components/TodoList.js`
```js
import React from 'react'
import PropTypes from 'prop-types'
import Todo from './Todo'
const TodoList = ({ todos, onTodoClick }) => (
<ul>
{todos.map((todo, index) => (
<Todo key={index} {...todo} onClick={() => onTodoClick(index)} />
))}
</ul>
)
TodoList.propTypes = {
todos: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}).isRequired
).isRequired,
onTodoClick: PropTypes.func.isRequired
}
export default TodoList
```
#### `components/Link.js`
```js
import React from 'react'
import PropTypes from 'prop-types'
const Link = ({ active, children, onClick }) => {
if (active) {
return <span>{children}</span>
}
return (
<a
href=""
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}
Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired
}
export default Link
```
#### `components/Footer.js`
```js
import React from 'react';
import FilterLink from '../containers/FilterLink';
import { VisibilityFilters } from '../actions';
const Footer = () => (
<div>
<span>Show: </span>
<FilterLink filter={VisibilityFilters.SHOW_ALL}>All</FilterLink>
<FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>Active</FilterLink>
<FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>Completed</FilterLink>
</div>
);
export default Footer;
```
#### `components/App.js`
```js
import React from 'react';
import Footer from './Footer';
import AddTodo from '../containers/AddTodo';
import VisibleTodoList from '../containers/VisibleTodoList';
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
);
export default App;
```
### Компоненты-контейнеры
А теперь настало время подключить эти компоненты представления к Redux, создав некоторые компоненты-контейнеры. Технически, контейнер — это просто React-компонент, который использует [`store.subscribe()`](../api/Store.md#subscribe) для чтения части Redux-дерева состояний и поставляет props представлению, которое он рендерит.
Вы можете написать компонент-контейнер вручную, но вместо этого мы предлагаем генерировать контейнеры с помощью библиотечной функции React Redux [`connect()`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options), которая предоставляет много полезных оптимизаций для предотвращения ненужных ре-рендеров. (Одним из результатов этого является то, что вам больше не придется беспокоиться о [React performance suggestion](https://facebook.github.io/react/docs/advanced-performance.html) своей реализации `shouldComponentUpdate`).
Чтобы использовать `connect()`, вам нужно определить специальную функцию `mapStateToProps`, которая говорит, как трансформировать текущее Redux-состояние стора в props, которые вы хотите передать в оборачиваемое (контейнером) представление. Например, `VisibleTodoList` требуется вычислить `todos` для передачи в `TodoList`, так что нам нужно определить функцию, которая фильтрует `state.todos` согласно `state.visibilityFilter`, и использовать ее в `mapStateToProps`:
```js
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed)
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed)
case 'SHOW_ALL':
default:
return todos
}
}
const mapStateToProps = state => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
```
В дополнение к чтению состояния контейнеры могут отправлять экшены (dispatch actions). В похожем стиле вы можете определить функцию `mapDispatchToProps()`, которая получает метод [`dispatch()`](../api/Store.md#dispatch) и возвращает колбек props, который вы можете вставить в представление. Например, мы хотим, чтобы контейнер `VisibleTodoList` вставил prop `onTodoClick` в представление `TodoList` и еще мы хотим, чтобы `onTodoClick` отправлял `TOGGLE_TODO` экшен:
```js
const mapDispatchToProps = dispatch => {
return {
onTodoClick: id => {
dispatch(toggleTodo(id))
}
}
}
```
Наконец, мы создаем `VisibleTodoList`вызывая `connect()` и передал эти две функции:
```js
import { connect } from 'react-redux'
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
export default VisibleTodoList
```
Это основы React Redux API, но там есть несколько комбинаций и мощных опций, поэтому мы рекомендуем вам подробно изучить [эту документацию](https://github.com/reactjs/react-redux). В случае если вы переживаете, что `mapStateToProps` создает слишком много новых объектов, то вам будет полезно узнать о [вычислении полученных данных](../recipes/ComputingDerivedData.md) с [reselect](https://github.com/reactjs/reselect).
Остальные компоненты-контейнеры вы найдете ниже:
#### `containers/FilterLink.js`
```js
import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'
const mapStateToProps = (state, ownProps) => {
return {
active: ownProps.filter === state.visibilityFilter
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
onClick: () => {
dispatch(setVisibilityFilter(ownProps.filter))
}
}
}
const FilterLink = connect(
mapStateToProps,
mapDispatchToProps
)(Link)
export default FilterLink
```
#### `containers/VisibleTodoList.js`
```js
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos
case 'SHOW_COMPLETED':
return todos.filter(t => t.completed)
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed)
}
}
const mapStateToProps = state => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter)
}
}
const mapDispatchToProps = dispatch => {
return {
onTodoClick: id => {
dispatch(toggleTodo(id))
}
}
}
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
export default VisibleTodoList
```
### Другие Компоненты
#### `containers/AddTodo.js`
Напомним, как было [упомянуто ранее ](#designing-other-components) и представление, и логика для компонента `AddTodo` смешаны в одном определении.
```js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form
onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}
>
<input
ref={node => {
input = node
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
export default AddTodo
```
Если вы не знакомы с атрибутом `ref`, прочитайте эту [документацию](https://facebook.github.io/react/docs/refs-and-the-dom.html), чтобы ознакомиться с рекомендуемым использованием этот атрибут.
### Связывание контейнеров внутри компонента
#### `components/App.js`
```js
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
)
export default App
```
## Передаем стор
Всем компонентам-контейнерам необходим доступ к Redux-стору (store), для того чтобы они могли подписаться на него. Как вариант — передать его как prop в каждый контейнер. Однако это становится утомительным, так как вы должны подключать `store`, даже если представления просто рендерят контейнер глубоко в дереве компонентов.
Мы рекомендуем другой вариант — использовать специальный React Redux компонент [`<Provider>`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#provider-store), вызов которого [магически](https://facebook.github.io/react/docs/context.html) делает стор доступным всем контейнерам в приложении без его явной передачи. Вам нужно только воспользоваться им единожды, когда вы рендерите корневой компонент:
#### `index.js`
```js
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './components/App'
const store = createStore(todoApp)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
```
## Следующие шаги
Прочитайте [полный исходный код для этого руководства](ExampleTodoList.md) для лучшего усваивания полученных знаний.
А затем прямиком в [руководство для опытных](../advanced/README.md) для изучения обработки сетевых запросов и роутинга
Вам также нужно потратить некоторое время, чтобы ** [прочитать документы React-Redux](https://react-redux.js.org)**, чтобы получить
лучшее понимание того, как использовать React и Redux вместе.
|
{
"pile_set_name": "Github"
}
|
form=词
tags=
春入番江雨。
满湖山、莺啼燕雨,
前歌後舞。
闻道行骢行且止,
却听谯楼更鼓。
正未卜,
阴晴同否。
老子胸中高小范,
这精神、堪更开封府。
新治足,
旧民苦。
扁舟浩荡乘风去。
看莱衣、思贤堂上,
寿觞朝举。
六十二三前度者,
敢望香山老傅。
又过了、午年端午。
采采菖蒲三三节,
寄我公、矫矫扶天路。
重归衮,
到相圃。
灯共墙檠语。
记昨朝、芒鞋蓑笠,
冷风斜雨。
月入宫槐槐影澹,
化作槐花无数。
恍不记、鳌头压处。
不恨扬州吾不梦,
恨梦中、不醉琼花露。
空耿耿,
吊终古。
千蜂万蝶春为主。
怅何人、老忆江南,
北朝开府。
看取当年风景在,
不待花奴催鼓。
且未说、春丁分俎。
一曲沧浪邀吾和,
笑先生、尚是邯郸步。
如秉苘,
续残炬。
风雨东篱晚。
渺人间、南北东西,
平芜烟远。
旧日携壶吹帽处,
一色沈冥何限。
天不遣、魂销肠断。
不是苦无看山分,
料青山、也自羞人面。
秋後瘦,
老来倦。
惊回昨梦青山转。
恨一林、金粟都空,
静无人见。
默默黄花明朝有,
只待插花寻伴。
又谁笑、今朝蝶怨。
潦倒玉山休重醉,
到簪萸、忍待人频劝。
今又惜,
几人健。
何处从头说。
但倾尊、淋漓醉墨,
疏疏密密。
看取两轮东西者,
也是樊笼中物。
这光景、年来都别。
白发道人隆中像,
笑相逢、对拥炉边雪。
又过了,
上元节。
纸窗旋补寒穿穴。
柳黏窗、青青过雨,
劝君休折。
睡不成酣酒先醒,
花底东风又别。
夜复夜、吟魂飞越。
典却西湖东湖住,
十三年不出今朝出。
容易得,
二三月。
襟泪涔涔雨。
料骚魂、水解千年,
依然轻举。
还看吴儿胥涛上,
高出浪花几许。
绝倒是、东南旗鼓。
风雨蛟龙争何事,
问彩丝、香粽犹存否。
溪女伴,
采莲语。
古人不似今人苦。
漫追谈、少日风流,
三三五五。
谁似鄱阳鸱夷者,
相望怀沙终古。
待唤醒、重听金缕。
尚有远游当年恨,
恨南公、不见秦为楚。
天又暮,
黯凝伫。
锦岸吴船鼓。
问沙鸥、当日沈湘,
是何端午。
长恨青青朱门艾,
结束腰身似虎。
空泪落、婵媛嬃女。
我醉招累清醒否,
算平生、清又醒还误。
累笑我,
醉中语。
黄头舞棹临江处。
向人间、独竞南风,
叫云激楚。
笑倒两崖人如蚁,
不管颓波千屡。
忽惊抱、汨罗无柱。
欸乃渔歌斜阳外,
几书生、能办投湘赋。
歌此恨,
泪如缕。
绝北寒声动。
渺黄昏、叶满长安,
云迷章贡。
最苦周公千年後,
正与莽新同梦。
五十国、纷纷入中。
摇颺都人歌郿坞,
问何如、昨日菘高颂。
胪九锡,
竟谁风。
当初共道擎天重。
奈天教、垓下风寒,
滹沱兵冻。
寂寞放翁南园记,
带得园柑进奉。
怅回首、何人修凤。
寄语权门趋炎者,
这朝廷、不是邦昌宋。
真与赝,
可能共。
拍瓮春醅动。
洞庭霜、压绿堆黄,
林苞堪贡。
况有老人潭边菊,
摇落赏心入梦。
数百岁、半来许中。
儿女牵衣团栾处,
绕公公、愿献生申颂。
公性歰,
待重风。
人生一笑何时重。
奈今朝、有客无鱼,
有鱼留冻。
何似尊前斑斓起,
低唱浅斟齐奉。
也不待、烹龙炰凤。
此会明年知谁健,
说边愁、望断先生宋。
醒最苦,
醉聊共。
破帽吹愁去。
绕郊墟、残灰败壁,
冷烟斜雨。
舞马梦惊城乌起,
散作童妖灶语。
漫说与、谢仙一句。
犹记醉归西州路,
问行人、望望骊烽误。
几未失,
丧公屦。
高高况是兴亡处。
望平沙、落日湖光,
暗淮沈楚。
寂寞西陵歌又舞,
疑冢嵯峨新土。
黯牛笛、参差归路。
试问文君容赊否,
待东篱、更就黄花浦。
拚酩酊,
涴蓝缕。
七十三年矣。
记小人、四百四十,
五番甲子。
看到蓬莱水清浅,
休说树犹日如此。
但梦梦、昨非今是。
一曲尊前离鸾操,
抚铜仙、清泪如铅水。
歌未断,
我先醉。
新来画得耆英似。
似灞桥、风雪吟肩,
水仙梅弟。
里巷依稀灵光在,
飞过劫灰如洗。
笑少伴、乌衣馀几。
老子平生何曾默,
暮年诗、句句皆成史。
个亥字,
甲申起。
秋老寒香圃。
自春来、桔槔闲了,
去天尺五。
陌上踏歌来何暮,
收得黄云如土。
但稽首、福星初度。
不是使君人间佛,
甚今朝、欲雨今朝雨。
持寿酒,
为公舞。
虎头画手谁甚许。
写天人、方瞳红颊,
共宾笑语。
卫戟连营三千士,
簇簇满城箫鼓。
早恐是、留公不住。
飞去翩翩嫌白鹭,
算来年、稀姓多登府。
祝千岁,
奉明主。
少日都门路。
听长亭、青山落日,
不如归去。
十八年间来往断,
白首人间今古。
又惊绝、五更一句。
道是流离蜀天子,
甚当初、一似吴儿语。
臣再拜,
泪如雨。
画堂客馆真无数。
记画桥、黄竹歌声,
桃花前度。
风雨断魂苏季子,
春梦家山何处。
谁不愿、封侯万户。
寂暮江南轮四角,
问长安、道上无人住。
啼尽血,
向谁诉。
世事如何说。
似举鞍、回头笑问,
并州儿葛。
手障尘埃黄花路,
千里龙沙如雪。
著破帽、萧萧馀发。
行过故人柴桑里,
抚长松、老倒山间月。
聊共舞,
命相瑟。
春风五老多年别。
看使君、神交意气,
依然晚合。
袖有玉龙提携去,
满眼黄金台骨。
说不尽、古人痴绝。
我醉看天天看我,
听秋风、吹动檐间铁。
长啸起,
两山裂。
岁事峥嵘甚。
是当年、爆竹驱傩,
插金幡胜。
忽晓阑街儿童语,
不为上元
|
{
"pile_set_name": "Github"
}
|
Plugins.Animation.Frames
========================
Класс, который используется для "нарезки" картинок из одной тайловой картинки.
Обычно кадры анимации похожи между собой и имеет смысл множество их собрать в одно изображение подобно технологии css-sprites.
Допустим, у вас ширина кадра анимации 50 пикселей, высота - 40, 15 кадров. Вы можете нарисовать их в три ряда в картинке размером 250*120.

### Инициализация
```js
new Animation.Frames( Image image, int width = null, int height = null )
```
* `image` (*Image*) - картинка-источник для нарезки
* `width` (*int*) - ширина кадра. Равен ширине картинки, если `null`
* `height` (*int*) - высота кадра. Равен высоте картинки, если `null`
```js
var frames = new Animation.Frames( images.get('ship'), 100 );
```
### Методы
`get length` - количество кадров в массиве
```js
console.log( frames.length );
```
#### get
```js
canvasElement get( int index );
```
Возвращает картинку-кадр, часть исходной картинки.
```js
var frame = frames.get( 5 );
```
|
{
"pile_set_name": "Github"
}
|
/* Taxonomy Classification: 0000300602130000031110 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 3 inter-file/inter-proc
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 6 N/A
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 2 constant
* ADDRESS ALIAS 1 yes, one level
* INDEX ALIAS 3 N/A
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 0 no
* LOOP COMPLEXITY 0 N/A
* ASYNCHRONY 0 no
* TAINT 3 file read
* RUNTIME ENV. DEPENDENCE 1 yes
* MAGNITUDE 1 1 byte
* CONTINUOUS/DISCRETE 1 continuous
* SIGNEDNESS 0 no
*/
/*
Copyright 2004 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.
*/
#include <assert.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE * f;
char buf[10];
f = fopen("TestInputFile1", "r");
assert(f != NULL);
/* BAD */
fgets(buf, 11, f);
fclose(f);
return 0;
}
|
{
"pile_set_name": "Github"
}
|
{
"General": {
"12HourClock": "12-часовой формат времени",
"24HourClock": "24-часовой формат времени",
"AbandonedCarts": "Нереализованные покупки",
"AboutPiwikX": "О Matomo %s",
"Action": "Действие",
"Actions": "Действия",
"Add": "Добавить",
"AfterEntry": "после захода сюда",
"All": "Все",
"AllowPiwikArchivingToTriggerBrowser": "Архив отчетов при просмотре в браузере",
"AllWebsitesDashboard": "Статистика всех сайтов",
"And": "и",
"API": "API",
"Apply": "Применить",
"ArchivingInlineHelp": "Для сайтов со средней или высокой нагрузкой рекомендуется отменить архивирование данных при входе в веб-аналитику через браузер. Вместо этого лучше назначить cron-задачу, чтобы Matomo автоматически формировал отчеты каждый час.",
"ArchivingTriggerDescription": "Для сайтов с высокой нагрузкой настоятельно рекомендуется %1$sназначить cron-задачу%2$s, которая будет формировать отчеты автоматически.",
"AuthenticationMethodSmtp": "Метод аутентификации для SMTP",
"AverageOrderValue": "Средняя стоимость заказа",
"AveragePrice": "Средняя цена",
"AverageQuantity": "Среднее количество",
"AverageX": "Ср. %s",
"BackToPiwik": "Вернуться к Matomo",
"Broken": "Сломалось",
"BrokenDownReportDocumentation": "Он разбит на различные отчёты, которые отображаются в виде спарклайнов внизу страницы. Вы можете увеличить графики обычным кликом по ним.",
"Cancel": "Отмена",
"CannotUnzipFile": "Не могу распаковать файл %1$s: %2$s",
"ChangePassword": "Изменить пароль",
"ChangeTagCloudView": "Учтите, что Вы можете просматривать отчёт не только через облако тегов. Используйте элементы управления внизу отчёта для переключения вариантов просмотра.",
"ChooseDate": "Выбор даты, сейчас выбрана дата %s",
"ChooseLanguage": "Выбрать язык",
"ChoosePeriod": "Выбрать период",
"ClickHere": "Нажмите здесь для получения дополнительной информации.",
"DoubleClickToChangePeriod": "Нажмите два раза, что бы применить текущий период.",
"Close": "Закрыть",
"ClickToSearch": "Нажмите для поиска",
"Copy": "Скопировать",
"Confirm": "Подтвердить",
"ColumnActionsPerVisit": "Действия за посещение",
"ColumnActionsPerVisitDocumentation": "Среднее количество действий (просмотры страниц, загрузки или внешние ссылки), которое было выполнено во время визитов.",
"ColumnAverageGenerationTime": "Среднее время генерации страницы",
"ColumnViewsWithGenerationTime": "Просмотры страниц с временем генерации",
"ColumnAverageGenerationTimeDocumentation": "Среднее время, затраченное на генерацию страницы. Этот показатель включает в себя время, затраченное сервером для генерации веб-страницы, а также время, которое потребовалось для посетителей, чтобы скачать ответ от сервера. Маленькое значение показателя 'Среднее время генерации' означает более быстрый веб-сайт для ваших посетителей!",
"ColumnAverageTimeOnPage": "Среднее время просмотра страницы",
"ColumnAverageTimeOnPageDocumentation": "Общее время, которое посетители провели на данной странице (только на странице, а не на всем сайте).",
"ColumnAvgTimeOnSite": "Среднее время на сайте",
"ColumnSumTimeOnSite": "Общее время на сайте",
"ColumnAvgTimeOnSiteDocumentation": "Средняя длительность посещения.",
"ColumnBounceRate": "Показатель отказов",
"ColumnBounceRateDocumentation": "Процент визитов, которые имели только один просмотр страницы. Это означает, что пользователь покинул сайт сразу со стартовой страницы.",
"ColumnBounces": "Отказы",
"RealTime": "Реальное время",
"ColumnBouncesDocumentation": "Число посещений, которые начались и закончились на этой странице. Это значит, что посетитель покинул сайт после просмотра только одной страницы.",
"ColumnConversionRate": "Конверсия",
"ColumnConversionRateDocumentation": "Процент посещений, которые внесли вклад в конверсию целей.",
"ColumnDestinationPage": "Страница назначения",
"ColumnEntrances": "Входы на сайт",
"ColumnEntrancesDocumentation": "Число посещений, который начались с этой страницы.",
"ColumnExitRate": "Процент выходов",
"ColumnExitRateDocumentation": "Процент посещений, которые закончились после просмотра данной страницы.",
"ColumnExits": "Выходы из сайта",
"ColumnExitsDocumentation": "Число посещений, которые закончились этой страницей.",
"ColumnGenerationTime": "Время генерации",
"ColumnPageGenerationTime": "Время генерации страницы",
"ColumnKeyword": "Ключевое слово",
"ColumnLabel": "Обозначение",
"ColumnHits": "Хиты",
"ColumnMaxActions": "Макс. действий за одно посещение",
"ColumnNbActions": "Действия",
"ColumnNbActionsDocumentation": "Количество действий, выполненных вашими пользователями. К событиям относятся просмотры страниц, загрузки и внешние ссылки.",
"ColumnNbUniqVisitors": "Уникальные посетители",
"ColumnNbUniqVisitorsDocumentation": "Число неповторяющихся посетителей, приходящих на ваш на ваш веб-сайт. Каждый пользователь засчитывается только один раз, даже если они посещают веб-сайт несколько раз в день.",
"ColumnNbUsers": "Пользователи",
"ColumnNbUsersDocumentation": "Число пользователей logged на вашем Веб-сайте. Это число уникальных пользователей для которых установлен User ID (с помощью функции Tracking-кода 'setUserId').",
"ColumnNbVisits": "Посещения",
"ColumnNbVisitsDocumentation": "Если посетитель приходит на ваш веб-сайт впервые, или если они посещают страницу спустя 30 минут и более с момента их последнего просмотра страницы, это будет как новое посещение.",
"ColumnPageBounceRateDocumentation": "Процент посещений, которые начались на этой странице и сразу же закончились (посетитель ушел на другой сайт или закрыл вкладку).",
"ColumnPageviews": "Просмотры страниц",
"ColumnPageviewsDocumentation": "Количество просмотров этой страницы.",
"ColumnPercentageVisits": "%% Посещений",
"ColumnRevenue": "Прибыль",
"ColumnSumVisitLength": "Общее время, проведенное посетителями (в секундах)",
"ColumnTotalPageviews": "Всего просмотров страниц",
"ColumnUniqueEntrances": "Уникальные входы",
"ColumnUniqueExits": "Уникальные выходы",
"ColumnUniquePageviews": "Уникальные просмотры страниц",
"ColumnUniquePageviewsDocumentation": "Число посещений, которые включали также эту страницу. Если страница была просмотрена одним пользователем несколько раз, это засчитывается как одно посещение страницы.",
"ColumnValuePerVisit": "Стоимость визита",
"ColumnViewedAfterSearch": "Кликнули по результату в поиске",
"ColumnViewedAfterSearchDocumentation": "Число раз, когда посетители посещали эту страницу после того, как они пользовались поиском на вашем сайте и кликнули по найденной странице.",
"ColumnVisitDuration": "Продолжительность посещения (секунд)",
"ColumnVisitsWithConversions": "Повторные посещения",
"ComputedMetricAverage": "Ср. %1$s для %2$s",
"ComputedMetricAverageDocumentation": "Среднее значение «%1$s» для «%2$s»",
"ComputedMetricAverageShortDocumentation": "Среднее значение для «%1$s».",
"ComputedMetricRate": "%s Ставка",
"ComputedMetricRateDocumentation": "Соотношение «%1$s» из «%2$s».",
"ComputedMetricRateShortDocumentation": "Процент «%1$s».",
"ComputedMetricCountDocumentation": "Число %s",
"ComputedMetricSum": "Всего %s",
"ComputedMetricSumDocumentation": "Общее количество (сумма) %s",
"ComputedMetricMax": "Максимум %s",
"ComputedMetricMaxDocumentation": "Максимальное значение для %s",
"ComputedMetricMin": "Минимум %s",
"ComputedMetricMinDocumentation": "Минимальное значение для %s",
"ComputedMetricUniqueCount": "Уникальных %s",
"ComputedMetricUniqueCountDocumentation": "Уникальное число для %s",
"ComputedMetricCountWithValue": "Вхождений %s",
"ComputedMetricCountWithValueDocumentation": "Количество вхождений, для которых установлено значение %s",
"ConfigFileIsNotWritable": "Файл конфигурации Matomo %1$s закрыт для записи, ваши изменения не будут сохранены. %2$s Пожалуйста, измените разрешения конфигурационного файла и разрешите запись в него.",
"Continue": "Продолжить",
"ContinueToPiwik": "Перейти к Matomo",
"CurrentlyUsingUnsecureHttp": "Сейчас вы используете Matomo через незащищённое соединение. Это делает Matomo уязвимым к разного рода эксплойтам. Некоторые функции (напр., файлы cookies) могут не работать. Мы рекомендуем настроить Matomo с использованием защищённого соединения для большей безопасности.",
"CreationDate": "Дата создания",
"CreatedByUser": "сделано %s",
"CurrentMonth": "Текущий месяц",
"CurrentWeek": "Текущая неделя",
"CurrentYear": "Текущий год",
"Daily": "Ежедневно",
"DailyReport": "ежедневно",
"DailyReports": "Ежедневные отчеты",
"DailySum": "сумма за день",
"DashboardForASpecificWebsite": "Сводная статистика для отдельного сайта",
"DataForThisGraphHasBeenPurged": "Данные для этого графика, которые старше чем %s месяцев и были очищены.",
"DataForThisTagCloudHasBeenPurged": "Данные для этого облака тегов, которые старше чем %s месяцев и были очищены.",
"Date": "Дата",
"DateRange": "Диапазон дат:",
"DateRangeFrom": "С",
"DateRangeFromTo": "С %1$s по %2$s",
"DateRangeInPeriodList": "диапазон дат:",
"DateRangeTo": "До",
"DaysHours": "%1$s дн. %2$s час",
"DaysSinceFirstVisit": "Дней с момента первого посещения",
"DaysSinceLastEcommerceOrder": "Дней с момента последнего электронного заказа.",
"DaysSinceLastVisit": "Дней прошло с момента последнего посещения",
"Default": "По умолчанию",
"DefaultAppended": "(по умолчанию)",
"Delete": "Удалить",
"Description": "Описание",
"Desktop": "Desktop-приложение",
"Details": "Детали",
"Discount": "Скидки",
"DisplaySimpleTable": "Показать пример таблицы",
"DisplayTableWithGoalMetrics": "Показать таблицу с метрикой целей",
"DisplayTableWithMoreMetrics": "Показать таблицу с большим объемом метрики",
"Documentation": "Документация",
"Donate": "Пожертвовать",
"Done": "Завершено",
"Download": "Скачать",
"DownloadFail_FileExists": "Файл %s уже существует!",
"DownloadFail_FileExistsContinue": "Пытаюсь продолжить скачивание %s, но полностью скаченный файл уже существует!",
"DownloadFail_HttpRequestFail": "Не удалось загрузить файл! Что-то может быть не так с сайтом откуда вы скачиваете. Вы можете попробовать попозже или получить файл самостоятельно.",
"DownloadFullVersion": "%1$sСкачайте%2$s полную версию! Смотрите здесь: %3$s",
"DownloadPleaseRemoveExisting": "Если вы хотите его заменить, пожалуйста, удалите существующий файл.",
"Downloads": "Загрузки",
"EcommerceOrders": "Заказы",
"EcommerceVisitStatusDesc": "Статус посещения \"Электронной коммерции\" на конец посещения",
"EcommerceVisitStatusEg": "Например, чтобы выбрать все посещения, когда был совершен электронный заказ, API-запрос будет содержать: %s",
"Edit": "Редактировать",
"EncryptedSmtpTransport": "Выберите тип шифрования транспортном уровне, требуемое вашим SMTP сервером.",
"Error": "Ошибка",
"Errors": "Ошибки",
"ErrorRequest": "Ой... возникла проблема во время выполнения запроса. Возможно причиной тому временная проблема на сервере, или Вами был запрошен отчет, содержащий большой объем данных. Пожалуйста, повторите попытку. Если ошибка повторяется, пожалуйста %1$sсвяжитесь с администратором Matomo%2$s.",
"EvolutionOverPeriod": "Изменения за период",
"EvolutionSummaryGeneric": "%1$s в %2$s по сравнению с %3$s в %4$s. Изменения: %5$s",
"ExceptionContactSupportGeneric": "Если вы продолжаете получать эту ошибку, пожалуйста, %1$sобратитесь к администратору Matomo%2$s за помощью.",
"ExceptionCheckUserHasSuperUserAccessOrIsTheUser": "Пользователь должен быть либо суперпользователем, либо пользователем «%s».",
"ExceptionConfigurationFileNotFound": "Конфигурационный файл {%s} не может быть найден.",
"ExceptionConfigurationFileExistsButNotReadable": "Файл конфигурации %s, похоже, существует, но Matomo не смог его прочитать.",
"ExceptionConfigurationFilePleaseCheckReadableByUser": "Пожалуйста, проверьте, что %1$s читается пользователем «%2$s».",
"ExceptionDatabaseVersion": "Версия вашего %1$s — %2$s, но Matomo требует хотя бы %3$s.",
"ExceptionDatabaseVersionNewerThanCodebase": "Исполняемые файлы Matomo устаревшей версии %1$s, а база данных Matomo уже обновлена до новой версии %2$s.",
"ExceptionDatabaseVersionNewerThanCodebaseWait": "Возможно Ваш Matomo-администратор только что закончил процесс обновления. Попробуйте повторить позже.",
"ExceptionFileIntegrity": "Проверка целостности не удалась: %s",
"ExceptionFilesizeMismatch": "Размер файла не совпадает: %1$s (ожидался: %2$s, обнаружен: %3$s)",
"ExceptionIncompatibleClientServerVersions": "Версия %1$s вашего клиента — %2$s, она не совместима с сервером версии %3$s.",
"ExceptionInvalidAggregateReportsFormat": "Определение формата отчётов «%1$s» неверно. Попробуйте любое из следующих действий: %2$s.",
"ExceptionInvalidArchiveTimeToLive": "Время архивирования (в секундах) должно быть больше нуля",
"ExceptionInvalidDateFormat": "Формат даты должен быть: %1$s или любое другое ключевое слово, поддерживаемое функцией %2$s (см. %3$s, чтобы узнать больше)",
"ExceptionInvalidDateBeforeFirstWebsite": "Дата «%1$s» — это дата до того, как первый сайт был в сети. Попробуйте дату после %2$s (отметка времени %3$s).",
"ExceptionInvalidDateRange": "Дата «%1$s» не входит в корректный промежуток. Она должна быть следующего формата: %2$s.",
"ExceptionInvalidPeriod": "Период «%1$s» не поддерживается. Попробуйте вместо него другой из доступных: %2$s",
"ExceptionInvalidRendererFormat": "Формат рендерера «%1$s» неверен. Попробуйте вместо него другой из доступных: %2$s.",
"ExceptionInvalidReportRendererFormat": "Формат отчёта «%1$s» неверен. Попробуйте вместо него другой из доступных: %2$s.",
"ExceptionInvalidStaticGraphType": "Тип статичного графика «%1$s» неверен. Попробуйте любое из следующих действий: %2$s.",
"ExceptionInvalidToken": "Токен неверен.",
"ExceptionLanguageFileNotFound": "Файл языка «%s» не найден.",
"ExceptionMethodNotFound": "Метод «%1$s» не существует или недоступен в модуле «%2$s».",
"ExceptionMissingFile": "Отсутствует файл: %s",
"ExceptionUnexpectedFile": "В вашем Matomo были найдены файлы, но мы не ожидали их.",
"ExceptionUnexpectedFilePleaseDelete": "Пожалуйста, удалите эти файлы, чтобы избежать ошибок.",
"ExceptionUnexpectedDirectory": "В вашем Matomo были найдены директории, но мы не ожидали их.",
"ExceptionUnexpectedDirectoryPleaseDelete": "Пожалуйста, удалите эти директории, чтобы избежать ошибок.",
"ExceptionFileToDelete": "Файл для удаления: %s",
"ExceptionDirectoryToDelete": "Директория для удаления: %s",
"ExceptionNonceMismatch": "Не могу проверить элемент безопасности для этой формы.",
"ExceptionPrivilege": "Вы не можете получить доступ к этому ресурсу, так как он требует прав %s.",
"ExceptionPrivilegeAccessWebsite": "Вы не можете получить доступ к этому ресурсу, так как он требует прав %s к сайту id = %d.",
"ExceptionCapabilityAccessWebsite": "Вы не можете получить доступ к этому ресурсу, так как он требует прав %s для сайта id = %d.",
"ExceptionPrivilegeAtLeastOneWebsite": "Вы не можете получить доступ к этому ресурсу, так как он требует прав %s по крайней мере для одного веб-сайта.",
"ExceptionUnableToStartSession": "Не удалось запустить сессию.",
"ExceptionUndeletableFile": "Невозможно удалить %s",
"ExceptionUnreadableFileDisabledMethod": "Конфигурационный файл {%1$s} не может быть прочтен. Возможно, на вашем хосте отключен %2$s.",
"ExceptionReportNotFound": "Запрашиваемый отчёт не существует.",
"ExceptionWidgetNotFound": "Запрашиваемый виджет не существует.",
"ExceptionReportNotEnabled": "Запрошенный отчёт не включен. Это означает, как правило, что либо выключен плагин, который определяет этот отчёт, либо нет прав доступа к этому отчёту.",
"ExceptionWidgetNotEnabled": "Запрошенный виджет не включен. Как правило это означает либо плагин, который определяет виджет деактивирован, либо вы не имеете достаточно прав доступа к этому виджет.",
"ExpandDataTableFooter": "Изменить визуализацию или настроить отчёт",
"Export": "Экспорт",
"ExportAsImage": "Экспортировать как изображение",
"ExportThisReport": "Экспортировать в другие форматы",
"Faq": "FAQ",
"FileIntegrityWarning": "Проверка целостности файлов завершилась неудачей и возвратила ошибки. Вам следует исправлять проблему и обновлять страницу до тех пор, пока она не отобразится без ошибок.",
"FileIntegrityWarningReupload": "Ошибки ниже могут быть обусловлены частичной или неудавшейся загрузкой файлов Matomo.",
"FileIntegrityWarningReuploadBis": "Попробуйте заново загрузить все файлы Matomo в режиме BINARY.",
"First": "Первый",
"Flatten": "Сгладить",
"ForcedSSL": "Принудительное SSL-соединение",
"ForceSSLRecommended": "Мы рекомендуем использовать Matomo только через безопасные SSL-соединения. Чтобы предотвратить небезопасный доступ через http, добавьте %1$s в разделе %2$s в вашем Matomo файле config\/config.ini.php.",
"NotPossibleWithoutHttps": "Внимание: выполнение этого без настройки SSL-сертификата для использования HTTPS приведет к поломке Matomo.",
"UseSSLInstall": "Мы рекомендуем использовать Matomo только через безопасные SSL-соединения. Пожалуйста, %1$sнажмите здесь, чтобы продолжить процесс установки через SSL%2$s.",
"ForExampleShort": "напр.,",
"Forums": "Форумы",
"FromReferrer": "источник",
"Generic": "Общий",
"GeneralInformation": "Общая информация",
"GeneralSettings": "Общие настройки",
"GetStarted": "Приступить",
"GiveUsYourFeedback": "Оставьте нам отзыв!",
"Goal": "Цель",
"GoTo": "Перейти к %s",
"GoTo2": "Перейти",
"GraphHelp": "Больше информации про отображение графиков в Matomo.",
"HelloUser": "Привет, %s!",
"Help": "Помощь",
"HelpResources": "Справочные ресурсы",
"HelpTranslatePiwik": "Возможно, вы захотите %1$sпомочь нам улучшить переводы в Matomo%2$s?",
"Hide": "скрыть",
"HoursMinutes": "%1$s час %2$s мин",
"Id": "Id",
"IfArchivingIsFastYouCanSetupCronRunMoreOften": "Предполагая, что архивирование выполняется быстро, вы можете настроить crontab для более частой работы.",
"InfoFor": "Информация для %s",
"Installed": "Установлено",
"InvalidDateRange": "Неверный период, пожалуйста, попробуйте снова",
"InvalidResponse": "Полученные данные некорректны.",
"IP": "IP",
"JsTrackingTag": "JavaScript Tracking-код",
"KpiMetric": "KPI Метрика",
"Language": "Язык",
"Languages": "Языки",
"LastDays": "Прошедшие %s дни (включая сегодня)",
"LastDaysShort": "%s последних дней",
"LearnMore": "%1$s узнайте больше %2$s",
"Live": "Прямой эфир",
"Loading": "Загрузка...",
"LoadingData": "Загрузка данных...",
"LoadingPopover": "Загрузка %s...",
"LoadingPopoverFor": "Загрузка %s для",
"Locale": "ru_RU.UTF-8",
"Logout": "Выйти",
"MainMetrics": "Основные показатели",
"Matches": "Совпадений",
"MediumToHighTrafficItIsRecommendedTo": "Для сайтов со средней или высокой нагрузкой мы рекомендуем формировать отчеты за сегодняшний день каждые полчаса (%1$s сек) или каждый час (%2$s сек).",
"Metadata": "Метаданные",
"Metric": "Показатель",
"Metrics": "Показатели",
"MetricsToPlot": "Метрики для построения графика",
"MetricToPlot": "Метрика для построения графика",
"MinutesSeconds": "%1$s мин %2$s сек",
"Mobile": "Мобильное приложение",
"Monthly": "Ежемесячно",
"MonthlyReport": "ежемесячно",
"MonthlyReports": "Ежемесячные отчеты",
"More": "Ещё",
"MoreDetails": "Детализация",
"MoreLowerCase": "ещё",
"MultiSitesSummary": "Все проекты",
"Name": "Имя",
"NbActions": "Количество действий",
"NbInteractions": "Количество взаимодействий",
"NbSearches": "Количество обращений к внутреннему поиску",
"NeedMoreHelp": "Нужна помощь?",
"Never": "Никогда",
"New": "Новое",
"NewReportsWillBeProcessedByCron": "Если архивирование Matomo не провоцируется браузером, новые отчеты производятся с помощью crontab-задач.",
"NewUpdatePiwikX": "Новое обновление: Matomo %s",
"NewVisitor": "Новый посетитель",
"NewVisits": "Новые посещения",
"Next": "Далее",
"No": "Нет",
"NoDataForGraph": "Нет данных для построения графика.",
"NoDataForTagCloud": "Нет данных по этим тегам",
"NotDefined": "%s не определено",
"Note": "Заметка",
"NotInstalled": "Не установлено",
"NotRecommended": "не рекомендуется",
"NotValid": "%s неверный",
"NumberOfVisits": "Количество посещений",
"NUsers": "%s пользователей",
"NVisits": "%s посещений",
"NUniqueVisitors": "%s уникальных посетителей",
"Ok": "ОК",
"OneAction": "1 действие",
"OneVisit": "1 посещение",
"OnlyEnterIfRequired": "Введите имя пользователя, если ваш SMTP сервер требует этого.",
"OnlyEnterIfRequiredPassword": "Введите пароль, если ваш SMTP сервер требует этого.",
"SmtpFromEmailHelp": "По умолчанию noreply@{DOMAIN}, где {DOMAIN} будет заменено на значение вашего домена Matomo.%1$s<br> Если отправка писем не работает, вам может понадобиться установить этот адрес, совпадающий с вашим пользователем SMTP.",
"NameShownInTheSenderColumn": "Имя, отображаемое в поле отправителя",
"OnlyUsedIfUserPwdIsSet": "Используется если имя пользователя\/пароль заданы, спросите у своего провайдера, если не уверены в выборе метода.",
"OpenSourceWebAnalytics": "открытая\/свободная аналитическая платформа",
"OperationAtLeast": "Не менее",
"OperationAtMost": "Не более",
"OperationContains": "Содержит",
"OperationDoesNotContain": "Не содержит",
"OperationEquals": "равно",
"OperationGreaterThan": "Больше чем",
"OperationIs": "Есть",
"OperationIsNot": "Не",
"OperationLessThan": "Меньше чем",
"OperationNotEquals": "Не равно",
"OperationStartsWith": "Начинается с",
"OperationEndsWith": "Заканчивается с",
"OptionalSmtpPort": "Необязательно. По умолчанию используется 25 для незашифрованного и TLS SMTP соединения, и 465 для SSL SMTP.",
"Options": "Настройки",
"Or": "или",
"OrCancel": "или %1$s отмените %2$s",
"Others": "Другие",
"Outlink": "Исходящая ссылка",
"Outlinks": "Исходящие ссылки",
"OverlayRowActionTooltip": "Смотреть аналитику прямо на вашем сайте (откроется в новом окне)",
"OverlayRowActionTooltipTitle": "Открыть страницу с наложением",
"Overview": "Обзор",
"Pages": "Страницы",
"Pagination": "%1$s–%2$s из %3$s",
"PaginationWithoutTotal": "%1$s–%2$s",
"ParameterMustIntegerBetween": "Параметр %1$s должен быть целым числом между %2$s и %3$s.",
"Password": "Пароль",
"Period": "Период",
"Piechart": "Круговая диаграмма",
"Print": "Печать",
"Profiles": "Профили",
"MatomoIsACollaborativeProjectYouCanContributeAndDonateNextRelease": "%1$sMatomo%2$s, ранее известный как Piwik — это совместный проект, предложенный вам членами %7$sкоманды Matomo%8$s, а также многими другими участниками по всему миру. <br\/> Если вы поклонник Matomo, вы можете помочь: узнать, %3$sкак принять участие в Matomo%4$s, или %5$sпожертвовать сейчас%6$s, чтобы помочь финансировать следующий замечательный релиз Matomo!",
"PiwikXIsAvailablePleaseNotifyPiwikAdmin": "Доступен %1$s. Пожалуйста, сообщите %2$sадминистратору Matomo%3$s.",
"PiwikXIsAvailablePleaseUpdateNow": "Matomo %1$s доступен для скачивания. %2$s Пожалуйста, обновитесь!%3$s (см. %4$s изменения%5$s).",
"PleaseContactYourPiwikAdministrator": "Пожалуйста, обратитесь к администратору Matomo.",
"PleaseSpecifyValue": "Пожалуйста, определите значение для «%s».",
"PleaseUpdatePiwik": "Пожалуйста, обновите Matomo",
"Plugin": "Плагин",
"Plugins": "Плагины",
"PoweredBy": "Powered by",
"Previous": "Назад",
"PreviousDays": "Прошедшие %s дни (не включая сегодня)",
"PreviousDaysShort": "%s предыдущих дней",
"Price": "Цена",
"ProductConversionRate": "Конверсия для товара",
"ProductRevenue": "Прибыль с товара",
"Measurable": "Единица измерения",
"Measurables": "Единицы измерения",
"MeasurableId": "ID единицы измерения",
"PurchasedProducts": "Купленные товары",
"Quantity": "Количество",
"RangeReports": "Другие периоды",
"ReadThisToLearnMore": "%1$sПрочтите это, чтобы узнать больше.%2$s",
"Recommended": "Рекомендуется",
"RecordsToPlot": "Записи для построения графика",
"Refresh": "Обновить",
"RefreshPage": "Обновить страницу",
"RelatedReport": "Связанный отчет",
"RelatedReports": "Связанные отчеты",
"Remove": "Удалить",
"Report": "Отчёт",
"ReportGeneratedFrom": "Этот отчет был сформирован с использованием данных: %s.",
"Reports": "Отчёты",
"ReportsContainingTodayWillBeProcessedAtMostEvery": "Архив отчётов на каждые Х секунд",
"RearchiveTimeIntervalOnlyForTodayReports": "Это влияет только на отчёты (или другие диапазоны дат, включая сегодня)",
"ReportsWillBeProcessedAtMostEveryHour": "Следовательно, отчёты обрабатываются каждый час.",
"RequestTimedOut": "Время ожидания запроса к %s истекло. Пожалуйста, попробуйте снова.",
"Required": "%s необходимо",
"Required2": "Необходимо",
"ReturningVisitor": "Вернувшийся посетитель",
"ReturningVisitorAllVisits": "Посмотреть все визиты",
"RowEvolutionRowActionTooltip": "Посмотрите, как показатели для этой строки менялись с течением времени",
"RowEvolutionRowActionTooltipTitle": "Открыть динамику по этой строке",
"Rows": "Строки",
"RowsToDisplay": "Строки для отображения",
"Save": "Сохранить",
"SaveImageOnYourComputer": "Чтобы сохранить изображение на компьютере, нажмите правой кнопкой на нём и выберите «Сохранить изображение как...»",
"Search": "Поиск",
"Clear": "Очистить",
"SearchNoResults": "Нет результатов",
"Security": "Безопасность",
"SeeAll": "просмотреть всё",
"SeeTheOfficialDocumentationForMoreInformation": "Смотрите %1$sофициальную документацию%2$s чтобы узнать больше.",
"SeeThisFaq": "Посмотрите %1$sэти частые вопросы%2$s.",
"Segment": "Сегмент",
"SelectYesIfYouWantToSendEmailsViaServer": "Выберите «Да», если вы хотите отсылать e-mail письма через определённый сервер, вместо использования локальной mail функции.",
"Settings": "Настройки",
"Shipping": "Доставка",
"Show": "показать",
"SingleWebsitesDashboard": "Статистика по сайту",
"SmallTrafficYouCanLeaveDefault": "Для сайтов с небольшой нагрузкой вы можете оставить %s сек. по умолчанию, и просматривать отчёты в реальном времени.",
"SmtpEncryption": "Шифрование SMTP",
"SmtpPassword": "Пароль SMTP",
"SmtpPort": "Порт SMTP",
"SmtpServerAddress": "Адрес SMTP-сервера",
"SmtpUsername": "Имя пользователя SMTP",
"Source": "Источник",
"StatisticsAreNotRecorded": "Отслеживание посетителей Matomo в настоящее время отключено! Вы можете повторно включить отслеживание установив record_statistics = 1 в файле config\/config.ini.php.",
"Subtotal": "Сумма",
"Summary": "Сводный отчёт",
"Table": "Таблица",
"TagCloud": "Теги",
"Tax": "Налог (комиссия)",
"TimeAgo": "%s назад",
"TimeFormat": "Формат времени",
"TimeOnPage": "Время, проведённое на странице",
"ToDeleteAllDirectoriesRunThisCommand": "Чтобы удалить все директории сразу, вы можете запустить эту команду:",
"ToDeleteAllFilesRunThisCommand": "Чтобы удалить все файлы сразу, вы можете запустить эту команду:",
"Total": "Всего",
"Totals": "Всего",
"TotalRatioTooltip": "Это %1$s из всех %2$s %3$s в %4$s.",
"TotalRevenue": "Общая прибыль",
"TotalVisitsPageviewsActionsRevenue": "(Всего: %1$s визиты, %2$s просмотры страниц, %3$s действия, %4$s выручка)",
"TrackingScopeAction": "Действие",
"TrackingScopePage": "Страница",
"TrackingScopeVisit": "Посещение",
"TransitionsRowActionTooltip": "Посмотрите, что посетители делали до и после просмотра этой страницы",
"TransitionsRowActionTooltipTitle": "Открыть переходы",
"TranslatorName": "Ademaro, Joker Interactive, Важенин Илья (компания Codax), Nelde Maxim, Andrey, Vadim Nekhai, UptimePal",
"UniquePurchases": "Уникальные покупки",
"Unknown": "Неизвестно",
"Upload": "Закачать",
"UsePlusMinusIconsDocumentation": "Используйте иконки плюс и минус слева для навигации",
"UserId": "ID пользователя",
"UserIds": "ID пользователя",
"Username": "Имя пользователя",
"UseSMTPServerForEmail": "Использовать SMTP сервер для e-mail",
"Value": "Значение",
"VBarGraph": "Столбчатая диаграмма",
"View": "Смотреть",
"ViewDocumentationFor": "Смотреть документацию для %1$s",
"Visit": "Посещение",
"VisitId": "ID посещения",
"VisitConvertedGoal": "Посещение, сконвертированное как минимум одной целью",
"VisitConvertedGoalId": "Посещение, которое сконвертировало определенную цель",
"VisitConvertedNGoals": "Посещение сконвертировало %s целей",
"VisitDuration": "Примерная продолжительность посещения (секунд)",
"Visitor": "Посетитель",
"VisitorID": "ID посетителя",
"VisitorIP": "IP посетителя",
"VisitorIPs": "IPы посетителя",
"Visitors": "Посетители",
"VisitsWith": "Посещения с %s",
"VisitorFingerprint": "Отпечаток пальца",
"VisitorSettings": "Настройки посетителей",
"VisitType": "Тип посещения",
"VisitTypes": "Типы посещений",
"VisitTypeExample": "Например, чтобы выбрать всех посетителей, которые вернулисть на сайт, включая тех, кто уже купил что-то в свои предыдущие визиты, API-запрос будет содержать: %s",
"Warning": "Предупреждение",
"Warnings": "Предупреждения",
"WarningPhpVersionXIsTooOld": "Версия PHP %s, которую вы используете, завершила свой жизненый цикл (EOL). Настоятельно рекомендуем обновиться до текущей версии, т. к. использование устаревшей версии подвергает вас уязвимостям в безопасности и ошибкам, которые устранены в более свежей версии PHP.",
"WarningPiwikWillStopSupportingPHPVersion": "Matomo прекратит поддержку PHP %1$s в следующей версии. Обновите ваш PHP, по крайней мере, до версии PHP %2$s !",
"YouMustUpgradePhpVersionToReceiveLatestPiwik": "Вы должны обновить версию PHP, чтобы получить последнее обновление Matomo.",
"PiwikCannotBeUpgradedBecausePhpIsTooOld": "Matomo не может быть обновлён до последней основной версии, потому что ваша версия PHP является слишком старой.",
"PleaseUpgradeYourPhpVersionSoYourPiwikDataStaysSecure": "Пожалуйста, обновите версию PHP, по крайней мере до PHP %s, что бы Matomo оставался безопасным.",
"ValidatorErrorEmptyValue": "Значение должно быть предоставлено.",
"ValidatorErrorNotANumber": "Значение не является числом.",
"ValidatorErrorNumberTooLow": "Значение «%1$s» слишком мало. Это значение должно быть не меньше %2$s.",
"ValidatorErrorNumberTooHigh": "Значение «%1$s» слишком велико. Это значение должно быть не больше %2$s.",
"ValidatorErrorCharacterTooShort": "Значение содержит символы «%1$s», но должно содержать как минимум символы %2$s.",
"ValidatorErrorCharacterTooLong": "Значение содержит «%1$s» символов, но должно содержать не более %2$s символов.",
"ValidatorErrorNotUrlLike": "Значение «%s» не похоже на URL.",
"ValidatorErrorNotEmailLike": "Значение «%s» не похоже на email.",
"ValidatorErrorNoValidRegex": "Значение «%s» не похоже на регулярное выражение.",
"ValidatorErrorXNotWhitelisted": "Значение «%1$s» не допускается, используйте одно из: %2$s.",
"ValidatorErrorInvalidDateTimeFormat": "Дата «%1$s» неправильного формата, пожалуйста, используйте %2$s",
"WarningFileIntegrityNoManifest": "Проверка целостности не может быть проведена из-за отсутствия manifest.inc.php.",
"WarningFileIntegrityNoManifestDeployingFromGit": "Если вы делаете деплой Matomo из Git, это сообщение является нормальным.",
"WarningFileIntegrityNoMd5file": "Проверка целостности не может быть проведена из-за отсутствия функции md5_file().",
"WarningPasswordStored": "%1$sВнимание:%2$s Этот пароль будет сохранен в конфигурационном файле на сервере в незашифрованном виде, и будет виден любому, кто имеет доступ к файловой системе сервера.",
"WarningDebugOnDemandEnabled": "Режим слежения за %1$s включен. Из соображений безопасности он должен быть включен только в небольшой период времени. Чтобы отключить его, установите %2$s на %3$s в %4$s",
"Website": "Сайт",
"Weekly": "Еженедельно",
"WeeklyReport": "еженедельно",
"WeeklyReports": "Еженедельные отчеты",
"WellDone": "Отлично!",
"Widgets": "Виджеты",
"Widget": "Виджет",
"XComparedToY": "%1$s в сравнении с %2$s",
"XFromY": "%1$s – %2$s",
"YearlyReport": "ежегодно",
"YearlyReports": "Ежегодные отчеты",
"YearsDays": "%1$s г. %2$s дн.",
"Yes": "Да",
"YouAreCurrentlyUsing": "Вы используете версию Matomo %s.",
"YouAreViewingDemoMessage": "Вы просматриваете демо %1$sMatomo%2$s",
"YouMustBeLoggedIn": "Вы должны зайти на сайт, чтобы получить доступ к этому функционалу.",
"YourChangesHaveBeenSaved": "Изменения сохранены.",
"YourSessionHasExpired": "Ваша сессия истекла в связи с неактивностью. Пожалуйста войдите, чтобы продолжить.",
"ThankYouForUsingMatomo": "Спасибо за использование Matomo",
"TheMatomoTeam": "Команда Matomo",
"PleaseTryAgain": "Пожалуйста, попробуйте еще раз",
"VisualizationDoesNotSupportComparison": "Эта визуализация не поддерживает сравнение сегментов \/ периодов.",
"ChangeInX": "Изменения в %1$s",
"Comparisons": "Сравнение",
"ClickToRemoveComp": "Нажмите, чтобы удалить это сравнение.",
"MaximumNumberOfSegmentsComparedIs": "Максимальное количество сегментов, которые можно сравнивать одновременно, равно%s.",
"MaximumNumberOfPeriodsComparedIs": "Максимальне количество периодов, которые можно сравнить одновременно: %s."
},
"Mobile": {
"AboutPiwikMobile": "О Matomo Mobile",
"AccessUrlLabel": "URL для доступа",
"Account": "Учетная запись",
"Accounts": "Аккаунты",
"AddAccount": "Добавить аккаунт",
"AddPiwikDemo": "Добавить демо Matomo",
"Advanced": "Расширенные",
"AnonymousAccess": "Анонимный доступ",
"AnonymousTracking": "Анонимное отслеживание",
"AskForAnonymousTrackingPermission": "При включении Matomo Mobile будет отправлять анонимные данные на matomo.org. Отправляемые данные помогают разработчикам Matomo Mobile лучше понять, как Вы используете приложение. Отправляемая информация: клики по меню и настройкам, название и версия ОС, ошибки, которые возникают в Matomo Mobile. Мы НЕ отслеживаем ваши данные аналитики. Эти анонимные данные никогда не станут доступными для кого-то ещё. Вы можете отключить\/включить анонимное слежение в Настройках в любое время.",
"ChooseHttpTimeout": "Выберите значение тайм-аута HTTP",
"ChooseMetric": "Выберите показатель",
"ChooseReport": "Выберите отчёт",
"ChooseSegment": "Выберите сегмент",
"ConfirmRemoveAccount": "Вы хотите удалить этот акаунт?",
"DefaultReportDate": "Дата отчёта",
"EmailUs": "Отправьте нам email",
"EnableGraphsLabel": "Отображать графики",
"EvolutionGraph": "Исторический график",
"HelpUsToImprovePiwikMobile": "Вы хотите включить анонимное отслеживание использования в Matomo Mobile?",
"HowtoDeleteAnAccount": "Нажмите и удерживайте для удаления аккаунта.",
"HowtoDeleteAnAccountOniOS": "Проведите справа налево, чтобы удалить учётную запись.",
"HowtoLoginAnonymous": "Оставьте имя пользователя и пароль пустым для анонимного входа",
"HttpIsNotSecureWarning": "Ваш токен авторизации в Matomo (token_auth) отправляется в незащищенном виде, если Вы используете \"HTTP\". Поэтому мы рекомендуем HTTPS для безопасности передачи информации по интернету. Желаете продолжить?",
"HttpTimeout": "Тайм-аут HTTP",
"IncompatiblePiwikVersion": "Используемая версия Matomo несовместима с Matomo Mobile 2. Обновите Matomo и попробуйте снова или установите Matomo Mobile 1.",
"LastUpdated": "Последнее обновление: %s",
"LoadingReport": "Загрузка %s",
"LoginCredentials": "Полномочия",
"LoginToPiwikToChangeSettings": "Войдите на сервер Matomo для создания и изменения веб-сайтов, пользователей или изменения общих параметров, таких как «Отчёт по умолчанию».",
"LoginUseHttps": "Использовать https",
"MatomoMobile": "Мобильное приложение Matomo",
"MultiChartLabel": "Отображать спарклайны",
"NavigationBack": "Назад",
"NetworkError": "Ошибка сети",
"NetworkErrorWithStatusCode": "Произошла ошибка «%1$s». Запрос вернул статус: «%2$s». URL был: «%3$s». Пожалуйста, проверьте введенный URL и лог ошибок на сервере для более детальной информации по ошибке и способам её решения.",
"NetworkErrorWithStatusCodeShort": "Ошибка сети %s",
"NetworkNotReachable": "Сеть недоступна",
"NoAccountIsSelected": "Вы должны выбрать учетную запись. Добавьте новую учетную запись, если вы этого еще не сделали.",
"NoDataShort": "Нет данных",
"NoPiwikAccount": "Нет аккаунта Matomo?",
"NoReportsShort": "Нет отчетов",
"NoVisitorFound": "Посетителей не найдено",
"NoVisitorsShort": "Нет посетителей",
"NoWebsiteFound": "Сайт не найден",
"NoWebsitesShort": "Нет сайтов",
"PullDownToRefresh": "Потяните вниз, чтобы обновить...",
"PossibleSslError": "Возможно ошибка SSL-сертификата",
"PossibleSslErrorExplanation": "Произошла ошибка, которая может быть вызвана неверным или самоподписанным сертификатом: \"%s\". Игнорирование проверки SSL может не помешать входу на сайт для вас, но это менее безопасно. Вы можете изменить проверку SSL в любое время в настройках.",
"IgnoreSslError": "Игнорировать ошибку SSL",
"RatingDontRemindMe": "Не напоминать мне",
"RatingNotNow": "Не сейчас",
"RatingNow": "OK, сейчас оценю",
"RatingPleaseRateUs": "Мобильное приложение Matomo бесплатно, мы будем очень благодарны вам, если вы найдете минутку, чтобы оценить приложение в %1$s. Если у вас есть предложения по новым функциям или вы нашли баг, пожалуйста свяжитесь с %2$s",
"ReleaseToRefresh": "Отпустите, чтобы обновить...",
"Reloading": "Обновление...",
"RequestTimedOutShort": "Ошибка времени ожидания в сети",
"RestrictedCompatibility": "Ограниченная совместимость",
"RestrictedCompatibilityExplanation": "Используемая версия Matomo %s не полностью поддерживается Matomo Mobile 2. Возможны ошибки во время работы. Мы рекомендуем либо обновить Matomo до последней версии, либо использовать Matomo Mobile 1.",
"SaveSuccessError": "Пожалуйста, проверьте настройки",
"SearchWebsite": "Искать сайты",
"ShowAll": "Показать все",
"ShowLess": "Показать меньше",
"StaticGraph": "Обзор графика",
"TopVisitedWebsites": "Самые посещаемые вебсайты",
"TryIt": "Попробуйте!",
"UseSearchBarHint": "Здесь отображаются только первые %s сайтов. Пожалуйста, используйте строку поиска, чтобы получить доступ к других вашим сайтам.",
"VerifyAccount": "Верификация аккаунта",
"ValidateSslCertificate": "Проверить SSL-сертификат",
"VerifyLoginData": "Убедитесь, что Вы ввели имя пользователя и пароль правильно.",
"YouAreOffline": "Извините, но Вы сейчас офлайн",
"ExceptionNoViewAccess": "Пожалуйста, проверьте свои имя и пароль и убедитесь, что у вас есть доступ %s, по крайней мере, к одному сайту.",
"Mobile_HowtoExitAndroid": "Пожалуйста, нажмите НАЗАД еще раз, чтобы выйти",
"MatomoMarketplace": "Matomo Marketplace",
"EnterAuthCode": "Введите код аутентификации",
"EnterCorrectAuthCode": "Введите правильный код аутентификации",
"EnterAuthCodeExplanation": "Похоже, вы используете двухфакторную аутентификацию. Пожалуйста, введите шестизначный код для входа в свою учетную запись."
},
"RowEvolution": {
"AvailableMetrics": "Доступные показатели",
"CompareDocumentation": "Нажмите на ссылку ниже, чтобы открыть всплывающее окно для другой строки из той же самой таблицы для сравнения нескольких записей.<br \/>Используйте shift+клик, чтобы пометить строку для дальнейшего сравнения без открытия всплывающего окна.",
"CompareRows": "Сравнить записи",
"ComparingRecords": "Сравнение %s строк",
"Documentation": "Нажмите на показатели, для отображения динамики на большом графике. Используйте shift+клик для отображения нескольких показателей одновременно.",
"MetricBetweenText": "между %1$s и %2$s",
"MetricChangeText": "%s изменений за период",
"MetricMinMax": "%1$s выставленый между %2$s и %3$s больше периода",
"MetricsFor": "Показатели для %s",
"MultiRowEvolutionTitle": "Динамика нескольких строк",
"PickAnotherRow": "Выберите другую строку для сравнения",
"PickARow": "Выберите строку для сравнения"
}
}
|
{
"pile_set_name": "Github"
}
|
{
"about_opensource_title": "Это приложение с открытым исходным кодом",
"about_opensource_message": "Мы приветствуем ваше участие в развитии этого приложения. Если вы заинтересованы, присоединяйтесь к нам на Github по адресу",
"about_opensource_link": "https://github.com/greymass/anchor",
"about_message_1": "Anchor - автономное настольное приложение, которое напрямую подключается к блокцепи EOS через конечную точку API по вашему выбору.",
"about_message_2": "Ваши ключи никогда не покидают приложение и хранятся только в зашифрованном виде, обеспечивая высокий уровень безопасности.",
"about_more": "Пожалуйста, посетите https://greymass.com, если хотите больше узнать о нас.",
"about_issues": "Если у вас возникли проблемы с самим приложением, напишите нам о проблеме на github по адресу:",
"about_issues_link": "https://github.com/greymass/anchor/issues",
"about_greymass_message_1": "Это приложение является инициативой, возглавляемой Greymass.",
"about_greymass_message_2": "Если вы хотите узнать больше о нашей команде и других проектах, которые мы запланировали для EOS, мы приглашаем вас посетить нас по адресу:",
"about_license_type": "Лицензия MIT (MIT)",
"about_license_body_1": "Copyright (c) 2018-настоящее время Greymass",
"about_license_body_2": "Данная лицензия разрешает, безвозмездно, лицам, получившим копию данного программного обеспечения и сопутствующей документации (в дальнейшем именуемыми \"Программное Обеспечение\"), использовать Программное Обеспечение без ограничений, включая неограниченное право на использование, копирование, изменение, объединение, публикацию, распространение, сублицензирование и/или продажу копий Программного Обеспечения, также как и лицам, которым предоставляется данное Программное Обеспечение, при соблюдении следующих условий:",
"about_license_body_3": "Вышеупомянутое уведомление об авторских правах и данные условия должны быть включены во все копии или значимые части данного Программного Обеспечения.",
"about_license_body_4": "ДАННОЕ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ «КАК ЕСТЬ», БЕЗ ЛЮБОГО ВИДА ГАРАНТИЙ, ЯВНО ВЫРАЖЕННЫХ ИЛИ ПОДРАЗУМЕВАЕМЫХ, ВКЛЮЧАЯ, НО НЕ ОГРАНИЧИВАЯСЬ ГАРАНТИЯМИ ТОВАРНОЙ ПРИГОДНОСТИ, СООТВЕТСТВИЯ ПО ЕГО КОНКРЕТНОМУ НАЗНАЧЕНИЮ И НЕНАРУШЕНИЯ ПРАВ. НИ В КАКОМ СЛУЧАЕ АВТОРЫ ИЛИ ПРАВООБЛАДАТЕЛИ НЕ НЕСУТ ОТВЕТСТВЕННОСТИ ПО ИСКАМ О ВОЗМЕЩЕНИИ УЩЕРБА, УБЫТКОВ ИЛИ ДРУГИХ ТРЕБОВАНИЙ ПО ДЕЙСТВУЮЩИМ КОНТРАКТАМ, ДЕЛИКТАМ ИЛИ ИНОМУ, ВОЗНИКШИМ ИЗ, ИМЕЮЩИМ ПРИЧИНОЙ ИЛИ СВЯЗАННЫМ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ ИЛИ ИСПОЛЬЗОВАНИЕМ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ ИЛИ ИНЫМИ ДЕЙСТВИЯМИ С ПРОГРАММНЫМ ОБЕСПЕЧЕНИЕМ."
}
|
{
"pile_set_name": "Github"
}
|
---
title: Elixir School
layout: home
version: 2.0.0
---
Elixir School — главный ресурс для тех, кто хочет изучить язык программирования Elixir.
Независимо от вашего опыта в разработке ПО, вы найдёте все необходимое в уроках и на вспомогательных ресурсах.
Благодаря тяжёлому труду добровольцев, Elixir School был переведён на множество языков. Некоторые из этих переводов: [Việt ngữ][vi], [简体中文][zh-hans], [繁體中文][zh-hant], [Español][es], [Slovenčina][sk], [日本語][ja], [Polski][pl], [Português][pt], [Русский][ru], [Bahasa Indonesia][id], [Bahasa Melayu][ms], [Український][uk], [한국어][ko], [Italiano][it], [Deutsch][de], [বাংলা][bn], [Türkçe][tr] и [ภาษาไทย][th].
Мы приветствуем любую помощь и призываем присоединиться к нам, чтобы сделать Elixir School лучше, в GitHub [elixirschool/elixirschool](https://github.com/elixirschool/elixirschool)!
[es]: /es/
[it]: /it/
[ja]: /ja/
[ko]: /ko/
[pl]: /pl/
[pt]: /pt/
[ru]: /ru/
[sk]: /sk/
[vi]: /vi/
[id]: /id/
[ms]: /ms/
[uk]: /uk/
[de]: /de/
[bn]: /bn/
[tr]: /tr/
[th]: /th/
[zh-hans]: /zh-hans/
[zh-hant]: /zh-hant/
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.core.getter;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* 数组类型的Get接口
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public interface ArrayType {
/**
* 获取Object型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
String[] getObjs(String key);
/**
* 获取String型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
String[] getStrs(String key);
/**
* 获取Integer型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Integer[] getInts(String key);
/**
* 获取Short型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Short[] getShorts(String key);
/**
* 获取Boolean型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Boolean[] getBools(String key);
/**
* 获取Long型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Long[] getLongs(String key);
/**
* 获取Character型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Character[] getChars(String key);
/**
* 获取Double型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Double[] getDoubles(String key);
/**
* 获取Byte型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
Byte[] getBytes(String key);
/**
* 获取BigInteger型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
BigInteger[] getBigIntegers(String key);
/**
* 获取BigDecimal型属性值数组
*
* @param key 属性名
* @return 属性值列表
*/
BigDecimal[] getBigDecimals(String key);
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.core.builder;
/**
* 使用{@link ToStringBuilder}创建<code>toString</code>
*
* <p>
* 这个类是作为单例对象使用的。没有必要每次都实例化一个新样式。 只需实例化一次,
* 根据需要自定义值,并将结果存储在公共静态final变量中,供程序的其余部分访问.
* </p>
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class StandardToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
public StandardToStringStyle() {
super();
}
@Override
public boolean isUseClassName() {
return super.isUseClassName();
}
@Override
public void setUseClassName(final boolean useClassName) {
super.setUseClassName(useClassName);
}
@Override
public boolean isUseShortClassName() {
return super.isUseShortClassName();
}
@Override
public void setUseShortClassName(final boolean useShortClassName) {
super.setUseShortClassName(useShortClassName);
}
@Override
public boolean isUseIdentityHashCode() {
return super.isUseIdentityHashCode();
}
@Override
public void setUseIdentityHashCode(final boolean useIdentityHashCode) {
super.setUseIdentityHashCode(useIdentityHashCode);
}
@Override
public boolean isUseFieldNames() {
return super.isUseFieldNames();
}
@Override
public void setUseFieldNames(final boolean useFieldNames) {
super.setUseFieldNames(useFieldNames);
}
@Override
public boolean isDefaultFullDetail() {
return super.isDefaultFullDetail();
}
@Override
public void setDefaultFullDetail(final boolean defaultFullDetail) {
super.setDefaultFullDetail(defaultFullDetail);
}
@Override
public boolean isArrayContentDetail() {
return super.isArrayContentDetail();
}
@Override
public void setArrayContentDetail(final boolean arrayContentDetail) {
super.setArrayContentDetail(arrayContentDetail);
}
@Override
public String getArrayStart() {
return super.getArrayStart();
}
@Override
public void setArrayStart(final String arrayStart) {
super.setArrayStart(arrayStart);
}
@Override
public String getArrayEnd() {
return super.getArrayEnd();
}
@Override
public void setArrayEnd(final String arrayEnd) {
super.setArrayEnd(arrayEnd);
}
@Override
public String getArraySeparator() {
return super.getArraySeparator();
}
@Override
public void setArraySeparator(final String arraySeparator) {
super.setArraySeparator(arraySeparator);
}
@Override
public String getContentStart() {
return super.getContentStart();
}
@Override
public void setContentStart(final String contentStart) {
super.setContentStart(contentStart);
}
@Override
public String getContentEnd() {
return super.getContentEnd();
}
@Override
public void setContentEnd(final String contentEnd) {
super.setContentEnd(contentEnd);
}
@Override
public String getFieldNameValueSeparator() {
return super.getFieldNameValueSeparator();
}
@Override
public void setFieldNameValueSeparator(final String fieldNameValueSeparator) {
super.setFieldNameValueSeparator(fieldNameValueSeparator);
}
@Override
public String getFieldSeparator() {
return super.getFieldSeparator();
}
@Override
public void setFieldSeparator(final String fieldSeparator) {
super.setFieldSeparator(fieldSeparator);
}
@Override
public boolean isFieldSeparatorAtStart() {
return super.isFieldSeparatorAtStart();
}
@Override
public void setFieldSeparatorAtStart(final boolean fieldSeparatorAtStart) {
super.setFieldSeparatorAtStart(fieldSeparatorAtStart);
}
@Override
public boolean isFieldSeparatorAtEnd() {
return super.isFieldSeparatorAtEnd();
}
@Override
public void setFieldSeparatorAtEnd(final boolean fieldSeparatorAtEnd) {
super.setFieldSeparatorAtEnd(fieldSeparatorAtEnd);
}
@Override
public String getNullText() {
return super.getNullText();
}
@Override
public void setNullText(final String nullText) {
super.setNullText(nullText);
}
@Override
public String getSizeStartText() {
return super.getSizeStartText();
}
@Override
public void setSizeStartText(final String sizeStartText) {
super.setSizeStartText(sizeStartText);
}
@Override
public String getSizeEndText() {
return super.getSizeEndText();
}
@Override
public void setSizeEndText(final String sizeEndText) {
super.setSizeEndText(sizeEndText);
}
@Override
public String getSummaryObjectStartText() {
return super.getSummaryObjectStartText();
}
@Override
public void setSummaryObjectStartText(final String summaryObjectStartText) {
super.setSummaryObjectStartText(summaryObjectStartText);
}
@Override
public String getSummaryObjectEndText() {
return super.getSummaryObjectEndText();
}
@Override
public void setSummaryObjectEndText(final String summaryObjectEndText) {
super.setSummaryObjectEndText(summaryObjectEndText);
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.extra.effect.provider;
import org.aoju.bus.extra.effect.EffectProvider;
import org.xerial.snappy.Snappy;
import java.io.IOException;
/**
* 基于snappy的数据压缩
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class SnappyProvider implements EffectProvider {
@Override
public byte[] compress(byte[] data) throws IOException {
return Snappy.compress(data);
}
@Override
public byte[] uncompress(byte[] data) throws IOException {
return Snappy.uncompress(data);
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.tracer.transport;
import org.aoju.bus.logger.Logger;
import org.aoju.bus.tracer.Builder;
import org.aoju.bus.tracer.transport.jaxb.TpicMap;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.bind.*;
import javax.xml.soap.SOAPHeader;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import java.util.HashMap;
import java.util.Map;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class SoapHeaderTransport {
private static final SOAPHeaderMarshaller SOAP_HEADER_MARSHALLER = new SOAPHeaderMarshaller();
private static final ResultMarshaller RESULT_MARSHALLER = new ResultMarshaller();
private static final ElementUnmarshaller ELEMENT_UNMARSHALLER = new ElementUnmarshaller();
private static final SourceUnmarshaller SOURCE_UNMARSHALLER = new SourceUnmarshaller();
private final JAXBContext jaxbContext;
public SoapHeaderTransport() {
try {
jaxbContext = JAXBContext.newInstance(TpicMap.class);
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public Map<String, String> parseSoapHeader(final Element soapHeader) {
final NodeList tpicHeaders = soapHeader.getElementsByTagNameNS(Builder.SOAP_HEADER_NAMESPACE, Builder.TPIC_HEADER);
final HashMap<String, String> contextMap = new HashMap<>();
if (tpicHeaders != null && tpicHeaders.getLength() > 0) {
final int items = tpicHeaders.getLength();
for (int i = 0; i < items; i++) {
contextMap.putAll(parseTpicHeader((Element) tpicHeaders.item(i)));
}
}
return contextMap;
}
public Map<String, String> parseTpicHeader(final Element element) {
return parseTpicHeader(ELEMENT_UNMARSHALLER, element);
}
public Map<String, String> parseTpicHeader(final Source source) {
return parseTpicHeader(SOURCE_UNMARSHALLER, source);
}
private <T> Map<String, String> parseTpicHeader(final Unmarshallable<T> unmarshallable, final T xmlContext) {
try {
if (xmlContext != null) {
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final JAXBElement<TpicMap> unmarshal = unmarshallable.unmarshal(unmarshaller, xmlContext);
if (unmarshal != null) {
return unmarshal.getValue().unwrapValues();
}
}
} catch (JAXBException e) {
Logger.warn("Unable to parse TPIC header: {}", e.getMessage());
Logger.debug("WithStack: Unable to parse TPIC header: {}", e.getMessage(), e);
}
return new HashMap<>();
}
public void renderSoapHeader(final Map<String, String> context, final SOAPHeader soapHeader) {
renderSoapHeader(SOAP_HEADER_MARSHALLER, context, soapHeader);
}
public void renderSoapHeader(final Map<String, String> context, final Result result) {
renderSoapHeader(RESULT_MARSHALLER, context, result);
}
private <T> void renderSoapHeader(final Marshallable<T> marshallable, final Map<String, String> context, T xmlContext) {
try {
final Marshaller marshaller = jaxbContext.createMarshaller();
marshallable.marshal(marshaller, TpicMap.wrap(context), xmlContext);
} catch (JAXBException e) {
Logger.warn("Unable to render TPIC header: {}", e.getMessage());
Logger.debug("WithStack: Unable to render TPIC header: {}", e.getMessage(), e);
}
}
private interface Unmarshallable<T> {
JAXBElement<TpicMap> unmarshal(Unmarshaller unmarshaller, T xmlContext) throws JAXBException;
}
private interface Marshallable<T> {
void marshal(Marshaller marshaller, TpicMap tpic, T xmlContext) throws JAXBException;
}
private static class SourceUnmarshaller implements Unmarshallable<Source> {
@Override
public JAXBElement<TpicMap> unmarshal(final Unmarshaller unmarshaller, final Source source) throws JAXBException {
return unmarshaller.unmarshal(source, TpicMap.class);
}
}
private static class ElementUnmarshaller implements Unmarshallable<Element> {
@Override
public JAXBElement<TpicMap> unmarshal(final Unmarshaller unmarshaller, final Element element) throws JAXBException {
return unmarshaller.unmarshal(element, TpicMap.class);
}
}
private static class ResultMarshaller implements Marshallable<Result> {
@Override
public void marshal(final Marshaller marshaller, final TpicMap tpic, final Result result) throws JAXBException {
marshaller.marshal(tpic, result);
}
}
private static class SOAPHeaderMarshaller implements Marshallable<SOAPHeader> {
@Override
public void marshal(final Marshaller marshaller, final TpicMap tpic, final SOAPHeader soapHeader) throws JAXBException {
marshaller.marshal(tpic, soapHeader);
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.image.galaxy.data;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class MergeAttributesCoercion implements AttributesCoercion {
private final Attributes newAttrs;
private final AttributesCoercion next;
public MergeAttributesCoercion(Attributes mergedAttrs, AttributesCoercion next) {
this.newAttrs = mergedAttrs;
this.next = next;
}
@Override
public String remapUID(String uid) {
return next != null ? next.remapUID(uid) : uid;
}
@Override
public void coerce(Attributes attrs, Attributes modified) {
Attributes.unifyCharacterSets(attrs, newAttrs);
if (modified != null) {
attrs.update(Attributes.UpdatePolicy.OVERWRITE, newAttrs, modified);
} else {
attrs.addAll(newAttrs);
}
if (next != null)
next.coerce(attrs, modified);
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.office.magic.filter.draw;
import com.sun.star.drawing.XDrawPage;
import com.sun.star.drawing.XDrawPages;
import com.sun.star.drawing.XDrawPagesSupplier;
import com.sun.star.lang.XComponent;
import org.aoju.bus.logger.Logger;
import org.aoju.bus.office.Context;
import org.aoju.bus.office.magic.Draw;
import org.aoju.bus.office.magic.Lo;
import org.aoju.bus.office.magic.filter.Filter;
import org.aoju.bus.office.magic.filter.FilterChain;
/**
* 此筛选器用于从文档中选择特定页面,以便仅转换所选页面
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class PageSelectorFilter implements Filter {
private final int page;
/**
* 创建一个新的过滤器,在转换文档时选择指定的页面(只转换给定的页面).
*
* @param page 要转换的页码.
*/
public PageSelectorFilter(final int page) {
super();
this.page = page;
}
@Override
public void doFilter(
final Context context, final XComponent document, final FilterChain chain)
throws Exception {
Logger.debug("Applying the PageSelectorFilter");
// 此筛选器只能用于绘制文档
if (Draw.isDraw(document)) {
selectPage(document);
}
// 用链中的下一个过滤器
chain.doFilter(context, document);
}
private void selectPage(final XComponent document) throws Exception {
final XDrawPages drawPages = Lo.qi(XDrawPagesSupplier.class, document).getDrawPages();
final int pageCount = drawPages.getCount();
// 删除除要选择的页面之外的所有页面.
int seekIdx = Math.min(pageCount, Math.max(0, page - 1));
for (int i = 0; i < pageCount; i++) {
XDrawPage drawPage = null;
if (i < seekIdx) {
drawPage = Lo.qi(XDrawPage.class, drawPages.getByIndex(0));
} else if (i > seekIdx) {
drawPage = Lo.qi(XDrawPage.class, drawPages.getByIndex(1));
}
if (drawPage != null) {
drawPages.remove(drawPage);
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.http.magic;
import org.aoju.bus.core.lang.Symbol;
import org.aoju.bus.http.Httpd;
import java.util.Map;
/**
* GET参数构造器
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class GetBuilder extends RequestBuilder<GetBuilder> {
public GetBuilder(Httpd httpd) {
super(httpd);
}
@Override
public RequestCall build() {
if (params != null) {
url = appendParams(url, params);
}
return new GetRequest(url, tag, params, headers, id).build(httpd);
}
protected String appendParams(String url, Map<String, String> params) {
if (url == null || params == null || params.isEmpty()) {
return url;
}
StringBuilder builder = new StringBuilder();
params.forEach((k, v) -> {
if (builder.length() == 0) {
builder.append(Symbol.QUESTION_MARK);
} else if (builder.length() > 0) {
builder.append(Symbol.AND);
}
builder.append(k);
builder.append(Symbol.EQUAL).append(v);
});
return url + builder.toString();
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.image.nimble.opencv;
import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;
import java.io.IOException;
import java.util.Locale;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class NativeJLSImageReaderSpi extends ImageReaderSpi {
public static final String[] NAMES = {"jpeg-ls-cv", "jpeg-ls", "JPEG-LS"};
public static final String[] SUFFIXES = {"jls"};
public static final String[] MIMES = {"image/jpeg-ls"};
public NativeJLSImageReaderSpi() {
super("Bus Team", "1.5", NAMES, SUFFIXES, MIMES, NativeImageReader.class.getName(),
new Class[]{ImageInputStream.class}, new String[]{NativeJLSImageWriterSpi.class.getName()}, false, // supportsStandardStreamMetadataFormat
null, // nativeStreamMetadataFormatName
null, // nativeStreamMetadataFormatClassName
null, // extraStreamMetadataFormatNames
null, // extraStreamMetadataFormatClassNames
false, // supportsStandardImageMetadataFormat
null, null, null, null);
}
@Override
public String getDescription(Locale locale) {
return "Natively-accelerated JPEG-LS Image Reader (CharLS based)";
}
@Override
public boolean canDecodeInput(Object source) throws IOException {
if (!(source instanceof ImageInputStream)) {
return false;
}
ImageInputStream iis = (ImageInputStream) source;
iis.mark();
int byte1 = iis.read();
int byte2 = iis.read();
int byte3 = iis.read();
int byte4 = iis.read();
iis.reset();
// Magic numbers for JPEG (general jpeg marker): 0xFFD8
// Start of Frame, also known as SOF55, indicates a JPEG-LS file
return (byte1 == 0xFF) && (byte2 == 0xD8) && (byte3 == 0xFF) && (byte4 == 0xF7);
}
@Override
public ImageReader createReaderInstance(Object extension) {
return new NativeImageReader(this, false);
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.image.metric.service;
import org.aoju.bus.image.Dimse;
import org.aoju.bus.image.Status;
import org.aoju.bus.image.UID;
import org.aoju.bus.image.galaxy.data.Attributes;
import org.aoju.bus.image.metric.Association;
import org.aoju.bus.image.metric.Commands;
import org.aoju.bus.image.metric.ImageException;
import org.aoju.bus.image.metric.internal.pdu.Presentation;
import java.io.IOException;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class BasicCEchoSCP extends AbstractService {
public BasicCEchoSCP() {
super(UID.VerificationSOPClass);
}
public BasicCEchoSCP(String... sopClasses) {
super(sopClasses);
}
@Override
public void onDimse(Association as,
Presentation pc,
Dimse dimse,
Attributes cmd,
Attributes data) throws IOException {
if (dimse != Dimse.C_ECHO_RQ)
throw new ImageException(Status.UnrecognizedOperation);
as.tryWriteDimseRSP(pc, Commands.mkEchoRSP(cmd, Status.Success));
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org and other 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 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. *
********************************************************************************/
package org.aoju.bus.forest.complex;
import org.aoju.bus.forest.Complex;
import java.util.Collection;
/**
* ANY逻辑混合规则,即任意一个规则满足时就满足,
* 当没有规则的时候,就是不满足
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class AnyComplex<E> extends MixComplex<E> implements Complex<E> {
public AnyComplex() {
super(null);
}
public AnyComplex(Collection<? extends Complex<? extends E>> filters) {
super(filters);
}
@Override
public AnyComplex<E> mix(Complex<? extends E> filter) {
add(filter);
return this;
}
@Override
public boolean on(E entry) {
Complex[] filters = this.filters.toArray(new Complex[0]);
for (Complex filter : filters) {
if (filter.on(entry)) {
return true;
}
}
return false;
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org Greg Messner and other 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 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. *
********************************************************************************/
package org.aoju.bus.gitlab.models;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.HashMap;
import java.util.Map;
/**
* Enum for the various Pipeline status values.
*
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public enum PipelineStatus {
RUNNING, PENDING, SUCCESS, FAILED, CANCELED, SKIPPED, MANUAL;
private static Map<String, PipelineStatus> valuesMap = new HashMap<>(6);
static {
for (PipelineStatus status : PipelineStatus.values())
valuesMap.put(status.toValue(), status);
}
@JsonCreator
public static PipelineStatus forValue(String value) {
return valuesMap.get(value);
}
@JsonValue
public String toValue() {
return (name().toLowerCase());
}
@Override
public String toString() {
return (name().toLowerCase());
}
}
|
{
"pile_set_name": "Github"
}
|
/*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2020 aoju.org Greg Messner and other 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 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. *
********************************************************************************/
package org.aoju.bus.gitlab.models;
import org.aoju.bus.gitlab.JacksonJson;
/**
* @author Kimi Liu
* @version 6.1.0
* @since JDK 1.8+
*/
public class WikiPage {
private String title;
private String content;
private String slug;
private String format;
public WikiPage() {
}
public WikiPage(String title, String slug, String content) {
this.title = title;
this.slug = slug;
this.content = content;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public String toString() {
return (JacksonJson.toJsonString(this));
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* @file xmc_ecat.c
* @date 2017-04-27
*
* @cond
*********************************************************************************************************************
* XMClib v2.1.20 - XMC Peripheral Driver Library
*
* Copyright (c) 2015-2018, Infineon Technologies AG
* 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 the copyright holders 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.
*
* To improve the quality of the software, users are encouraged to share modifications, enhancements or bug fixes with
* Infineon Technologies AG dave@infineon.com).
*********************************************************************************************************************
*
* Change History
* --------------
*
* 2015-10-21:
* - Initial Version
*
* 2015-12-27:
* - Add clock gating control in enable/disable APIs
*
* 2017-04-27:
* - Changed XMC_ECAT_ReadPhy() and XMC_ECAT_WritePhy() to release the MII access and check that the master enables take over of MII management control
*
* @endcond
*/
/*******************************************************************************
* HEADER FILES
*******************************************************************************/
#include <xmc_ecat.h>
#if defined (ECAT0)
#include <xmc_scu.h>
/*******************************************************************************
* MACROS
*******************************************************************************/
/*******************************************************************************
* API IMPLEMENTATION
*******************************************************************************/
/* The function defines the access state to the MII management for the PDI interface*/
__STATIC_INLINE void XMC_ECAT_lRequestPhyAccessToMII(void)
{
ECAT0->MII_PDI_ACS_STATE = 0x1;
}
__STATIC_INLINE void XMC_ECAT_lReleasePhyAccessToMII(void)
{
ECAT0->MII_PDI_ACS_STATE = 0x0;
}
/* EtherCAT module clock ungating and deassert reset API (Enables ECAT) */
void XMC_ECAT_Enable(void)
{
XMC_SCU_CLOCK_UngatePeripheralClock(XMC_SCU_PERIPHERAL_CLOCK_ECAT0);
XMC_SCU_RESET_DeassertPeripheralReset(XMC_SCU_PERIPHERAL_RESET_ECAT0);
while (XMC_SCU_RESET_IsPeripheralResetAsserted(XMC_SCU_PERIPHERAL_RESET_ECAT0) == true){}
}
/* EtherCAT module clock gating and assert reset API (Disables ECAT)*/
void XMC_ECAT_Disable(void)
{
XMC_SCU_RESET_AssertPeripheralReset(XMC_SCU_PERIPHERAL_RESET_ECAT0);
while (XMC_SCU_RESET_IsPeripheralResetAsserted(XMC_SCU_PERIPHERAL_RESET_ECAT0) == false){}
XMC_SCU_CLOCK_GatePeripheralClock(XMC_SCU_PERIPHERAL_CLOCK_ECAT0);
}
/* EtherCAT initialization function */
void XMC_ECAT_Init(XMC_ECAT_CONFIG_t *const config)
{
XMC_ECAT_Enable();
/* The process memory is not accessible until the ESC Configuration Area is loaded successfully. */
/* words 0x0-0x3 */
ECAT0->EEP_DATA[0U] = config->dword[0U];
ECAT0->EEP_DATA[1U] = config->dword[1U];
ECAT0->EEP_CONT_STAT |= (uint16_t)((uint16_t)0x4U << (uint16_t)ECAT_EEP_CONT_STAT_CMD_REG_Pos);
/* words 0x4-0x7 */
ECAT0->EEP_DATA[0U] = config->dword[2U];
ECAT0->EEP_DATA[1U] = config->dword[3U];
ECAT0->EEP_CONT_STAT |= (uint16_t)((uint16_t)0x4U << (uint16_t)ECAT_EEP_CONT_STAT_CMD_REG_Pos);
while (ECAT0->EEP_CONT_STAT & ECAT_EEP_CONT_STAT_L_STAT_Msk)
{
/* Wait until the EEPROM_Loaded signal is active */
}
}
/* EtherCAT application event enable API */
void XMC_ECAT_EnableEvent(uint32_t event)
{
ECAT0->AL_EVENT_MASK |= event;
}
/* EtherCAT application event disable API */
void XMC_ECAT_DisableEvent(uint32_t event)
{
ECAT0->AL_EVENT_MASK &= ~event;
}
/* EtherCAT application event status reading API */
uint32_t XMC_ECAT_GetEventStatus(void)
{
return (ECAT0->AL_EVENT_REQ);
}
/* EtherCAT SyncManager channel disable function*/
void XMC_ECAT_DisableSyncManChannel(const uint8_t channel)
{
((ECAT0_SM_Type *)(void*)((uint8_t *)(void*)ECAT0_SM0 + (channel * 8U)))->SM_PDI_CTR |= 0x1U;
}
/* EtherCAT SyncManager channel enable function*/
void XMC_ECAT_EnableSyncManChannel(const uint8_t channel)
{
((ECAT0_SM_Type *)(void*)((uint8_t *)(void*)ECAT0_SM0 + (channel * 8U)))->SM_PDI_CTR &= (uint8_t)(~0x1U);
}
/* EtherCAT PHY register read function*/
XMC_ECAT_STATUS_t XMC_ECAT_ReadPhy(uint8_t phy_addr, uint8_t reg_addr, uint16_t *data)
{
XMC_ECAT_STATUS_t status;
if ((ECAT0->MII_ECAT_ACS_STATE != 0) || ((ECAT0->MII_PDI_ACS_STATE & ECAT_MII_PDI_ACS_STATE_FORCE_PDI_ACS_S_Msk) != 0))
{
status = XMC_ECAT_STATUS_ERROR;
}
else
{
XMC_ECAT_lRequestPhyAccessToMII();
ECAT0->MII_PHY_ADR = phy_addr;
ECAT0->MII_PHY_REG_ADR = reg_addr;
ECAT0->MII_CONT_STAT = 0x0100U; /* read instruction */
while ((ECAT0->MII_CONT_STAT & ECAT_MII_CONT_STAT_BUSY_Msk) != 0U){}
if ((ECAT0->MII_CONT_STAT & ECAT_MII_CONT_STAT_ERROR_Msk) != 0U)
{
ECAT0->MII_CONT_STAT = 0; /* Clear error */
status = XMC_ECAT_STATUS_ERROR;
}
else
{
*data = (uint16_t)ECAT0->MII_PHY_DATA;
status = XMC_ECAT_STATUS_OK;
}
XMC_ECAT_lReleasePhyAccessToMII();
}
return status;
}
/* EtherCAT PHY register write function*/
XMC_ECAT_STATUS_t XMC_ECAT_WritePhy(uint8_t phy_addr, uint8_t reg_addr, uint16_t data)
{
XMC_ECAT_STATUS_t status;
if ((ECAT0->MII_ECAT_ACS_STATE != 0) || ((ECAT0->MII_PDI_ACS_STATE & ECAT_MII_PDI_ACS_STATE_FORCE_PDI_ACS_S_Msk) != 0))
{
status = XMC_ECAT_STATUS_ERROR;
}
else
{
XMC_ECAT_lRequestPhyAccessToMII();
ECAT0->MII_PHY_ADR = phy_addr;
ECAT0->MII_PHY_REG_ADR = reg_addr;
ECAT0->MII_PHY_DATA = data;
ECAT0->MII_CONT_STAT = 0x0200U; /* write instruction */
while ((ECAT0->MII_CONT_STAT & ECAT_MII_CONT_STAT_BUSY_Msk) != 0U){}
if ((ECAT0->MII_CONT_STAT & ECAT_MII_CONT_STAT_ERROR_Msk) != 0U)
{
ECAT0->MII_CONT_STAT = 0; /* Clear error */
status = XMC_ECAT_STATUS_ERROR;
}
else
{
status = XMC_ECAT_STATUS_OK;
}
XMC_ECAT_lReleasePhyAccessToMII();
}
return status;
}
#endif
|
{
"pile_set_name": "Github"
}
|
# -*- coding: UTF-8 -*-
textlist=[
u"""بحمد الله ومنّته، أطلقنا اليوم واجهة سطح المكتب لبرنامج مشكال لتشكيل النصوص العربية آليا مفتوح المصدر،
وبهذا يتوفر حاليا تطبيقان للبرنامج على الوب .
وعلى سطح المكتب لنظام وندوز. وسيتوفر لنظام لينكس.
""",
u"""أسطورة أزمة المحتوى العربي على الإنترنت
حين تجرب، غير ما مرة، البحث بالعربية في الإنترنت ولا تجد ما يشبع حاجتك، تعرف بأن المحتوى العربي على الإنترنت يعاني نقصا فظيعا. لا تحتاج إلى جوجل أو غيرها لإخبارك بأن نسبة 1% التي يمثلها المحتوى العربي من مجموع المحتوى على الإنترنت، نسبة ضئيلة جدا. أنت تدرك ذلك منذ زمن، كما تدرك أنه قد مرت سنوات منذ سمعت أول مرة بأن المحتوى العربي على الإنترنت بالكاد يمثل تلك النسبة الهزيلة، ولا شيء تغير طيلة تلك السنوات. الكثير من الحبر سال حول الموضوع، وكثير من المؤتمرات انعقدت دون فائدة. المأساة أنك لو تتبعت تفاصيل تلك المؤتمرات التي تتحدث عن أزمة المحتوى العربي، لوجدت كل المتحدثين فيها يرطنون حول الموضوع بالانجليزية. ولا شك، أنك لو حاولت تبادل الحديث مع أحدهم، ولو في الشارع في موضوع عام، لما وجدته قادرا على تركيب جملة عربية خالصة لا تدخلها كلمات إنجليزية -أو فرنسية- بمناسبة أو دونها.
محمد الساحلي
""",
u""" أهم ميزة لمشكال أنه يقترح تشكيلا آليا للنص، ومن ثمّ يمكن للمستخدم أن يصحح التشكيل، إذا وجد به خطأ، أو لم يكن المقصود كذلك, وهذه الميزة تجعل من الإصدار الحالي التجريبي مساعدا للتشكيل أكثر من كونه تشكيلا آليا,
""",
u"""تشكيل النصوص العربية أهم مسائل معالجة اللغة العربية، بلوغه يقتضي تجاوز عقبات عديدة، وقد أهمّت هذه المسألة الكثير من الباحثين، وحتى الشركات
""",
u""" أهم ميزة لمشكال أنه يقترح تشكيلا آليا للنص، ومن ثمّ يمكن للمستخدم أن يصحح التشكيل، إذا وجد به خطأ، أو لم يكن المقصود كذلك, وهذه الميزة تجعل من الإصدار الحالي التجريبي مساعدا للتشكيل أكثر من كونه تشكيلا آليا,
""",
u"""
يقدم البرنامج وظيفة نادرة لخدمة اللغة العربية ( لغة القرآن ) فهو يساعد المستخدم لتشكيل النص ، حيث يقوم البرنامج بمعالجة النص بعد وضعه في المربع المخصص له ووضع التشكيل عليه ( الفتحة والضمة والكسرة و.... الخ ) ومن ثم يمكن للمستخدم النقر على أي كلمة لتصحيح التشكيل وتغييره إذا كان فيه خطأ
البرنامج هو مساعد لعملية التشكيل أكثر منه مشكل آلي ، حيث لا غنى عن معرفة المستخدم في تصحيح بعض الأخطاء وتعديل التشكيل في بعض الكلمات ، لكن مسألة التشكيل ستكون سهلة وسريعة ومريحة جدا للمستخدم العربي بواسطة هذا البرنامج
"""
,
u"الولد مريض.",
u"الطائر فوق الشجرة.",
u"البستان جميل.",
u"قطف محمد زهرة.",
u"الشمس طالعة.",
u"شم علي وردة.",
u"يعيش السمك في الماء.",
u"يكثر النخيل في مصر.",
u"السماء ممطرة.",
u"الحديقة جميلة.",
u"يقطف علي الأزهار.",
u"يلعب الغلمان بالكرة.",
u"ينزل المطر من السماء .",
u"يسير السحاب.",
u"تطلع الشمس .",
u"تسير السفن في البحار.",
u"تجف الأرض .",
u"يشتد البرد في الجبال.",
u"الثوب نظيف.",
u"القطار سريع.",
u"العصفور في القفص .",
u"الولد يأكل الفاكهة .",
u"الثور يحرث الأرض .",
u"القمر في السماء.",
u"ركب إبراهيم الحصان .",
u"سمعت النصيحة.",
u"يداعب إسماعيل القط.",
u"يسطع النور في الحجرة .",
u"يحصد الفلاح القمح.",
u"تجري السفينة على الماء.",
u"تأكل الشاة فولا وشعيرا .",
u"هل تحب السفر.",
u"فريد يجري في الشارع.",
u"يحب الولد البرتقال.",
u"علي يركب الحمار.",
u"يحترق الحطب.",
u"الكلب ينام في البستان.",
u"يتسلق الغلمان الجبل.",
u"افترس الذئب كبشا.",
u"يسبح الأولاد في البحار.",
u"البستاني يجمع الأزهار.",
u"المداد في الدواة.",
u"الثعلب يأكل الدجاج.",
u"الحديد يذوب في النار.",
u"يفتح محمد الباب.",
u"الثمر يتساقط على الأرض.",
u"يشتري التاجر القطن.",
u"يزرع الفلاح القصب.",
u"تصنع الأحذية من الجلد.",
u"يقرأ سعيد الكتاب.",
u"العصفور يغرد على الشجرة.",
u"يدخل الهواء في الحجرة.",
u"يذهب العمال إلى المصنع.",
u"العصفور مسجون في القفص.",
u"تبيض الدجاجة.",
u"يقرأ محمد كتابا.",
u"يطيع أحمد أباه.",
u"الحصان يجر العربة.",
u"يشتد الحر في الصيف.",
u"الفأر يخاف من الهر.",
u"الحصان يأكل الشعير.",
u"المريض يرجو الشفاء.",
u"الولد يلعب بالكرة.",
u"كسر محمود الغصن.",
u"يصنع النجار بابا.",
u"الطبيب يعالج المريض.",
u"الخادم يفتح النافذة.",
u"يسبح الغلام في النهر.",
u"يعود الغريب إلى بلده.",
u"يذهب التلميذ إلى المدرسة.",
u"نام الطفل على السرير.",
u"قطعت الحبل بالسكين.",
u"يرضى المعلم عن التلميذ المؤدب.",
u"جرى الكلب.",
u"وقف الرجل.",
u"دقت الساعة.",
u"جاءت البنت.",
u"ضاع الكتاب.",
u"باضت الدجاجة.",
u"أغسل يدي.",
u"ينبح الكلب.",
u"ألبس ثيابي.",
u"ينتبه الحارس.",
u"يلعب بالكرة.",
u"تأكل البنت.",
u"نمشي في الحقول.",
u"تذبل الوردة.",
u"العب بالكرة.",
u"نم مبكرا.",
u"أطعم قطك.",
u"تمهل في السير.",
u"نظف ثيابك.",
u"أجد مضغ الطعام.",
u"جنى الفلاح قطنه وباعه ثم اشترى ببعض ثمنه ما يحتاج إليه.",
u"نظر الطفل إلى الطائر وهو يحلق في السماء.",
u"هبت العواصف ليلا فأطفأت المصابيح واقتلعت الأشجار.",
u"سطا الذئب على الغنم فافترس واحدة وفر هاربا.",
u"ادخل البستان ومتع نفسك بمنظره ، ولا تعبث بأزهاره وثماره.",
u"لا تكثر من الكلام ، ولا تنطق بما لا تعلم.",
u"اغسل يديك قبل الأكل وبعده ، ونظف أسنانك ، ولا تدخل الطعام على الطعام.",
u"الفأرة تخاف من القط.",
u"الدجاجة تبيض كل يوم بيضة.",
u"الكلب يركض وراء صاحبه.",
u"الأم تطعم أولادها.",
u"الولد أراد الجلوس.",
u"الخادم نظف الغرفة.",
u"الرجل سبح في النهر.",
u"علي سافر إلى فرنسا.",
u"سار القطار.",
u"مرض الغلام.",
u"طار الصقر.",
u"نزل المطر.",
u"سافر والدي.",
u"عطش الزرع .",
u"يغرد العصفور.",
u"يثمر البستان.",
u"يبيع التاجر البن.",
u"يغسل الولد يديه.",
u"يجني الفلاح القطن.",
u"أحترم المعلم.",
u"أقرأ في الكتاب.",
u"أحفظ الدرس.",
u"أشتغل في الحديقة.",
u"أنظف الحذاء.",
u"أنطق بالصدق.",
u"طار العصفور.",
u"يعوم السمك.",
u"جرى الحصان.",
u"يلسع البعوض.",
u"لعب الولد.",
u"تأكل البنت.",
u"حضر الغائب.",
u"يطير الذباب.",
u"فاض النهر.",
u"يربح التاجر.",
u"شد التلميذ الحبل.",
u"يربح السابق جائزة.",
u"طوت البنت الثوب.",
u"يصيد الثعلب دجاجة.",
u"أكل الذئب الخروف.",
u"يبيع القصاب اللحم.",
u"مزق الغلام الورق.",
u"صنع النجار كرسيا.",
u"حلبت الفتاة البقرة.",
u"رمى الصياد الشبكة.",
u"أيقظ الرعد النائم.",
u"طبخت المرأة الطعام.",
u"أكل الحمار الفول.",
u"أبصر الرجل الهلال.",
#نعت
u" هذا كتاب مفيد .",
u"قرأت كتابا مفيدا .",
u"نظرت في كتاب مفيد .",
u"هذا ميدان فسيح .",
u"رأيت ميدانا فسيحا .",
u"جريت في ميدان فسيح .",
u"تفتحت الوردة الجميلة .",
u"قطفت الوردة الجميلة .",
u"نظرت إلى الوردة الجميلة .",
u"الولد المهذب يحبه أبوه .",
u"لا تشرب الماء الراكد .",
u"الحذاء الجديد يضر القدم .",
u"أكثر من القراءة في الكتب النافعة , زرت ضاحية بديعة.",
u"يضر الصديق الكاذب صديقه .",
u"للجمل عنق طويل .",
u"عدو عاقل خير من صديق جاهل .",
u"تنافسوا في العمل الصالح .",
u"يحب الناس الحاكم العادل .",
u"وضعت الصورة في إطار بديع .",
u"الأكل الكثير يضر المعدة .",
u"أكره السير في الطرق المزدحمة .",
u"تحمل الشجرة ثمارا ناضجة .",
u"في السماء نجوم لامعة .",
u"للطاووس ريش جميل .",
u"أرى في الجو سحابا كثيفا .",
u"ربح التاجر الأمين .",
u"يقرأ علي كتابا مفيدا .",
u"نزل من السماء مطر غزير .",
u"يلبس علي حذاء واسعا .",
u"يكثر النخل في البساتين المثمرة .",
#المبتدا والخبر
u"التفاحة حلوة .",
u"الصورة جميلة .",
u"القطار سريع .",
u"النظافة واجبة .",
u"الجري مفيد .",
u"الأرض مستديرة .",
u"الدواة مملوءة .",
u"الهواء متجدد .",
u"الحذاء جديد .",
u"المزاح مضر .",
u"التاجر أمين .",
u"الحديقة فسيحة .",
u"المعلم حاضر .",
u"الفقير محتاج .",
u"الشجرة مثمرة .",
#الجملة الفعلية
u" يفترس النمر .",
u"تنضج الفاكهة .",
u"يحضر المسافر .",
u"يشتد الحر .",
u"يسبح السمك .",
u"يندم الكسلان .",
u"السيارة سريعة .",
u"القط ألوف .",
u"لمع البرق .",
u"يشتد البرد .",
u"عوى الذئب .",
u"اقطف الوردة .",
u"خذ الكتاب .",
#الجملة الاسمية
u"الدار واسعة .",
u"الشارع مزدحم .",
u"الجو معتدل .",
u"الطريقة ضيقة .",
u"الغبار ثائر .",
u"الفأرة مختبئة .",
u"الماء رائق .",
u"يسرج الخادم الحصان .",
u"يسقط الخادم .",
u"الزجاج مكسور .",
u"البرد قارس .",
u"القط جائع .",
u"يشتد الحر في الصيف .",
u"جنى الفلاح القطن .",
u"يجول التاجر في البلاد .",
u"النوافذ مفتوحة .",
u"تزدحم المدينة بالسكان .",
u"الولد نائم .",
u"الكتاب نافع .",
u"البحر هائج .",
u"الشمس مشرقة .",
u"المطر كثير .",
u"الحجرة مظلمة .",
u"ضاع المفتاح .",
u"يثمر البستان .",
u"أسرع القطار .",
u"يغرد الطائر .",
u"زاد النيل .",
u"يضيء المصباح .",
u"ما شكل البرتقالة ؟ ما لونها ؟.",
u"هل أكلت برتقالة ؟ كيف وجدت طعمها ؟ أناعمة هي أم خشنة ؟.",
u"بكم تشتري البرتقالة ؟.",
#نصب الفعل المضارع
u"أريد أن أجيد السباحة .",
u"أرجو أن يعتدل الجو .",
u"لن أكتب .",
u"لن يفوز الكسلان .",
u"سرني أن تزورنا .",
u"لن أضرب القط .",
u"إذن تقيم عندنا .",
u"إذن تربح تجارتك .",
u"جئت كي أتعلم .",
u"خرجت كي أتنزه .",
u"أتعلم كي أخدم الوطن .",
u"لن يبيع أبي حصانه.",
u"هززت الشجرة كي يسقط ثمرها .",
u"لا يجوز للإنسان أن يجلس في مجرى الهواء .",
u"فتحت نوافذ الجحرة كي يتجدد هواؤها .",
u"كن مؤدبا كي تكون محبوبا .",
u"يشتغل الإنسان بالنهار وينام بالليل .",
u"يجب عليك أن تنظف أسنانك كل يوم .",
u"سأعتاد التبكير في النوم ، إذن يصح بدنك .",
u"يقرأ سعيد في الضوء الضعيف .",
u"يتعب الإنسان في صغره كي يرتاح في كبره .",
u"يسرني أن تحضر .",
u"يأكل الإنسان كي ينمو .",
u"الحسود لن يسود .",
u"على المسافر أن يتزود .",
u"اشتريت منزلا كي أسكنه .",
u"إن عدت إلى الذنب فلن أسامحك .",
u"يحرث الفلاح الأرض كي يزرعها .",
u"يرغب التاجر في أن يربح .",
u"يؤلم العين أن تنظر إلى الشمس .",
u"التلميذ الكسلان لن ينجح .",
u"يصدق التاجر كي يرضي الله .",
u"تبنى السجون كي يدخلها المجرمون .",
u"لا يستطيع الأعمى أن يقرأ المكتوب .",
u"أحب أن أسافر .",
u"أسرعت كي أدرك القطار .",
u"جئت كي أسلم عليك .",
u"يؤلمني أن تعذب الحيوان .",
u"يسرني أن أنجح .",
u"أطاع كي يحبه أبوه .",
u"لن يعود الغائب .",
u"المذنب لن يعود إلى ذنبه .",
u"محمد لن يتأخر في الصباح .",
u"أخوك لن يتعرض للبرد .",
u"لن أسافر وحدي .",
u"لن أبطئ في المشي .",
u"جلس الولد كي يستريح .",
u"إذن يذهب التعب .",
# جزم الفعل المضارع
u"لم يحفظ محمد درسه .",
u"لا تأكل وأنت شبعان .",
u"لم ينقطع نزول المطر .",
u"لا تكثر من الضحك .",
u"لم يقبض أحد على اللص .",
u"لا تسرع في السير .",
u"إن تفتح نوافذ الحجرة يتجدد هواؤها .",
u"إن تجلس في مجرى الهواء تمرض .",
u"إن يسافر أخوك تسافر معه .",
u"غامت السماء ولم تمطر .",
u"إن تقرب من النار تشعر بحرارتها .",
u"لم يحضر علي البارحة .",
u"إن تتلف شيئا لغيرك تدفع ثمنه .",
u"لا تتعود كثرة المزاح .",
u"إن تضرب قطا يخمشك .",
u"لا تشرب وأنت تعب .",
u"لا تبلع طعاما قبل أن تجيد مضغه .",
u"العصفور لم يغرد .",
u"مشيت كثيرا ولم أتعب .",
u"لم يثمر البستان .",
u"القطار لم يتأخر عن موعده .",
u"لم يحضر محمد مع أخيه .",
u"لم أتعلم السباحة .",
u"لم أضيع وقتا في اللعب .",
u"الفلاح لم يحلب بقرته .",
u"لا تلوث يديك بالمداد .",
u"لا تتلف أثاث المنزل .",
u"لا تضرب من هو أصغر منك .",
u"لا تأخذ ما ليس لك .",
u"لا تشرب بعد الجري .",
u"لا تلبس الملابس الضيقة .",
u"لم يسافر محمد .",
u"لا ترافق الأشرار .",
u"لم يلعب الولد .",
u"لا تعذب الحيوان .",
u"لم يأكل القط .",
u"لا تهمل دروسك .",
u"لم ينكسر الزجاج .",
u"لم يرسل الغائب رسالة إلى أهله .",
u"لم يحرث الفلاح أرضه .",
u"لا تشرب الماء الكدر .",
u"لا تكذب .",
#كان وأخواتها
u"الزحام شديد .",
u"كان الزحام شديدا .",
u"البيت نظيف .",
u"كان البيت نظيفا .",
u"الثوب قصير .",
u"صار الثوب قصيرا .",
u"البرد قارس .",
u"صار البرد قارسا .",
u"الخادم قوي .",
u"ليس الخادم قويا .",
u"العامل نشيط .",
u"ليس العامل نشيطا .",
u"النهم مريض .",
u"أصبح النهم مريضا .",
u"الجو ممطر .",
u"أصبح الجو ممطرا .",
u"العامل متعب .",
u"أمسى العامل متعبا .",
u"الزهر ذابل .",
u"أمسى الزهر ذابلا .",
u"الغمام كثيف .",
u"أضحى الغمام كثيفا .",
u"الشارع مزدحم .",
u"أضحى الشارع مزدحما .",
u"المطر غزير .",
u"ظل المطر غزيرا .",
u"المصباح متقد .",
u"بات المصباح متقدا .",
u"المريض متألم .",
u"بات المريض متألما .",
u"يصبح المداد جافا .",
u"يبيت البحر هائجا .",
u"يظل العامل مشتغلا .",
u"يمسي الناجح مسرورا .",
u"يضحي الشارع مزدحما .",
u"أصبحت الغرفة نظيفة.",
u"باتت البحيرة هائجة .",
u"ظلت العاملة مشتغلة .",
u"أمست الناجحة مسرورة .",
u"أضحت المدينة مزدحمة .",
u"تصبح الغرفة نظيفة .",
u"تبيت البحيرة هائجة .",
u"تظل العاملة مشتغلة .",
u"تمسي الناجحة مسرورة .",
u"تضحي المدينة مزدحمة .",
#إن وأخواتها
u" إن الجمل صبور .",
u"إن الهرم قديم .",
u"علمت أن الامتحان قريب .",
u"يسرني أن الزهرة ناضرة .",
u"كأن الكتاب أستاذ .",
u"كأن القمر مصباح .",
u"البيت جديد لكن الأثاث قديم .",
u"شبت النار لكن الخسائر قليلة .",
u"ليت الفاكهة ناضجة .",
u"ليت القمر طالع .",
u"لعل الكتاب رخيص.",
u"لعل المريض نائم .",
]
|
{
"pile_set_name": "Github"
}
|
/*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK 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 THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO 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 THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors:
* Gradient Systems
*/
#ifndef S_CLASS_H
#define S_CLASS_H
#define RS_CLASS_DESC 50
#define S_CLASS_DESC_MIN 35
/*
* S_CLASS table structure
*/
struct S_CLASS_TBL {
ds_key_t id;
ds_key_t subcat_id;
char desc[RS_CLASS_DESC + 1];
};
int mk_s_class(void *pDest, ds_key_t kIndex);
int pr_s_class(void *pSrc);
int ld_s_class(void *pSrc);
#endif
|
{
"pile_set_name": "Github"
}
|
# Практическое занятие: Генерация Javadoc из примера проекта
Javadoc является стандартным выводом для API Java. Создание Javadoc довольно простое. Javadoc генерируется с помощью так называемого «доклета». Различные доклеты могут по-разному анализировать аннотации Java и создавать разные выходные данные. Но по большому счету почти каждая документация по Java использует стандартный доклет. Выходные данные Javadoc знакомы разработчикам Java и приветствуются ими.
Javadoc поддерживается Oracle. Разработчики могут интегрировать вывод Javadoc непосредственно в свою IDE, что делает документацию удобной и легко доступной. Фактически, Javadoc часто доставляется таким образом, а не разворачивается и загружается на сервер. Javadoc содержит только справочную документацию. В документацию нельзя добавлять какие-либо концептуальные файлы справки или изменять макет.
[Генерация Javadoc](#generate)
[Javadoc и проверка ошибок](#error)
[Изучение параметров Javadoc](#parameters)
[Автоматическое создание Javadoc](#build)
<a name="generate"></a>
## 👨💻 Генерация Javadoc
В этом упражнении создадим Javadoc из загруженного ранее [примера проекта Java](Get-the-sample-Java-project.md). Посмотреть итоговый [вывод Javadoc можно здесь](https://idratherbewriting.com/learnapidoc/assets/files/javadoc/index.html).
1. В Eclipse переходим в **File > Export**;
2. Раскроем **Java** и выберем **Javadoc**. И нажмем кнопку **Next**;
3. Выбираем свой проект и пакет. После, в правой панели классы, которые нужно включить в Javadoc: в этом примере это будут **Dynamite.java** и **ACMESmartphone.java**.

Выбирать класс `App.java`, который содержит метод `main` не нужно, потому что не нужно предоставлять документацию по Java для вашей программы. Javadoc предоставит документацию для классов, которые разработчики могут использовать в своих программах. В этом примере проекта основной метод включен в App.java, но он мог бы быть включен в файл и с другим именем.
4. Выбираем вариант видимости: Private, Package, Protected, или Public. Как правило выбирают **Public**.
API, может иметь множество вспомогательных или служебных классов, используемых в бэкэнде, но разработчиками будет использоваться только определенное количество классов. Эти классы созданы public. Классы, которые разработчики будут использовать, формируют аспект API библиотеки классов.
5. Убедимся, что радиобаттон **Use standard doclet** выбран (Выбирается по умолчанию).
6. Нажимаем кнопку **Browse** и выбираем место, куда выводить сгенерированный Javadoc. По умолчанию он будет генерироваться в подпапке `doc`, созданной в той же папке, где хранится код. Таким образом, просматривать Javadoc можно непосредственно в Eclipse IDE.
На этом занятии выберем другое место вывода (например, папку на рабочем столе или в документах), отличное от используемого по умолчанию. Причина в том, что проект уже имеет сгенерированный Javadoc в папке с документами, поэтому можно даже не понять, что файл Javadoc создан, т.к. новый вывод просто перезапишет существующие файлы документов.
> Когда разработчики предоставляют библиотеки Java, они часто добавляют документацию непосредственно в JAR-файл. Пользователи привыкли искать документацию в папке doc.
7. Нажимаем **Next** и видим окно с дополнительными настройками конфигураций.

Здесь вы можете выбрать пропуски тегов, такие как @author и @deprecated. Как правило, исключается тег @author, поскольку он может быть важен только внутри, а не снаружи. Можно выбрать различные параметры во фрейме Javadoc. Если есть кастомизированная таблица стилей, то указать ее можно здесь. Скорее всего, изменения стиля будут только поверхностными, например, с цветами.
8. Нажимаем **Next**

Здесь можно выбрать HTML-страницу, которая будет [обзорной страницей в Javadoc](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#overviewcomment). Можно выбрать любую HTML-страницу, и она будет включена в индекс.
9. Нажимаем кнопку **Finish**
Если кнопка **Finish** неактивна, это может быть связано с тем, что Eclipse не может найти нужный исполняемый файл Javadoc. Можно нажать **Configure** и найти файл вручную. На MacBook Pro файл Javadoc находится по адресу `/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/bin/javadoc`.
Если будет предложено обновить местоположение Javadoc (которое, вероятно, отличается от местоположения рабочего пространства Eclipse), стоит это сделать, нажав **Yes to all**.
Перейдите к месту назначения и откройте файл index.html в браузере, чтобы просмотреть файлы.
> Если возникли проблемы со сборкой Javadoc, получившуюся документацию можно посмотреть [здесь](https://idratherbewriting.com/learnapidoc/assets/files/javadoc/index.html).
<a name="error"></a>
## Javadoc и проверка ошибок
Javadoc также проверяет теги по фактическому коду. Если есть параметры, исключения или возвраты, которые не соответствуют параметрам, исключениям или возвратам в фактическом коде, то Javadoc будет показывать предупреждения.

<a name="parameters"></a>
## 👨💻 Изучение параметров Javadoc
Можно попробовать удалять некоторые параметры из метода и снова генерировать Javadoc. Перед этим нужно убедиться, что окно консоли открыто, чтобы можно было видеть предупреждения об ошибках.
<a name="build"></a>
## Автоматическое создание Javadoc
В большинстве проектов файл Javadoc никогда не создается вручную, как описано здесь. Javadoc позволяет строить его из командной строки, передавая ему файл конфигурации. У большинства разработчиков есть инструмент управления сборкой, где они могут настраивать выходные данные из своего кода, включая Javadoc. Если разработчики попросят собрать Javadoc, скорее всего, их система управления сборкой может быть несколько примитивной. Тем не менее, может быть полезно создать выходные данные Javadoc самостоятельно (как описано здесь), чтобы протестировать и просмотреть выходные данные, прежде чем создавать их с помощью инструмента управления сборкой.
|
{
"pile_set_name": "Github"
}
|
AF: Afghanistan
AX: 'Åland Islands'
AL: Albania
DZ: Algeria
AS: 'American Samoa'
AD: Andorra
AO: Angola
AI: Anguilla
AQ: Antarctica
AG: 'Antigua & Barbuda'
AR: Argentina
AM: Armenia
AW: Aruba
AU: Australia
AT: Austria
AZ: Azerbaijan
BS: Bahamas
BH: Bahrain
BD: Bangladesh
BB: Barbados
BY: Belarus
BE: Belgium
BZ: Belize
BJ: Benin
BM: Bermuda
BT: Bhutan
BO: Bolivia
BA: 'Bosnia & Herzegovina'
BW: Botswana
BV: 'Bouvet Island'
BR: Brazil
IO: 'British Indian Ocean Territory'
VG: 'British Virgin Islands'
BN: Brunei
BG: Bulgaria
BF: 'Burkina Faso'
BI: Burundi
KH: Cambodia
CM: Cameroon
CA: Canada
CV: 'Cape Verde'
BQ: 'Caribbean Netherlands'
KY: 'Cayman Islands'
CF: 'Central African Republic'
TD: Chad
CL: Chile
CN: China
CX: 'Christmas Island'
CC: 'Cocos (Keeling) Islands'
CO: Colombia
KM: Comoros
CG: 'Congo - Brazzaville'
CD: 'Congo - Kinshasa'
CK: 'Cook Islands'
CR: 'Costa Rica'
CI: 'Côte d’Ivoire'
HR: Croatia
CU: Cuba
CW: Curaçao
CY: Cyprus
CZ: Czechia
DK: Denmark
DJ: Djibouti
DM: Dominica
DO: 'Dominican Republic'
EC: Ecuador
EG: Egypt
SV: 'El Salvador'
GQ: 'Equatorial Guinea'
ER: Eritrea
EE: Estonia
SZ: Eswatini
ET: Ethiopia
FK: 'Falkland Islands'
FO: 'Faroe Islands'
FJ: Fiji
FI: Finland
FR: France
GF: 'French Guiana'
PF: 'French Polynesia'
TF: 'French Southern Territories'
GA: Gabon
GM: Gambia
GE: Georgia
DE: Germany
GH: Ghana
GI: Gibraltar
GR: Greece
GL: Greenland
GD: Grenada
GP: Guadeloupe
GU: Guam
GT: Guatemala
GG: Guernsey
GN: Guinea
GW: Guinea-Bissau
GY: Guyana
HT: Haiti
HM: 'Heard & McDonald Islands'
HN: Honduras
HK: 'Hong Kong SAR China'
HU: Hungary
IS: Iceland
IN: India
ID: Indonesia
IR: Iran
IQ: Iraq
IE: Ireland
IM: 'Isle of Man'
IL: Israel
IT: Italy
JM: Jamaica
JP: Japan
JE: Jersey
JO: Jordan
KZ: Kazakhstan
KE: Kenya
KI: Kiribati
KW: Kuwait
KG: Kyrgyzstan
LA: Laos
LV: Latvia
LB: Lebanon
LS: Lesotho
LR: Liberia
LY: Libya
LI: Liechtenstein
LT: Lithuania
LU: Luxembourg
MO: 'Macao SAR China'
MG: Madagascar
MW: Malawi
MY: Malaysia
MV: Maldives
ML: Mali
MT: Malta
MH: 'Marshall Islands'
MQ: Martinique
MR: Mauritania
MU: Mauritius
YT: Mayotte
MX: Mexico
FM: Micronesia
MD: Moldova
MC: Monaco
MN: Mongolia
ME: Montenegro
MS: Montserrat
MA: Morocco
MZ: Mozambique
MM: 'Myanmar (Burma)'
NA: Namibia
NR: Nauru
NP: Nepal
NL: Netherlands
NC: 'New Caledonia'
NZ: 'New Zealand'
NI: Nicaragua
NE: Niger
NG: Nigeria
NU: Niue
NF: 'Norfolk Island'
KP: 'North Korea'
MK: 'North Macedonia'
MP: 'Northern Mariana Islands'
'NO': Norway
OM: Oman
PK: Pakistan
PW: Palau
PS: 'Palestinian Territories'
PA: Panama
PG: 'Papua New Guinea'
PY: Paraguay
PE: Peru
PH: Philippines
PN: 'Pitcairn Islands'
PL: Poland
PT: Portugal
PR: 'Puerto Rico'
QA: Qatar
RE: Réunion
RO: Romania
RU: Russia
RW: Rwanda
WS: Samoa
SM: 'San Marino'
ST: 'São Tomé & Príncipe'
SA: 'Saudi Arabia'
SN: Senegal
RS: Serbia
SC: Seychelles
SL: 'Sierra Leone'
SG: Singapore
SX: 'Sint Maarten'
SK: Slovakia
SI: Slovenia
SB: 'Solomon Islands'
SO: Somalia
ZA: 'South Africa'
GS: 'South Georgia & South Sandwich Islands'
KR: 'South Korea'
SS: 'South Sudan'
ES: Spain
LK: 'Sri Lanka'
BL: 'St. Barthélemy'
SH: 'St. Helena'
KN: 'St. Kitts & Nevis'
LC: 'St. Lucia'
MF: 'St. Martin'
PM: 'St. Pierre & Miquelon'
VC: 'St. Vincent & Grenadines'
SD: Sudan
SR: Suriname
SJ: 'Svalbard & Jan Mayen'
SE: Sweden
CH: Switzerland
SY: Syria
TW: Taiwan
TJ: Tajikistan
TZ: Tanzania
TH: Thailand
TL: Timor-Leste
TG: Togo
TK: Tokelau
TO: Tonga
TT: 'Trinidad & Tobago'
TN: Tunisia
TR: Turkey
TM: Turkmenistan
TC: 'Turks & Caicos Islands'
TV: Tuvalu
UM: 'U.S. Outlying Islands'
VI: 'U.S. Virgin Islands'
UG: Uganda
UA: Ukraine
AE: 'United Arab Emirates'
GB: 'United Kingdom'
US: 'United States'
UY: Uruguay
UZ: Uzbekistan
VU: Vanuatu
VA: 'Vatican City'
VE: Venezuela
VN: Vietnam
WF: 'Wallis & Futuna'
EH: 'Western Sahara'
YE: Yemen
ZM: Zambia
ZW: Zimbabwe
|
{
"pile_set_name": "Github"
}
|
//TODO: Осталось сделать только список цветов с перебором по букве диска
//TODO: И аналогично для цвета фона градусника/картинок/текста и самого градусника
/*
Copyright (c) 2010-present Maximus5
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. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
*/
#ifdef _DEBUG
// Раскомментировать, чтобы сразу после загрузки плагина показать MessageBox, чтобы прицепиться дебаггером
// #define SHOW_STARTED_MSGBOX
// #define SHOW_WRITING_RECTS
#endif
#include "../common/Common.h"
#include "../common/CEStr.h"
#ifdef _DEBUG
#pragma warning( disable : 4995 )
#endif
#include "../common/pluginW1761.hpp" // Отличается от 995 наличием SynchoApi
#ifdef _DEBUG
#pragma warning( default : 4995 )
#endif
#define GDIPVER 0x0110
#include "../common/GdiPlusLt.h"
#include "../common/xmllite.h"
#include "../common/MStrDup.h"
#include "../common/MStream.h"
#include "../common/UnicodeChars.h"
#include "../common/FarVersion.h"
#include "../common/MSectionSimple.h"
#include "../common/WThreads.h"
#include "ConEmuBg.h"
#define MAKEFARVERSION(major,minor,build) ( ((major)<<8) | (minor) | ((build)<<16))
#define DBGSTR(s) OutputDebugString(s);
#if defined(__GNUC__)
extern "C" {
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved);
void WINAPI SetStartupInfoW(void *aInfo);
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo);
void WINAPI GetPluginInfoWcmn(void *piv);
};
#endif
#ifndef DT_HIDEPREFIX
#define DT_HIDEPREFIX 0x00100000
#endif
HMODULE ghPluginModule = NULL; // ConEmuBg.dll - сам плагин
//wchar_t* gszRootKey = NULL;
FarVersion gFarVersion = {};
static RegisterBackground_t gfRegisterBackground = NULL;
bool gbInStartPlugin = false;
bool gbSetStartupInfoOk = false;
ConEmuBgSettings gSettings[] = {
{L"PluginEnabled", (LPBYTE)&gbBackgroundEnabled, REG_BINARY, 1},
{L"XmlConfigFile", (LPBYTE)gsXmlConfigFile, REG_SZ, countof(gsXmlConfigFile)},
//{L"LinesColor", (LPBYTE)&gcrLinesColor, REG_DWORD, 4},
//{L"HilightType", (LPBYTE)&giHilightType, REG_DWORD, 4},
//{L"HilightPlugins", (LPBYTE)&gbHilightPlugins, REG_BINARY, 1},
//{L"HilightPlugBack", (LPBYTE)&gcrHilightPlugBack, REG_DWORD, 4},
{NULL}
};
BOOL gbBackgroundEnabled = FALSE;
wchar_t gsXmlConfigFile[MAX_PATH] = {};
BOOL gbMonitorFileChange = FALSE;
//COLORREF gcrLinesColor = RGB(0,0,0xA8); // чуть светлее синего
//int giHilightType = 0; // 0 - линии, 1 - полосы
//BOOL gbHilightPlugins = FALSE;
//COLORREF gcrHilightPlugBack = RGB(0xA8,0,0); // чуть светлее красного
// minimal(?) FAR version 2.0 alpha build FAR_X_VER
int WINAPI GetMinFarVersionW(void)
{
// ACTL_SYNCHRO required
return MAKEFARVERSION(2,0,std::max(1007,FAR_X_VER));
}
void WINAPI GetPluginInfoWcmn(void *piv)
{
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(GetPluginInfoW)(piv);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(GetPluginInfoW)(piv);
else
FUNC_X(GetPluginInfoW)(piv);
}
BOOL gbInfoW_OK = FALSE;
void WINAPI ExitFARW(void);
void WINAPI ExitFARW3(void*);
int WINAPI ConfigureW(int ItemNumber);
int WINAPI ConfigureW3(void*);
bool FMatch(LPCWSTR asMask, LPWSTR asPath);
#include "../common/SetExport.h"
ExportFunc Far3Func[] =
{
{"ExitFARW", (void*)ExitFARW, (void*)ExitFARW3},
{"ConfigureW", (void*)ConfigureW, (void*)ConfigureW3},
{NULL}
};
BOOL WINAPI DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
ghPluginModule = (HMODULE)hModule;
//ghWorkingModule = hModule;
HeapInitialize();
#ifdef SHOW_STARTED_MSGBOX
if (!IsDebuggerPresent())
MessageBoxA(NULL, "ConEmuBg*.dll loaded", "ConEmuBg plugin", 0);
#endif
bool lbExportsChanged = false;
if (LoadFarVersion())
{
if (gFarVersion.dwVerMajor == 3)
{
lbExportsChanged = ChangeExports( Far3Func, ghPluginModule );
if (!lbExportsChanged)
{
_ASSERTE(lbExportsChanged);
}
}
}
}
break;
case DLL_PROCESS_DETACH:
HeapDeinitialize();
break;
}
return TRUE;
}
#if defined(CRTSTARTUP)
extern "C" {
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved);
};
BOOL WINAPI _DllMainCRTStartup(HANDLE hDll,DWORD dwReason,LPVOID lpReserved)
{
DllMain(hDll, dwReason, lpReserved);
return TRUE;
}
#endif
BOOL LoadFarVersion()
{
wchar_t ErrText[512]; ErrText[0] = 0;
BOOL lbRc = LoadFarVersion(gFarVersion, ErrText);
if (!lbRc)
{
gFarVersion.dwVerMajor = 2;
gFarVersion.dwVerMinor = 0;
gFarVersion.dwBuild = FAR_X_VER;
}
return lbRc;
}
void WINAPI SetStartupInfoW(void *aInfo)
{
gbSetStartupInfoOk = true;
if (!gFarVersion.dwVerMajor) LoadFarVersion();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(SetStartupInfoW)(aInfo);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(SetStartupInfoW)(aInfo);
else
FUNC_X(SetStartupInfoW)(aInfo);
//_ASSERTE(gszRootKey!=NULL && *gszRootKey!=0);
gbInfoW_OK = TRUE;
StartPlugin(FALSE);
}
struct DrawInfo
{
LPCWSTR szVolume, szVolumeRoot, szVolumeSize, szVolumeFree;
DWORD nDriveType;
enum {
dib_Small = 0, dib_Large = 1, dib_Off = 2
} nSpaceBar;
wchar_t szPic[MAX_PATH]; // Это относительный путь! считая от папки с плагином ("img/plugin.png")
wchar_t szText[MAX_PATH]; // Текст, который отображается под картинкой ("G: 128Gb")
COLORREF crBack[32]; // Цвет фона
int nBackCount;
COLORREF crDark[32]; // Цвет спрайтов, текста, фона градусника
int nDarkCount;
COLORREF crLight[32]; // Цвет градусника
int nLightCount;
enum DrawInfoFlags
{
dif_PicFilled = 0x0000001,
dif_TextFilled = 0x0000002,
dif_BackFilled = 0x0000004,
dif_DarkFilled = 0x0000008,
dif_LightFilled = 0x0000010,
dif_ShiftBackColor = 0x0000020,
dif_Disabled = 0x8000000,
};
DWORD Flags; // of DrawInfoFlags
};
bool gbGdiPlusInitialized = false;
typedef HRESULT (WINAPI* CreateXmlReader_t)(REFIID riid, void** ppvObject, void* pMalloc);
CreateXmlReader_t gfCreateXmlReader = NULL;
HMODULE ghXmlLite = NULL;
struct XmlConfigFile
{
MSectionSimple* cr;
FILETIME FileTime;
LPBYTE FileData;
DWORD FileSize;
};
XmlConfigFile XmlFile = {};
wchar_t* gpszXmlFile = NULL;
wchar_t* gpszXmlFolder = NULL;
HANDLE ghXmlNotification = NULL;
const wchar_t* szDefaultXmlName = L"Background.xml";
void ReportFail(LPCWSTR asInfo)
{
wchar_t szTitle[128];
swprintf_c(szTitle, L"ConEmuBg, PID=%u", GetCurrentProcessId());
wchar_t* pszErr = lstrmerge(asInfo,
L"\n" L"Config value: ", gsXmlConfigFile[0] ? gsXmlConfigFile : szDefaultXmlName,
L"\n" L"Expanded: ", gpszXmlFile ? gpszXmlFile : L"<NULL>");
MessageBox(NULL, pszErr, szTitle, MB_ICONSTOP|MB_SYSTEMMODAL);
free(pszErr);
}
bool WasXmlLoaded()
{
return (XmlFile.FileData != NULL);
}
// Возвращает TRUE, если файл изменился
bool CheckXmlFile(bool abUpdateName /*= false*/)
{
bool lbChanged = false, lbNeedCheck = false;
DWORD nNotify = 0;
wchar_t szErr[128];
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
MSectionLockSimple CS; CS.Lock(XmlFile.cr);
if (abUpdateName)
{
bool lbNameOk = false;
size_t cchMax = MAX_PATH+1;
if (!gpszXmlFile)
gpszXmlFile = (wchar_t*)malloc(cchMax*sizeof(*gpszXmlFile));
if (gpszXmlFile)
{
gpszXmlFile[0] = 0;
// If config file has full path or environment variable (supposing full path with %FARHOME% or %ConEmuDir%)
if (*gsXmlConfigFile && (wcschr(gsXmlConfigFile, L'\\') || wcschr(gsXmlConfigFile, L'%')))
{
DWORD nRc = ExpandEnvironmentStrings(gsXmlConfigFile, gpszXmlFile, MAX_PATH+1);
if (!nRc || nRc > MAX_PATH)
{
gpszXmlFile[0] = 0;
ReportFail(L"Too long xml path after ExpandEnvironmentStrings");
}
else
{
lbNameOk = true;
}
}
if (!lbNameOk && !*gpszXmlFile)
{
LPCWSTR pszXmlName = *gsXmlConfigFile ? gsXmlConfigFile : szDefaultXmlName;
int nNameLen = lstrlen(pszXmlName);
if (GetModuleFileName(ghPluginModule, gpszXmlFile, MAX_PATH-nNameLen))
{
wchar_t* pszSlash = wcsrchr(gpszXmlFile, L'\\');
if (pszSlash) pszSlash++; else pszSlash = gpszXmlFile;
_wcscpy_c(pszSlash, cchMax-(pszSlash-gpszXmlFile), pszXmlName);
lbNameOk = true;
}
}
}
if (!lbNameOk)
{
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
};
ReportFail(L"Can't initialize name of xml file");
lbChanged = false;
goto wrap;
}
// Notification - мониторинг изменения файла
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (gpszXmlFolder)
free(gpszXmlFolder);
gpszXmlFolder = lstrdup(gpszXmlFile);
if (gpszXmlFolder)
{
wchar_t* pszSlash = wcsrchr(gpszXmlFolder, L'\\');
if (pszSlash)
{
if (wcschr(gpszXmlFolder, L'\\') < pszSlash)
pszSlash[0] = 0;
else
pszSlash[1] = 0;
}
//Issue 1230
if (gbMonitorFileChange)
{
ghXmlNotification = FindFirstChangeNotification(gpszXmlFolder, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE);
}
else
{
_ASSERTE(ghXmlNotification==NULL);
lbNeedCheck = true;
}
}
}
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
nNotify = WaitForSingleObject(ghXmlNotification, 0);
if (nNotify == WAIT_OBJECT_0)
{
lbNeedCheck = true;
//FindNextChangeNotification(ghXmlNotification); -- в конце позовем
}
}
// в первый раз - выставляем строго
if (!lbNeedCheck && !XmlFile.FileData)
lbNeedCheck = true;
if (gpszXmlFile && *gpszXmlFile && lbNeedCheck)
{
HANDLE hFile = CreateFile(gpszXmlFile, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL);
if (hFile && hFile != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION inf = {};
GetFileInformationByHandle(hFile, &inf);
if (!inf.nFileSizeLow)
{
ReportFail(L"Configuration xml file is empty");
}
else if (!XmlFile.FileData)
{
lbChanged = true;
}
else
{
if ((memcmp(&inf.ftLastWriteTime, &XmlFile.FileTime, sizeof(XmlFile.FileTime)) != 0)
|| (inf.nFileSizeLow != XmlFile.FileSize))
{
lbChanged = true;
}
}
if (lbChanged)
{
DWORD dwRead = 0;
LPBYTE ptrData = (LPBYTE)calloc(inf.nFileSizeLow+1, sizeof(*ptrData));
if (!ptrData)
{
swprintf_c(szErr, L"Can't allocate %u bytes for xml configuration", inf.nFileSizeLow+1);
ReportFail(szErr);
}
else if (!ReadFile(hFile, ptrData, inf.nFileSizeLow, &dwRead, NULL) || (dwRead != inf.nFileSizeLow))
{
swprintf_c(szErr, L"Can't read %u bytes from xml configuration file", inf.nFileSizeLow);
ReportFail(szErr);
}
else
{
if (XmlFile.FileData)
free(XmlFile.FileData);
XmlFile.FileData = ptrData;
ptrData = NULL;
XmlFile.FileSize = dwRead;
}
if (ptrData) // Если ошибка, освободить память
free(ptrData);
}
// Done
CloseHandle(hFile);
}
else
{
// В первый раз - на отсутствие файла ругнемся
if (!XmlFile.FileData)
{
ReportFail(L"Configuration xml file was not found in the plugin folder");
}
}
}
// Если файла нет, или его не удалось прочитать - подсунем пустышку
if (!XmlFile.FileData)
{
XmlFile.FileSize = 0;
XmlFile.FileData = (LPBYTE)calloc(1,sizeof(*XmlFile.FileData));
}
wrap:
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE) && (nNotify == WAIT_OBJECT_0))
{
FindNextChangeNotification(ghXmlNotification);
}
return lbChanged;
}
#define DllGetFunction(hModule, FunctionName) FunctionName = (FunctionName##_t)GetProcAddress(hModule, #FunctionName)
enum tag_GdiStrMagics
{
eGdiStr_Decoder = 0x2001,
eGdiStr_Image = 0x2002,
};
struct CachedImage
{
DWORD nMagic;
BOOL bUsed;
// Имя картинки
wchar_t sImgName[MAX_PATH]; // i.e. L"img/plugin.png"
// Хэндлы. CompatibleDC & Bitmap
HDC hDc;
HBITMAP hBmp, hOldBmp;
int nWidth, nHeight;
// Next pointer
CachedImage *pNextImage;
bool Init(LPCWSTR apszName, HDC ahDc, UINT anWidth, UINT anHeight, const HDC hScreenDC)
{
_ASSERTE(hDc==NULL && hBmp==NULL && hOldBmp==NULL);
nMagic = eGdiStr_Image;
bUsed = TRUE;
wcscpy_c(sImgName, apszName);
//hDc = ahDc; ahDc = NULL;
//hBmp = ahBmp; ahBmp = NULL;
//hOldBmp = ahOldBmp; ahOldBmp = NULL;
nWidth = anWidth;
nHeight = anHeight;
hDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nWidth, nHeight);
if (!hDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed in CachedImage::Init");
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
return false;
}
hOldBmp = (HBITMAP)SelectObject(hDc, hBmp);
//BitBlt, MaskBlt, AlphaBlend, TransparentBlt
BitBlt(hDc, 0, 0, nWidth, nHeight, ahDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
return true;
};
// Деструктор
void Close()
{
sImgName[0] = 0;
if (hOldBmp && hDc)
{
SelectObject(hDc, hOldBmp);
hOldBmp = NULL;
}
if (hDc)
{
DeleteDC(hDc);
hDc = NULL;
}
if (hBmp)
{
DeleteObject(hBmp);
hBmp = NULL;
}
if (pNextImage)
{
pNextImage->Close();
}
free(this);
};
};
struct GDIPlusDecoder
{
DWORD nMagic;
HMODULE hGDIPlus;
ULONG_PTR gdiplusToken; bool bTokenInitialized;
HRESULT nLastError;
BOOL bCoInitialized;
wchar_t sModulePath[MAX_PATH];
CachedImage *pImages;
typedef Gdiplus::Status(WINAPI *GdiplusStartup_t)(ULONG_PTR *token, const Gdiplus::GdiplusStartupInput *input, void /*Gdiplus::GdiplusStartupOutput*/ *output);
typedef VOID (WINAPI *GdiplusShutdown_t)(ULONG_PTR token);
typedef Gdiplus::Status(WINAPI *GdipCreateBitmapFromFile_t)(GDIPCONST WCHAR* filename, Gdiplus::GpBitmap **bitmap);
typedef Gdiplus::Status(WINAPI *GdipGetImageWidth_t)(Gdiplus::GpImage *image, UINT *width);
typedef Gdiplus::Status(WINAPI *GdipGetImageHeight_t)(Gdiplus::GpImage *image, UINT *height);
typedef Gdiplus::Status(WINAPI *GdipDisposeImage_t)(Gdiplus::GpImage *image);
//typedef Gdiplus::Status(WINAPI *GdipCreateHBITMAPFromBitmap_t)(Gdiplus::GpBitmap* bitmap, HBITMAP* hbmReturn, ARGB background);
typedef Gdiplus::Status(WINAPI *GdipDrawImageI_t)(Gdiplus::GpGraphics *graphics, Gdiplus::GpImage *image, INT x, INT y);
typedef Gdiplus::Status(WINAPI *GdipCreateFromHDC_t)(HDC hdc, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipDeleteGraphics_t)(Gdiplus::GpGraphics *graphics);
typedef Gdiplus::Status(WINAPI *GdipGetDC_t)(Gdiplus::GpGraphics* graphics, HDC * hdc);
typedef Gdiplus::Status(WINAPI *GdipReleaseDC_t)(Gdiplus::GpGraphics* graphics, HDC hdc);
typedef Gdiplus::Status(WINAPI *GdipGetImageGraphicsContext_t)(Gdiplus::GpImage *image, Gdiplus::GpGraphics **graphics);
typedef Gdiplus::Status(WINAPI *GdipBitmapConvertFormat_t)(Gdiplus::GpBitmap *pInputBitmap, Gdiplus::PixelFormat format, Gdiplus::DitherType dithertype, Gdiplus::PaletteType palettetype, Gdiplus::ColorPalette *palette, DWORD alphaThresholdPercent);
GdiplusStartup_t GdiplusStartup;
GdiplusShutdown_t GdiplusShutdown;
GdipCreateBitmapFromFile_t GdipCreateBitmapFromFile;
GdipGetImageWidth_t GdipGetImageWidth;
GdipGetImageHeight_t GdipGetImageHeight;
GdipDisposeImage_t GdipDisposeImage;
//GdipCreateHBITMAPFromBitmap_t GdipCreateHBITMAPFromBitmap;
GdipDrawImageI_t GdipDrawImageI;
GdipCreateFromHDC_t GdipCreateFromHDC;
GdipDeleteGraphics_t GdipDeleteGraphics;
GdipGetDC_t GdipGetDC;
GdipReleaseDC_t GdipReleaseDC;
GdipGetImageGraphicsContext_t GdipGetImageGraphicsContext;
GdipBitmapConvertFormat_t GdipBitmapConvertFormat;
bool Init()
{
nMagic = eGdiStr_Decoder;
hGDIPlus = NULL; gdiplusToken = 0; bTokenInitialized = false;
nLastError = 0;
if (!GetModuleFileName(ghPluginModule, sModulePath, countof(sModulePath)))
{
ReportFail(L"GetModuleFileName failed in GDIPlusDecoder::Init");
sModulePath[0] = 0;
}
else
{
wchar_t* pszSlash = wcsrchr(sModulePath, L'\\');
if (pszSlash)
pszSlash[1] = 0; // Оставить слеш.
else
sModulePath[0] = 0; // Ошибка?
}
bool result = false;
HRESULT hrCoInitialized = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
bCoInitialized = SUCCEEDED(hrCoInitialized);
_ASSERTE(bCoInitialized);
//wchar_t FullPath[MAX_PATH*2+15]; FullPath[0] = 0;
hGDIPlus = LoadLibraryW(L"GdiPlus.dll");
if (!hGDIPlus)
{
ReportFail(L"GdiPlus.dll not found!");
}
else
{
DllGetFunction(hGDIPlus, GdiplusStartup);
DllGetFunction(hGDIPlus, GdiplusShutdown);
DllGetFunction(hGDIPlus, GdipCreateBitmapFromFile);
DllGetFunction(hGDIPlus, GdipGetImageWidth);
DllGetFunction(hGDIPlus, GdipGetImageHeight);
DllGetFunction(hGDIPlus, GdipDisposeImage);
//DllGetFunction(hGDIPlus, GdipCreateHBITMAPFromBitmap);
DllGetFunction(hGDIPlus, GdipDrawImageI);
DllGetFunction(hGDIPlus, GdipCreateFromHDC);
DllGetFunction(hGDIPlus, GdipDeleteGraphics);
DllGetFunction(hGDIPlus, GdipGetDC);
DllGetFunction(hGDIPlus, GdipReleaseDC);
DllGetFunction(hGDIPlus, GdipGetImageGraphicsContext);
DllGetFunction(hGDIPlus, GdipBitmapConvertFormat); // may be absent in old versions of GdiPlus.dll
if (GdiplusStartup && GdiplusShutdown && GdipCreateBitmapFromFile
&& GdipGetImageWidth && GdipGetImageHeight
&& GdipDisposeImage //&& GdipCreateHBITMAPFromBitmap
&& GdipDrawImageI && GdipCreateFromHDC && GdipDeleteGraphics
&& GdipGetDC && GdipReleaseDC && GdipGetImageGraphicsContext
)
{
Gdiplus::GdiplusStartupInput gdiplusStartupInput;
Gdiplus::Status lRc = GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
result = (lRc == Gdiplus::Ok);
if (!result)
{
nLastError = GetLastError();
GdiplusShutdown(gdiplusToken); bTokenInitialized = false;
ReportFail(L"GdiplusStartup failed");
}
else
{
bTokenInitialized = true;
}
}
else
{
ReportFail(L"Functions not found in GdiPlus.dll");
}
if (!result)
FreeLibrary(hGDIPlus);
}
return result;
};
// При использовании в фаре GdiPlus иногда может зависать на FreeLibrary.
// Причины пока не выяснены
static DWORD WINAPI FreeThreadProc(LPVOID lpParameter)
{
struct GDIPlusDecoder* p = (struct GDIPlusDecoder*)lpParameter;
if (p && p->hGDIPlus)
{
FreeLibrary(p->hGDIPlus);
}
return 0;
}
void Close()
{
if (pImages)
{
pImages->Close();
pImages = NULL;
}
if (bTokenInitialized)
{
GdiplusShutdown(gdiplusToken);
bTokenInitialized = false;
}
if (hGDIPlus)
{
//FreeLibrary(hGDIPlus);
DWORD nFreeTID = 0, nWait = 0, nErr = 0;
HANDLE hFree = apiCreateThread(FreeThreadProc, this, &nFreeTID, "Bg::FreeThreadProc");
if (!hFree)
{
nErr = GetLastError();
FreeLibrary(hGDIPlus);
}
else
{
nWait = WaitForSingleObject(hFree, 5000);
if (nWait != WAIT_OBJECT_0)
apiTerminateThread(hFree, 100);
CloseHandle(hFree);
}
UNREFERENCED_PARAMETER(nErr);
hGDIPlus = NULL;
}
if (bCoInitialized)
{
bCoInitialized = FALSE;
CoUninitialize();
}
free(this);
};
CachedImage* GetImage(LPCWSTR asRelativeName)
{
if (!asRelativeName || !*asRelativeName)
return NULL;
size_t cchFullName = MAX_PATH*2;
wchar_t* szFullName = (wchar_t*)malloc(cchFullName*sizeof(*szFullName));
size_t cchName = MAX_PATH;
wchar_t* szName = (wchar_t*)malloc(cchName*sizeof(*szName));
size_t cchError = MAX_PATH*3;
wchar_t* szError = (wchar_t*)malloc(cchError*sizeof(*szError));
wchar_t* psz = NULL;
Gdiplus::Status lRc;
Gdiplus::GpBitmap *bmp = NULL;
Gdiplus::GpGraphics *gr = NULL;
CachedImage *pI = NULL, *pLast = NULL;
UINT nW = 0, nH = 0;
HDC hDc = NULL, hCompDc = NULL;
HBITMAP hBmp = NULL, hOldBmp = NULL;
const HDC hScreenDC = GetDC(0);
if (!szFullName || !szName || !szError)
{
ReportFail(L"Can't allocate memory for szFullName");
goto wrap;
}
if (*asRelativeName == L'\\' || *asRelativeName == L'/')
asRelativeName++;
// Заменить "/" на "\"
_wcscpy_c(szName, cchName, asRelativeName);
psz = wcschr(szName, L'/');
while (psz)
{
*psz = L'\\';
psz = wcschr(psz+1, L'/');
}
// Lowercase, для сравнения
CharLowerBuff(szName, lstrlen(szName));
// Может уже есть?
pI = pImages;
while (pI != NULL)
{
pLast = pI;
if (pI->bUsed && lstrcmp(pI->sImgName, szName) == 0)
{
goto wrap;
}
pI = pI->pNextImage;
}
// Загрузить из файла
_ASSERTE(pI == NULL);
pI = NULL;
_wcscpy_c(szFullName, cchFullName, sModulePath);
_wcscat_c(szFullName, cchFullName, szName);
lRc = GdipCreateBitmapFromFile(szFullName, &bmp);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"Can't load image, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
_ASSERTE(bmp == NULL);
bmp = NULL;
goto wrap;
}
if (GdipBitmapConvertFormat)
{
Gdiplus::ColorPalette pal[2];
pal[0].Flags = Gdiplus::PaletteFlagsGrayScale;
pal[0].Count = 2;
pal[0].Entries[0] = (DWORD)0;
pal[0].Entries[1] = (DWORD)-1;
GdipBitmapConvertFormat(bmp, PixelFormat1bppIndexed, Gdiplus::DitherTypeSolid, Gdiplus::PaletteTypeFixedBW, pal, 0);
}
if (((lRc = GdipGetImageWidth(bmp, &nW)) != Gdiplus::Ok) || (GdipGetImageHeight(bmp, &nH) != Gdiplus::Ok)
|| (nW < 1) || (nH < 1))
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GetImageSize failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
hCompDc = CreateCompatibleDC(hScreenDC);
hBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
if (!hCompDc || !hBmp)
{
ReportFail(L"CreateCompatible[DC|Bitmap] failed");
goto wrap;
}
hOldBmp = (HBITMAP)SelectObject(hCompDc, hBmp);
lRc = GdipCreateFromHDC(hCompDc, &gr);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipCreateFromHDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
lRc = GdipDrawImageI(gr, bmp, 0, 0);
if (lRc != Gdiplus::Ok)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipDrawImageI failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
//lRc = GdipGetImageGraphicsContext(bmp, &gr);
//if (lRc != Gdiplus::Ok || !gr)
//{
// swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetImageGraphicsContext failed, Err=%i\n%s", (int)lRc, szFullName);
// ReportFail(szError);
// goto wrap;
//}
lRc = GdipGetDC(gr, &hDc);
if (lRc != Gdiplus::Ok || !hDc)
{
swprintf_c(szError, cchError/*#SECURELEN*/, L"GdipGetDC failed, Err=%i\n%s", (int)lRc, szFullName);
ReportFail(szError);
goto wrap;
}
#ifdef _DEBUG
//SelectObject(hDc, (HPEN)GetStockObject(WHITE_PEN));
//MoveToEx(hDc, 0,0, NULL);
//LineTo(hDc, nW, nH);
/*{
RECT rcDbg = {nW/2,nH/2, nW, nH};
FillRect(hDc, &rcDbg, (HBRUSH)GetStockObject(WHITE_BRUSH));
//BitBlt(hScreenDC, 0, 0, nW, nH, hDc, 0, 0, SRCCOPY); // PATINVERT/PATPAINT?
}*/
#endif
// OK, теперь можно запомнить в кеше
if (!pLast)
{
_ASSERTE(pImages == NULL);
pImages = (CachedImage*)calloc(1,sizeof(CachedImage));
pI = pImages;
}
else
{
pI = (CachedImage*)calloc(1,sizeof(CachedImage));
pLast->pNextImage = pI;
}
if (!pI)
{
ReportFail(L"Can't allocate memory for CachedImage");
goto wrap;
}
// Done
if (!pI->Init(szName, hDc, nW, nH, hScreenDC))
{
if (pLast)
pLast->pNextImage = NULL;
if (pI == pImages)
pImages = NULL;
pI->Close();
pI = NULL;
goto wrap;
}
wrap:
if (szFullName)
free(szFullName);
if (szName)
free(szName);
if (szError)
free(szError);
if (hDc && gr)
GdipReleaseDC(gr, hDc);
if (gr)
GdipDeleteGraphics(gr);
if (hCompDc && hOldBmp)
SelectObject(hCompDc, hOldBmp);
if (hCompDc)
DeleteDC(hCompDc);
if (hBmp)
DeleteObject(hBmp);
if (bmp)
GdipDisposeImage(bmp);
if (hScreenDC)
ReleaseDC(0, hScreenDC);
return pI;
}
};
GDIPlusDecoder* gpDecoder = NULL;
bool GdipInit()
{
if (gbGdiPlusInitialized)
return true; // уже
_ASSERTE(XmlFile.cr && XmlFile.cr->IsInitialized());
// Загрузить его содержимое
CheckXmlFile(true);
// Инициализация XMLLite
ghXmlLite = LoadLibrary(L"xmllite.dll");
if (!ghXmlLite)
{
ReportFail(L"xmllite.dll not found");
}
else
{
gfCreateXmlReader = (CreateXmlReader_t)GetProcAddress(ghXmlLite, "CreateXmlReader");
if (!gfCreateXmlReader)
{
ReportFail(L"function CreateXmlReader in the xmllite.dll not found");
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
}
gpDecoder = (GDIPlusDecoder*)calloc(1,sizeof(*gpDecoder));
if (!gpDecoder->Init())
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = true;
return true;
}
void GdipDone()
{
if (!gbGdiPlusInitialized)
return; // Не выполнялось
MSectionLockSimple CS;
if (XmlFile.cr)
{
CS.Lock(XmlFile.cr);
}
if (ghXmlLite)
{
FreeLibrary(ghXmlLite);
ghXmlLite = NULL;
}
gfCreateXmlReader = NULL;
if (gpszXmlFile)
{
free(gpszXmlFile);
gpszXmlFile = NULL;
}
if (gpszXmlFolder)
{
free(gpszXmlFolder);
gpszXmlFolder = NULL;
}
if (XmlFile.FileData)
{
free(XmlFile.FileData);
XmlFile.FileData = NULL;
}
XmlFile.FileSize = 0;
if (ghXmlNotification && (ghXmlNotification != INVALID_HANDLE_VALUE))
{
FindCloseChangeNotification(ghXmlNotification);
ghXmlNotification = NULL;
}
if (XmlFile.cr)
{
CS.Unlock();
SafeDelete(XmlFile.cr);
}
if (gpDecoder)
{
gpDecoder->Close();
gpDecoder = NULL;
}
gbGdiPlusInitialized = false;
}
bool CompareNames(LPCWSTR asMaskList, LPWSTR asPath)
{
if (!asMaskList || !asPath)
return false;
if ((*asMaskList && !*asPath) || (*asPath && !*asMaskList))
return false;
wchar_t szMask[MAX_PATH];
while (*asMaskList)
{
LPCWSTR pszSep = wcschr(asMaskList, L'|');
if (pszSep)
{
int nLen = (int)std::min((INT_PTR)countof(szMask)-1,(INT_PTR)(pszSep-asMaskList));
lstrcpyn(szMask, asMaskList, nLen+1);
szMask[nLen] = 0;
}
else
{
lstrcpyn(szMask, asMaskList, countof(szMask));
}
wchar_t* pszSlash = wcschr(szMask, L'/');
while (pszSlash)
{
*pszSlash = L'\\';
pszSlash = wcschr(pszSlash+1, L'/');
}
if (FMatch(szMask, asPath))
return true;
if (!pszSep)
break;
asMaskList = pszSep+1;
}
return false;
}
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE R, G, B, Dummy;
};
};
};
void ParseColors(LPCWSTR asColors, BOOL abSwap/*RGB->COLORREF*/, COLORREF (&crValues)[32], int &nCount)
{
int i = 0;
wchar_t* pszEnd = NULL;
while (asColors && *asColors)
{
if (abSwap)
{
// Нам нужен COLORREF - это перевернутые R&B
RGBColor rgb = {}, bgr;
if (*asColors == L'#')
bgr.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
bgr.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
rgb.R = bgr.B;
rgb.G = bgr.G;
rgb.B = bgr.R;
crValues[i++] = rgb.clr;
}
else
{
RGBColor rgb;
if (*asColors == L'#')
rgb.clr = wcstoul(asColors+1, &pszEnd, 16) & 0xFFFFFF;
else
rgb.clr = wcstoul(asColors, &pszEnd, 10) & 0xFFFFFF;
crValues[i++] = rgb.clr;
}
if (pszEnd && *pszEnd == L'|')
asColors = pszEnd + 1;
else
break;
}
nCount = i;
//while (i < countof(crValues))
//{
// crValues[i++] = (COLORREF)-1;
//}
}
int FillPanelParams(PaintBackgroundArg* pBk, BkPanelInfo *pPanel, DrawInfo *pDraw)
{
int iFound = 0;
MStream strm;
IXmlReader* pXmlReader = NULL;
HRESULT hr = S_OK;
//int WindowType = -1;
struct ChunkInfo
{
enum {
ci_WindowNone = 0,
ci_WindowPanels = 1,
ci_WindowEditor = 2,
ci_WindowViewer = 3,
} WindowType;
enum {
ci_PanelNone = 0,
ci_PanelDrive = 1,
ci_PanelPlugin = 2,
ci_PanelTree = 3,
ci_PanelQView = 4,
ci_PanelInfo = 5,
} PanelType;
BOOL CondFailed;
bool Valid()
{
if (WindowType == ci_WindowNone)
return false;
if (WindowType == ci_WindowPanels)
{
if (PanelType == ci_PanelNone)
return false;
}
return true;
}
bool Equal(ChunkInfo* pTest)
{
if (pTest->WindowType == ci_WindowNone || pTest->WindowType != this->WindowType)
return false;
if (pTest->WindowType == ci_WindowPanels)
{
if (pTest->PanelType == ci_PanelNone || pTest->PanelType != this->PanelType)
return false;
}
if (CondFailed)
return false;
return true;
}
};
bool bFound = false;
ChunkInfo Test = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
ChunkInfo Panel = {ChunkInfo::ci_WindowPanels, ChunkInfo::ci_PanelNone};
MSectionLockSimple CS;
LPWSTR pszFormat = lstrdup(pPanel->szFormat ? pPanel->szFormat : L"");
size_t nMaxLen = lstrlen(pPanel->szCurDir ? pPanel->szCurDir : L"");
LPWSTR pszPath = (wchar_t*)malloc((nMaxLen+2)*sizeof(*pszPath));
_wcscpy_c(pszPath, nMaxLen+1, pPanel->szCurDir ? pPanel->szCurDir : L"");
if (nMaxLen > 1 && pszPath[nMaxLen-1] != L'\\')
{
pszPath[nMaxLen] = L'\\';
pszPath[nMaxLen+1] = 0;
}
BOOL bTempPath = FALSE;
wchar_t szTemp[MAX_PATH+1];
// Проверка, путь - %TEMP%?
if (*pszPath)
{
if (!bTempPath)
{
lstrcpyn(szTemp, pszPath, countof(szTemp));
CharUpperBuff(szTemp, lstrlen(szTemp));
if (wcsstr(szTemp, L"\\TEMP\\") != NULL)
bTempPath = TRUE;
}
if (!bTempPath && GetTempPath(countof(szTemp)-1, szTemp))
{
szTemp[countof(szTemp)-1] = 0;
if (lstrcmpi(pszPath, szTemp) == 0)
bTempPath = TRUE;
}
}
pDraw->Flags = 0;
if (pBk->Place == pbp_Panels)
{
Panel.WindowType = ChunkInfo::ci_WindowPanels;
if (pPanel->bPlugin)
{
Panel.PanelType = ChunkInfo::ci_PanelPlugin;
}
else if (pPanel->nPanelType == PTYPE_FILEPANEL)
{
Panel.PanelType = ChunkInfo::ci_PanelDrive;
}
else
{
switch (pPanel->nPanelType)
{
case PTYPE_TREEPANEL:
Panel.PanelType = ChunkInfo::ci_PanelTree;
break;
case PTYPE_QVIEWPANEL:
Panel.PanelType = ChunkInfo::ci_PanelQView;
break;
case PTYPE_INFOPANEL:
Panel.PanelType = ChunkInfo::ci_PanelInfo;
break;
}
}
}
else if (pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer)
{
Panel.WindowType = (pBk->Place == pbp_Editor) ? ChunkInfo::ci_WindowEditor : ChunkInfo::ci_WindowViewer;
}
else
{
_ASSERTE(pBk->Place == pbp_Panels || pBk->Place == pbp_Editor || pBk->Place == pbp_Viewer);
goto wrap;
}
CS.Lock(XmlFile.cr);
if (!XmlFile.FileData || !XmlFile.FileSize)
{
CS.Unlock();
goto wrap;
}
strm.SetData(XmlFile.FileData, XmlFile.FileSize);
CS.Unlock();
hr = gfCreateXmlReader(IID_IXmlReader, (void**)&pXmlReader, NULL);
if (SUCCEEDED(hr))
{
hr = pXmlReader->SetInput(&strm);
// read through the stream
XmlNodeType nodeType;
while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
{
PCWSTR pszName = NULL;
PCWSTR pszValue = NULL;
#ifdef _DEBUG
PCWSTR pszPrefix = NULL;
#endif
PCWSTR pszAttrName = NULL;
PCWSTR pszAttrValue = NULL;
switch (nodeType)
{
case XmlNodeType_EndElement:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (SUCCEEDED(hr))
{
bool bEndWindow = (lstrcmpi(pszName, L"window") == 0);
if (bEndWindow || (lstrcmpi(pszName, L"panel") == 0))
{
if (bEndWindow)
Test.WindowType = ChunkInfo::ci_WindowNone;
Test.PanelType = ChunkInfo::ci_PanelNone;
Test.CondFailed = FALSE;
if (bFound)
iFound = TRUE;
}
}
break;
case XmlNodeType_Element:
hr = pXmlReader->GetLocalName(&pszName, NULL);
if (FAILED(hr))
{
continue;
}
if (lstrcmpi(pszName, L"window") == 0)
{
// Сначала - сброс
Test.WindowType = ChunkInfo::ci_WindowNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"PANELS") == 0 || lstrcmpi(pszAttrValue, L"PANEL") == 0)
Test.WindowType = ChunkInfo::ci_WindowPanels;
else if (lstrcmpi(pszAttrValue, L"EDITOR") == 0)
Test.WindowType = ChunkInfo::ci_WindowEditor;
else if (lstrcmpi(pszAttrValue, L"VIEWER") == 0)
Test.WindowType = ChunkInfo::ci_WindowViewer;
// Check
if (Test.WindowType != Panel.WindowType)
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"panel") == 0)
{
if ((Test.WindowType == ChunkInfo::ci_WindowNone) || (Test.WindowType != Panel.WindowType))
{
Test.CondFailed = TRUE;
}
else
{
// Сначала - сброс
Test.PanelType = ChunkInfo::ci_PanelNone;
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"DRIVE") == 0)
Test.PanelType = ChunkInfo::ci_PanelDrive;
else if (lstrcmpi(pszAttrValue, L"PLUGIN") == 0)
Test.PanelType = ChunkInfo::ci_PanelPlugin;
else if (lstrcmpi(pszAttrValue, L"TREE") == 0)
Test.PanelType = ChunkInfo::ci_PanelTree;
else if (lstrcmpi(pszAttrValue, L"QVIEW") == 0)
Test.PanelType = ChunkInfo::ci_PanelQView;
else if (lstrcmpi(pszAttrValue, L"INFO") == 0)
Test.PanelType = ChunkInfo::ci_PanelInfo;
else
Test.PanelType = ChunkInfo::ci_PanelNone;
// Check
if (Test.PanelType != Panel.PanelType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"drivetype") == 0)
{
DWORD nDriveType = DRIVE_UNKNOWN;
if (lstrcmpi(pszAttrValue, L"NO_ROOT_DIR") == 0)
nDriveType = DRIVE_NO_ROOT_DIR;
else if (lstrcmpi(pszAttrValue, L"REMOVABLE") == 0)
nDriveType = DRIVE_REMOVABLE;
else if (lstrcmpi(pszAttrValue, L"FIXED") == 0)
nDriveType = DRIVE_FIXED;
else if (lstrcmpi(pszAttrValue, L"REMOTE") == 0)
nDriveType = DRIVE_REMOTE;
else if (lstrcmpi(pszAttrValue, L"CDROM") == 0)
nDriveType = DRIVE_CDROM;
else if (lstrcmpi(pszAttrValue, L"RAMDISK") == 0)
nDriveType = DRIVE_RAMDISK;
else
nDriveType = DRIVE_UNKNOWN;
// Check
if (nDriveType != pDraw->nDriveType)
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"pathtype") == 0)
{
if (lstrcmpi(pszAttrValue, L"TEMP") == 0)
{
if (!bTempPath)
Test.CondFailed = TRUE;
}
}
else if (lstrcmpi(pszAttrName, L"pathmatch") == 0)
{
if (!CompareNames(pszAttrValue, pszPath))
Test.CondFailed = TRUE;
}
else if (lstrcmpi(pszAttrName, L"format") == 0)
{
if (!CompareNames(pszAttrValue, pszFormat))
Test.CondFailed = TRUE;
}
}
}
} while (!Test.CondFailed && (hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
}
else if (Test.Valid() && Test.Equal(&Panel))
{
if (lstrcmpi(pszName, L"disabled") == 0)
{
pDraw->Flags |= DrawInfo::dif_Disabled;
iFound = TRUE;
break;
}
// Блок подошел, больше не проверяем
bFound = true;
// Смотрим, что там настроили
if (lstrcmpi(pszName, L"color") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"rgb") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_dark") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"rgb_light") == 0)
{
// Нам нужен COLORREF - это перевернутые R&B
ParseColors(pszAttrValue, TRUE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crBack, pDraw->nBackCount);
pDraw->Flags |= DrawInfo::dif_BackFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_dark") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crDark, pDraw->nDarkCount);
pDraw->Flags |= DrawInfo::dif_DarkFilled;
}
else if (lstrcmpi(pszAttrName, L"bgr_light") == 0)
{
ParseColors(pszAttrValue, FALSE/*RGB->COLORREF*/, pDraw->crLight, pDraw->nLightCount);
pDraw->Flags |= DrawInfo::dif_LightFilled;
}
else if (lstrcmpi(pszAttrName, L"shift") == 0)
{
if (lstrcmpi(pszAttrValue, L"yes") == 0)
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"space") == 0)
{
// Смотрим атрибуты
hr = pXmlReader->MoveToFirstAttribute();
if (SUCCEEDED(hr))
{
do {
#ifdef _DEBUG
hr = pXmlReader->GetPrefix(&pszPrefix, NULL);
#endif
if (SUCCEEDED(hr = pXmlReader->GetLocalName(&pszAttrName, NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
if (lstrcmpi(pszAttrName, L"type") == 0)
{
if (lstrcmpi(pszAttrValue, L"large") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Large;
else if (lstrcmpi(pszAttrValue, L"off") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Off;
else //if (lstrcmpi(pszAttrValue, L"small") == 0)
pDraw->nSpaceBar = DrawInfo::dib_Small;
}
}
}
} while ((hr = pXmlReader->MoveToNextAttribute()) == S_OK);
}
}
else if (lstrcmpi(pszName, L"title") == 0)
{
//TODO: Обработка функций
hr = pXmlReader->Read(&nodeType);
if (SUCCEEDED(hr) && (nodeType == XmlNodeType_Text))
{
hr = pXmlReader->GetValue(&pszValue, NULL);
//lstrcpyn(pDraw->szText, pszValue, countof(pDraw->szPic));
// szTemp
pDraw->szText[0] = 0;
szTemp[0] = 0;
wchar_t* pszDst = pDraw->szText;
wchar_t* pszEnd = pDraw->szText+countof(pDraw->szText)-1;
wchar_t* pszTemp = szTemp;
wchar_t* pszTempEnd = szTemp+countof(szTemp)-1;
bool bPlain = false;
while (TRUE)
{
if (*pszValue == L'"')
{
if (!bPlain)
{
bPlain = true;
}
else if (pszValue[1] == L'"')
{
pszValue++;
*(pszDst++) = L'"';
}
else
{
bPlain = false;
}
pszValue++;
}
else if (bPlain)
{
*(pszDst++) = *(pszValue++);
if (pszDst >= pszEnd)
break;
}
else if (!*pszValue || wcschr(L" \t\r\n+", *pszValue))
{
if (*szTemp)
{
*pszTemp = 0;
LPCWSTR pszVar = szTemp;
if (lstrcmpi(szTemp, L"VOLUME") == 0)
lstrcpyn(szTemp, pDraw->szVolume, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMESIZE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeSize, countof(szTemp));
else if (lstrcmpi(szTemp, L"VOLUMEFREE") == 0)
lstrcpyn(szTemp, pDraw->szVolumeFree, countof(szTemp));
else if (lstrcmpi(szTemp, L"PANELFORMAT") == 0)
lstrcpyn(szTemp, pPanel->szFormat ? pPanel->szFormat : L"", countof(szTemp));
int nTempLen = lstrlen(pszVar);
if ((pszDst + nTempLen) >= pszEnd)
break;
lstrcpyn(pszDst, pszVar, nTempLen+1);
pszDst += nTempLen;
pszTemp = szTemp;
*szTemp = 0;
}
if (!*pszValue)
break;
pszValue++;
}
else
{
*(pszTemp++) = *(pszValue++);
if (pszTemp >= pszTempEnd)
break;
}
}
while ((pszDst > pDraw->szText) && (*(pszDst-1) == L' '))
pszDst--;
*pszDst = 0; // ASCIIZ
pDraw->Flags |= DrawInfo::dif_TextFilled;
}
}
else if (lstrcmpi(pszName, L"img") == 0)
{
if (SUCCEEDED(hr = pXmlReader->MoveToAttributeByName(L"ref", NULL)))
{
if (SUCCEEDED(hr = pXmlReader->GetValue(&pszAttrValue, NULL)))
{
lstrcpyn(pDraw->szPic, pszAttrValue, countof(pDraw->szPic));
pDraw->Flags |= DrawInfo::dif_PicFilled;
}
}
}
}
break;
default:
; // GCC warning elimination
}
} // end - while (!iFound && (S_OK == (hr = pXmlReader->Read(&nodeType))))
pXmlReader->Release();
}
wrap:
if (pszPath)
free(pszPath);
if (pszFormat)
free(pszFormat);
return iFound;
}
// HSB
#if 0
struct HSBColor
{
double Hue, Saturnation, Brightness;
};
struct RGBColor
{
union
{
COLORREF clr;
struct
{
BYTE Red, Green, Blue, Dummy;
};
};
};
void COLORREF2HSB(COLORREF rgbclr, HSBColor& hsb)
{
double minRGB, maxRGB, Delta;
double H, s, b;
RGBColor rgb; rgb.clr = rgbclr;
H = 0.0;
minRGB = std::min(std::min(rgb.Red, rgb.Green), rgb.Blue);
maxRGB = std::max(std::max(rgb.Red, rgb.Green), rgb.Blue);
Delta = (maxRGB - minRGB);
b = maxRGB;
if (maxRGB != 0.0)
{
s = 255.0 * Delta / maxRGB;
}
else
{
s = 0.0;
}
if (s != 0.0)
{
if (rgb.Red == maxRGB)
{
H = (rgb.Green - rgb.Blue) / Delta;
}
else if (rgb.Green == maxRGB)
{
H = 2.0 + (rgb.Blue - rgb.Red) / Delta;
}
else if (rgb.Blue == maxRGB)
{
H = 4.0 + (rgb.Red - rgb.Green) / Delta;
}
}
else
{
H = -1.0;
}
H = H * 60 ;
if (H < 0.0)
{
H = H + 360.0;
}
hsb.Hue = H;
hsb.Saturnation = s * 100 / 255;
hsb.Brightness = b * 100 / 255;
}
inline BYTE ClrPart(double v)
{
return (v < 0) ? 0 : (v > 1) ? 255 : (int)(v*255);
}
inline double Abs(double v)
{
return (v < 0) ? (-v) : v;
}
void HSB2COLORREF(const HSBColor& hsb, COLORREF& rgbclr)
{
RGBColor rgb = {};
double C, H1, m, X;
//C = (1 - Abs(2*(hsb.Brightness/100.0) - 1)) * (hsb.Saturnation/100.0);
C = (hsb.Brightness/100.0) * (hsb.Saturnation/100.0);
H1 = (hsb.Hue / 60);
X = C*(1 - Abs((H1 - 2*(int)(H1 / 2)) - 1));
m = 0;// (hsb.Brightness/100.0) - (C / 2); -- пока без доп.яркости
if ((hsb.Brightness == 0) || (hsb.Hue < 0 || hsb.Hue >= 360))
{
rgb.clr = 0;
}
else if (hsb.Saturnation == 0)
{
rgb.Red = rgb.Green = rgb.Blue = ClrPart(hsb.Brightness/100);
}
else
{
// double r=0,g=0,b=0;
// double temp1,temp2;
// temp2 = (((hsb.Brightness/100)<=0.5)
// ? (hsb.Brightness/100)*(1.0+(hsb.Saturnation/100))
// : (hsb.Brightness/100)+(hsb.Saturnation/100)-((hsb.Brightness/100)*(hsb.Saturnation/100)));
// temp1 = 2.0*(hsb.Brightness/100)-temp2;
//
// double t3[]={hsb.Hue/360+1.0/3.0,hsb.Hue/360,(hsb.Hue/360)-1.0/3.0};
// double clr[]={0,0,0};
// for(int i=0;i<3;i++)
// {
// if(t3[i]<0)
// t3[i]+=1.0;
// if(t3[i]>1)
// t3[i]-=1.0;
//
// if(6.0*t3[i] < 1.0)
// clr[i]=temp1+(temp2-temp1)*t3[i]*6.0;
// else if(2.0*t3[i] < 1.0)
// clr[i]=temp2;
// else if(3.0*t3[i] < 2.0)
// clr[i]=(temp1+(temp2-temp1)*((2.0/3.0)-t3[i])*6.0);
// else
// clr[i]=temp1;
// }
// r=clr[0];
// g=clr[1];
// b=clr[2];
//rgb.Red = ClrPart(255*r); rgb.Green = ClrPart(255*g); rgb.Blue = ClrPart(255*b);
if (0 <= H1 && H1 < 1)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(0+m);
}
else if (1 <= H1 && H1 < 2)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(0+m);
}
else if (2 <= H1 && H1 < 3)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(C+m); rgb.Blue = ClrPart(X+m);
}
else if (3 <= H1 && H1 < 4)
{
rgb.Red = ClrPart(0+m); rgb.Green = ClrPart(X+m); rgb.Blue = ClrPart(C+m);
}
else if (4 <= H1 && H1 < 5)
{
rgb.Red = ClrPart(X+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(C+m);
}
else if (5 <= H1 && H1 < 6)
{
rgb.Red = ClrPart(C+m); rgb.Green = ClrPart(0+m); rgb.Blue = ClrPart(X+m);
}
}
rgbclr = rgb.clr;
}
#endif
//#define RETURN_HSV(h, s, v) {HSV.H = h; HSV.S = s; HSV.V = v; return
//HSV;}
//
//#define RETURN_RGB(r, g, b) {RGB.R = r; RGB.G = g; RGB.B = b; return
//RGB;}
#define UNDEFINED 0
// Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure
// red always maps to 6 in this implementation. Therefore UNDEFINED can be
// defined as 0 in situations where only unsigned numbers are desired.
//typedef struct {float R, G, B;} RGBType;
//
//typedef struct {float H, S, V;} HSVType;
struct HSVColor
{
int H; // (0..1)*360
int S; // (0..1)*100
int V; // (0..1)*100
};
void RGB2HSV(const RGBColor& rgb, HSVColor& HSV)
{
// rgb are each on [0, 1]. S and V are returned on [0, 1] and H is
// returned on [0, 1]. Exception: H is returned UNDEFINED if S==0.
int R = rgb.R, G = rgb.G, B = rgb.B, v, x, f;
int i;
x = std::min(R, G);
x = std::min(x, B);
v = std::max(R, G);
v = std::max(v, B);
if (v == x)
{
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else if (v == 0)
{
_ASSERTE(v!=0);
HSV.H = UNDEFINED;
HSV.S = 0;
HSV.V = v;
}
else
{
f = (R == x) ? G - B : ((G == x) ? B - R : R - G); // -255 .. 255
i = (R == x) ? 3 : ((G == x) ? 5 : 1);
HSV.H = (((360*i) - ((360*f)/(v - x)))/6);
HSV.S = (100*(v - x))/v;
HSV.V = 100*v/255;
}
}
inline BYTE ClrPart(int v)
{
return (v < 0) ? 0 : (v > 100) ? 255 : (int)((v*255)/100);
}
void HSV2RGB(const HSVColor& HSV, RGBColor& rgb)
{
rgb.clr = 0;
// H is given on [0, 1] or UNDEFINED. S and V are given on [0, 1].
// rgb are each returned on [0, 1].
int h = HSV.H * 6, s = HSV.S, v = HSV.V, m, n, f;
int i;
//if (h == 0) h = 1;
if ((HSV.H < 0) /*== UNDEFINED*/ || (!HSV.H && !HSV.V))
{
rgb.R = rgb.G = rgb.B = ClrPart(v);
}
else
{
//i = floorf(h);
if (HSV.H < 60)
i = 0;
else if (HSV.H < 120)
i = 1;
else if (HSV.H < 180)
i = 2;
else if (HSV.H < 240)
i = 3;
else if (HSV.H < 300)
i = 4;
else if (HSV.H < 360)
i = 5;
else
i = 6;
//TODO:
f = h - i*360;
if(!(i & 1)) f = 360 - f; // if i is even
m = v * (100 - s) / 100;
n = v * (100 - s * f / 360) / 100;
#define RETURN_RGB(r,g,b) rgb.R = ClrPart(r); rgb.G = ClrPart(g); rgb.B = ClrPart(b);
switch (i)
{
case 6:
case 0: RETURN_RGB(v, n, m); break;
case 1: RETURN_RGB(n, v, m); break;
case 2: RETURN_RGB(m, v, n); break;
case 3: RETURN_RGB(m, n, v); break;
case 4: RETURN_RGB(n, m, v); break;
case 5: RETURN_RGB(v, m, n); break;
default: RETURN_RGB(0, 0, 0);
}
}
}
// Сколько линий в области статуса (без учета рамок)
int GetStatusLineCount(struct PaintBackgroundArg* pBk, BOOL bLeft)
{
if (!(pBk->FarPanelSettings.ShowStatusLine))
{
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
_ASSERTE(pBk->FarPanelSettings.ShowStatusLine);
return 0;
}
if ((bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType) != PTYPE_FILEPANEL)
{
_ASSERTE(((UINT)(bLeft ? pBk->LeftPanel.nPanelType : pBk->RightPanel.nPanelType)) <= PTYPE_INFOPANEL);
return 0;
}
RECT rcPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
if ((rcPanel.bottom-rcPanel.top) <= ((pBk->FarPanelSettings.ShowColumnTitles) ? 5 : 4))
return 1; // минимальная высота панели
COORD bufSize = {(SHORT)(rcPanel.right-rcPanel.left+1), std::min<SHORT>(10, (SHORT)(rcPanel.bottom-rcPanel.top))};
COORD bufCoord = {0,0};
HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi = {};
short nShiftX = 0, nShiftY = 0;
if (GetConsoleScreenBufferInfo(hStd, &csbi))
{
// Начиная с какой-то версии в фаре поменяли координаты :(
if (rcPanel.top <= 1)
{
nShiftY = csbi.dwSize.Y - (csbi.srWindow.Bottom - csbi.srWindow.Top + 1);
}
}
SMALL_RECT readRect = {
(SHORT)rcPanel.left + nShiftX,
(SHORT)(rcPanel.bottom-bufSize.Y)+nShiftY,
(SHORT)rcPanel.right+nShiftX,
(SHORT)rcPanel.bottom+nShiftY
};
PCHAR_INFO pChars = (PCHAR_INFO)malloc(bufSize.X*bufSize.Y*sizeof(*pChars));
if (!pChars)
{
_ASSERTE(pChars);
return 1;
}
int nLines = 0;
BOOL lbReadRc = ReadConsoleOutputW(hStd, pChars, bufSize, bufCoord, &readRect);
if (!lbReadRc)
{
_ASSERTE(lbReadRc);
}
else
{
for (int i = 2; i <= bufSize.Y; i++)
{
if ((pChars[bufSize.X*(bufSize.Y-i)].Char.UnicodeChar == ucBoxDblVertSinglRight)
|| (pChars[bufSize.X*(bufSize.Y-i)+bufSize.X-1].Char.UnicodeChar == ucBoxDblVertSinglLeft))
{
nLines = i - 1;
break;
}
}
}
// Что-то при запуске (1.7x?) иногда картинки прыгают, как будто статус сразу не нашли
#ifdef _DEBUG
int nArea = -1;
if (nLines<1)
{
static bool bWarnLines = false;
if (!bWarnLines)
{
nArea = GetMacroArea();
if (nArea == 1/*MACROAREA_SHELL*/ || nArea == 5/*MACROAREA_SEARCH*/)
{
bWarnLines = true;
// Far 3.0.3716. Assert при старте. Плагин активирован, а панелей на экране еще НЕТ.
_ASSERTE(nLines>0);
}
}
}
#endif
free(pChars);
return nLines;
}
void FormatSize(ULARGE_INTEGER size, wchar_t* out)
{
if (size.QuadPart)
{
// Сформатировать размер
uint64_t lSize = size.QuadPart, lDec = 0;
const wchar_t *SizeSymbol[]={L"B",L"KB",L"MB",L"GB",L"TB",L"PB"};
for (size_t n = 0; n < countof(SizeSymbol); n++)
{
if (lSize < 1000)
{
if (lDec > 0 && lDec < 10 && lSize < 10)
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u.%u %s", (UINT)lSize, (UINT)lDec, SizeSymbol[n]);
else
swprintf_c(out, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[n]);
break;
}
uint64_t lNext = lSize >> 10;
lDec = (lSize % 1024) / 100;
lSize = lNext;
}
//if (!*szVolumeSize)
//{
// swprintf_c(szVolumeSize, MAX_PATH/*#SECURELEN*/, L"%u %s", (UINT)lSize, SizeSymbol[countof(SizeSymbol)-1]);
//}
}
}
int PaintPanel(struct PaintBackgroundArg* pBk, BOOL bLeft, COLORREF& crOtherColor, int& cOtherDrive)
{
DrawInfo* pDraw = (DrawInfo*)calloc(sizeof(*pDraw), 1);
if (!pDraw)
return FALSE;
wchar_t szDbg[128];
// Инициализация и начальное определение размеров и прочего...
int nStatusLines = GetStatusLineCount(pBk, bLeft);
RECT rcPanel = bLeft ? pBk->rcDcLeft : pBk->rcDcRight;
RECT rcConPanel = bLeft ? pBk->LeftPanel.rcPanelRect : pBk->RightPanel.rcPanelRect;
BkPanelInfo *bkInfo = bLeft ? &pBk->LeftPanel : &pBk->RightPanel;
// Не должен содержать рамки
int nPanelWidth = std::max<int>(1, rcConPanel.right - rcConPanel.left + 1); // ширина в символах
int nPanelHeight = std::max<int>(1, rcConPanel.bottom - rcConPanel.top + 1); // высота в символах
RECT rcWork = {}; //rcPanel;
rcWork.left = rcPanel.left + ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.right = rcPanel.right - ((rcPanel.right - rcPanel.left + 1) / nPanelWidth);
rcWork.top = rcPanel.top + ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcWork.bottom = rcPanel.bottom - ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
RECT rcInt = rcWork;
if (nStatusLines > 0)
rcInt.bottom -= ((rcPanel.bottom - rcPanel.top + 1) * (nStatusLines + 1) / nPanelHeight);
int nMaxPicSize = (rcInt.bottom - rcInt.top) * 35 / 100;
ULARGE_INTEGER llTotalSize = {}, llFreeSize = {};
UINT nDriveType = DRIVE_UNKNOWN;
BOOL bProgressAllowed = FALSE; // Градусник свободного места
int nMaxVolumeLen = lstrlen(bkInfo->szCurDir ? bkInfo->szCurDir : L"");
wchar_t* szVolumeRoot = (wchar_t*)calloc(nMaxVolumeLen+2,sizeof(*szVolumeRoot));
wchar_t* szVolumeSize = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeSize));
wchar_t* szVolumeFree = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolumeFree));
wchar_t* szVolume = (wchar_t*)calloc(MAX_PATH,sizeof(*szVolume));
if (bkInfo->szCurDir && *bkInfo->szCurDir)
{
if (!bkInfo->bPlugin)
{
// Определить размер свободного места на диске
bool lbSizeOk = false, lbTypeOk = false;
_wcscpy_c(szVolumeRoot, nMaxVolumeLen+2, bkInfo->szCurDir);
if (szVolumeRoot[nMaxVolumeLen-1] != L'\\')
{
szVolumeRoot[nMaxVolumeLen++] = L'\\';
szVolumeRoot[nMaxVolumeLen] = 0;
}
int nLen = lstrlen(szVolumeRoot);
while (!(lbSizeOk && lbTypeOk) && (nLen > 0))
{
// To determine whether a drive is a USB-type drive,
// call SetupDiGetDeviceRegistryProperty and specify the SPDRP_REMOVAL_POLICY property.
ULARGE_INTEGER llTotal = {}, llFree = {};
UINT nType = DRIVE_UNKNOWN;
if (!lbSizeOk && GetDiskFreeSpaceEx(szVolumeRoot, &llFree, &llTotal, NULL))
{
llTotalSize.QuadPart = llTotal.QuadPart;
llFreeSize.QuadPart = llFree.QuadPart;
lbSizeOk = TRUE;
}
if (!lbTypeOk && ((nType = GetDriveType(szVolumeRoot)) != DRIVE_UNKNOWN))
{
nDriveType = nType;
lbTypeOk = TRUE;
}
// Если не все определили - пробуем откусить папку
if (!lbSizeOk || !lbTypeOk)
{
if (szVolumeRoot[nLen-1] != L'\\')
{
_ASSERTE(szVolumeRoot[nLen-1] == L'\\');
break;
}
szVolumeRoot[--nLen] = 0;
// Найти следующий слеш
while ((nLen > 0) && (szVolumeRoot[nLen-1] != L'\\'))
nLen--;
// Пропустить все слеши
while ((nLen > 0) && (szVolumeRoot[nLen-1] == L'\\'))
nLen--;
// Откусить
szVolumeRoot[nLen] = 0;
}
}
FormatSize(llTotalSize, szVolumeSize);
FormatSize(llFreeSize, szVolumeFree);
}
// Извлечь "Букву" диска
LPCWSTR psz = bkInfo->szCurDir;
if (psz[0] == L'\\' && psz[1] == L'\\' && (psz[2] == L'.' || psz[2] == L'?') && psz[3] == L'\\')
{
psz += 4;
if (psz[0] == L'U' && psz[1] == L'N' && psz[2] == L'C' && psz[3] == L'\\')
psz += 4;
}
LPCWSTR pszSlash = wcschr(psz, L'\\');
if (!pszSlash)
pszSlash = wcschr(psz, L'/');
if (!pszSlash)
pszSlash = psz + lstrlen(psz);
if (pszSlash > psz)
lstrcpyn(szVolume, psz, (int)(pszSlash - psz + 1));
}
pDraw->szVolume = szVolume;
pDraw->szVolumeRoot = szVolumeRoot;
pDraw->szVolumeSize = szVolumeSize;
pDraw->szVolumeFree = szVolumeFree;
pDraw->nDriveType = nDriveType;
if (nDriveType != DRIVE_UNKNOWN && nDriveType != DRIVE_CDROM && nDriveType != DRIVE_NO_ROOT_DIR)
{
bProgressAllowed = TRUE;
}
else
{
bProgressAllowed = FALSE;
}
// Если есть xml - получить из него настройки для текущего случая
if (gfCreateXmlReader && XmlFile.FileData && XmlFile.FileSize)
{
FillPanelParams(pBk, bkInfo, pDraw);
}
if ((pDraw->Flags & DrawInfo::dif_Disabled))
{
if (pBk->dwLevel == 0)
{
DWORD nPanelBackIdx = CONBACKCOLOR(pBk->nFarColors[col_PanelText]);
COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
swprintf_c(szDbg, L"ConEmuBk: Disabled %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
crPanel);
DBGSTR(szDbg);
HBRUSH hBr = CreateSolidBrush(crPanel);
FillRect(pBk->hdc, &rcPanel, hBr);
DeleteObject(hBr);
}
}
else
{
// Если не было задано - инициализируем умолчания
if (!(pDraw->Flags & DrawInfo::dif_BackFilled))
{
if (bkInfo->bPlugin)
{
pDraw->crBack[0] = RGB(128,128,128);
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
pDraw->crBack[0] = 0x00D98C; break;
case DRIVE_REMOTE:
pDraw->crBack[0] = 0xFF00E6; break;
case DRIVE_CDROM:
pDraw->crBack[0] = 0x7E00FF; break;
case DRIVE_RAMDISK:
pDraw->crBack[0] = 0x008080; break;
default:
pDraw->crBack[0] = 0xFF0000;
}
pDraw->Flags |= DrawInfo::dif_ShiftBackColor;
}
pDraw->nBackCount = 1;
}
int nLetter = 0;
if ((pDraw->Flags & DrawInfo::dif_ShiftBackColor) && pDraw->crBack && (szVolume[1] == L':'))
{
nLetter = (szVolume[0] >= L'a' && szVolume[0] <= L'b') ? (szVolume[0] - L'a' + 24) :
(szVolume[0] >= L'c' && szVolume[0] <= L'z') ? (szVolume[0] - L'c') :
(szVolume[0] >= L'A' && szVolume[0] <= L'B') ? (szVolume[0] - L'A' + 24) :
(szVolume[0] >= L'C' && szVolume[0] <= L'Z') ? (szVolume[0] - L'C') :
0;
if (pDraw->nBackCount > 0)
{
_ASSERTE(pDraw->nBackCount <= countof(pDraw->crBack));
pDraw->crBack[0] = pDraw->crBack[nLetter % pDraw->nBackCount];
}
else
{
// Сконвертить в HSV, сдвинуть, и обратно в COLORREF
int nShift = (nLetter % 5) * 15;
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
//COLORREF2HSB(pDraw->crBack, hsb);
RGB2HSV(rgb, hsv);
#ifdef _DEBUG
HSV2RGB(hsv, rgb);
#endif
//hsv.H += nShift;
hsv.S -= nShift;
if (hsv.S < 0) hsv.S += 100;
hsv.V = hsv.V / 2;
HSV2RGB(hsv, rgb);
//hsv.Brightness *= 0.7;
//HSB2COLORREF(hsb, clr);
if (bLeft)
{
crOtherColor = rgb.clr;
cOtherDrive = nLetter;
}
else if ((rgb.clr == crOtherColor) && (cOtherDrive != nLetter))
{
hsv.H += 15;
HSV2RGB(hsv, rgb);
}
pDraw->crBack[0] = rgb.clr;
}
}
// Цвет спрайтов, текста, фона градусника
if (!(pDraw->Flags & DrawInfo::dif_DarkFilled))
{
RGBColor rgb; rgb.clr = *pDraw->crBack;
rgb.R = (BYTE)((int)rgb.R * 2 / 3);
rgb.G = (BYTE)((int)rgb.G * 2 / 3);
rgb.B = (BYTE)((int)rgb.B * 2 / 3);
pDraw->crDark[0] = rgb.clr;
pDraw->nDarkCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nDarkCount > 0)
{
_ASSERTE(pDraw->nDarkCount <= countof(pDraw->crDark));
pDraw->crDark[0] = pDraw->crDark[nLetter % pDraw->nDarkCount];
}
}
// Цвет градусника
if (!(pDraw->Flags & DrawInfo::dif_LightFilled))
{
HSVColor hsv = {};
RGBColor rgb; rgb.clr = *pDraw->crBack;
RGB2HSV(rgb, hsv);
hsv.H += 20;
hsv.S = std::min(100,hsv.S+25);
hsv.V = std::min(100,hsv.V+25);
HSV2RGB(hsv, rgb);
pDraw->crLight[0] = rgb.clr;
pDraw->nLightCount = 1;
}
else if (pDraw->Flags & DrawInfo::dif_ShiftBackColor)
{
if (pDraw->nLightCount > 0)
{
_ASSERTE(pDraw->nLightCount <= countof(pDraw->crLight));
pDraw->crLight[0] = pDraw->crLight[nLetter % pDraw->nLightCount];
}
}
if (!(pDraw->Flags & DrawInfo::dif_PicFilled))
{
if (bkInfo->bPlugin)
{
wcscpy_c(pDraw->szPic, L"img/plugin.png");
}
else
{
switch (nDriveType)
{
case DRIVE_REMOVABLE:
wcscpy_c(pDraw->szPic, L"img/drive_removable.png"); break;
case DRIVE_REMOTE:
wcscpy_c(pDraw->szPic, L"img/drive_network.png"); break;
case DRIVE_CDROM:
wcscpy_c(pDraw->szPic, L"img/drive_cdrom.png"); break;
case DRIVE_RAMDISK:
wcscpy_c(pDraw->szPic, L"img/drive_ramdisk.png"); break;
default:
wcscpy_c(pDraw->szPic, L"img/drive_fixed.png");
}
}
}
if (!(pDraw->Flags & DrawInfo::dif_TextFilled))
{
TODO("Размер диска");
wcscpy_c(pDraw->szText, szVolume);
}
// Поехали рисовать
if (pBk->dwLevel == 0)
{
swprintf_c(szDbg, L"ConEmuBk: %s - {%i,%i,%i,%i) #%06X\n",
bLeft ? L"Left" : L"Right", rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom,
*pDraw->crBack);
DBGSTR(szDbg);
HBRUSH hBrush = CreateSolidBrush(*pDraw->crBack);
FillRect(pBk->hdc, &rcPanel, hBrush);
DeleteObject(hBrush);
}
LOGFONT lf = {};
lf.lfHeight = std::max<LONG>(20, (rcInt.bottom - rcInt.top) * 12 / 100);
lf.lfWeight = 700;
lstrcpy(lf.lfFaceName, L"Arial");
// GO
HFONT hText = CreateFontIndirect(&lf);
HFONT hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
#define IMG_SHIFT_X 0
#define IMG_SHIFT_Y 0
#define LINE_SHIFT_Y (lf.lfHeight)
#define LINE_SHIFT_X (lf.lfHeight/6)
// Determine appropriate font size:
int nY = std::max(rcInt.top, rcInt.bottom - (LINE_SHIFT_Y));
RECT rcText = {rcInt.left+IMG_SHIFT_X, nY, rcInt.right-LINE_SHIFT_X, nY+LINE_SHIFT_Y};
RECT rcTemp = rcText;
DrawText(pBk->hdc, pDraw->szText, -1, &rcTemp, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_CALCRECT);
LONG width = rcText.right - rcText.left;
LONG actualWidth = rcTemp.right - rcTemp.left;
if (actualWidth > width)
{
// Delete current font:
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
// Create new font of appropriate size:
lf.lfHeight = lf.lfHeight * width / actualWidth;
hText = CreateFontIndirect(&lf);
hOldFont = (HFONT)SelectObject(pBk->hdc, hText);
}
CachedImage* pI = NULL;
if (gpDecoder && *pDraw->szPic)
{
pI = gpDecoder->GetImage(pDraw->szPic);
if (pI)
{
int nPicDim = std::max(pI->nWidth,pI->nHeight);
int nW = std::min(nMaxPicSize,nPicDim), nH = std::min(nMaxPicSize,nPicDim); //TODO: Пропорционально pI->nWidth/pI->nHeight
if (pI && (rcWork.top <= (rcText.top - nH - IMG_SHIFT_Y)) && (rcWork.left <= (rcWork.right - nW - IMG_SHIFT_X)))
{
// - картинки чисто черного цвета
#if 0
const HDC hScreenDC = GetDC(0);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, SRCCOPY);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCAND);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// OK
#if 1
const HDC hScreenDC = GetDC(0);
HDC hMaskDC = CreateCompatibleDC(hScreenDC);
HBITMAP hMaskBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldMaskBmp = (HBITMAP)SelectObject(hMaskDC, hMaskBmp);
StretchBlt(hMaskDC, 0, 0, nW, nH, pI->hDc, 0,0, pI->nWidth, pI->nHeight, NOTSRCCOPY);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
HBRUSH hDarkBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hOldBr = (HBRUSH)SelectObject(hInvDC, hDarkBr);
BitBlt(hInvDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hInvDC, hOldBr);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
hOldBr = (HBRUSH)SelectObject(hReadyDC, hBackBr);
BitBlt(hMaskDC, 0, 0, nW, nH,
hMaskDC, 0,0, DSTINVERT);
BitBlt(hReadyDC, 0, 0, nW, nH,
hMaskDC, 0,0, MERGECOPY);
SelectObject(hReadyDC, hOldBr);
BitBlt(hReadyDC, 0, 0, nW, nH,
hInvDC, 0,0, SRCPAINT);
DeleteObject(hDarkBr);
DeleteObject(hBackBr);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hMaskDC, hOldMaskBmp);
DeleteObject(hMaskBmp);
DeleteDC(hMaskDC);
ReleaseDC(0, hScreenDC);
#endif
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hDarkBr = CreateSolidBrush(/*RGB(128,128,128)*/ *pDraw->crDark);
FillRect(hInvDC, &rcFill, hDarkBr);
DeleteObject(hDarkBr);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight,
pI->hDc, 0,0, SRCAND);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
//SetStretchBltMode(hReadyDC, HALFTONE);
rcFill.right = nW; rcFill.bottom = nH;
FillRect(hReadyDC, &rcFill, (HBRUSH)GetStockObject(BLACK_BRUSH));
StretchBlt(hReadyDC, 0, 0, nW, nH, hInvDC, 0,0, pI->nWidth, pI->nHeight, SRCINVERT);
BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
ReleaseDC(0, hScreenDC);
#endif
// - Черная окантовка вокруг плагиновой картинки
#if 0
const HDC hScreenDC = GetDC(0);
HDC hInvDC = CreateCompatibleDC(hScreenDC);
HBITMAP hInvBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldInvBmp = (HBITMAP)SelectObject(hInvDC, hInvBmp);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, SRCCOPY); //NOTSRCCOPY
HDC hCompDC = CreateCompatibleDC(hScreenDC);
HBITMAP hCompBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldCompBmp = (HBITMAP)SelectObject(hCompDC, hCompBmp);
HDC hBackDC = CreateCompatibleDC(hScreenDC);
HBITMAP hBackBmp = CreateCompatibleBitmap(hScreenDC, pI->nWidth, pI->nHeight);
HBITMAP hOldBackBmp = (HBITMAP)SelectObject(hBackDC, hBackBmp);
HBRUSH hPaintBr = CreateSolidBrush(*pDraw->crDark);
HBRUSH hBackBr = CreateSolidBrush(*pDraw->crBack);
RECT rcFill = {0,0,pI->nWidth, pI->nHeight};
HBRUSH hOldCompBr = (HBRUSH)SelectObject(hCompDC, hBackBr);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hInvDC, 0, 0, pI->nWidth, pI->nHeight, pI->hDc, 0,0, NOTSRCCOPY);
HBRUSH hOldBackBr = (HBRUSH)SelectObject(hBackDC, hPaintBr);
BitBlt(hBackDC, 0, 0, pI->nWidth, pI->nHeight, hInvDC, 0,0, MERGECOPY);
BitBlt(hCompDC, 0, 0, pI->nWidth, pI->nHeight, hBackDC, 0,0, SRCPAINT);
HDC hReadyDC = CreateCompatibleDC(hScreenDC);
HBITMAP hReadyBmp = CreateCompatibleBitmap(hScreenDC, nW, nH);
HBITMAP hOldReadyBmp = (HBITMAP)SelectObject(hReadyDC, hReadyBmp);
StretchBlt(hReadyDC, 0, 0, nW, nH, hCompDC, 0,0, pI->nWidth, pI->nHeight, SRCCOPY); //NOTSRCCOPY
BOOL lbBitRc = BitBlt(pBk->hdc, rcWork.right - nW - IMG_SHIFT_X, rcText.top - nH - IMG_SHIFT_Y, nW, nH,
hReadyDC, 0,0, SRCCOPY);
SelectObject(hReadyDC, hOldReadyBmp);
DeleteObject(hReadyBmp);
DeleteDC(hReadyDC);
DeleteObject(hPaintBr);
SelectObject(hCompDC, hOldCompBr);
DeleteObject(hBackBr);
SelectObject(hInvDC, hOldInvBmp);
DeleteObject(hInvBmp);
DeleteDC(hInvDC);
SelectObject(hCompDC, hOldCompBmp);
DeleteObject(hCompBmp);
DeleteDC(hCompDC);
SelectObject(hBackDC, hOldBackBmp);
DeleteObject(hBackBmp);
DeleteDC(hBackDC);
ReleaseDC(0, hScreenDC);
#endif
}
}
}
SetBkMode(pBk->hdc, TRANSPARENT);
SetTextColor(pBk->hdc, *pDraw->crDark);
DrawText(pBk->hdc, pDraw->szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
/*
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
swprintf_c(szText, L"Volume: «%s» %s, Format: «%s»", szVolume, szVolumeSize, bkInfo->szFormat ? bkInfo->szFormat : L"");
DrawText(pBk->hdc, szText, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
if (bkInfo->szCurDir)
DrawText(pBk->hdc, bkInfo->szCurDir, -1, &rcText, DT_HIDEPREFIX|DT_RIGHT|DT_SINGLELINE|DT_TOP|DT_PATH_ELLIPSIS);
OffsetRect(&rcText, 0, LINE_SHIFT_Y);
*/
TODO("В Far3 можно и в плагинах свободное место получить");
if (bProgressAllowed && pDraw->nSpaceBar == DrawInfo::dib_Off)
bProgressAllowed = FALSE;
if (bProgressAllowed && (nStatusLines > 0) && !bkInfo->bPlugin && llTotalSize.QuadPart)
{
//llTotalSize = {},
HBRUSH hUsedBr = CreateSolidBrush(*pDraw->crLight);
HBRUSH hFreeBr = CreateSolidBrush(*pDraw->crDark);
RECT rcUsed = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork : rcPanel;
int iShift = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? 0 : 2;
rcUsed.top = rcUsed.bottom - (nStatusLines+iShift) * ((rcPanel.bottom - rcPanel.top + 1) / nPanelHeight);
rcUsed.right = rcUsed.right - (int)((uint64_t)(rcUsed.right - rcUsed.left + 1) * llFreeSize.QuadPart / llTotalSize.QuadPart);
if (rcUsed.right > rcWork.right)
{
_ASSERTE(rcUsed.right <= rcWork.right);
rcUsed.right = rcWork.right;
}
else if (rcUsed.right < rcWork.left)
{
_ASSERTE(rcUsed.right >= rcWork.left);
rcUsed.right = rcWork.left;
}
RECT rcFree = rcUsed;
rcFree.left = rcUsed.right;
rcFree.right = (pDraw->nSpaceBar == DrawInfo::dib_Small) ? rcWork.right : rcPanel.right;
FillRect(pBk->hdc, &rcFree, hFreeBr);
FillRect(pBk->hdc, &rcUsed, hUsedBr);
DeleteObject(hUsedBr);
DeleteObject(hFreeBr);
}
SelectObject(pBk->hdc, hOldFont);
DeleteObject(hText);
}
// Free pointers
free(pDraw);
free(szVolume);
free(szVolumeSize);
free(szVolumeFree);
return TRUE;
}
int WINAPI PaintConEmuBackground(struct PaintBackgroundArg* pBk)
{
int iLeftRc = 0, iRightRc = 0;
if (pBk->Place == pbp_Finalize)
{
GdipDone();
return TRUE;
}
if (!gbGdiPlusInitialized)
{
if (!GdipInit())
{
return FALSE;
}
}
else
{
// Проверить, может содержимое xml-ки изменилось?
CheckXmlFile();
}
wchar_t szDbg[128];
COLORREF crOtherColor = (COLORREF)-1;
int cOtherDrive = -1;
if (pBk->LeftPanel.bVisible)
{
iLeftRc = PaintPanel(pBk, TRUE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->LeftPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Left - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
if (pBk->RightPanel.bVisible)
{
iRightRc = PaintPanel(pBk, FALSE/*bLeft*/, crOtherColor, cOtherDrive);
}
else
{
RECT rcConPanel = pBk->RightPanel.rcPanelRect;
swprintf_c(szDbg, L"ConEmuBk: Invisible Right - {%i,%i,%i,%i)\n",
rcConPanel.left, rcConPanel.top, rcConPanel.right, rcConPanel.bottom);
DBGSTR(szDbg);
}
UNREFERENCED_PARAMETER(iLeftRc); UNREFERENCED_PARAMETER(iRightRc);
return TRUE;
//DWORD nPanelBackIdx = (pBk->nFarColors[col_PanelText] & 0xF0) >> 4;
//
//if (bDragBackground)
//{
// if (pBk->LeftPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->LeftPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcLeft, hBr);
// DeleteObject(hBr);
// }
//
// if (pBk->RightPanel.bVisible)
// {
// COLORREF crPanel = pBk->crPalette[nPanelBackIdx];
//
// if (pBk->RightPanel.bPlugin && gbHilightPlugins)
// crPanel = gcrHilightPlugBack;
//
// HBRUSH hBr = CreateSolidBrush(crPanel);
// FillRect(pBk->hdc, &pBk->rcDcRight, hBr);
// DeleteObject(hBr);
// }
//}
//
//if ((pBk->LeftPanel.bVisible || pBk->RightPanel.bVisible) /*&& pBk->MainFont.nFontHeight>0*/)
//{
// HPEN hPen = CreatePen(PS_SOLID, 1, gcrLinesColor);
// HPEN hOldPen = (HPEN)SelectObject(pBk->hdc, hPen);
// HBRUSH hBrush = CreateSolidBrush(gcrLinesColor);
// int nCellHeight = 12;
//
// if (pBk->LeftPanel.bVisible)
// nCellHeight = pBk->rcDcLeft.bottom / (pBk->LeftPanel.rcPanelRect.bottom - pBk->LeftPanel.rcPanelRect.top + 1);
// else
// nCellHeight = pBk->rcDcRight.bottom / (pBk->RightPanel.rcPanelRect.bottom - pBk->RightPanel.rcPanelRect.top + 1);
//
// int nY1 = (pBk->LeftPanel.bVisible) ? pBk->rcDcLeft.top : pBk->rcDcRight.top;
// int nY2 = (pBk->rcDcLeft.bottom >= pBk->rcDcRight.bottom) ? pBk->rcDcLeft.bottom : pBk->rcDcRight.bottom;
// int nX1 = (pBk->LeftPanel.bVisible) ? 0 : pBk->rcDcRight.left;
// int nX2 = (pBk->RightPanel.bVisible) ? pBk->rcDcRight.right : pBk->rcDcLeft.right;
//
// bool bDrawStipe = true;
//
// for(int Y = nY1; Y < nY2; Y += nCellHeight)
// {
// if (giHilightType == 0)
// {
// MoveToEx(pBk->hdc, nX1, Y, NULL);
// LineTo(pBk->hdc, nX2, Y);
// }
// else if (giHilightType == 1)
// {
// if (bDrawStipe)
// {
// bDrawStipe = false;
// RECT rc = {nX1, Y - nCellHeight + 1, nX2, Y};
// FillRect(pBk->hdc, &rc, hBrush);
// }
// else
// {
// bDrawStipe = true;
// }
// }
// }
//
// SelectObject(pBk->hdc, hOldPen);
// DeleteObject(hPen);
// DeleteObject(hBrush);
//}
//
//return TRUE;
}
void WINAPI OnConEmuLoaded(struct ConEmuLoadedArg* pConEmuInfo)
{
gfRegisterBackground = pConEmuInfo->RegisterBackground;
ghPluginModule = pConEmuInfo->hPlugin;
if (gfRegisterBackground && gbBackgroundEnabled)
{
StartPlugin(FALSE/*считать параметры из реестра*/);
}
}
void SettingsLoad()
{
if (!gbSetStartupInfoOk)
{
_ASSERTE(gbSetStartupInfoOk);
return;
}
if (!*gsXmlConfigFile)
{
lstrcpyn(gsXmlConfigFile, szDefaultXmlName, countof(gsXmlConfigFile));
}
if (gFarVersion.dwVerMajor == 1)
SettingsLoadA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsLoadW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsLoadW)();
else
FUNC_X(SettingsLoadW)();
}
void SettingsLoadReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegOpenKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, KEY_READ, &hkey))
{
DWORD nVal, nType, nSize; BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_BINARY), &cVal, &(nSize = sizeof(cVal))))
*((BOOL*)p->pValue) = (cVal != 0);
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_DWORD), (LPBYTE)&nVal, &(nSize = sizeof(nVal))))
*((DWORD*)p->pValue) = nVal;
}
else if (p->nValueType == REG_SZ)
{
wchar_t szValue[MAX_PATH] = {};
if (!RegQueryValueExW(hkey, p->pszValueName, 0, &(nType = REG_SZ), (LPBYTE)szValue, &(nSize = sizeof(szValue))))
lstrcpyn((wchar_t*)p->pValue, szValue, p->nValueSize);
}
}
RegCloseKey(hkey);
}
}
void SettingsSave()
{
if (gFarVersion.dwVerMajor == 1)
SettingsSaveA();
else if (gFarVersion.dwBuild >= FAR_Y2_VER)
FUNC_Y2(SettingsSaveW)();
else if (gFarVersion.dwBuild >= FAR_Y1_VER)
FUNC_Y1(SettingsSaveW)();
else
FUNC_X(SettingsSaveW)();
}
void SettingsSaveReg(LPCWSTR pszRegKey)
{
HKEY hkey = NULL;
if (!RegCreateKeyExW(HKEY_CURRENT_USER, pszRegKey, 0, 0, 0, KEY_ALL_ACCESS, 0, &hkey, NULL))
{
BYTE cVal;
for (ConEmuBgSettings *p = gSettings; p->pszValueName; p++)
{
if (p->nValueType == REG_BINARY)
{
_ASSERTE(p->nValueSize == 1);
cVal = (BYTE)*(BOOL*)p->pValue;
RegSetValueExW(hkey, p->pszValueName, 0, REG_BINARY, &cVal, sizeof(cVal));
}
else if (p->nValueType == REG_DWORD)
{
_ASSERTE(p->nValueSize == 4);
RegSetValueExW(hkey, p->pszValueName, 0, REG_DWORD, p->pValue, p->nValueSize);
}
else if (p->nValueType == REG_SZ)
{
RegSetValueExW(hkey, p->pszValueName, 0, REG_SZ, p->pValue, sizeof(wchar_t)*(1+lstrlenW((wchar_t*)p->pValue)));
}
}
RegCloseKey(hkey);
}
}
void StartPlugin(BOOL bConfigure)
{
if (gbInStartPlugin)
{
// Вложенных вызовов быть не должно
_ASSERTE(gbInStartPlugin==false);
return;
}
gbInStartPlugin = true;
if (!XmlFile.cr)
{
XmlFile.cr = new MSectionSimple(true);
}
if (!bConfigure)
{
SettingsLoad();
}
static bool bWasRegistered = false;
if (gfRegisterBackground)
{
if (gbBackgroundEnabled)
{
if (bConfigure && bWasRegistered)
{
RegisterBackgroundArg upd = {sizeof(RegisterBackgroundArg), rbc_Redraw};
gfRegisterBackground(&upd);
}
else
{
RegisterBackgroundArg reg = {sizeof(RegisterBackgroundArg), rbc_Register, ghPluginModule};
reg.PaintConEmuBackground = ::PaintConEmuBackground;
reg.dwPlaces = pbp_Panels;
reg.dwSuggestedLevel = 0;
gfRegisterBackground(®);
bWasRegistered = true;
}
}
else
{
RegisterBackgroundArg unreg = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&unreg);
bWasRegistered = false;
}
}
else
{
bWasRegistered = false;
}
// Вернуть флаг обратно
gbInStartPlugin = false;
}
void ExitPlugin(void)
{
if (gfRegisterBackground != NULL)
{
RegisterBackgroundArg inf = {sizeof(RegisterBackgroundArg), rbc_Unregister, ghPluginModule};
gfRegisterBackground(&inf);
}
// Вообще-то это нужно делать в нити отрисовки, но на всякий случай, дернем здесь (LastChance)
GdipDone();
gbSetStartupInfoOk = false;
}
void WINAPI ExitFARW(void)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
void WINAPI ExitFARW3(void*)
{
ExitPlugin();
if (gFarVersion.dwBuild>=FAR_Y2_VER)
FUNC_Y2(ExitFARW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
FUNC_Y1(ExitFARW)();
else
FUNC_X(ExitFARW)();
}
LPCWSTR GetMsgW(int aiMsg)
{
if (gFarVersion.dwVerMajor==1)
return L"";
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(GetMsgW)(aiMsg);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(GetMsgW)(aiMsg);
else
return FUNC_X(GetMsgW)(aiMsg);
}
HANDLE WINAPI OpenW(const void* Info)
{
HANDLE hResult = NULL;
if (gFarVersion.dwBuild>=FAR_Y2_VER)
hResult = FUNC_Y2(OpenW)(Info);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
hResult = FUNC_Y1(OpenW)(Info);
else
{
_ASSERTE(FALSE && "Must not called in Far2");
}
return hResult;
}
int WINAPI ConfigureW(int ItemNumber)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(ItemNumber);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(ItemNumber);
else
return FUNC_X(ConfigureW)(ItemNumber);
}
int WINAPI ConfigureW3(void*)
{
if (gFarVersion.dwVerMajor==1)
return false;
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(ConfigureW)(0);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(ConfigureW)(0);
else
return FUNC_X(ConfigureW)(0);
}
HANDLE OpenPluginWcmn(int OpenFrom,INT_PTR Item)
{
HANDLE hResult = (gFarVersion.dwVerMajor >= 3) ? NULL : INVALID_HANDLE_VALUE;
if (!gbInfoW_OK)
return hResult;
ConfigureW(0);
return hResult;
}
bool FMatch(LPCWSTR asMask, LPWSTR asPath)
{
if (!asMask || !asPath)
return false;
if ((*asMask && !*asPath) || (*asPath && !*asMask))
return false;
if (gFarVersion.dwVerMajor==1)
{
bool lbRc = false;
int nMaskLen = lstrlenW(asMask);
char* pszMask = (char*)malloc(nMaskLen+1);
int nPathLen = lstrlenW(asPath);
char* pszPath = (char*)malloc(nPathLen+1);
if (pszMask && pszPath)
{
WideCharToMultiByte(CP_ACP, 0, asMask, nMaskLen+1, pszMask, nMaskLen+1, 0,0);
WideCharToMultiByte(CP_ACP, 0, asPath, nPathLen+1, pszPath, nPathLen+1, 0,0);
lbRc = FMatchA(pszMask, pszPath);
}
if (pszMask)
free(pszMask);
if (pszPath)
free(pszPath);
return lbRc;
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
return FUNC_Y2(FMatchW)(asMask, asPath);
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
return FUNC_Y1(FMatchW)(asMask, asPath);
else
return FUNC_X(FMatchW)(asMask, asPath);
}
int GetMacroArea()
{
int nMacroArea = 0/*MACROAREA_OTHER*/;
if (gFarVersion.dwVerMajor==1)
{
_ASSERTE(gFarVersion.dwVerMajor>1);
nMacroArea = 1; // в Far 1.7x не поддерживается
}
else if (gFarVersion.dwBuild>=FAR_Y2_VER)
nMacroArea = FUNC_Y2(GetMacroAreaW)();
else if (gFarVersion.dwBuild>=FAR_Y1_VER)
nMacroArea = FUNC_Y1(GetMacroAreaW)();
else
nMacroArea = FUNC_X(GetMacroAreaW)();
return nMacroArea;
}
|
{
"pile_set_name": "Github"
}
|
/* Copyright (c) 2007 Christopher J. W. Lloyd
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 (MIT)
Copyright (c) 2013 Clover Studio Ltd. 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 <Foundation/Foundation.h>
@interface NSURLConnection (SendAsync)
@end
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 2007 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/*
** lib_key_name.c
**
** The routine key_name().
**
*/
#include <curses.priv.h>
MODULE_ID("$Id: lib_key_name.c,v 1.3 2008/10/11 20:15:14 tom Exp $")
NCURSES_EXPORT(NCURSES_CONST char *)
key_name(wchar_t c)
{
cchar_t my_cchar;
wchar_t *my_wchars;
size_t len;
/* FIXME: move to _nc_globals */
static char result[MB_LEN_MAX + 1];
memset(&my_cchar, 0, sizeof(my_cchar));
my_cchar.chars[0] = c;
my_cchar.chars[1] = L'\0';
my_wchars = wunctrl(&my_cchar);
len = wcstombs(result, my_wchars, sizeof(result) - 1);
if (isEILSEQ(len) || (len == 0)) {
return 0;
}
result[len] = '\0';
return result;
}
|
{
"pile_set_name": "Github"
}
|
<!--
****************************************************************************
* Copyright (c) 1998-2010,2015 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************
* @Id: curs_bkgd.3x,v 1.23 2015/07/21 00:11:05 tom Exp @
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<meta name="generator" content="Manpage converted by man2html - see http://invisible-island.net/scripts/readme.html#others_scripts">
<TITLE>curs_bkgd 3x</TITLE>
<link rev=made href="mailto:bug-ncurses@gnu.org">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1 class="no-header">curs_bkgd 3x</H1>
<PRE>
<STRONG><A HREF="curs_bkgd.3x.html">curs_bkgd(3x)</A></STRONG> <STRONG><A HREF="curs_bkgd.3x.html">curs_bkgd(3x)</A></STRONG>
</PRE>
<H2><a name="h2-NAME">NAME</a></H2><PRE>
<STRONG>bkgdset</STRONG>, <STRONG>wbkgdset</STRONG>, <STRONG>bkgd</STRONG>, <STRONG>wbkgd</STRONG>, <STRONG>getbkgd</STRONG> - <STRONG>curses</STRONG> window
background manipulation routines
</PRE>
<H2><a name="h2-SYNOPSIS">SYNOPSIS</a></H2><PRE>
<STRONG>#include</STRONG> <STRONG><curses.h></STRONG>
<STRONG>void</STRONG> <STRONG>bkgdset(chtype</STRONG> <EM>ch</EM><STRONG>);</STRONG>
<STRONG>void</STRONG> <STRONG>wbkgdset(WINDOW</STRONG> <STRONG>*</STRONG><EM>win,</EM> <EM>chtype</EM> <EM>ch</EM><STRONG>);</STRONG>
<STRONG>int</STRONG> <STRONG>bkgd(chtype</STRONG> <EM>ch</EM><STRONG>);</STRONG>
<STRONG>int</STRONG> <STRONG>wbkgd(WINDOW</STRONG> <STRONG>*</STRONG><EM>win</EM><STRONG>,</STRONG> <STRONG>chtype</STRONG> <EM>ch</EM><STRONG>);</STRONG>
<STRONG>chtype</STRONG> <STRONG>getbkgd(WINDOW</STRONG> <STRONG>*</STRONG><EM>win</EM><STRONG>);</STRONG>
</PRE>
<H2><a name="h2-DESCRIPTION">DESCRIPTION</a></H2><PRE>
</PRE>
<H3><a name="h3-bkgdset">bkgdset</a></H3><PRE>
The <STRONG>bkgdset</STRONG> and <STRONG>wbkgdset</STRONG> routines manipulate the back-
ground of the named window. The window background is a
<STRONG>chtype</STRONG> consisting of any combination of attributes (i.e.,
rendition) and a character. The attribute part of the
background is combined (OR'ed) with all non-blank charac-
ters that are written into the window with <STRONG>waddch</STRONG>. Both
the character and attribute parts of the background are
combined with the blank characters. The background
becomes a property of the character and moves with the
character through any scrolling and insert/delete
line/character operations.
To the extent possible on a particular terminal, the
attribute part of the background is displayed as the
graphic rendition of the character put on the screen.
</PRE>
<H3><a name="h3-bkgd">bkgd</a></H3><PRE>
The <STRONG>bkgd</STRONG> and <STRONG>wbkgd</STRONG> functions set the background property
of the current or specified window and then apply this
setting to every character position in that window:
<STRONG>o</STRONG> The rendition of every character on the screen is
changed to the new background rendition.
<STRONG>o</STRONG> Wherever the former background character appears, it
is changed to the new background character.
</PRE>
<H3><a name="h3-getbkgd">getbkgd</a></H3><PRE>
The <STRONG>getbkgd</STRONG> function returns the given window's current
background character/attribute pair.
</PRE>
<H2><a name="h2-RETURN-VALUE">RETURN VALUE</a></H2><PRE>
The routines <STRONG>bkgd</STRONG> and <STRONG>wbkgd</STRONG> return the integer <STRONG>OK</STRONG>. The
SVr4.0 manual says "or a non-negative integer if <STRONG>immedok</STRONG>
is set", but this appears to be an error.
</PRE>
<H2><a name="h2-NOTES">NOTES</a></H2><PRE>
Note that <STRONG>bkgdset</STRONG> and <STRONG>bkgd</STRONG> may be macros.
</PRE>
<H2><a name="h2-PORTABILITY">PORTABILITY</a></H2><PRE>
These functions are described in the XSI Curses standard,
Issue 4. It specifies that <STRONG>bkgd</STRONG> and <STRONG>wbkgd</STRONG> return <STRONG>ERR</STRONG> on
failure, but gives no failure conditions.
</PRE>
<H2><a name="h2-SEE-ALSO">SEE ALSO</a></H2><PRE>
<STRONG><A HREF="ncurses.3x.html">curses(3x)</A></STRONG>, <STRONG><A HREF="curs_addch.3x.html">curs_addch(3x)</A></STRONG>, <STRONG><A HREF="curs_attr.3x.html">curs_attr(3x)</A></STRONG>, <STRONG>curs_out-</STRONG>
<STRONG><A HREF="curs_outopts.3x.html">opts(3x)</A></STRONG>
<STRONG><A HREF="curs_bkgd.3x.html">curs_bkgd(3x)</A></STRONG>
</PRE>
<div class="nav">
<ul>
<li><a href="#h2-NAME">NAME</a></li>
<li><a href="#h2-SYNOPSIS">SYNOPSIS</a></li>
<li><a href="#h2-DESCRIPTION">DESCRIPTION</a>
<ul>
<li><a href="#h3-bkgdset">bkgdset</a></li>
<li><a href="#h3-bkgd">bkgd</a></li>
<li><a href="#h3-getbkgd">getbkgd</a></li>
</ul>
</li>
<li><a href="#h2-RETURN-VALUE">RETURN VALUE</a></li>
<li><a href="#h2-NOTES">NOTES</a></li>
<li><a href="#h2-PORTABILITY">PORTABILITY</a></li>
<li><a href="#h2-SEE-ALSO">SEE ALSO</a></li>
</ul>
</div>
</BODY>
</HTML>
|
{
"pile_set_name": "Github"
}
|
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* This file is part of the program and library *
* SCIP --- Solving Constraint Integer Programs *
* *
* Copyright (C) 2002-2013 Konrad-Zuse-Zentrum *
* fuer Informationstechnik Berlin *
* *
* SCIP is distributed under the terms of the ZIB Academic License. *
* *
* You should have received a copy of the ZIB Academic License *
* along with SCIP; see the file COPYING. If not email to scip@zib.de. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
In the following, some of the names depend on your machine and your
compilation settings:
- $(OSTYPE): the operating system
the string returned by "uname -s" in lower case with the following
replacements:
- "cygwin*" is replaced by only "cygwin"
- "irix??" is replaced by only "irix"
- "windows*" is replaced by only "windows"
- $(ARCH): the architecture
the string returned by "uname -m", modified by the following
rules to subsume some architectures:
- "sun??" is replaced by "sparc"
- "i?86" is replaced by "x86"
- "IP??" is replaced by "mips"
- "9000????" is replaced by "hppa"
- "Power Macintosh" is replaced by "ppc"
- "00??????????" is replaced by "pwr4"
- $(COMP): the compiler
"gnu", "intel", "compaq", "sun", "insure", ... (see make/ directory)
- $(OPT): the optimization level of compilation
"dbg", "opt", or "prf"
- $(LPS): the LP solver to use
"spx", "spx132", "clp", "cpx", "xprs", "msk"
For example, if you want to install SCIP on a Linux system with a x86 processor
using the gnu compiler in debug mode, and using Soplex version >= 1.4.0
as LP solver, you would have the following names:
- $(OSTYPE) = linux
- $(ARCH) = x86
- $(COMP) = gnu
- $(OPT) = dbg
- $(LPS) = spx
-----------------------------------------------------------------------------
Here is what you have to do to get the callable library example project
using SCIP as a library running:
1. Install and compile SCIP as described in the INSTALL file of SCIP's main
directory, and make sure to create the necessary softlinks in SCIP's lib
directory
2. In Makefile, edit the variable SCIPDIR if necessary - it should
point to the directory that contains SCIP.
3. Compile the callable library example project:
In the main directory, enter "make OPT=<...> LPS=<...> COMP=<...>"
with the following options:
- "OPT=opt" to use optimized compilation mode (default)
- "OPT=dbg" to use debug compilation mode
- "OPT=prf" to use performance analysis compilation mode
- "LPS=spx" to use SOPLEX Version >= 1.4.0 as LP solver (default)
- "LPS=cpx" to use CPLEX as LP solver
- "LPS=xprs" to use XPRESS as LP solver
- "LPS=msk" to use MOSEK as LP solver
- "LPS=clp" to use CLP as LP solver
- "COMP=gnu" to use GNU c/c++ compiler (default)
- "IPOPT=true" to enable using Ipopt as NLP solver
- other compilers are available (see make/ directory)
4. To run the program enter "bin/sciplib.$(OSTYPE).$(ARCH).$(COMP).$(OPT).$(LPS)"
(e.g. "bin/sciplib.linux.x86.gnu.opt.spx") or "bin/sciplib" which is a link
to last compiled version
5. To generate the documentation, you need to have doxygen installed, and
enter "make doc"
On some machines, you should use gmake instead of make.
|
{
"pile_set_name": "Github"
}
|
True
True
True
True
True
True
True
True
True
Exception
Exception
|
{
"pile_set_name": "Github"
}
|
// mkerrors_nacl.sh /home/rsc/pub/nacl/native_client/src/trusted/service_runtime/include/sys/errno.h
// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT
package syscall
// TODO(brainman): populate errors in zerrors_windows.go
const (
ERROR_FILE_NOT_FOUND = 2
ERROR_NO_MORE_FILES = 18
ERROR_BROKEN_PIPE = 109
ERROR_INSUFFICIENT_BUFFER = 122
ERROR_MOD_NOT_FOUND = 126
ERROR_PROC_NOT_FOUND = 127
ERROR_DIRECTORY = 267
// TODO(brainman): should use value for EWINDOWS that does not clashes with anything else
EWINDOWS = 99999 /* otherwise unused */
)
// TODO(brainman): fix all needed for os
const (
EPERM = 1
ENOENT = 2
ESRCH = 3
EINTR = 4
EIO = 5
ENXIO = 6
E2BIG = 7
ENOEXEC = 8
EBADF = 9
ECHILD = 10
EAGAIN = 11
ENOMEM = 12
EACCES = 13
EFAULT = 14
EBUSY = 16
EEXIST = 17
EXDEV = 18
ENODEV = 19
ENOTDIR = ERROR_DIRECTORY
EISDIR = 21
EINVAL = 22
ENFILE = 23
EMFILE = 24
ENOTTY = 25
EFBIG = 27
ENOSPC = 28
ESPIPE = 29
EROFS = 30
EMLINK = 31
EPIPE = 32
ENAMETOOLONG = 36
ENOSYS = 38
EDQUOT = 122
EDOM = 33
ERANGE = 34
ENOMSG = 35
ECHRNG = 37
EL3HLT = 39
EL3RST = 40
ELNRNG = 41
EUNATCH = 42
ENOCSI = 43
EL2HLT = 44
EDEADLK = 45
ENOLCK = 46
EBADE = 50
EBADR = 51
EXFULL = 52
ENOANO = 53
EBADRQC = 54
EBADSLT = 55
EBFONT = 57
ENOSTR = 60
ENODATA = 61
ETIME = 62
ENOSR = 63
ENONET = 64
ENOPKG = 65
EREMOTE = 66
ENOLINK = 67
EADV = 68
ESRMNT = 69
ECOMM = 70
EPROTO = 71
EMULTIHOP = 74
ELBIN = 75
EDOTDOT = 76
EBADMSG = 77
EFTYPE = 79
ENOTUNIQ = 80
EBADFD = 81
EREMCHG = 82
ELIBACC = 83
ELIBBAD = 84
ELIBSCN = 85
ELIBMAX = 86
ELIBEXEC = 87
ENMFILE = 89
ENOTEMPTY = 90
ELOOP = 92
EOPNOTSUPP = 95
EPFNOSUPPORT = 96
ECONNRESET = 104
ENOBUFS = 105
EAFNOSUPPORT = 106
EPROTOTYPE = 107
ENOTSOCK = 108
ENOPROTOOPT = 109
ESHUTDOWN = 110
ECONNREFUSED = 111
EADDRINUSE = 112
ECONNABORTED = 113
ENETUNREACH = 114
ENETDOWN = 115
ETIMEDOUT = 116
EHOSTDOWN = 117
EHOSTUNREACH = 118
EINPROGRESS = 119
EALREADY = 120
EDESTADDRREQ = 121
EPROTONOSUPPORT = 123
ESOCKTNOSUPPORT = 124
EADDRNOTAVAIL = 125
ENETRESET = 126
EISCONN = 127
ENOTCONN = 128
ETOOMANYREFS = 129
EPROCLIM = 130
EUSERS = 131
EWOULDBLOCK = 141
ESTALE = 133
ENOMEDIUM = 135
ENOSHARE = 136
ECASECLASH = 137
EILSEQ = 138
EOVERFLOW = 139
ECANCELED = 140
EL2NSYNC = 88
EIDRM = 91
EMSGSIZE = 132
)
|
{
"pile_set_name": "Github"
}
|
/*****************************************************************************
* *
* File: cxgb2.c *
* $Revision: 1.25 $ *
* $Date: 2005/06/22 00:43:25 $ *
* Description: *
* Chelsio 10Gb Ethernet Driver. *
* *
* This program 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. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program; if not, see <http://www.gnu.org/licenses/>. *
* *
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED *
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF *
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. *
* *
* http://www.chelsio.com *
* *
* Copyright (c) 2003 - 2005 Chelsio Communications, Inc. *
* All rights reserved. *
* *
* Maintainers: maintainers@chelsio.com *
* *
* Authors: Dimitrios Michailidis <dm@chelsio.com> *
* Tina Yang <tainay@chelsio.com> *
* Felix Marti <felix@chelsio.com> *
* Scott Bardone <sbardone@chelsio.com> *
* Kurt Ottaway <kottaway@chelsio.com> *
* Frank DiMambro <frank@chelsio.com> *
* *
* History: *
* *
****************************************************************************/
#include "common.h"
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/if_vlan.h>
#include <linux/mii.h>
#include <linux/sockios.h>
#include <linux/dma-mapping.h>
#include <linux/uaccess.h>
#include "cpl5_cmd.h"
#include "regs.h"
#include "gmac.h"
#include "cphy.h"
#include "sge.h"
#include "tp.h"
#include "espi.h"
#include "elmer0.h"
#include <linux/workqueue.h>
static inline void schedule_mac_stats_update(struct adapter *ap, int secs)
{
schedule_delayed_work(&ap->stats_update_task, secs * HZ);
}
static inline void cancel_mac_stats_update(struct adapter *ap)
{
cancel_delayed_work(&ap->stats_update_task);
}
#define MAX_CMDQ_ENTRIES 16384
#define MAX_CMDQ1_ENTRIES 1024
#define MAX_RX_BUFFERS 16384
#define MAX_RX_JUMBO_BUFFERS 16384
#define MAX_TX_BUFFERS_HIGH 16384U
#define MAX_TX_BUFFERS_LOW 1536U
#define MAX_TX_BUFFERS 1460U
#define MIN_FL_ENTRIES 32
#define DFLT_MSG_ENABLE (NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK | \
NETIF_MSG_TIMER | NETIF_MSG_IFDOWN | NETIF_MSG_IFUP |\
NETIF_MSG_RX_ERR | NETIF_MSG_TX_ERR)
/*
* The EEPROM is actually bigger but only the first few bytes are used so we
* only report those.
*/
#define EEPROM_SIZE 32
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR("Chelsio Communications");
MODULE_LICENSE("GPL");
static int dflt_msg_enable = DFLT_MSG_ENABLE;
module_param(dflt_msg_enable, int, 0);
MODULE_PARM_DESC(dflt_msg_enable, "Chelsio T1 default message enable bitmap");
#define HCLOCK 0x0
#define LCLOCK 0x1
/* T1 cards powersave mode */
static int t1_clock(struct adapter *adapter, int mode);
static int t1powersave = 1; /* HW default is powersave mode. */
module_param(t1powersave, int, 0);
MODULE_PARM_DESC(t1powersave, "Enable/Disable T1 powersaving mode");
static int disable_msi = 0;
module_param(disable_msi, int, 0);
MODULE_PARM_DESC(disable_msi, "Disable Message Signaled Interrupt (MSI)");
static const char pci_speed[][4] = {
"33", "66", "100", "133"
};
/*
* Setup MAC to receive the types of packets we want.
*/
static void t1_set_rxmode(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct t1_rx_mode rm;
rm.dev = dev;
mac->ops->set_rx_mode(mac, &rm);
}
static void link_report(struct port_info *p)
{
if (!netif_carrier_ok(p->dev))
netdev_info(p->dev, "link down\n");
else {
const char *s = "10Mbps";
switch (p->link_config.speed) {
case SPEED_10000: s = "10Gbps"; break;
case SPEED_1000: s = "1000Mbps"; break;
case SPEED_100: s = "100Mbps"; break;
}
netdev_info(p->dev, "link up, %s, %s-duplex\n",
s, p->link_config.duplex == DUPLEX_FULL
? "full" : "half");
}
}
void t1_link_negotiated(struct adapter *adapter, int port_id, int link_stat,
int speed, int duplex, int pause)
{
struct port_info *p = &adapter->port[port_id];
if (link_stat != netif_carrier_ok(p->dev)) {
if (link_stat)
netif_carrier_on(p->dev);
else
netif_carrier_off(p->dev);
link_report(p);
/* multi-ports: inform toe */
if ((speed > 0) && (adapter->params.nports > 1)) {
unsigned int sched_speed = 10;
switch (speed) {
case SPEED_1000:
sched_speed = 1000;
break;
case SPEED_100:
sched_speed = 100;
break;
case SPEED_10:
sched_speed = 10;
break;
}
t1_sched_update_parms(adapter->sge, port_id, 0, sched_speed);
}
}
}
static void link_start(struct port_info *p)
{
struct cmac *mac = p->mac;
mac->ops->reset(mac);
if (mac->ops->macaddress_set)
mac->ops->macaddress_set(mac, p->dev->dev_addr);
t1_set_rxmode(p->dev);
t1_link_start(p->phy, mac, &p->link_config);
mac->ops->enable(mac, MAC_DIRECTION_RX | MAC_DIRECTION_TX);
}
static void enable_hw_csum(struct adapter *adapter)
{
if (adapter->port[0].dev->hw_features & NETIF_F_TSO)
t1_tp_set_ip_checksum_offload(adapter->tp, 1); /* for TSO only */
t1_tp_set_tcp_checksum_offload(adapter->tp, 1);
}
/*
* Things to do upon first use of a card.
* This must run with the rtnl lock held.
*/
static int cxgb_up(struct adapter *adapter)
{
int err = 0;
if (!(adapter->flags & FULL_INIT_DONE)) {
err = t1_init_hw_modules(adapter);
if (err)
goto out_err;
enable_hw_csum(adapter);
adapter->flags |= FULL_INIT_DONE;
}
t1_interrupts_clear(adapter);
adapter->params.has_msi = !disable_msi && !pci_enable_msi(adapter->pdev);
err = request_irq(adapter->pdev->irq, t1_interrupt,
adapter->params.has_msi ? 0 : IRQF_SHARED,
adapter->name, adapter);
if (err) {
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
goto out_err;
}
t1_sge_start(adapter->sge);
t1_interrupts_enable(adapter);
out_err:
return err;
}
/*
* Release resources when all the ports have been stopped.
*/
static void cxgb_down(struct adapter *adapter)
{
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
free_irq(adapter->pdev->irq, adapter);
if (adapter->params.has_msi)
pci_disable_msi(adapter->pdev);
}
static int cxgb_open(struct net_device *dev)
{
int err;
struct adapter *adapter = dev->ml_priv;
int other_ports = adapter->open_device_map & PORT_MASK;
napi_enable(&adapter->napi);
if (!adapter->open_device_map && (err = cxgb_up(adapter)) < 0) {
napi_disable(&adapter->napi);
return err;
}
__set_bit(dev->if_port, &adapter->open_device_map);
link_start(&adapter->port[dev->if_port]);
netif_start_queue(dev);
if (!other_ports && adapter->params.stats_update_period)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
t1_vlan_mode(adapter, dev->features);
return 0;
}
static int cxgb_close(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct cmac *mac = p->mac;
netif_stop_queue(dev);
napi_disable(&adapter->napi);
mac->ops->disable(mac, MAC_DIRECTION_TX | MAC_DIRECTION_RX);
netif_carrier_off(dev);
clear_bit(dev->if_port, &adapter->open_device_map);
if (adapter->params.stats_update_period &&
!(adapter->open_device_map & PORT_MASK)) {
/* Stop statistics accumulation. */
smp_mb__after_atomic();
spin_lock(&adapter->work_lock); /* sync with update task */
spin_unlock(&adapter->work_lock);
cancel_mac_stats_update(adapter);
}
if (!adapter->open_device_map)
cxgb_down(adapter);
return 0;
}
static struct net_device_stats *t1_get_stats(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct net_device_stats *ns = &dev->stats;
const struct cmac_statistics *pstats;
/* Do a full update of the MAC stats */
pstats = p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FULL);
ns->tx_packets = pstats->TxUnicastFramesOK +
pstats->TxMulticastFramesOK + pstats->TxBroadcastFramesOK;
ns->rx_packets = pstats->RxUnicastFramesOK +
pstats->RxMulticastFramesOK + pstats->RxBroadcastFramesOK;
ns->tx_bytes = pstats->TxOctetsOK;
ns->rx_bytes = pstats->RxOctetsOK;
ns->tx_errors = pstats->TxLateCollisions + pstats->TxLengthErrors +
pstats->TxUnderrun + pstats->TxFramesAbortedDueToXSCollisions;
ns->rx_errors = pstats->RxDataErrors + pstats->RxJabberErrors +
pstats->RxFCSErrors + pstats->RxAlignErrors +
pstats->RxSequenceErrors + pstats->RxFrameTooLongErrors +
pstats->RxSymbolErrors + pstats->RxRuntErrors;
ns->multicast = pstats->RxMulticastFramesOK;
ns->collisions = pstats->TxTotalCollisions;
/* detailed rx_errors */
ns->rx_length_errors = pstats->RxFrameTooLongErrors +
pstats->RxJabberErrors;
ns->rx_over_errors = 0;
ns->rx_crc_errors = pstats->RxFCSErrors;
ns->rx_frame_errors = pstats->RxAlignErrors;
ns->rx_fifo_errors = 0;
ns->rx_missed_errors = 0;
/* detailed tx_errors */
ns->tx_aborted_errors = pstats->TxFramesAbortedDueToXSCollisions;
ns->tx_carrier_errors = 0;
ns->tx_fifo_errors = pstats->TxUnderrun;
ns->tx_heartbeat_errors = 0;
ns->tx_window_errors = pstats->TxLateCollisions;
return ns;
}
static u32 get_msglevel(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return adapter->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct adapter *adapter = dev->ml_priv;
adapter->msg_enable = val;
}
static const char stats_strings[][ETH_GSTRING_LEN] = {
"TxOctetsOK",
"TxOctetsBad",
"TxUnicastFramesOK",
"TxMulticastFramesOK",
"TxBroadcastFramesOK",
"TxPauseFrames",
"TxFramesWithDeferredXmissions",
"TxLateCollisions",
"TxTotalCollisions",
"TxFramesAbortedDueToXSCollisions",
"TxUnderrun",
"TxLengthErrors",
"TxInternalMACXmitError",
"TxFramesWithExcessiveDeferral",
"TxFCSErrors",
"TxJumboFramesOk",
"TxJumboOctetsOk",
"RxOctetsOK",
"RxOctetsBad",
"RxUnicastFramesOK",
"RxMulticastFramesOK",
"RxBroadcastFramesOK",
"RxPauseFrames",
"RxFCSErrors",
"RxAlignErrors",
"RxSymbolErrors",
"RxDataErrors",
"RxSequenceErrors",
"RxRuntErrors",
"RxJabberErrors",
"RxInternalMACRcvError",
"RxInRangeLengthErrors",
"RxOutOfRangeLengthField",
"RxFrameTooLongErrors",
"RxJumboFramesOk",
"RxJumboOctetsOk",
/* Port stats */
"RxCsumGood",
"TxCsumOffload",
"TxTso",
"RxVlan",
"TxVlan",
"TxNeedHeadroom",
/* Interrupt stats */
"rx drops",
"pure_rsps",
"unhandled irqs",
"respQ_empty",
"respQ_overflow",
"freelistQ_empty",
"pkt_too_big",
"pkt_mismatch",
"cmdQ_full0",
"cmdQ_full1",
"espi_DIP2ParityErr",
"espi_DIP4Err",
"espi_RxDrops",
"espi_TxDrops",
"espi_RxOvfl",
"espi_ParityErr"
};
#define T2_REGMAP_SIZE (3 * 1024)
static int get_regs_len(struct net_device *dev)
{
return T2_REGMAP_SIZE;
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct adapter *adapter = dev->ml_priv;
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
strlcpy(info->bus_info, pci_name(adapter->pdev),
sizeof(info->bus_info));
}
static int get_sset_count(struct net_device *dev, int sset)
{
switch (sset) {
case ETH_SS_STATS:
return ARRAY_SIZE(stats_strings);
default:
return -EOPNOTSUPP;
}
}
static void get_strings(struct net_device *dev, u32 stringset, u8 *data)
{
if (stringset == ETH_SS_STATS)
memcpy(data, stats_strings, sizeof(stats_strings));
}
static void get_stats(struct net_device *dev, struct ethtool_stats *stats,
u64 *data)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
const struct cmac_statistics *s;
const struct sge_intr_counts *t;
struct sge_port_stats ss;
s = mac->ops->statistics_update(mac, MAC_STATS_UPDATE_FULL);
t = t1_sge_get_intr_counts(adapter->sge);
t1_sge_get_port_stats(adapter->sge, dev->if_port, &ss);
*data++ = s->TxOctetsOK;
*data++ = s->TxOctetsBad;
*data++ = s->TxUnicastFramesOK;
*data++ = s->TxMulticastFramesOK;
*data++ = s->TxBroadcastFramesOK;
*data++ = s->TxPauseFrames;
*data++ = s->TxFramesWithDeferredXmissions;
*data++ = s->TxLateCollisions;
*data++ = s->TxTotalCollisions;
*data++ = s->TxFramesAbortedDueToXSCollisions;
*data++ = s->TxUnderrun;
*data++ = s->TxLengthErrors;
*data++ = s->TxInternalMACXmitError;
*data++ = s->TxFramesWithExcessiveDeferral;
*data++ = s->TxFCSErrors;
*data++ = s->TxJumboFramesOK;
*data++ = s->TxJumboOctetsOK;
*data++ = s->RxOctetsOK;
*data++ = s->RxOctetsBad;
*data++ = s->RxUnicastFramesOK;
*data++ = s->RxMulticastFramesOK;
*data++ = s->RxBroadcastFramesOK;
*data++ = s->RxPauseFrames;
*data++ = s->RxFCSErrors;
*data++ = s->RxAlignErrors;
*data++ = s->RxSymbolErrors;
*data++ = s->RxDataErrors;
*data++ = s->RxSequenceErrors;
*data++ = s->RxRuntErrors;
*data++ = s->RxJabberErrors;
*data++ = s->RxInternalMACRcvError;
*data++ = s->RxInRangeLengthErrors;
*data++ = s->RxOutOfRangeLengthField;
*data++ = s->RxFrameTooLongErrors;
*data++ = s->RxJumboFramesOK;
*data++ = s->RxJumboOctetsOK;
*data++ = ss.rx_cso_good;
*data++ = ss.tx_cso;
*data++ = ss.tx_tso;
*data++ = ss.vlan_xtract;
*data++ = ss.vlan_insert;
*data++ = ss.tx_need_hdrroom;
*data++ = t->rx_drops;
*data++ = t->pure_rsps;
*data++ = t->unhandled_irqs;
*data++ = t->respQ_empty;
*data++ = t->respQ_overflow;
*data++ = t->freelistQ_empty;
*data++ = t->pkt_too_big;
*data++ = t->pkt_mismatch;
*data++ = t->cmdQ_full[0];
*data++ = t->cmdQ_full[1];
if (adapter->espi) {
const struct espi_intr_counts *e;
e = t1_espi_get_intr_counts(adapter->espi);
*data++ = e->DIP2_parity_err;
*data++ = e->DIP4_err;
*data++ = e->rx_drops;
*data++ = e->tx_drops;
*data++ = e->rx_ovflw;
*data++ = e->parity_err;
}
}
static inline void reg_block_dump(struct adapter *ap, void *buf,
unsigned int start, unsigned int end)
{
u32 *p = buf + start;
for ( ; start <= end; start += sizeof(u32))
*p++ = readl(ap->regs + start);
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs,
void *buf)
{
struct adapter *ap = dev->ml_priv;
/*
* Version scheme: bits 0..9: chip version, bits 10..15: chip revision
*/
regs->version = 2;
memset(buf, 0, T2_REGMAP_SIZE);
reg_block_dump(ap, buf, 0, A_SG_RESPACCUTIMER);
reg_block_dump(ap, buf, A_MC3_CFG, A_MC4_INT_CAUSE);
reg_block_dump(ap, buf, A_TPI_ADDR, A_TPI_PAR);
reg_block_dump(ap, buf, A_TP_IN_CONFIG, A_TP_TX_DROP_COUNT);
reg_block_dump(ap, buf, A_RAT_ROUTE_CONTROL, A_RAT_INTR_CAUSE);
reg_block_dump(ap, buf, A_CSPI_RX_AE_WM, A_CSPI_INTR_ENABLE);
reg_block_dump(ap, buf, A_ESPI_SCH_TOKEN0, A_ESPI_GOSTAT);
reg_block_dump(ap, buf, A_ULP_ULIMIT, A_ULP_PIO_CTRL);
reg_block_dump(ap, buf, A_PL_ENABLE, A_PL_CAUSE);
reg_block_dump(ap, buf, A_MC5_CONFIG, A_MC5_MASK_WRITE_CMD);
}
static int get_link_ksettings(struct net_device *dev,
struct ethtool_link_ksettings *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
u32 supported, advertising;
supported = p->link_config.supported;
advertising = p->link_config.advertising;
if (netif_carrier_ok(dev)) {
cmd->base.speed = p->link_config.speed;
cmd->base.duplex = p->link_config.duplex;
} else {
cmd->base.speed = SPEED_UNKNOWN;
cmd->base.duplex = DUPLEX_UNKNOWN;
}
cmd->base.port = (supported & SUPPORTED_TP) ? PORT_TP : PORT_FIBRE;
cmd->base.phy_address = p->phy->mdio.prtad;
cmd->base.autoneg = p->link_config.autoneg;
ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.supported,
supported);
ethtool_convert_legacy_u32_to_link_mode(cmd->link_modes.advertising,
advertising);
return 0;
}
static int speed_duplex_to_caps(int speed, int duplex)
{
int cap = 0;
switch (speed) {
case SPEED_10:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10baseT_Full;
else
cap = SUPPORTED_10baseT_Half;
break;
case SPEED_100:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_100baseT_Full;
else
cap = SUPPORTED_100baseT_Half;
break;
case SPEED_1000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_1000baseT_Full;
else
cap = SUPPORTED_1000baseT_Half;
break;
case SPEED_10000:
if (duplex == DUPLEX_FULL)
cap = SUPPORTED_10000baseT_Full;
}
return cap;
}
#define ADVERTISED_MASK (ADVERTISED_10baseT_Half | ADVERTISED_10baseT_Full | \
ADVERTISED_100baseT_Half | ADVERTISED_100baseT_Full | \
ADVERTISED_1000baseT_Half | ADVERTISED_1000baseT_Full | \
ADVERTISED_10000baseT_Full)
static int set_link_ksettings(struct net_device *dev,
const struct ethtool_link_ksettings *cmd)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
u32 advertising;
ethtool_convert_link_mode_to_legacy_u32(&advertising,
cmd->link_modes.advertising);
if (!(lc->supported & SUPPORTED_Autoneg))
return -EOPNOTSUPP; /* can't change speed/duplex */
if (cmd->base.autoneg == AUTONEG_DISABLE) {
u32 speed = cmd->base.speed;
int cap = speed_duplex_to_caps(speed, cmd->base.duplex);
if (!(lc->supported & cap) || (speed == SPEED_1000))
return -EINVAL;
lc->requested_speed = speed;
lc->requested_duplex = cmd->base.duplex;
lc->advertising = 0;
} else {
advertising &= ADVERTISED_MASK;
if (advertising & (advertising - 1))
advertising = lc->supported;
advertising &= lc->supported;
if (!advertising)
return -EINVAL;
lc->requested_speed = SPEED_INVALID;
lc->requested_duplex = DUPLEX_INVALID;
lc->advertising = advertising | ADVERTISED_Autoneg;
}
lc->autoneg = cmd->base.autoneg;
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
return 0;
}
static void get_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
epause->autoneg = (p->link_config.requested_fc & PAUSE_AUTONEG) != 0;
epause->rx_pause = (p->link_config.fc & PAUSE_RX) != 0;
epause->tx_pause = (p->link_config.fc & PAUSE_TX) != 0;
}
static int set_pauseparam(struct net_device *dev,
struct ethtool_pauseparam *epause)
{
struct adapter *adapter = dev->ml_priv;
struct port_info *p = &adapter->port[dev->if_port];
struct link_config *lc = &p->link_config;
if (epause->autoneg == AUTONEG_DISABLE)
lc->requested_fc = 0;
else if (lc->supported & SUPPORTED_Autoneg)
lc->requested_fc = PAUSE_AUTONEG;
else
return -EINVAL;
if (epause->rx_pause)
lc->requested_fc |= PAUSE_RX;
if (epause->tx_pause)
lc->requested_fc |= PAUSE_TX;
if (lc->autoneg == AUTONEG_ENABLE) {
if (netif_running(dev))
t1_link_start(p->phy, p->mac, lc);
} else {
lc->fc = lc->requested_fc & (PAUSE_RX | PAUSE_TX);
if (netif_running(dev))
p->mac->ops->set_speed_duplex_fc(p->mac, -1, -1,
lc->fc);
}
return 0;
}
static void get_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
e->rx_max_pending = MAX_RX_BUFFERS;
e->rx_jumbo_max_pending = MAX_RX_JUMBO_BUFFERS;
e->tx_max_pending = MAX_CMDQ_ENTRIES;
e->rx_pending = adapter->params.sge.freelQ_size[!jumbo_fl];
e->rx_jumbo_pending = adapter->params.sge.freelQ_size[jumbo_fl];
e->tx_pending = adapter->params.sge.cmdQ_size[0];
}
static int set_sge_param(struct net_device *dev, struct ethtool_ringparam *e)
{
struct adapter *adapter = dev->ml_priv;
int jumbo_fl = t1_is_T1B(adapter) ? 1 : 0;
if (e->rx_pending > MAX_RX_BUFFERS || e->rx_mini_pending ||
e->rx_jumbo_pending > MAX_RX_JUMBO_BUFFERS ||
e->tx_pending > MAX_CMDQ_ENTRIES ||
e->rx_pending < MIN_FL_ENTRIES ||
e->rx_jumbo_pending < MIN_FL_ENTRIES ||
e->tx_pending < (adapter->params.nports + 1) * (MAX_SKB_FRAGS + 1))
return -EINVAL;
if (adapter->flags & FULL_INIT_DONE)
return -EBUSY;
adapter->params.sge.freelQ_size[!jumbo_fl] = e->rx_pending;
adapter->params.sge.freelQ_size[jumbo_fl] = e->rx_jumbo_pending;
adapter->params.sge.cmdQ_size[0] = e->tx_pending;
adapter->params.sge.cmdQ_size[1] = e->tx_pending > MAX_CMDQ1_ENTRIES ?
MAX_CMDQ1_ENTRIES : e->tx_pending;
return 0;
}
static int set_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
adapter->params.sge.rx_coalesce_usecs = c->rx_coalesce_usecs;
adapter->params.sge.coalesce_enable = c->use_adaptive_rx_coalesce;
adapter->params.sge.sample_interval_usecs = c->rate_sample_interval;
t1_sge_set_coalesce_params(adapter->sge, &adapter->params.sge);
return 0;
}
static int get_coalesce(struct net_device *dev, struct ethtool_coalesce *c)
{
struct adapter *adapter = dev->ml_priv;
c->rx_coalesce_usecs = adapter->params.sge.rx_coalesce_usecs;
c->rate_sample_interval = adapter->params.sge.sample_interval_usecs;
c->use_adaptive_rx_coalesce = adapter->params.sge.coalesce_enable;
return 0;
}
static int get_eeprom_len(struct net_device *dev)
{
struct adapter *adapter = dev->ml_priv;
return t1_is_asic(adapter) ? EEPROM_SIZE : 0;
}
#define EEPROM_MAGIC(ap) \
(PCI_VENDOR_ID_CHELSIO | ((ap)->params.chip_version << 16))
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *e,
u8 *data)
{
int i;
u8 buf[EEPROM_SIZE] __attribute__((aligned(4)));
struct adapter *adapter = dev->ml_priv;
e->magic = EEPROM_MAGIC(adapter);
for (i = e->offset & ~3; i < e->offset + e->len; i += sizeof(u32))
t1_seeprom_read(adapter, i, (__le32 *)&buf[i]);
memcpy(data, buf + e->offset, e->len);
return 0;
}
static const struct ethtool_ops t1_ethtool_ops = {
.get_drvinfo = get_drvinfo,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.get_ringparam = get_sge_param,
.set_ringparam = set_sge_param,
.get_coalesce = get_coalesce,
.set_coalesce = set_coalesce,
.get_eeprom_len = get_eeprom_len,
.get_eeprom = get_eeprom,
.get_pauseparam = get_pauseparam,
.set_pauseparam = set_pauseparam,
.get_link = ethtool_op_get_link,
.get_strings = get_strings,
.get_sset_count = get_sset_count,
.get_ethtool_stats = get_stats,
.get_regs_len = get_regs_len,
.get_regs = get_regs,
.get_link_ksettings = get_link_ksettings,
.set_link_ksettings = set_link_ksettings,
};
static int t1_ioctl(struct net_device *dev, struct ifreq *req, int cmd)
{
struct adapter *adapter = dev->ml_priv;
struct mdio_if_info *mdio = &adapter->port[dev->if_port].phy->mdio;
return mdio_mii_ioctl(mdio, if_mii(req), cmd);
}
static int t1_change_mtu(struct net_device *dev, int new_mtu)
{
int ret;
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
if (!mac->ops->set_mtu)
return -EOPNOTSUPP;
if ((ret = mac->ops->set_mtu(mac, new_mtu)))
return ret;
dev->mtu = new_mtu;
return 0;
}
static int t1_set_mac_addr(struct net_device *dev, void *p)
{
struct adapter *adapter = dev->ml_priv;
struct cmac *mac = adapter->port[dev->if_port].mac;
struct sockaddr *addr = p;
if (!mac->ops->macaddress_set)
return -EOPNOTSUPP;
memcpy(dev->dev_addr, addr->sa_data, dev->addr_len);
mac->ops->macaddress_set(mac, dev->dev_addr);
return 0;
}
static netdev_features_t t1_fix_features(struct net_device *dev,
netdev_features_t features)
{
/*
* Since there is no support for separate rx/tx vlan accel
* enable/disable make sure tx flag is always in same state as rx.
*/
if (features & NETIF_F_HW_VLAN_CTAG_RX)
features |= NETIF_F_HW_VLAN_CTAG_TX;
else
features &= ~NETIF_F_HW_VLAN_CTAG_TX;
return features;
}
static int t1_set_features(struct net_device *dev, netdev_features_t features)
{
netdev_features_t changed = dev->features ^ features;
struct adapter *adapter = dev->ml_priv;
if (changed & NETIF_F_HW_VLAN_CTAG_RX)
t1_vlan_mode(adapter, features);
return 0;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void t1_netpoll(struct net_device *dev)
{
unsigned long flags;
struct adapter *adapter = dev->ml_priv;
local_irq_save(flags);
t1_interrupt(adapter->pdev->irq, adapter);
local_irq_restore(flags);
}
#endif
/*
* Periodic accumulation of MAC statistics. This is used only if the MAC
* does not have any other way to prevent stats counter overflow.
*/
static void mac_stats_task(struct work_struct *work)
{
int i;
struct adapter *adapter =
container_of(work, struct adapter, stats_update_task.work);
for_each_port(adapter, i) {
struct port_info *p = &adapter->port[i];
if (netif_running(p->dev))
p->mac->ops->statistics_update(p->mac,
MAC_STATS_UPDATE_FAST);
}
/* Schedule the next statistics update if any port is active. */
spin_lock(&adapter->work_lock);
if (adapter->open_device_map & PORT_MASK)
schedule_mac_stats_update(adapter,
adapter->params.stats_update_period);
spin_unlock(&adapter->work_lock);
}
/*
* Processes elmer0 external interrupts in process context.
*/
static void ext_intr_task(struct work_struct *work)
{
struct adapter *adapter =
container_of(work, struct adapter, ext_intr_handler_task);
t1_elmer0_ext_intr_handler(adapter);
/* Now reenable external interrupts */
spin_lock_irq(&adapter->async_lock);
adapter->slow_intr_mask |= F_PL_INTR_EXT;
writel(F_PL_INTR_EXT, adapter->regs + A_PL_CAUSE);
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
spin_unlock_irq(&adapter->async_lock);
}
/*
* Interrupt-context handler for elmer0 external interrupts.
*/
void t1_elmer0_ext_intr(struct adapter *adapter)
{
/*
* Schedule a task to handle external interrupts as we require
* a process context. We disable EXT interrupts in the interim
* and let the task reenable them when it's done.
*/
adapter->slow_intr_mask &= ~F_PL_INTR_EXT;
writel(adapter->slow_intr_mask | F_PL_INTR_SGE_DATA,
adapter->regs + A_PL_ENABLE);
schedule_work(&adapter->ext_intr_handler_task);
}
void t1_fatal_err(struct adapter *adapter)
{
if (adapter->flags & FULL_INIT_DONE) {
t1_sge_stop(adapter->sge);
t1_interrupts_disable(adapter);
}
pr_alert("%s: encountered fatal error, operation suspended\n",
adapter->name);
}
static const struct net_device_ops cxgb_netdev_ops = {
.ndo_open = cxgb_open,
.ndo_stop = cxgb_close,
.ndo_start_xmit = t1_start_xmit,
.ndo_get_stats = t1_get_stats,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_rx_mode = t1_set_rxmode,
.ndo_do_ioctl = t1_ioctl,
.ndo_change_mtu = t1_change_mtu,
.ndo_set_mac_address = t1_set_mac_addr,
.ndo_fix_features = t1_fix_features,
.ndo_set_features = t1_set_features,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = t1_netpoll,
#endif
};
static int init_one(struct pci_dev *pdev, const struct pci_device_id *ent)
{
int i, err, pci_using_dac = 0;
unsigned long mmio_start, mmio_len;
const struct board_info *bi;
struct adapter *adapter = NULL;
struct port_info *pi;
pr_info_once("%s - version %s\n", DRV_DESCRIPTION, DRV_VERSION);
err = pci_enable_device(pdev);
if (err)
return err;
if (!(pci_resource_flags(pdev, 0) & IORESOURCE_MEM)) {
pr_err("%s: cannot find PCI device memory base address\n",
pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(64))) {
pci_using_dac = 1;
if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64))) {
pr_err("%s: unable to obtain 64-bit DMA for "
"consistent allocations\n", pci_name(pdev));
err = -ENODEV;
goto out_disable_pdev;
}
} else if ((err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) != 0) {
pr_err("%s: no usable DMA configuration\n", pci_name(pdev));
goto out_disable_pdev;
}
err = pci_request_regions(pdev, DRV_NAME);
if (err) {
pr_err("%s: cannot obtain PCI resources\n", pci_name(pdev));
goto out_disable_pdev;
}
pci_set_master(pdev);
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
bi = t1_get_board_info(ent->driver_data);
for (i = 0; i < bi->port_number; ++i) {
struct net_device *netdev;
netdev = alloc_etherdev(adapter ? 0 : sizeof(*adapter));
if (!netdev) {
err = -ENOMEM;
goto out_free_dev;
}
SET_NETDEV_DEV(netdev, &pdev->dev);
if (!adapter) {
adapter = netdev_priv(netdev);
adapter->pdev = pdev;
adapter->port[0].dev = netdev; /* so we don't leak it */
adapter->regs = ioremap(mmio_start, mmio_len);
if (!adapter->regs) {
pr_err("%s: cannot map device registers\n",
pci_name(pdev));
err = -ENOMEM;
goto out_free_dev;
}
if (t1_get_board_rev(adapter, bi, &adapter->params)) {
err = -ENODEV; /* Can't handle this chip rev */
goto out_free_dev;
}
adapter->name = pci_name(pdev);
adapter->msg_enable = dflt_msg_enable;
adapter->mmio_len = mmio_len;
spin_lock_init(&adapter->tpi_lock);
spin_lock_init(&adapter->work_lock);
spin_lock_init(&adapter->async_lock);
spin_lock_init(&adapter->mac_lock);
INIT_WORK(&adapter->ext_intr_handler_task,
ext_intr_task);
INIT_DELAYED_WORK(&adapter->stats_update_task,
mac_stats_task);
pci_set_drvdata(pdev, netdev);
}
pi = &adapter->port[i];
pi->dev = netdev;
netif_carrier_off(netdev);
netdev->irq = pdev->irq;
netdev->if_port = i;
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len - 1;
netdev->ml_priv = adapter;
netdev->hw_features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM;
netdev->features |= NETIF_F_SG | NETIF_F_IP_CSUM |
NETIF_F_RXCSUM | NETIF_F_LLTX;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
if (vlan_tso_capable(adapter)) {
netdev->features |=
NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_CTAG_RX;
netdev->hw_features |= NETIF_F_HW_VLAN_CTAG_RX;
/* T204: disable TSO */
if (!(is_T2(adapter)) || bi->port_number != 4) {
netdev->hw_features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO;
}
}
netdev->netdev_ops = &cxgb_netdev_ops;
netdev->hard_header_len += (netdev->hw_features & NETIF_F_TSO) ?
sizeof(struct cpl_tx_pkt_lso) : sizeof(struct cpl_tx_pkt);
netif_napi_add(netdev, &adapter->napi, t1_poll, 64);
netdev->ethtool_ops = &t1_ethtool_ops;
switch (bi->board) {
case CHBT_BOARD_CHT110:
case CHBT_BOARD_N110:
case CHBT_BOARD_N210:
case CHBT_BOARD_CHT210:
netdev->max_mtu = PM3393_MAX_FRAME_SIZE -
(ETH_HLEN + ETH_FCS_LEN);
break;
case CHBT_BOARD_CHN204:
netdev->max_mtu = VSC7326_MAX_MTU;
break;
default:
netdev->max_mtu = ETH_DATA_LEN;
break;
}
}
if (t1_init_sw_modules(adapter, bi) < 0) {
err = -ENODEV;
goto out_free_dev;
}
/*
* The card is now ready to go. If any errors occur during device
* registration we do not fail the whole card but rather proceed only
* with the ports we manage to register successfully. However we must
* register at least one net device.
*/
for (i = 0; i < bi->port_number; ++i) {
err = register_netdev(adapter->port[i].dev);
if (err)
pr_warn("%s: cannot register net device %s, skipping\n",
pci_name(pdev), adapter->port[i].dev->name);
else {
/*
* Change the name we use for messages to the name of
* the first successfully registered interface.
*/
if (!adapter->registered_device_map)
adapter->name = adapter->port[i].dev->name;
__set_bit(i, &adapter->registered_device_map);
}
}
if (!adapter->registered_device_map) {
pr_err("%s: could not register any net devices\n",
pci_name(pdev));
goto out_release_adapter_res;
}
pr_info("%s: %s (rev %d), %s %dMHz/%d-bit\n",
adapter->name, bi->desc, adapter->params.chip_revision,
adapter->params.pci.is_pcix ? "PCIX" : "PCI",
adapter->params.pci.speed, adapter->params.pci.width);
/*
* Set the T1B ASIC and memory clocks.
*/
if (t1powersave)
adapter->t1powersave = LCLOCK; /* HW default is powersave mode. */
else
adapter->t1powersave = HCLOCK;
if (t1_is_T1B(adapter))
t1_clock(adapter, t1powersave);
return 0;
out_release_adapter_res:
t1_free_sw_modules(adapter);
out_free_dev:
if (adapter) {
if (adapter->regs)
iounmap(adapter->regs);
for (i = bi->port_number - 1; i >= 0; --i)
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
out_disable_pdev:
pci_disable_device(pdev);
return err;
}
static void bit_bang(struct adapter *adapter, int bitdata, int nbits)
{
int data;
int i;
u32 val;
enum {
S_CLOCK = 1 << 3,
S_DATA = 1 << 4
};
for (i = (nbits - 1); i > -1; i--) {
udelay(50);
data = ((bitdata >> i) & 0x1);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
if (data)
val |= S_DATA;
else
val &= ~S_DATA;
udelay(50);
/* Set SCLOCK low */
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Write SCLOCK high */
val |= S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
}
}
static int t1_clock(struct adapter *adapter, int mode)
{
u32 val;
int M_CORE_VAL;
int M_MEM_VAL;
enum {
M_CORE_BITS = 9,
T_CORE_VAL = 0,
T_CORE_BITS = 2,
N_CORE_VAL = 0,
N_CORE_BITS = 2,
M_MEM_BITS = 9,
T_MEM_VAL = 0,
T_MEM_BITS = 2,
N_MEM_VAL = 0,
N_MEM_BITS = 2,
NP_LOAD = 1 << 17,
S_LOAD_MEM = 1 << 5,
S_LOAD_CORE = 1 << 6,
S_CLOCK = 1 << 3
};
if (!t1_is_T1B(adapter))
return -ENODEV; /* Can't re-clock this chip. */
if (mode & 2)
return 0; /* show current mode. */
if ((adapter->t1powersave & 1) == (mode & 1))
return -EALREADY; /* ASIC already running in mode. */
if ((mode & 1) == HCLOCK) {
M_CORE_VAL = 0x14;
M_MEM_VAL = 0x18;
adapter->t1powersave = HCLOCK; /* overclock */
} else {
M_CORE_VAL = 0xe;
M_MEM_VAL = 0x10;
adapter->t1powersave = LCLOCK; /* underclock */
}
/* Don't interrupt this serial stream! */
spin_lock(&adapter->tpi_lock);
/* Initialize for ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
val &= ~S_CLOCK;
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the ASIC clock synthesizer */
bit_bang(adapter, T_CORE_VAL, T_CORE_BITS);
bit_bang(adapter, N_CORE_VAL, N_CORE_BITS);
bit_bang(adapter, M_CORE_VAL, M_CORE_BITS);
udelay(50);
/* Finish ASIC core */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_CORE;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Initialize for memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= NP_LOAD;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
val &= ~S_CLOCK;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
/* Serial program the memory clock synthesizer */
bit_bang(adapter, T_MEM_VAL, T_MEM_BITS);
bit_bang(adapter, N_MEM_VAL, N_MEM_BITS);
bit_bang(adapter, M_MEM_VAL, M_MEM_BITS);
udelay(50);
/* Finish memory */
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val |= S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
udelay(50);
__t1_tpi_read(adapter, A_ELMER0_GPO, &val);
val &= ~S_LOAD_MEM;
udelay(50);
__t1_tpi_write(adapter, A_ELMER0_GPO, val);
spin_unlock(&adapter->tpi_lock);
return 0;
}
static inline void t1_sw_reset(struct pci_dev *pdev)
{
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 3);
pci_write_config_dword(pdev, A_PCICFG_PM_CSR, 0);
}
static void remove_one(struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
struct adapter *adapter = dev->ml_priv;
int i;
for_each_port(adapter, i) {
if (test_bit(i, &adapter->registered_device_map))
unregister_netdev(adapter->port[i].dev);
}
t1_free_sw_modules(adapter);
iounmap(adapter->regs);
while (--i >= 0) {
if (adapter->port[i].dev)
free_netdev(adapter->port[i].dev);
}
pci_release_regions(pdev);
pci_disable_device(pdev);
t1_sw_reset(pdev);
}
static struct pci_driver cxgb_pci_driver = {
.name = DRV_NAME,
.id_table = t1_pci_tbl,
.probe = init_one,
.remove = remove_one,
};
module_pci_driver(cxgb_pci_driver);
|
{
"pile_set_name": "Github"
}
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
unmanic.__init__.py
Written by: Josh.5 <jsunnex@gmail.com>
Date: 21 February 2017, (11:11 AM)
Copyright:
Copyright (C) Josh Sunnex - 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 sys
import warnings
from .unlogger import UnmanicLogger
__all__ = (
'UnmanicLogger',
)
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 1998-2014,2015 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
* and: Eric S. Raymond <esr@snark.thyrsus.com> *
* and: Thomas E. Dickey 1996-on *
* and: Juergen Pfeifer *
****************************************************************************/
/*
* $Id: curses.priv.h,v 1.547 2015/06/27 01:22:16 tom Exp $
*
* curses.priv.h
*
* Header file for curses library objects which are private to
* the library.
*
*/
#ifndef CURSES_PRIV_H
#define CURSES_PRIV_H 1
/* *INDENT-OFF* */
#include <ncurses_dll.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <ncurses_cfg.h>
#if USE_RCS_IDS
#define MODULE_ID(id) static const char Ident[] = id;
#else
#define MODULE_ID(id) /*nothing*/
#endif
#include <stddef.h> /* for offsetof */
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_SYS_BSDTYPES_H
#include <sys/bsdtypes.h> /* needed for ISC */
#endif
#if HAVE_LIMITS_H
# include <limits.h>
#elif HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#if defined __hpux
# ifndef EILSEQ
# define EILSEQ 47
# endif
#endif
#ifndef PATH_MAX
# if defined(_POSIX_PATH_MAX)
# define PATH_MAX _POSIX_PATH_MAX
# elif defined(MAXPATHLEN)
# define PATH_MAX MAXPATHLEN
# else
# define PATH_MAX 255 /* the Posix minimum path-size */
# endif
#endif
#if DECL_ERRNO
extern int errno;
#endif
/* Some systems have a broken 'select()', but workable 'poll()'. Use that */
#if HAVE_WORKING_POLL
#define USE_FUNC_POLL 1
#if HAVE_POLL_H
#include <poll.h>
#else
#include <sys/poll.h>
#endif
#else
#define USE_FUNC_POLL 0
#endif
#if HAVE_INTTYPES_H
# include <inttypes.h>
#else
# if HAVE_STDINT_H
# include <stdint.h>
# endif
#endif
/* include signal.h before curses.h to work-around defect in glibc 2.1.3 */
#include <signal.h>
/* Alessandro Rubini's GPM (general-purpose mouse) */
#if HAVE_LIBGPM && HAVE_GPM_H
#define USE_GPM_SUPPORT 1
#else
#define USE_GPM_SUPPORT 0
#endif
/* QNX mouse support */
#if defined(__QNX__) && !defined(__QNXNTO__)
#define USE_QNX_MOUSE 1
#else
#define USE_QNX_MOUSE 0
#endif
/* EMX mouse support */
#ifdef __EMX__
#define USE_EMX_MOUSE 1
#else
#define USE_EMX_MOUSE 0
#endif
/* kLIBC keyboard/mouse support */
#if defined(__OS2__) && defined(__KLIBC__)
#define USE_KLIBC_KBD 1
#define USE_KLIBC_MOUSE 1
#else
#define USE_KLIBC_KBD 0
#define USE_KLIBC_MOUSE 0
#endif
#define DEFAULT_MAXCLICK 166
#define EV_MAX 8 /* size of mouse circular event queue */
/*
* If we don't have signals to support it, don't add a sigwinch handler.
* In any case, resizing is an extended feature. Use it if we've got it.
*/
#if !NCURSES_EXT_FUNCS
#undef HAVE_SIZECHANGE
#define HAVE_SIZECHANGE 0
#endif
#if HAVE_SIZECHANGE && USE_SIGWINCH && defined(SIGWINCH)
#define USE_SIZECHANGE 1
#else
#define USE_SIZECHANGE 0
#undef USE_SIGWINCH
#define USE_SIGWINCH 0
#endif
/*
* When building in the MSYS2 environment, the automatic discovery of
* the path separator in configure doesn't work properly. So, if building
* for MinGW, we enforce the correct Windows PATH separator
*/
#ifdef __MINGW32__
# ifdef NCURSES_PATHSEP
# undef NCURSES_PATHSEP
# endif
# define NCURSES_PATHSEP ';'
#endif
/*
* If desired, one can configure this, disabling environment variables that
* point to custom terminfo/termcap locations.
*/
#ifdef USE_ROOT_ENVIRON
#define use_terminfo_vars() 1
#else
#define use_terminfo_vars() _nc_env_access()
extern NCURSES_EXPORT(int) _nc_env_access (void);
#endif
/*
* Not all platforms have memmove; some have an equivalent bcopy. (Some may
* have neither).
*/
#if USE_OK_BCOPY
#define memmove(d,s,n) bcopy(s,d,n)
#elif USE_MY_MEMMOVE
#define memmove(d,s,n) _nc_memmove(d,s,n)
extern NCURSES_EXPORT(void *) _nc_memmove (void *, const void *, size_t);
#endif
/*
* If we have va_copy(), use it for assigning va_list's.
*/
#if defined(HAVE___VA_COPY)
#define begin_va_copy(dst,src) __va_copy(dst, src)
#define end_va_copy(dst) va_end(dst)
#elif defined(va_copy) || defined(HAVE_VA_COPY)
#define begin_va_copy(dst,src) va_copy(dst, src)
#define end_va_copy(dst) va_end(dst)
#else
#define begin_va_copy(dst,src) (dst) = (src)
#define end_va_copy(dst) /* nothing */
#endif
/*
* Either/both S_ISxxx and/or S_IFxxx are defined in sys/types.h; some systems
* lack one or the other.
*/
#ifndef S_ISDIR
#define S_ISDIR(mode) ((mode & S_IFMT) == S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(mode) ((mode & S_IFMT) == S_IFREG)
#endif
/*
* Scroll hints are useless when hashmap is used
*/
#if !USE_SCROLL_HINTS
#if !USE_HASHMAP
#define USE_SCROLL_HINTS 1
#else
#define USE_SCROLL_HINTS 0
#endif
#endif
#if USE_SCROLL_HINTS
#define if_USE_SCROLL_HINTS(stmt) stmt
#else
#define if_USE_SCROLL_HINTS(stmt) /*nothing*/
#endif
#include <nc_string.h>
/*
* Options for terminal drivers, etc...
*/
#ifdef USE_TERM_DRIVER
#define USE_SP_RIPOFF 1
#define USE_SP_TERMTYPE 1
#define USE_SP_WINDOWLIST 1
#endif
/*
* Note: ht/cbt expansion flakes out randomly under Linux 1.1.47, but only
* when we're throwing control codes at the screen at high volume. To see
* this, re-enable USE_HARD_TABS and run worm for a while. Other systems
* probably don't want to define this either due to uncertainties about tab
* delays and expansion in raw mode.
*/
#define TRIES struct tries
typedef TRIES {
TRIES *child; /* ptr to child. NULL if none */
TRIES *sibling; /* ptr to sibling. NULL if none */
unsigned char ch; /* character at this node */
unsigned short value; /* code of string so far. 0 if none. */
#undef TRIES
} TRIES;
/*
* Common/troublesome character definitions
*/
#define StringOf(ch) {ch, 0}
#define L_BRACE '{'
#define R_BRACE '}'
#define S_QUOTE '\''
#define D_QUOTE '"'
#define VT_ACSC "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~"
/*
* Structure for palette tables
*/
#define MAXCOLUMNS 135
#define MAXLINES 66
#define FIFO_SIZE MAXCOLUMNS+2 /* for nocbreak mode input */
#define ACS_LEN 128
#define WINDOWLIST struct _win_list
#if USE_WIDEC_SUPPORT
#define _nc_bkgd _bkgrnd
#else
#undef _XOPEN_SOURCE_EXTENDED
#undef _XPG5
#define _nc_bkgd _bkgd
#define wgetbkgrnd(win, wch) ((*wch = win->_bkgd) != 0 ? OK : ERR)
#define wbkgrnd wbkgd
#endif
#undef NCURSES_OPAQUE
#define NCURSES_INTERNALS 1
#define NCURSES_OPAQUE 0
#include <curses.h> /* we'll use -Ipath directive to get the right one! */
typedef struct
{
NCURSES_COLOR_T red, green, blue; /* what color_content() returns */
NCURSES_COLOR_T r, g, b; /* params to init_color() */
int init; /* true if we called init_color() */
}
color_t;
/*
* If curses.h did not expose the SCREEN-functions, then we do not need the
* parameter in the corresponding unextended functions.
*/
#define USE_SP_FUNC_SUPPORT NCURSES_SP_FUNCS
#define USE_EXT_SP_FUNC_SUPPORT (NCURSES_SP_FUNCS && NCURSES_EXT_FUNCS)
#if NCURSES_SP_FUNCS
#define SP_PARM sp /* use parameter */
#define NCURSES_SP_ARG SP_PARM
#define NCURSES_SP_DCL SCREEN *NCURSES_SP_ARG
#define NCURSES_SP_DCL0 NCURSES_SP_DCL
#define NCURSES_SP_ARGx NCURSES_SP_ARG,
#define NCURSES_SP_DCLx SCREEN *NCURSES_SP_ARGx
#else
#define SP_PARM SP /* use global variable */
#define NCURSES_SP_ARG
#define NCURSES_SP_DCL
#define NCURSES_SP_DCL0 void
#define NCURSES_SP_ARGx
#define NCURSES_SP_DCLx
#endif
#include <nc_panel.h>
#define IsPreScreen(sp) (((sp) != 0) && sp->_prescreen)
#define HasTerminal(sp) (((sp) != 0) && (0 != ((sp)->_term)))
#define IsValidScreen(sp) (HasTerminal(sp) && !IsPreScreen(sp))
#if USE_REENTRANT
#define CurTerm _nc_prescreen._cur_term
#else
#define CurTerm cur_term
#endif
#if NCURSES_SP_FUNCS
#define TerminalOf(sp) ((sp) ? ((sp)->_term ? (sp)->_term : CurTerm) : CurTerm)
#else
#define TerminalOf(sp) CurTerm
#endif
#include <term.h>
#include <nc_termios.h>
/*
* Reduce dependency on cur_term global by using terminfo data from SCREEN's
* pointer to this data.
*/
#ifdef USE_SP_TERMTYPE
#undef CUR
#endif
#define SP_TERMTYPE TerminalOf(sp)->type.
#include <term_entry.h>
#include <nc_tparm.h>
/*
* Simplify ifdef's for the "*_ATTR" macros in case italics are not configured.
*/
#ifdef A_ITALIC
#define USE_ITALIC 1
#else
#define USE_ITALIC 0
#define A_ITALIC 0
#endif
/*
* Use these macros internally, to make tracing less verbose. But leave the
* option for compiling the tracing into the library.
*/
#if 1
#define ColorPair(n) NCURSES_BITS(n, 0)
#define PairNumber(a) (NCURSES_CAST(int,(((unsigned long)(a) & A_COLOR) >> NCURSES_ATTR_SHIFT)))
#else
#define ColorPair(pair) COLOR_PAIR(pair)
#define PairNumber(attr) PAIR_NUMBER(attr)
#endif
#define unColor(n) unColor2(AttrOf(n))
#define unColor2(a) ((a) & ALL_BUT_COLOR)
/*
* Extended-colors stores the color pair in a separate struct-member than the
* attributes. But for compatibility, we handle most cases where a program
* written for non-extended colors stores the color in the attributes by
* checking for a color pair in both places.
*/
#if NCURSES_EXT_COLORS
#define if_EXT_COLORS(stmt) stmt
#define SetPair(value,p) SetPair2((value).ext_color, AttrOf(value), p)
#define SetPair2(c,a,p) c = (p), \
a = (unColor2(a) | (A_COLOR & (unsigned) ColorPair(oldColor(c))))
#define GetPair(value) GetPair2((value).ext_color, AttrOf(value))
#define GetPair2(c,a) ((c) ? (c) : PairNumber(a))
#define oldColor(p) (((p) > 255) ? 255 : (p))
#define GET_WINDOW_PAIR(w) GetPair2((w)->_color, (w)->_attrs)
#define SET_WINDOW_PAIR(w,p) (w)->_color = (p)
#define SameAttrOf(a,b) (AttrOf(a) == AttrOf(b) && GetPair(a) == GetPair(b))
#define VIDATTR(sp,attr,pair) NCURSES_SP_NAME(vid_puts)(NCURSES_SP_ARGx attr, (short) pair, 0, NCURSES_OUTC_FUNC)
#else /* !NCURSES_EXT_COLORS */
#define if_EXT_COLORS(stmt) /* nothing */
#define SetPair(value,p) RemAttr(value, A_COLOR), \
SetAttr(value, AttrOf(value) | (A_COLOR & (attr_t) ColorPair(p)))
#define GetPair(value) PairNumber(AttrOf(value))
#define GET_WINDOW_PAIR(w) PairNumber(WINDOW_ATTRS(w))
#define SET_WINDOW_PAIR(w,p) WINDOW_ATTRS(w) &= ALL_BUT_COLOR, \
WINDOW_ATTRS(w) |= (A_COLOR & (attr_t) ColorPair(p))
#define SameAttrOf(a,b) (AttrOf(a) == AttrOf(b))
#define VIDATTR(sp,attr,pair) NCURSES_SP_NAME(vidputs)(NCURSES_SP_ARGx attr, NCURSES_OUTC_FUNC)
#endif /* NCURSES_EXT_COLORS */
#define NCURSES_OUTC_FUNC NCURSES_SP_NAME(_nc_outch)
#define NCURSES_PUTP2(name,value) NCURSES_SP_NAME(_nc_putp)(NCURSES_SP_ARGx name, value)
#define NCURSES_PUTP2_FLUSH(name,value) NCURSES_SP_NAME(_nc_putp_flush)(NCURSES_SP_ARGx name, value)
#if NCURSES_NO_PADDING
#define GetNoPadding(sp) ((sp) ? (sp)->_no_padding : _nc_prescreen._no_padding)
#define SetNoPadding(sp) _nc_set_no_padding(sp)
extern NCURSES_EXPORT(void) _nc_set_no_padding(SCREEN *);
#else
#define GetNoPadding(sp) FALSE
#define SetNoPadding(sp) /*nothing*/
#endif
#define WINDOW_ATTRS(w) ((w)->_attrs)
#define SCREEN_ATTRS(s) (*((s)->_current_attr))
#define GET_SCREEN_PAIR(s) GetPair(SCREEN_ATTRS(s))
#define SET_SCREEN_PAIR(s,p) SetPair(SCREEN_ATTRS(s), p)
#if USE_REENTRANT || NCURSES_SP_FUNCS
NCURSES_EXPORT(int *) _nc_ptr_Lines (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Cols (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Tabsize (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Escdelay (SCREEN *);
#endif
#if USE_REENTRANT
#define ptrLines(sp) (sp ? &(sp->_LINES) : &(_nc_prescreen._LINES))
#define ptrCols(sp) (sp ? &(sp->_COLS) : &(_nc_prescreen._COLS))
#define ptrTabsize(sp) (sp ? &(sp->_TABSIZE) : &(_nc_prescreen._TABSIZE))
#define ptrEscdelay(sp) (sp ? &(sp->_ESCDELAY) : &(_nc_prescreen._ESCDELAY))
#define SET_LINES(value) *_nc_ptr_Lines(SP_PARM) = value
#define SET_COLS(value) *_nc_ptr_Cols(SP_PARM) = value
#define SET_TABSIZE(value) *_nc_ptr_Tabsize(SP_PARM) = value
#define SET_ESCDELAY(value) *_nc_ptr_Escdelay(SP_PARM) = value
#else
#define ptrLines(sp) &LINES
#define ptrCols(sp) &COLS
#define ptrTabsize(sp) &TABSIZE
#define ptrEscdelay(sp) &ESCDELAY
#define SET_LINES(value) LINES = value
#define SET_COLS(value) COLS = value
#define SET_TABSIZE(value) TABSIZE = value
#define SET_ESCDELAY(value) ESCDELAY = value
#endif
#define TR_MUTEX(data) _tracef("%s@%d: me:%08lX COUNT:%2u/%2d/%6d/%2d/%s%9u: " #data, \
__FILE__, __LINE__, \
(unsigned long) (pthread_self()), \
data.__data.__lock, \
data.__data.__count, \
data.__data.__owner, \
data.__data.__kind, \
(data.__data.__nusers > 5) ? " OOPS " : "", \
data.__data.__nusers)
#define TR_GLOBAL_MUTEX(name) TR_MUTEX(_nc_globals.mutex_##name)
#if USE_WEAK_SYMBOLS
#if defined(__GNUC__)
# if defined __USE_ISOC99
# define _cat_pragma(exp) _Pragma(#exp)
# define _weak_pragma(exp) _cat_pragma(weak name)
# else
# define _weak_pragma(exp)
# endif
# define _declare(name) __extension__ extern __typeof__(name) name
# define weak_symbol(name) _weak_pragma(name) _declare(name) __attribute__((weak))
#else
# undef USE_WEAK_SYMBOLS
# define USE_WEAK_SYMBOLS 0
#endif
#endif
#ifdef USE_PTHREADS
#if USE_REENTRANT
#include <pthread.h>
extern NCURSES_EXPORT(void) _nc_init_pthreads(void);
extern NCURSES_EXPORT(void) _nc_mutex_init(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_lock(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_trylock(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_unlock(pthread_mutex_t *);
#define _nc_lock_global(name) _nc_mutex_lock(&_nc_globals.mutex_##name)
#define _nc_try_global(name) _nc_mutex_trylock(&_nc_globals.mutex_##name)
#define _nc_unlock_global(name) _nc_mutex_unlock(&_nc_globals.mutex_##name)
#else
#error POSIX threads requires --enable-reentrant option
#endif
#ifdef USE_PTHREADS
# if USE_WEAK_SYMBOLS
weak_symbol(pthread_sigmask);
weak_symbol(pthread_kill);
weak_symbol(pthread_self);
weak_symbol(pthread_equal);
weak_symbol(pthread_mutex_init);
weak_symbol(pthread_mutex_lock);
weak_symbol(pthread_mutex_unlock);
weak_symbol(pthread_mutex_trylock);
weak_symbol(pthread_mutexattr_settype);
weak_symbol(pthread_mutexattr_init);
extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
# undef sigprocmask
# define sigprocmask _nc_sigprocmask
# endif
#endif
#if HAVE_NANOSLEEP
#undef HAVE_NANOSLEEP
#define HAVE_NANOSLEEP 0 /* nanosleep suspends all threads */
#endif
#else /* !USE_PTHREADS */
#if USE_PTHREADS_EINTR
# if USE_WEAK_SYMBOLS
#include <pthread.h>
weak_symbol(pthread_sigmask);
weak_symbol(pthread_kill);
weak_symbol(pthread_self);
weak_symbol(pthread_equal);
extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
# undef sigprocmask
# define sigprocmask _nc_sigprocmask
# endif
#endif /* USE_PTHREADS_EINTR */
#define _nc_init_pthreads() /* nothing */
#define _nc_mutex_init(obj) /* nothing */
#define _nc_lock_global(name) /* nothing */
#define _nc_try_global(name) 0
#define _nc_unlock_global(name) /* nothing */
#endif /* USE_PTHREADS */
/*
* When using sp-funcs, locks are targeted to SCREEN-level granularity.
* So the locking is done in the non-sp-func (which calls the sp-func) rather
* than in the sp-func itself.
*
* Use the _nc_nonsp_XXX functions in the function using "NCURSES_SP_NAME()".
* Use the _nc_sp_XXX functions in the function using "#if NCURSES_SP_FUNCS".
*/
#if NCURSES_SP_FUNCS
#define _nc_nonsp_lock_global(name) /* nothing */
#define _nc_nonsp_try_global(name) 0
#define _nc_nonsp_unlock_global(name) /* nothing */
#define _nc_sp_lock_global(name) _nc_lock_global(name)
#define _nc_sp_try_global(name) _nc_try_global(name)
#define _nc_sp_unlock_global(name) _nc_unlock_global(name)
#else
#define _nc_nonsp_lock_global(name) _nc_lock_global(name)
#define _nc_nonsp_try_global(name) _nc_try_global(name)
#define _nc_nonsp_unlock_global(name) _nc_unlock_global(name)
#define _nc_sp_lock_global(name) /* nothing */
#define _nc_sp_try_global(name) 0
#define _nc_sp_unlock_global(name) /* nothing */
#endif
#if HAVE_GETTIMEOFDAY
# define PRECISE_GETTIME 1
# define TimeType struct timeval
#else
# define PRECISE_GETTIME 0
# define TimeType time_t
#endif
/*
* Definitions for color pairs
*/
typedef unsigned colorpair_t; /* type big enough to store PAIR_OF() */
#define C_SHIFT 9 /* we need more bits than there are colors */
#define C_MASK ((1 << C_SHIFT) - 1)
#define PAIR_OF(fg, bg) (colorpair_t) ((((fg) & C_MASK) << C_SHIFT) | ((bg) & C_MASK))
#define FORE_OF(c) (((c) >> C_SHIFT) & C_MASK)
#define BACK_OF(c) ((c) & C_MASK)
#define isDefaultColor(c) ((c) >= COLOR_DEFAULT || (c) < 0)
#define COLOR_DEFAULT C_MASK
#if defined(USE_BUILD_CC) || (defined(USE_TERMLIB) && !defined(NEED_NCURSES_CH_T))
#undef NCURSES_CH_T /* this is not a termlib feature */
#define NCURSES_CH_T void /* ...but we need a pointer in SCREEN */
#endif /* USE_TERMLIB */
#ifndef USE_TERMLIB
struct ldat
{
NCURSES_CH_T *text; /* text of the line */
NCURSES_SIZE_T firstchar; /* first changed character in the line */
NCURSES_SIZE_T lastchar; /* last changed character in the line */
NCURSES_SIZE_T oldindex; /* index of the line at last update */
};
#endif /* USE_TERMLIB */
typedef enum {
M_XTERM = -1 /* use xterm's mouse tracking? */
,M_NONE = 0 /* no mouse device */
#if USE_GPM_SUPPORT
,M_GPM /* use GPM */
#endif
#if USE_SYSMOUSE
,M_SYSMOUSE /* FreeBSD sysmouse on console */
#endif
#ifdef USE_TERM_DRIVER
,M_TERM_DRIVER /* Win32 console, etc */
#endif
} MouseType;
typedef enum {
MF_X10 = 0 /* conventional 3-byte format */
, MF_SGR1006 /* xterm private mode 1006, SGR-style */
#ifdef EXP_XTERM_1005
, MF_XTERM_1005 /* xterm UTF-8 private mode 1005 */
#endif
} MouseFormat;
/*
* Structures for scrolling.
*/
typedef struct {
unsigned long hashval;
int oldcount, newcount;
int oldindex, newindex;
} HASHMAP;
/*
* Structures for soft labels.
*/
struct _SLK;
#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
typedef struct
{
char *ent_text; /* text for the label */
char *form_text; /* formatted text (left/center/...) */
int ent_x; /* x coordinate of this field */
char dirty; /* this label has changed */
char visible; /* field is visible */
} slk_ent;
typedef struct _SLK {
bool dirty; /* all labels have changed */
bool hidden; /* soft labels are hidden */
WINDOW *win;
slk_ent *ent;
short maxlab; /* number of available labels */
short labcnt; /* number of allocated labels */
short maxlen; /* length of labels */
NCURSES_CH_T attr; /* soft label attribute */
} SLK;
#endif /* USE_TERMLIB */
typedef struct {
WINDOW *win; /* the window used in the hook */
int line; /* lines to take, < 0 => from bottom*/
int (*hook)(WINDOW *, int); /* callback for user */
} ripoff_t;
#if USE_GPM_SUPPORT
#undef buttons /* term.h defines this, and gpm uses it! */
#include <gpm.h>
#if USE_WEAK_SYMBOLS
weak_symbol(Gpm_Wgetch);
#endif
#ifdef HAVE_LIBDL
/* link dynamically to GPM */
typedef int *TYPE_gpm_fd;
typedef int (*TYPE_Gpm_Open) (Gpm_Connect *, int);
typedef int (*TYPE_Gpm_Close) (void);
typedef int (*TYPE_Gpm_GetEvent) (Gpm_Event *);
#define my_gpm_fd SP_PARM->_mouse_gpm_fd
#define my_Gpm_Open SP_PARM->_mouse_Gpm_Open
#define my_Gpm_Close SP_PARM->_mouse_Gpm_Close
#define my_Gpm_GetEvent SP_PARM->_mouse_Gpm_GetEvent
#else
/* link statically to GPM */
#define my_gpm_fd &gpm_fd
#define my_Gpm_Open Gpm_Open
#define my_Gpm_Close Gpm_Close
#define my_Gpm_GetEvent Gpm_GetEvent
#endif /* HAVE_LIBDL */
#endif /* USE_GPM_SUPPORT */
typedef struct {
long sequence;
bool last_used;
char *fix_sgr0; /* this holds the filtered sgr0 string */
char *last_bufp; /* help with fix_sgr0 leak */
TERMINAL *last_term;
} TGETENT_CACHE;
#define TGETENT_MAX 4
/*
* State of tparm().
*/
#define STACKSIZE 20
typedef struct {
union {
int num;
char *str;
} data;
bool num_type;
} STACK_FRAME;
#define NUM_VARS 26
typedef struct {
#ifdef TRACE
const char *tname;
#endif
const char *tparam_base;
STACK_FRAME stack[STACKSIZE];
int stack_ptr;
char *out_buff;
size_t out_size;
size_t out_used;
char *fmt_buff;
size_t fmt_size;
int dynamic_var[NUM_VARS];
int static_vars[NUM_VARS];
} TPARM_STATE;
typedef struct {
char *text;
size_t size;
} TRACEBUF;
/*
* The filesystem database normally uses a single-letter for the lower level
* of directories. Use a hexadecimal code for filesystems which do not
* preserve mixed-case names.
*/
#if MIXEDCASE_FILENAMES
#define LEAF_FMT "%c"
#define LEAF_LEN 1
#else
#define LEAF_FMT "%02x"
#define LEAF_LEN 2
#endif
/*
* TRACEMSE_FMT is no longer than 80 columns, there are 5 numbers that
* could at most have 10 digits, and the mask contains no more than 32 bits
* with each bit representing less than 15 characters. Usually the whole
* string is less than 80 columns, but this buffer size is an absolute
* limit.
*/
#define TRACEMSE_MAX (80 + (5 * 10) + (32 * 15))
#define TRACEMSE_FMT "id %2d at (%2d, %2d, %2d) state %4lx = {" /* } */
#ifdef USE_TERM_DRIVER
struct DriverTCB; /* Terminal Control Block forward declaration */
#define INIT_TERM_DRIVER() _nc_globals.term_driver = _nc_get_driver
#else
#define INIT_TERM_DRIVER() /* nothing */
#endif
typedef struct {
const char *name;
char *value;
} ITERATOR_VARS;
/*
* Global data which is not specific to a screen.
*/
typedef struct {
SIG_ATOMIC_T have_sigtstp;
SIG_ATOMIC_T have_sigwinch;
SIG_ATOMIC_T cleanup_nested;
bool init_signals;
bool init_screen;
char *comp_sourcename;
char *comp_termtype;
bool have_tic_directory;
bool keep_tic_directory;
const char *tic_directory;
char *dbi_list;
int dbi_size;
char *first_name;
char **keyname_table;
int init_keyname;
int slk_format;
char *safeprint_buf;
size_t safeprint_used;
TGETENT_CACHE tgetent_cache[TGETENT_MAX];
int tgetent_index;
long tgetent_sequence;
char *dbd_blob; /* string-heap for dbd_list[] */
char **dbd_list; /* distinct places to look for data */
int dbd_size; /* length of dbd_list[] */
time_t dbd_time; /* cache last updated */
ITERATOR_VARS dbd_vars[dbdLAST];
#ifndef USE_SP_WINDOWLIST
WINDOWLIST *_nc_windowlist;
#define WindowList(sp) _nc_globals._nc_windowlist
#endif
#if USE_HOME_TERMINFO
char *home_terminfo;
#endif
#if !USE_SAFE_SPRINTF
int safeprint_cols;
int safeprint_rows;
#endif
#ifdef USE_TERM_DRIVER
int (*term_driver)(struct DriverTCB*, const char*, int*);
#endif
#ifdef TRACE
bool init_trace;
char trace_fname[PATH_MAX];
int trace_level;
FILE *trace_fp;
char *tracearg_buf;
size_t tracearg_used;
TRACEBUF *tracebuf_ptr;
size_t tracebuf_used;
char tracechr_buf[40];
char *tracedmp_buf;
size_t tracedmp_used;
unsigned char *tracetry_buf;
size_t tracetry_used;
char traceatr_color_buf[2][80];
int traceatr_color_sel;
int traceatr_color_last;
#if !defined(USE_PTHREADS) && USE_REENTRANT
int nested_tracef;
#endif
#endif /* TRACE */
#ifdef USE_PTHREADS
pthread_mutex_t mutex_curses;
pthread_mutex_t mutex_tst_tracef;
pthread_mutex_t mutex_tracef;
int nested_tracef;
int use_pthreads;
#define _nc_use_pthreads _nc_globals.use_pthreads
#endif
#if USE_PTHREADS_EINTR
pthread_t read_thread; /* The reading thread */
#endif
} NCURSES_GLOBALS;
extern NCURSES_EXPORT_VAR(NCURSES_GLOBALS) _nc_globals;
#define N_RIPS 5
/*
* Global data which can be swept up into a SCREEN when one is created.
* It may be modified before the next SCREEN is created.
*/
typedef struct {
bool use_env;
bool filter_mode;
attr_t previous_attr;
#ifndef USE_SP_RIPOFF
ripoff_t rippedoff[N_RIPS];
ripoff_t *rsp;
#endif
TPARM_STATE tparm_state;
TTY *saved_tty; /* savetty/resetty information */
#if NCURSES_NO_PADDING
bool _no_padding; /* flag to set if padding disabled */
#endif
NCURSES_SP_OUTC _outch; /* output handler if not putc */
#if BROKEN_LINKER || USE_REENTRANT
chtype *real_acs_map;
int _LINES;
int _COLS;
int _TABSIZE;
int _ESCDELAY;
TERMINAL *_cur_term;
#ifdef TRACE
long _outchars;
const char *_tputs_trace;
#endif
#endif
bool use_tioctl;
} NCURSES_PRESCREEN;
/*
* Use screen-specific ripoff data (for softkeys) rather than global.
*/
#ifdef USE_SP_RIPOFF
#define safe_ripoff_sp (sp)->rsp
#define safe_ripoff_stack (sp)->rippedoff
#else
#define safe_ripoff_sp _nc_prescreen.rsp
#define safe_ripoff_stack _nc_prescreen.rippedoff
#endif
extern NCURSES_EXPORT_VAR(NCURSES_PRESCREEN) _nc_prescreen;
/*
* The SCREEN structure.
*/
struct screen {
int _ifd; /* input file descriptor for screen */
int _ofd; /* output file descriptor for screen */
FILE *_ofp; /* output file ptr for screen */
char *out_buffer; /* output buffer */
size_t out_limit; /* output buffer size */
size_t out_inuse; /* output buffer current use */
bool _filtered; /* filter() was called */
bool _prescreen; /* is in prescreen phase */
bool _use_env; /* LINES & COLS from environment? */
int _checkfd; /* filedesc for typeahead check */
TERMINAL *_term; /* terminal type information */
TTY _saved_tty; /* savetty/resetty information */
NCURSES_SIZE_T _lines; /* screen lines */
NCURSES_SIZE_T _columns; /* screen columns */
NCURSES_SIZE_T _lines_avail; /* lines available for stdscr */
NCURSES_SIZE_T _topstolen; /* lines stolen from top */
WINDOW *_curscr; /* current screen */
WINDOW *_newscr; /* virtual screen to be updated to */
WINDOW *_stdscr; /* screen's full-window context */
#define CurScreen(sp) (sp)->_curscr
#define NewScreen(sp) (sp)->_newscr
#define StdScreen(sp) (sp)->_stdscr
TRIES *_keytry; /* "Try" for use with keypad mode */
TRIES *_key_ok; /* Disabled keys via keyok(,FALSE) */
bool _tried; /* keypad mode was initialized */
bool _keypad_on; /* keypad mode is currently on */
bool _called_wgetch; /* check for recursion in wgetch() */
int _fifo[FIFO_SIZE]; /* input push-back buffer */
short _fifohead, /* head of fifo queue */
_fifotail, /* tail of fifo queue */
_fifopeek, /* where to peek for next char */
_fifohold; /* set if breakout marked */
int _endwin; /* are we out of window mode? */
NCURSES_CH_T *_current_attr; /* holds current attributes set */
int _coloron; /* is color enabled? */
int _color_defs; /* are colors modified */
int _cursor; /* visibility of the cursor */
int _cursrow; /* physical cursor row */
int _curscol; /* physical cursor column */
bool _notty; /* true if we cannot switch non-tty */
int _nl; /* True if NL -> CR/NL is on */
int _raw; /* True if in raw mode */
int _cbreak; /* 1 if in cbreak mode */
/* > 1 if in halfdelay mode */
int _echo; /* True if echo on */
int _use_meta; /* use the meta key? */
struct _SLK *_slk; /* ptr to soft key struct / NULL */
int slk_format; /* selected format for this screen */
/* cursor movement costs; units are 10ths of milliseconds */
#if NCURSES_NO_PADDING
bool _no_padding; /* flag to set if padding disabled */
#endif
int _char_padding; /* cost of character put */
int _cr_cost; /* cost of (carriage_return) */
int _cup_cost; /* cost of (cursor_address) */
int _home_cost; /* cost of (cursor_home) */
int _ll_cost; /* cost of (cursor_to_ll) */
#if USE_HARD_TABS
int _ht_cost; /* cost of (tab) */
int _cbt_cost; /* cost of (backtab) */
#endif /* USE_HARD_TABS */
int _cub1_cost; /* cost of (cursor_left) */
int _cuf1_cost; /* cost of (cursor_right) */
int _cud1_cost; /* cost of (cursor_down) */
int _cuu1_cost; /* cost of (cursor_up) */
int _cub_cost; /* cost of (parm_cursor_left) */
int _cuf_cost; /* cost of (parm_cursor_right) */
int _cud_cost; /* cost of (parm_cursor_down) */
int _cuu_cost; /* cost of (parm_cursor_up) */
int _hpa_cost; /* cost of (column_address) */
int _vpa_cost; /* cost of (row_address) */
/* used in tty_update.c, must be chars */
int _ed_cost; /* cost of (clr_eos) */
int _el_cost; /* cost of (clr_eol) */
int _el1_cost; /* cost of (clr_bol) */
int _dch1_cost; /* cost of (delete_character) */
int _ich1_cost; /* cost of (insert_character) */
int _dch_cost; /* cost of (parm_dch) */
int _ich_cost; /* cost of (parm_ich) */
int _ech_cost; /* cost of (erase_chars) */
int _rep_cost; /* cost of (repeat_char) */
int _hpa_ch_cost; /* cost of (column_address) */
int _cup_ch_cost; /* cost of (cursor_address) */
int _cuf_ch_cost; /* cost of (parm_cursor_right) */
int _inline_cost; /* cost of inline-move */
int _smir_cost; /* cost of (enter_insert_mode) */
int _rmir_cost; /* cost of (exit_insert_mode) */
int _ip_cost; /* cost of (insert_padding) */
/* used in lib_mvcur.c */
char * _address_cursor;
/* used in tty_update.c */
int _scrolling; /* 1 if terminal's smart enough to */
/* used in lib_color.c */
color_t *_color_table; /* screen's color palette */
int _color_count; /* count of colors in palette */
colorpair_t *_color_pairs; /* screen's color pair list */
int _pair_count; /* count of color pairs */
int _pair_limit; /* actual limit of color-pairs */
#if NCURSES_EXT_FUNCS
bool _assumed_color; /* use assumed colors */
bool _default_color; /* use default colors */
bool _has_sgr_39_49; /* has ECMA default color support */
int _default_fg; /* assumed default foreground */
int _default_bg; /* assumed default background */
int _default_pairs; /* count pairs using default color */
#endif
chtype _ok_attributes; /* valid attributes for terminal */
chtype _xmc_suppress; /* attributes to suppress if xmc */
chtype _xmc_triggers; /* attributes to process if xmc */
chtype * _acs_map; /* the real alternate-charset map */
bool * _screen_acs_map;
/* used in lib_vidattr.c */
bool _use_rmso; /* true if we may use 'rmso' */
bool _use_rmul; /* true if we may use 'rmul' */
#if USE_ITALIC
bool _use_ritm; /* true if we may use 'ritm' */
#endif
#if USE_KLIBC_KBD
bool _extended_key; /* true if an extended key */
#endif
/*
* These data correspond to the state of the idcok() and idlok()
* functions. A caveat is in order here: the XSI and SVr4
* documentation specify that these functions apply to the window which
* is given as an argument. However, ncurses implements this logic
* only for the newscr/curscr update process, _not_ per-window.
*/
bool _nc_sp_idlok;
bool _nc_sp_idcok;
/*
* These are the data that support the mouse interface.
*/
bool _mouse_initialized;
MouseType _mouse_type;
int _maxclick;
bool (*_mouse_event) (SCREEN *);
bool (*_mouse_inline)(SCREEN *);
bool (*_mouse_parse) (SCREEN *, int);
void (*_mouse_resume)(SCREEN *);
void (*_mouse_wrap) (SCREEN *);
int _mouse_fd; /* file-descriptor, if any */
bool _mouse_active; /* true if initialized */
mmask_t _mouse_mask; /* set via mousemask() */
mmask_t _mouse_mask2; /* OR's in press/release bits */
mmask_t _mouse_bstate;
MouseFormat _mouse_format; /* type of xterm mouse protocol */
NCURSES_CONST char *_mouse_xtermcap; /* string to enable/disable mouse */
MEVENT _mouse_events[EV_MAX]; /* hold the last mouse event seen */
MEVENT *_mouse_eventp; /* next free slot in event queue */
#if USE_GPM_SUPPORT
bool _mouse_gpm_loaded;
bool _mouse_gpm_found;
#ifdef HAVE_LIBDL
void *_dlopen_gpm;
TYPE_gpm_fd _mouse_gpm_fd;
TYPE_Gpm_Open _mouse_Gpm_Open;
TYPE_Gpm_Close _mouse_Gpm_Close;
TYPE_Gpm_GetEvent _mouse_Gpm_GetEvent;
#endif
Gpm_Connect _mouse_gpm_connect;
#endif /* USE_GPM_SUPPORT */
#if USE_EMX_MOUSE
int _emxmouse_wfd;
int _emxmouse_thread;
int _emxmouse_activated;
char _emxmouse_buttons[4];
#endif
#if USE_SYSMOUSE
MEVENT _sysmouse_fifo[FIFO_SIZE];
int _sysmouse_head;
int _sysmouse_tail;
int _sysmouse_char_width; /* character width */
int _sysmouse_char_height; /* character height */
int _sysmouse_old_buttons;
int _sysmouse_new_buttons;
#endif
#ifdef USE_TERM_DRIVER
MEVENT _drv_mouse_fifo[FIFO_SIZE];
int _drv_mouse_head;
int _drv_mouse_tail;
int _drv_mouse_old_buttons;
int _drv_mouse_new_buttons;
#endif
/*
* This supports automatic resizing
*/
#if USE_SIZECHANGE
int (*_resize)(NCURSES_SP_DCLx int y, int x);
int (*_ungetch)(SCREEN *, int);
#endif
/*
* These are data that support the proper handling of the panel stack on an
* per screen basis.
*/
struct panelhook _panelHook;
bool _sig_winch;
SCREEN *_next_screen;
/* hashes for old and new lines */
unsigned long *oldhash, *newhash;
HASHMAP *hashtab;
int hashtab_len;
int *_oldnum_list;
int _oldnum_size;
NCURSES_SP_OUTC _outch; /* output handler if not putc */
int _legacy_coding; /* see use_legacy_coding() */
#if USE_REENTRANT
char _ttytype[NAMESIZE];
int _ESCDELAY;
int _TABSIZE;
int _LINES;
int _COLS;
#ifdef TRACE
long _outchars;
const char *_tputs_trace;
#endif
#endif
#ifdef TRACE
char tracechr_buf[40];
char tracemse_buf[TRACEMSE_MAX];
#endif
#ifdef USE_SP_WINDOWLIST
WINDOWLIST* _windowlist;
#define WindowList(sp) (sp)->_windowlist
#endif
NCURSES_OUTC jump;
ripoff_t rippedoff[N_RIPS];
ripoff_t *rsp;
/*
* ncurses/ncursesw are the same up to this point.
*/
#if USE_WIDEC_SUPPORT
/* recent versions of 'screen' have partially-working support for
* UTF-8, but do not permit ACS at the same time (see tty_update.c).
*/
bool _screen_acs_fix;
bool _screen_unicode;
#endif
bool _use_tioctl;
};
extern NCURSES_EXPORT_VAR(SCREEN *) _nc_screen_chain;
extern NCURSES_EXPORT_VAR(SIG_ATOMIC_T) _nc_have_sigwinch;
WINDOWLIST {
WINDOWLIST *next;
SCREEN *screen; /* screen containing the window */
WINDOW win; /* WINDOW_EXT() needs to account for offset */
#if NCURSES_WIDECHAR
char addch_work[(MB_LEN_MAX * 9) + 1];
unsigned addch_used; /* number of bytes in addch_work[] */
int addch_x; /* x-position for addch_work[] */
int addch_y; /* y-position for addch_work[] */
#endif
};
#define WINDOW_EXT(w,m) (((WINDOWLIST *)((void *)((char *)(w) - offsetof(WINDOWLIST, win))))->m)
#define SP_PRE_INIT(sp) \
sp->_cursrow = -1; \
sp->_curscol = -1; \
sp->_nl = TRUE; \
sp->_raw = FALSE; \
sp->_cbreak = 0; \
sp->_echo = TRUE; \
sp->_fifohead = -1; \
sp->_endwin = TRUE; \
sp->_cursor = -1; \
WindowList(sp) = 0; \
sp->_outch = NCURSES_OUTC_FUNC; \
sp->jump = 0 \
/* usually in <limits.h> */
#ifndef UCHAR_MAX
#define UCHAR_MAX 255
#endif
/* The terminfo source is assumed to be 7-bit ASCII */
#define is7bits(c) ((unsigned)(c) < 128)
/* Checks for isprint() should be done on 8-bit characters (non-wide) */
#define is8bits(c) ((unsigned)(c) <= UCHAR_MAX)
#ifndef min
#define min(a,b) ((a) > (b) ? (b) : (a))
#endif
#ifndef max
#define max(a,b) ((a) < (b) ? (b) : (a))
#endif
/* usually in <unistd.h> */
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif
#ifndef R_OK
#define R_OK 4 /* Test for read permission. */
#endif
#ifndef W_OK
#define W_OK 2 /* Test for write permission. */
#endif
#ifndef X_OK
#define X_OK 1 /* Test for execute permission. */
#endif
#ifndef F_OK
#define F_OK 0 /* Test for existence. */
#endif
#if HAVE_FCNTL_H
#include <fcntl.h> /* may define O_BINARY */
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifdef TRACE
#if USE_REENTRANT
#define COUNT_OUTCHARS(n) _nc_count_outchars(n);
#else
#define COUNT_OUTCHARS(n) _nc_outchars += (n);
#endif
#else
#define COUNT_OUTCHARS(n) /* nothing */
#endif
#define RESET_OUTCHARS() COUNT_OUTCHARS(-_nc_outchars)
#define UChar(c) ((unsigned char)(c))
#define UShort(c) ((unsigned short)(c))
#define ChCharOf(c) ((chtype)(c) & (chtype)A_CHARTEXT)
#define ChAttrOf(c) ((chtype)(c) & (chtype)A_ATTRIBUTES)
#ifndef MB_LEN_MAX
#define MB_LEN_MAX 8 /* should be >= MB_CUR_MAX, but that may be a function */
#endif
#if USE_WIDEC_SUPPORT /* { */
#define isEILSEQ(status) (((size_t)status == (size_t)-1) && (errno == EILSEQ))
#define init_mb(state) memset(&state, 0, sizeof(state))
#if NCURSES_EXT_COLORS
#define NulColor , 0
#else
#define NulColor /* nothing */
#endif
#define NulChar 0,0,0,0 /* FIXME: see CCHARW_MAX */
#define CharOf(c) ((c).chars[0])
#define AttrOf(c) ((c).attr)
#define AddAttr(c,a) AttrOf(c) |= ((a) & A_ATTRIBUTES)
#define RemAttr(c,a) AttrOf(c) &= ~((a) & A_ATTRIBUTES)
#define SetAttr(c,a) AttrOf(c) = ((a) & A_ATTRIBUTES) | WidecExt(c)
#define NewChar2(c,a) { a, { c, NulChar } NulColor }
#define NewChar(ch) NewChar2(ChCharOf(ch), ChAttrOf(ch))
#if CCHARW_MAX == 5
#define CharEq(a,b) (((a).attr == (b).attr) \
&& (a).chars[0] == (b).chars[0] \
&& (a).chars[1] == (b).chars[1] \
&& (a).chars[2] == (b).chars[2] \
&& (a).chars[3] == (b).chars[3] \
&& (a).chars[4] == (b).chars[4] \
if_EXT_COLORS(&& (a).ext_color == (b).ext_color))
#else
#define CharEq(a,b) (!memcmp(&(a), &(b), sizeof(a)))
#endif
#define SetChar(ch,c,a) do { \
NCURSES_CH_T *_cp = &ch; \
memset(_cp, 0, sizeof(ch)); \
_cp->chars[0] = (wchar_t) (c); \
_cp->attr = (a); \
if_EXT_COLORS(SetPair(ch, PairNumber(a))); \
} while (0)
#define CHREF(wch) (&wch)
#define CHDEREF(wch) (*wch)
#define ARG_CH_T NCURSES_CH_T *
#define CARG_CH_T const NCURSES_CH_T *
#define PUTC_DATA char PUTC_buf[MB_LEN_MAX]; int PUTC_i, PUTC_n; \
mbstate_t PUT_st; wchar_t PUTC_ch
#define PUTC_INIT init_mb (PUT_st)
#define PUTC(ch) do { if(!isWidecExt(ch)) { \
if (Charable(ch)) { \
NCURSES_OUTC_FUNC (NCURSES_SP_ARGx CharOf(ch)); \
COUNT_OUTCHARS(1); \
} else { \
PUTC_INIT; \
for (PUTC_i = 0; PUTC_i < CCHARW_MAX; ++PUTC_i) { \
PUTC_ch = (ch).chars[PUTC_i]; \
if (PUTC_ch == L'\0') \
break; \
PUTC_n = (int) wcrtomb(PUTC_buf, \
(ch).chars[PUTC_i], &PUT_st); \
if (PUTC_n <= 0) { \
if (PUTC_ch && is8bits(PUTC_ch) && PUTC_i == 0) \
NCURSES_OUTC_FUNC (NCURSES_SP_ARGx CharOf(ch)); \
break; \
} else { \
int PUTC_j; \
for (PUTC_j = 0; PUTC_j < PUTC_n; ++PUTC_j) { \
NCURSES_OUTC_FUNC (NCURSES_SP_ARGx PUTC_buf[PUTC_j]); \
} \
} \
} \
COUNT_OUTCHARS(PUTC_i); \
} } } while (0)
#define BLANK NewChar2(' ', WA_NORMAL)
#define ZEROS NewChar2('\0', WA_NORMAL)
#define ISBLANK(ch) ((ch).chars[0] == L' ' && (ch).chars[1] == L'\0')
/*
* Wide characters cannot be represented in the A_CHARTEXT mask of
* attr_t's but an application might have set a narrow character there.
* But even in that case, it would only be a printable character, or
* zero. Otherwise we can use those bits to tell if a cell is the
* first or extension part of a wide character.
*/
#define WidecExt(ch) (int) (AttrOf(ch) & A_CHARTEXT)
#define isWidecBase(ch) (WidecExt(ch) == 1)
#define isWidecExt(ch) (WidecExt(ch) > 1 && WidecExt(ch) < 32)
#define SetWidecExt(dst, ext) AttrOf(dst) &= ~A_CHARTEXT, \
AttrOf(dst) |= (attr_t) (ext + 1)
#define if_WIDEC(code) code
#define Charable(ch) (((SP_PARM->_legacy_coding) \
|| (AttrOf(ch) & A_ALTCHARSET) \
|| (!isWidecExt(ch))) && \
(ch).chars[1] == L'\0' && \
_nc_is_charable(CharOf(ch)))
#define L(ch) L ## ch
#else /* }{ */
#define CharOf(c) ChCharOf(c)
#define AttrOf(c) ChAttrOf(c)
#define AddAttr(c,a) c |= (a)
#define RemAttr(c,a) c &= ~((a) & A_ATTRIBUTES)
#define SetAttr(c,a) c = ((c) & ~A_ATTRIBUTES) | (a)
#define NewChar(ch) (ch)
#define NewChar2(c,a) ((c) | (a))
#define CharEq(a,b) ((a) == (b))
#define SetChar(ch,c,a) ch = (c) | (a)
#define CHREF(wch) wch
#define CHDEREF(wch) wch
#define ARG_CH_T NCURSES_CH_T
#define CARG_CH_T NCURSES_CH_T
#define PUTC_DATA /* nothing */
#define PUTC(ch) NCURSES_OUTC_FUNC (NCURSES_SP_ARGx (int) ch)
#define BLANK (' '|A_NORMAL)
#define ZEROS ('\0'|A_NORMAL)
#define ISBLANK(ch) (CharOf(ch) == ' ')
#define isWidecExt(ch) (0)
#define if_WIDEC(code) /* nothing */
#define L(ch) ch
#endif /* } */
#define AttrOfD(ch) AttrOf(CHDEREF(ch))
#define CharOfD(ch) CharOf(CHDEREF(ch))
#define SetChar2(wch,ch) SetChar(wch,ChCharOf(ch),ChAttrOf(ch))
#define BLANK_ATTR A_NORMAL
#define BLANK_TEXT L(' ')
#define CHANGED -1
#define LEGALYX(w, y, x) \
((w) != 0 && \
((x) >= 0 && (x) <= (w)->_maxx && \
(y) >= 0 && (y) <= (w)->_maxy))
#define CHANGED_CELL(line,col) \
if (line->firstchar == _NOCHANGE) \
line->firstchar = line->lastchar = (NCURSES_SIZE_T) (col); \
else if ((col) < line->firstchar) \
line->firstchar = (NCURSES_SIZE_T) (col); \
else if ((col) > line->lastchar) \
line->lastchar = (NCURSES_SIZE_T) (col)
#define CHANGED_RANGE(line,start,end) \
if (line->firstchar == _NOCHANGE \
|| line->firstchar > (start)) \
line->firstchar = (NCURSES_SIZE_T) (start); \
if (line->lastchar == _NOCHANGE \
|| line->lastchar < (end)) \
line->lastchar = (NCURSES_SIZE_T) (end)
#define CHANGED_TO_EOL(line,start,end) \
if (line->firstchar == _NOCHANGE \
|| line->firstchar > (start)) \
line->firstchar = (NCURSES_SIZE_T) (start); \
line->lastchar = (NCURSES_SIZE_T) (end)
#define SIZEOF(v) (sizeof(v)/sizeof(v[0]))
#define FreeIfNeeded(p) if ((p) != 0) free(p)
/* FreeAndNull() is not a comma-separated expression because some compilers
* do not accept a mixture of void with values.
*/
#define FreeAndNull(p) free(p); p = 0
#include <nc_alloc.h>
/*
* Use these for tic/infocmp malloc failures. Generally the ncurses library
* tries to limp along after a failure.
*/
#define TYPE_MALLOC(type, size, name) \
name = typeMalloc(type, size); \
if (name == 0) \
_nc_err_abort(MSG_NO_MEMORY)
#define TYPE_REALLOC(type, size, name) \
name = typeRealloc(type, size, name); \
if (name == 0) \
_nc_err_abort(MSG_NO_MEMORY)
/*
* TTY bit definition for converting tabs to spaces.
*/
#ifdef TAB3
# define OFLAGS_TABS TAB3 /* POSIX specifies TAB3 */
#else
# ifdef XTABS
# define OFLAGS_TABS XTABS /* XTABS is usually the "same" */
# else
# ifdef OXTABS
# define OFLAGS_TABS OXTABS /* the traditional BSD equivalent */
# else
# define OFLAGS_TABS 0
# endif
# endif
#endif
/*
* Standardize/simplify common loops
*/
#define each_screen(p) p = _nc_screen_chain; p != 0; p = (p)->_next_screen
#define each_window(sp,p) p = WindowList(sp); p != 0; p = (p)->next
#define each_ripoff(p) p = safe_ripoff_stack; (p - safe_ripoff_stack) < N_RIPS; ++p
/*
* Prefixes for call/return points of library function traces. We use these to
* instrument the public functions so that the traces can be easily transformed
* into regression scripts.
*/
#define T_CALLED(fmt) "called {" fmt
#define T_CREATE(fmt) "create :" fmt
#define T_RETURN(fmt) "return }" fmt
#ifdef TRACE
#if USE_REENTRANT
#define TPUTS_TRACE(s) _nc_set_tputs_trace(s);
#else
#define TPUTS_TRACE(s) _nc_tputs_trace = s;
#endif
#define START_TRACE() \
if ((_nc_tracing & TRACE_MAXIMUM) == 0) { \
int t = _nc_getenv_num("NCURSES_TRACE"); \
if (t >= 0) \
trace((unsigned) t); \
}
/*
* Many of the _tracef() calls use static buffers; lock the trace state before
* trying to fill them.
*/
#if USE_REENTRANT
#define USE_TRACEF(mask) _nc_use_tracef(mask)
extern NCURSES_EXPORT(int) _nc_use_tracef (unsigned);
extern NCURSES_EXPORT(void) _nc_locked_tracef (const char *, ...) GCC_PRINTFLIKE(1,2);
#else
#define USE_TRACEF(mask) (_nc_tracing & (mask))
#define _nc_locked_tracef _tracef
#endif
#define TR(n, a) if (USE_TRACEF(n)) _nc_locked_tracef a
#define T(a) TR(TRACE_CALLS, a)
#define TRACE_RETURN(value,type) return _nc_retrace_##type((type)(value))
#define TRACE_RETURN1(value,dst) return _nc_retrace_##dst(value)
#define TRACE_RETURN2(value,dst,src) return _nc_retrace_##dst##_##src(value)
#define TRACE_RETURN_SP(value,type) return _nc_retrace_##type(SP_PARM, value)
#define NonNull(s) ((s) != 0 ? s : "<null>")
#define returnAttr(code) TRACE_RETURN(code,attr_t)
#define returnBits(code) TRACE_RETURN(code,unsigned)
#define returnBool(code) TRACE_RETURN(code,bool)
#define returnCPtr(code) TRACE_RETURN1(code,cptr)
#define returnCVoidPtr(code) TRACE_RETURN1(code,cvoid_ptr)
#define returnChar(code) TRACE_RETURN(code,char)
#define returnChtype(code) TRACE_RETURN(code,chtype)
#define returnCode(code) TRACE_RETURN(code,int)
#define returnIntAttr(code) TRACE_RETURN2(code,int,attr_t)
#define returnMMask(code) TRACE_RETURN_SP(code,mmask_t)
#define returnPtr(code) TRACE_RETURN1(code,ptr)
#define returnSP(code) TRACE_RETURN1(code,sp)
#define returnVoid T((T_RETURN(""))); return
#define returnVoidPtr(code) TRACE_RETURN1(code,void_ptr)
#define returnWin(code) TRACE_RETURN1(code,win)
extern NCURSES_EXPORT(NCURSES_BOOL) _nc_retrace_bool (int);
extern NCURSES_EXPORT(NCURSES_CONST void *) _nc_retrace_cvoid_ptr (NCURSES_CONST void *);
extern NCURSES_EXPORT(SCREEN *) _nc_retrace_sp (SCREEN *);
extern NCURSES_EXPORT(WINDOW *) _nc_retrace_win (WINDOW *);
extern NCURSES_EXPORT(attr_t) _nc_retrace_attr_t (attr_t);
extern NCURSES_EXPORT(char *) _nc_retrace_ptr (char *);
extern NCURSES_EXPORT(char *) _nc_trace_ttymode(TTY *tty);
extern NCURSES_EXPORT(char *) _nc_varargs (const char *, va_list);
extern NCURSES_EXPORT(chtype) _nc_retrace_chtype (chtype);
extern NCURSES_EXPORT(const char *) _nc_altcharset_name(attr_t, chtype);
extern NCURSES_EXPORT(const char *) _nc_retrace_cptr (const char *);
extern NCURSES_EXPORT(char) _nc_retrace_char (int);
extern NCURSES_EXPORT(int) _nc_retrace_int (int);
extern NCURSES_EXPORT(int) _nc_retrace_int_attr_t (attr_t);
extern NCURSES_EXPORT(mmask_t) _nc_retrace_mmask_t (SCREEN *, mmask_t);
extern NCURSES_EXPORT(unsigned) _nc_retrace_unsigned (unsigned);
extern NCURSES_EXPORT(void *) _nc_retrace_void_ptr (void *);
extern NCURSES_EXPORT(void) _nc_fifo_dump (SCREEN *);
#if USE_REENTRANT
NCURSES_WRAPPED_VAR(long, _nc_outchars);
NCURSES_WRAPPED_VAR(const char *, _nc_tputs_trace);
#define _nc_outchars NCURSES_PUBLIC_VAR(_nc_outchars())
#define _nc_tputs_trace NCURSES_PUBLIC_VAR(_nc_tputs_trace())
extern NCURSES_EXPORT(void) _nc_set_tputs_trace (const char *);
extern NCURSES_EXPORT(void) _nc_count_outchars (long);
#else
extern NCURSES_EXPORT_VAR(const char *) _nc_tputs_trace;
extern NCURSES_EXPORT_VAR(long) _nc_outchars;
#endif
extern NCURSES_EXPORT_VAR(unsigned) _nc_tracing;
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(const char *) _nc_viswbuf2 (int, const wchar_t *);
extern NCURSES_EXPORT(const char *) _nc_viswbufn (const wchar_t *, int);
#endif
extern NCURSES_EXPORT(const char *) _nc_viscbuf2 (int, const NCURSES_CH_T *, int);
extern NCURSES_EXPORT(const char *) _nc_viscbuf (const NCURSES_CH_T *, int);
#else /* !TRACE */
#define START_TRACE() /* nothing */
#define T(a)
#define TR(n, a)
#define TPUTS_TRACE(s)
#define returnAttr(code) return code
#define returnBits(code) return code
#define returnBool(code) return code
#define returnCPtr(code) return code
#define returnCVoidPtr(code) return code
#define returnChar(code) return ((char) code)
#define returnChtype(code) return code
#define returnCode(code) return code
#define returnIntAttr(code) return code
#define returnMMask(code) return code
#define returnPtr(code) return code
#define returnSP(code) return code
#define returnVoid return
#define returnVoidPtr(code) return code
#define returnWin(code) return code
#endif /* TRACE/!TRACE */
/*
* Workaround for defective implementation of gcc attribute warn_unused_result
*/
#if defined(__GNUC__) && defined(_FORTIFY_SOURCE)
#define IGNORE_RC(func) errno = (int) func
#else
#define IGNORE_RC(func) (void) func
#endif /* gcc workarounds */
/*
* Return-codes for tgetent() and friends.
*/
#define TGETENT_YES 1 /* entry is found */
#define TGETENT_NO 0 /* entry is not found */
#define TGETENT_ERR -1 /* an error occurred */
extern NCURSES_EXPORT(const char *) _nc_visbuf2 (int, const char *);
extern NCURSES_EXPORT(const char *) _nc_visbufn (const char *, int);
#define EMPTY_MODULE(name) \
extern NCURSES_EXPORT(void) name (void); \
NCURSES_EXPORT(void) name (void) { }
#define ALL_BUT_COLOR ((chtype)~(A_COLOR))
#define NONBLANK_ATTR (A_BOLD | A_DIM | A_BLINK | A_ITALIC)
#define TPARM_ATTR (A_STANDOUT | A_UNDERLINE | A_REVERSE | A_BLINK | A_DIM | A_BOLD | A_ALTCHARSET | A_INVIS | A_PROTECT)
#define XMC_CONFLICT (A_STANDOUT | A_UNDERLINE | A_REVERSE | A_BLINK | A_DIM | A_BOLD | A_INVIS | A_PROTECT | A_ITALIC)
#define XMC_CHANGES(c) ((c) & SP_PARM->_xmc_suppress)
#define toggle_attr_on(S,at) {\
if (PairNumber(at) > 0) {\
(S) = ((S) & ALL_BUT_COLOR) | (attr_t) (at);\
} else {\
(S) |= (attr_t) (at);\
}\
TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
#define toggle_attr_off(S,at) {\
if (PairNumber(at) > 0) {\
(S) &= ~(at|A_COLOR);\
} else {\
(S) &= ~(at);\
}\
TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
#define DelCharCost(sp,count) \
((parm_dch != 0) \
? sp->_dch_cost \
: ((delete_character != 0) \
? (sp->_dch1_cost * count) \
: INFINITY))
#define InsCharCost(sp,count) \
((parm_ich != 0) \
? sp->_ich_cost \
: ((enter_insert_mode && exit_insert_mode) \
? sp->_smir_cost + sp->_rmir_cost + (sp->_ip_cost * count) \
: ((insert_character != 0) \
? ((sp->_ich1_cost + sp->_ip_cost) * count) \
: INFINITY)))
#if USE_XMC_SUPPORT
#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
attr_t chg = AttrOf(SCREEN_ATTRS(sp)); \
VIDATTR(sp, AttrOf(c), GetPair(c)); \
if (magic_cookie_glitch > 0 \
&& XMC_CHANGES((chg ^ AttrOf(SCREEN_ATTRS(sp))))) { \
T(("%s @%d before glitch %d,%d", \
__FILE__, __LINE__, \
sp->_cursrow, \
sp->_curscol)); \
NCURSES_SP_NAME(_nc_do_xmc_glitch)(NCURSES_SP_ARGx chg); \
} \
}
#else
#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
VIDATTR(sp, AttrOf(c), GetPair(c)); \
}
#endif
/*
* Macros to make additional parameter to implement wgetch_events()
*/
#ifdef NCURSES_WGETCH_EVENTS
#define EVENTLIST_0th(param) param
#define EVENTLIST_1st(param) param
#define EVENTLIST_2nd(param) , param
#define TWAIT_MASK (TW_ANY | TW_EVENT)
#else
#define EVENTLIST_0th(param) void
#define EVENTLIST_1st(param) /* nothing */
#define EVENTLIST_2nd(param) /* nothing */
#define TWAIT_MASK TW_ANY
#endif
#if NCURSES_EXPANDED && NCURSES_EXT_FUNCS
#undef toggle_attr_on
#define toggle_attr_on(S,at) _nc_toggle_attr_on(&(S), at)
extern NCURSES_EXPORT(void) _nc_toggle_attr_on (attr_t *, attr_t);
#undef toggle_attr_off
#define toggle_attr_off(S,at) _nc_toggle_attr_off(&(S), at)
extern NCURSES_EXPORT(void) _nc_toggle_attr_off (attr_t *, attr_t);
#undef DelCharCost
#define DelCharCost(sp, count) NCURSES_SP_NAME(_nc_DelCharCost)(NCURSES_SP_ARGx count)
#undef InsCharCost
#define InsCharCost(sp, count) NCURSES_SP_NAME(_nc_InsCharCost)(NCURSES_SP_ARGx count)
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_DelCharCost) (NCURSES_SP_DCLx int _c);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_InsCharCost) (NCURSES_SP_DCLx int _c);
#undef UpdateAttrs
#define UpdateAttrs(sp,c) NCURSES_SP_NAME(_nc_UpdateAttrs)(NCURSES_SP_ARGx CHREF(c))
#if USE_WIDEC_SUPPORT || defined(NEED_NCURSES_CH_T)
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx CARG_CH_T _c);
#else
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx chtype c);
#endif
#if NCURSES_SP_FUNCS
extern NCURSES_EXPORT(int) _nc_DelCharCost (int);
extern NCURSES_EXPORT(int) _nc_InsCharCost (int);
extern NCURSES_EXPORT(void) _nc_UpdateAttrs (CARG_CH_T);
#endif /* NCURSES_SP_FUNCS */
#else
extern NCURSES_EXPORT(void) _nc_expanded (void);
#endif
#if !NCURSES_EXT_FUNCS
#define set_escdelay(value) ESCDELAY = value
#endif
#if !HAVE_GETCWD
#define getcwd(buf,len) getwd(buf)
#endif
/* charable.c */
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(bool) _nc_is_charable(wchar_t);
extern NCURSES_EXPORT(int) _nc_to_char(wint_t);
extern NCURSES_EXPORT(wint_t) _nc_to_widechar(int);
#endif
/* comp_captab.c */
typedef struct {
short nte_name; /* offset of name to hash on */
int nte_type; /* BOOLEAN, NUMBER or STRING */
short nte_index; /* index of associated variable in its array */
short nte_link; /* index in table of next hash, or -1 */
} name_table_data;
typedef struct
{
short from;
short to;
short source;
} alias_table_data;
/* doupdate.c */
#if USE_XMC_SUPPORT
extern NCURSES_EXPORT(void) _nc_do_xmc_glitch (attr_t);
#endif
/* hardscroll.c */
#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
extern NCURSES_EXPORT(void) _nc_linedump (void);
#endif
/* lib_acs.c */
extern NCURSES_EXPORT(void) _nc_init_acs (void); /* corresponds to traditional 'init_acs()' */
extern NCURSES_EXPORT(int) _nc_msec_cost (const char *const, int); /* used by 'tack' program */
/* lib_addch.c */
#if USE_WIDEC_SUPPORT
NCURSES_EXPORT(int) _nc_build_wch(WINDOW *win, ARG_CH_T ch);
#endif
/* lib_addstr.c */
#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(int) _nc_wchstrlen(const cchar_t *);
#endif
/* lib_color.c */
extern NCURSES_EXPORT(bool) _nc_reset_colors(void);
/* lib_getch.c */
extern NCURSES_EXPORT(int) _nc_wgetch(WINDOW *, int *, int EVENTLIST_2nd(_nc_eventlist *));
/* lib_insch.c */
extern NCURSES_EXPORT(int) _nc_insert_ch(SCREEN *, WINDOW *, chtype);
/* lib_mvcur.c */
#define INFINITY 1000000 /* cost: too high to use */
extern NCURSES_EXPORT(int) _nc_mvcur(int yold, int xold, int ynew, int xnew);
extern NCURSES_EXPORT(void) _nc_mvcur_init (void);
extern NCURSES_EXPORT(void) _nc_mvcur_resume (void);
extern NCURSES_EXPORT(void) _nc_mvcur_wrap (void);
extern NCURSES_EXPORT(int) _nc_scrolln (int, int, int, int);
extern NCURSES_EXPORT(void) _nc_screen_init (void);
extern NCURSES_EXPORT(void) _nc_screen_resume (void);
extern NCURSES_EXPORT(void) _nc_screen_wrap (void);
/* lib_mouse.c */
extern NCURSES_EXPORT(bool) _nc_has_mouse (SCREEN *);
/* lib_mvcur.c */
#define INFINITY 1000000 /* cost: too high to use */
#define BAUDBYTE 9 /* 9 = 7 bits + 1 parity + 1 stop */
/* lib_setup.c */
extern NCURSES_EXPORT(char *) _nc_get_locale(void);
extern NCURSES_EXPORT(int) _nc_unicode_locale(void);
extern NCURSES_EXPORT(int) _nc_locale_breaks_acs(TERMINAL *);
extern NCURSES_EXPORT(int) _nc_setupterm(NCURSES_CONST char *, int, int *, int);
extern NCURSES_EXPORT(void) _nc_tinfo_cmdch(TERMINAL *, int);
/* lib_set_term.c */
extern NCURSES_EXPORT(int) _nc_ripoffline(int, int(*)(WINDOW*, int));
/* lib_setup.c */
#define SETUP_FAIL ERR
#define ret_error(code, fmt, arg) if (errret) {\
*errret = code;\
returnCode(SETUP_FAIL);\
} else {\
fprintf(stderr, fmt, arg);\
exit(EXIT_FAILURE);\
}
#define ret_error1(code, fmt, arg) ret_error(code, "'%s': " fmt, arg)
#define ret_error0(code, msg) if (errret) {\
*errret = code;\
returnCode(SETUP_FAIL);\
} else {\
fprintf(stderr, msg);\
exit(EXIT_FAILURE);\
}
/* lib_tstp.c */
#if USE_SIGWINCH
extern NCURSES_EXPORT(int) _nc_handle_sigwinch(SCREEN *);
#else
#define _nc_handle_sigwinch(a) /* nothing */
#endif
/* lib_wacs.c */
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(void) _nc_init_wacs(void);
#endif
typedef struct {
char *s_head; /* beginning of the string (may be null) */
char *s_tail; /* end of the string (may be null) */
size_t s_size; /* current remaining size available */
size_t s_init; /* total size available */
} string_desc;
/* strings.c */
extern NCURSES_EXPORT(string_desc *) _nc_str_init (string_desc *, char *, size_t);
extern NCURSES_EXPORT(string_desc *) _nc_str_null (string_desc *, size_t);
extern NCURSES_EXPORT(string_desc *) _nc_str_copy (string_desc *, string_desc *);
extern NCURSES_EXPORT(bool) _nc_safe_strcat (string_desc *, const char *);
extern NCURSES_EXPORT(bool) _nc_safe_strcpy (string_desc *, const char *);
#if !HAVE_STRSTR
#define strstr _nc_strstr
extern NCURSES_EXPORT(char *) _nc_strstr (const char *, const char *);
#endif
/* safe_sprintf.c */
extern NCURSES_EXPORT(char *) _nc_printf_string (const char *, va_list);
/* tries.c */
extern NCURSES_EXPORT(int) _nc_add_to_try (TRIES **, const char *, unsigned);
extern NCURSES_EXPORT(char *) _nc_expand_try (TRIES *, unsigned, int *, size_t);
extern NCURSES_EXPORT(int) _nc_remove_key (TRIES **, unsigned);
extern NCURSES_EXPORT(int) _nc_remove_string (TRIES **, const char *);
/* elsewhere ... */
extern NCURSES_EXPORT(ENTRY *) _nc_delink_entry (ENTRY *, TERMTYPE *);
extern NCURSES_EXPORT(SCREEN *) _nc_screen_of (WINDOW *);
extern NCURSES_EXPORT(TERMINAL*) _nc_get_cur_term (void);
extern NCURSES_EXPORT(WINDOW *) _nc_makenew (int, int, int, int, int);
extern NCURSES_EXPORT(char *) _nc_trace_buf (int, size_t);
extern NCURSES_EXPORT(char *) _nc_trace_bufcat (int, const char *);
extern NCURSES_EXPORT(char *) _nc_tracechar (SCREEN *, int);
extern NCURSES_EXPORT(char *) _nc_tracemouse (SCREEN *, MEVENT const *);
extern NCURSES_EXPORT(char *) _nc_trace_mmask_t (SCREEN *, mmask_t);
extern NCURSES_EXPORT(int) _nc_access (const char *, int);
extern NCURSES_EXPORT(int) _nc_baudrate (int);
extern NCURSES_EXPORT(int) _nc_freewin (WINDOW *);
extern NCURSES_EXPORT(int) _nc_getenv_num (const char *);
extern NCURSES_EXPORT(int) _nc_keypad (SCREEN *, int);
extern NCURSES_EXPORT(int) _nc_ospeed (int);
extern NCURSES_EXPORT(int) _nc_outch (int);
extern NCURSES_EXPORT(int) _nc_putchar (int);
extern NCURSES_EXPORT(int) _nc_putp(const char *, const char *);
extern NCURSES_EXPORT(int) _nc_putp_flush(const char *, const char *);
extern NCURSES_EXPORT(int) _nc_read_termcap_entry (const char *const, TERMTYPE *const);
extern NCURSES_EXPORT(int) _nc_setup_tinfo(const char *, TERMTYPE *);
extern NCURSES_EXPORT(int) _nc_setupscreen (int, int, FILE *, int, int);
extern NCURSES_EXPORT(int) _nc_timed_wait (SCREEN *, int, int, int * EVENTLIST_2nd(_nc_eventlist *));
extern NCURSES_EXPORT(void) _nc_do_color (int, int, int, NCURSES_OUTC);
extern NCURSES_EXPORT(void) _nc_flush (void);
extern NCURSES_EXPORT(void) _nc_free_and_exit (int) GCC_NORETURN;
extern NCURSES_EXPORT(void) _nc_free_entry (ENTRY *, TERMTYPE *);
extern NCURSES_EXPORT(void) _nc_freeall (void);
extern NCURSES_EXPORT(void) _nc_hash_map (void);
extern NCURSES_EXPORT(void) _nc_init_keytry (SCREEN *);
extern NCURSES_EXPORT(void) _nc_keep_tic_dir (const char *);
extern NCURSES_EXPORT(void) _nc_make_oldhash (int i);
extern NCURSES_EXPORT(void) _nc_scroll_oldhash (int n, int top, int bot);
extern NCURSES_EXPORT(void) _nc_scroll_optimize (void);
extern NCURSES_EXPORT(void) _nc_set_buffer (FILE *, int);
extern NCURSES_EXPORT(void) _nc_setenv_num (const char *, int);
extern NCURSES_EXPORT(void) _nc_signal_handler (int);
extern NCURSES_EXPORT(void) _nc_synchook (WINDOW *);
extern NCURSES_EXPORT(void) _nc_trace_tries (TRIES *);
#if NO_LEAKS
extern NCURSES_EXPORT(void) _nc_alloc_entry_leaks(void);
extern NCURSES_EXPORT(void) _nc_captoinfo_leaks(void);
extern NCURSES_EXPORT(void) _nc_codes_leaks(void);
extern NCURSES_EXPORT(void) _nc_comp_captab_leaks(void);
extern NCURSES_EXPORT(void) _nc_comp_error_leaks(void);
extern NCURSES_EXPORT(void) _nc_comp_scan_leaks(void);
extern NCURSES_EXPORT(void) _nc_db_iterator_leaks(void);
extern NCURSES_EXPORT(void) _nc_keyname_leaks(void);
extern NCURSES_EXPORT(void) _nc_names_leaks(void);
extern NCURSES_EXPORT(void) _nc_tgetent_leaks(void);
#endif
#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(NCURSES_CH_T) _nc_render (WINDOW *, NCURSES_CH_T);
extern NCURSES_EXPORT(int) _nc_waddch_nosync (WINDOW *, const NCURSES_CH_T);
extern NCURSES_EXPORT(void) _nc_scroll_window (WINDOW *, int const, int const, int const, NCURSES_CH_T);
#endif
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(int) _nc_insert_wch(WINDOW *, const cchar_t *);
#endif
#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(size_t) _nc_wcrtomb (char *, wchar_t, mbstate_t *);
#endif
#if USE_SIZECHANGE
extern NCURSES_EXPORT(void) _nc_update_screensize (SCREEN *);
#endif
#if HAVE_RESIZETERM
extern NCURSES_EXPORT(void) _nc_resize_margins (WINDOW *);
#else
#define _nc_resize_margins(wp) /* nothing */
#endif
#ifdef NCURSES_WGETCH_EVENTS
extern NCURSES_EXPORT(int) _nc_eventlist_timeout(_nc_eventlist *);
#else
#define wgetch_events(win, evl) wgetch(win)
#define wgetnstr_events(win, str, maxlen, evl) wgetnstr(win, str, maxlen)
#endif
/*
* Wide-character macros to hide some platform-differences.
*/
#if USE_WIDEC_SUPPORT
#if defined(__MINGW32__)
/*
* MinGW has wide-character functions, but they do not work correctly.
*/
extern int __MINGW_NOTHROW _nc_wctomb(char *, wchar_t);
#define wctomb(s,wc) _nc_wctomb(s,wc)
#define wcrtomb(s,wc,n) _nc_wctomb(s,wc)
extern int __MINGW_NOTHROW _nc_mbtowc(wchar_t *, const char *, size_t);
#define mbtowc(pwc,s,n) _nc_mbtowc(pwc,s,n)
extern int __MINGW_NOTHROW _nc_mblen(const char *, size_t);
#define mblen(s,n) _nc_mblen(s, n)
#endif /* __MINGW32__ */
#if HAVE_MBTOWC && HAVE_MBLEN
#define reset_mbytes(state) IGNORE_RC(mblen(NULL, (size_t) 0)), IGNORE_RC(mbtowc(NULL, NULL, (size_t) 0))
#define count_mbytes(buffer,length,state) mblen(buffer,length)
#define check_mbytes(wch,buffer,length,state) \
(int) mbtowc(&wch, buffer, length)
#define state_unused
#elif HAVE_MBRTOWC && HAVE_MBRLEN
#define reset_mbytes(state) init_mb(state)
#define count_mbytes(buffer,length,state) mbrlen(buffer,length,&state)
#define check_mbytes(wch,buffer,length,state) \
(int) mbrtowc(&wch, buffer, length, &state)
#else
make an error
#endif
#endif /* USE_WIDEC_SUPPORT */
/*
* Not everyone has vsscanf(), but we'd like to use it for scanw().
*/
#if !HAVE_VSSCANF
extern int vsscanf(const char *str, const char *format, va_list __arg);
#endif
/* scroll indices */
extern NCURSES_EXPORT_VAR(int *) _nc_oldnums;
#define USE_SETBUF_0 0
#define NC_OUTPUT(sp) ((sp != 0) ? sp->_ofp : stdout)
/*
* On systems with a broken linker, define 'SP' as a function to force the
* linker to pull in the data-only module with 'SP'.
*/
#define _nc_alloc_screen_sp() typeCalloc(SCREEN, 1)
#if BROKEN_LINKER
#define SP _nc_screen()
extern NCURSES_EXPORT(SCREEN *) _nc_screen (void);
extern NCURSES_EXPORT(int) _nc_alloc_screen (void);
extern NCURSES_EXPORT(void) _nc_set_screen (SCREEN *);
#define CURRENT_SCREEN _nc_screen()
#else
/* current screen is private data; avoid possible linking conflicts too */
extern NCURSES_EXPORT_VAR(SCREEN *) SP;
#define CURRENT_SCREEN SP
#define _nc_alloc_screen() ((SP = _nc_alloc_screen_sp()) != 0)
#define _nc_set_screen(sp) SP = sp
#endif
#if NCURSES_SP_FUNCS
#define CURRENT_SCREEN_PRE (IsPreScreen(CURRENT_SCREEN) ? CURRENT_SCREEN : new_prescr())
#else
#define CURRENT_SCREEN_PRE CURRENT_SCREEN
#endif
/*
* We don't want to use the lines or columns capabilities internally, because
* if the application is running multiple screens under X, it's quite possible
* they could all have type xterm but have different sizes! So...
*/
#define screen_lines(sp) (sp)->_lines
#define screen_columns(sp) (sp)->_columns
extern NCURSES_EXPORT(int) _nc_slk_initialize (WINDOW *, int);
extern NCURSES_EXPORT(int) _nc_format_slks (NCURSES_SP_DCLx int _c);
/*
* Some constants related to SLK's
*/
#define MAX_SKEY_OLD 8 /* count of soft keys */
#define MAX_SKEY_LEN_OLD 8 /* max length of soft key text */
#define MAX_SKEY_PC 12 /* This is what most PC's have */
#define MAX_SKEY_LEN_PC 5
/* Macro to check whether or not we use a standard format */
#define SLK_STDFMT(fmt) (fmt < 3)
/* Macro to determine height of label window */
#define SLK_LINES(fmt) (SLK_STDFMT(fmt) ? 1 : ((fmt) - 2))
#define MAX_SKEY(fmt) (SLK_STDFMT(fmt)? MAX_SKEY_OLD : MAX_SKEY_PC)
#define MAX_SKEY_LEN(fmt) (SLK_STDFMT(fmt)? MAX_SKEY_LEN_OLD : MAX_SKEY_LEN_PC)
/*
* Common error messages
*/
#define MSG_NO_MEMORY "Out of memory"
#define MSG_NO_INPUTS "Premature EOF"
extern NCURSES_EXPORT(int) _nc_set_tty_mode(TTY *);
extern NCURSES_EXPORT(int) _nc_get_tty_mode(TTY *);
/* timed_wait flag definitions */
#define TW_NONE 0
#define TW_INPUT 1
#define TW_MOUSE 2
#define TW_ANY (TW_INPUT | TW_MOUSE)
#define TW_EVENT 4
#define SetSafeOutcWrapper(outc) \
SCREEN* sp = CURRENT_SCREEN; \
struct screen outc_wrapper; \
if (sp==0) { \
sp = &outc_wrapper; \
memset(sp,0,sizeof(struct screen)); \
sp->_outch = _nc_outc_wrapper; \
}\
sp->jump = outc
#ifdef USE_TERM_DRIVER
typedef struct _termInfo
{
bool caninit;
bool hascolor;
bool initcolor;
bool canchange;
int tabsize;
int maxcolors;
int maxpairs;
int nocolorvideo;
int numbuttons;
int numlabels;
int labelwidth;
int labelheight;
const color_t* defaultPalette;
} TerminalInfo;
typedef struct term_driver {
bool isTerminfo;
const char* (*td_name)(struct DriverTCB*);
bool (*td_CanHandle)(struct DriverTCB*, const char*, int*);
void (*td_init)(struct DriverTCB*);
void (*td_release)(struct DriverTCB*);
int (*td_size)(struct DriverTCB*, int* Line, int *Cols);
int (*td_sgmode)(struct DriverTCB*, int setFlag, TTY*);
chtype (*td_conattr)(struct DriverTCB*);
int (*td_hwcur)(struct DriverTCB*, int yold, int xold, int y, int x);
int (*td_mode)(struct DriverTCB*, int progFlag, int defFlag);
bool (*td_rescol)(struct DriverTCB*);
bool (*td_rescolors)(struct DriverTCB*);
void (*td_color)(struct DriverTCB*, int fore, int color, int(*)(SCREEN*, int));
int (*td_doBeepOrFlash)(struct DriverTCB*, int);
void (*td_initpair)(struct DriverTCB*, int, int, int);
void (*td_initcolor)(struct DriverTCB*, int, int, int, int);
void (*td_docolor)(struct DriverTCB*, int, int, int, int(*)(SCREEN*, int));
void (*td_initmouse)(struct DriverTCB*);
int (*td_testmouse)(struct DriverTCB*, int EVENTLIST_2nd(_nc_eventlist*));
void (*td_setfilter)(struct DriverTCB*);
void (*td_hwlabel)(struct DriverTCB*, int, char*);
void (*td_hwlabelOnOff)(struct DriverTCB*, int);
int (*td_update)(struct DriverTCB*);
int (*td_defaultcolors)(struct DriverTCB*, int, int);
int (*td_print)(struct DriverTCB*, char*, int);
int (*td_getsize)(struct DriverTCB*, int*, int*);
int (*td_setsize)(struct DriverTCB*, int, int);
void (*td_initacs)(struct DriverTCB*, chtype*, chtype*);
void (*td_scinit)(SCREEN *);
void (*td_scexit)(SCREEN *);
int (*td_twait)(struct DriverTCB*, int, int, int* EVENTLIST_2nd(_nc_eventlist*));
int (*td_read)(struct DriverTCB*, int*);
int (*td_nap)(struct DriverTCB*, int);
int (*td_kpad)(struct DriverTCB*, int);
int (*td_kyOk)(struct DriverTCB*, int, int);
bool (*td_kyExist)(struct DriverTCB*, int);
int (*td_cursorSet)(struct DriverTCB*, int);
} TERM_DRIVER;
typedef struct DriverTCB
{
TERMINAL term; /* needs to be the first Element !!! */
TERM_DRIVER* drv; /* The driver for that Terminal */
SCREEN* csp; /* The screen that owns that Terminal */
TerminalInfo info; /* Driver independent core capabilities of the Terminal */
void* prop; /* Driver dependent property storage to be used by the Driver */
long magic;
} TERMINAL_CONTROL_BLOCK;
#define NCDRV_MAGIC(id) (0x47110000 | (id&0xffff))
#define NCDRV_TINFO 0x01
#define NCDRV_WINCONSOLE 0x02
#define TCBOf(sp) ((TERMINAL_CONTROL_BLOCK*)(TerminalOf(sp)))
#define InfoOf(sp) TCBOf(sp)->info
#define CallDriver(sp,method) TCBOf(sp)->drv->method(TCBOf(sp))
#define CallDriver_1(sp,method,arg1) TCBOf(sp)->drv->method(TCBOf(sp),arg1)
#define CallDriver_2(sp,method,arg1,arg2) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2)
#define CallDriver_3(sp,method,arg1,arg2,arg3) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3)
#define CallDriver_4(sp,method,arg1,arg2,arg3,arg4) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3,arg4)
extern NCURSES_EXPORT_VAR(const color_t*) _nc_cga_palette;
extern NCURSES_EXPORT_VAR(const color_t*) _nc_hls_palette;
extern NCURSES_EXPORT(int) _nc_get_driver(TERMINAL_CONTROL_BLOCK*, const char*, int*);
extern NCURSES_EXPORT(void) _nc_get_screensize_ex(SCREEN *, TERMINAL *, int *, int *);
#endif /* USE_TERM_DRIVER */
/*
* Entrypoints which are actually provided in the terminal driver, which would
* be an sp-name otherwise.
*/
#ifdef USE_TERM_DRIVER
#define TINFO_HAS_KEY _nc_tinfo_has_key
#define TINFO_DOUPDATE _nc_tinfo_doupdate
#define TINFO_MVCUR _nc_tinfo_mvcur
extern NCURSES_EXPORT(int) TINFO_HAS_KEY(SCREEN*, int);
extern NCURSES_EXPORT(int) TINFO_DOUPDATE(SCREEN *);
extern NCURSES_EXPORT(int) TINFO_MVCUR(SCREEN*, int, int, int, int);
#else
#define TINFO_HAS_KEY NCURSES_SP_NAME(has_key)
#define TINFO_DOUPDATE NCURSES_SP_NAME(doupdate)
#define TINFO_MVCUR NCURSES_SP_NAME(_nc_mvcur)
#endif
/*
* Entrypoints using an extra parameter with the terminal driver.
*/
#ifdef USE_TERM_DRIVER
extern NCURSES_EXPORT(void) _nc_get_screensize(SCREEN *, TERMINAL *, int *, int *);
extern NCURSES_EXPORT(int) _nc_setupterm_ex(TERMINAL **, NCURSES_CONST char *, int , int *, int);
#define TINFO_GET_SIZE(sp, tp, lp, cp) \
_nc_get_screensize(sp, tp, lp, cp)
#define TINFO_SET_CURTERM(sp, tp) \
NCURSES_SP_NAME(set_curterm)(sp, tp)
#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
_nc_setupterm_ex(tpp, name, fd, err, reuse)
#else /* !USE_TERM_DRIVER */
extern NCURSES_EXPORT(void) _nc_get_screensize(SCREEN *, int *, int *);
#define TINFO_GET_SIZE(sp, tp, lp, cp) \
_nc_get_screensize(sp, lp, cp)
#define TINFO_SET_CURTERM(sp, tp) \
set_curterm(tp)
#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
_nc_setupterm(name, fd, err, reuse)
#endif /* !USE_TERM_DRIVER */
#ifdef USE_TERM_DRIVER
#if defined(USE_WIN32CON_DRIVER)
#include <nc_mingw.h>
extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_WIN_DRIVER;
extern NCURSES_EXPORT(int) _nc_mingw_isatty(int fd);
extern NCURSES_EXPORT(int) _nc_mingw_isconsole(int fd);
extern NCURSES_EXPORT(int) _nc_mingw_console_read(
SCREEN *sp,
HANDLE fd,
int *buf);
extern NCURSES_EXPORT(int) _nc_mingw_testmouse(
SCREEN * sp,
HANDLE fd,
int delay);
#else
#endif
extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_TINFO_DRIVER;
#endif
#if defined(USE_TERM_DRIVER) && defined(USE_WIN32CON_DRIVER)
#define NC_ISATTY(fd) _nc_mingw_isatty(fd)
#else
#define NC_ISATTY(fd) isatty(fd)
#endif
#ifdef USE_TERM_DRIVER
# define IsTermInfo(sp) ((TCBOf(sp) != 0) && ((TCBOf(sp)->drv->isTerminfo)))
# define HasTInfoTerminal(sp) ((0 != TerminalOf(sp)) && IsTermInfo(sp))
# if defined(USE_WIN32CON_DRIVER)
# define IsTermInfoOnConsole(sp) (IsTermInfo(sp)&&_nc_mingw_isconsole(TerminalOf(sp)->Filedes))
#else
# define IsTermInfoOnConsole(sp) FALSE
# endif
#else
# define IsTermInfo(sp) TRUE
# define HasTInfoTerminal(sp) (0 != TerminalOf(sp))
# define IsTermInfoOnConsole(sp) FALSE
#endif
#define IsValidTIScreen(sp) (HasTInfoTerminal(sp))
/*
* Exported entrypoints beyond the published API
*/
#if NCURSES_SP_FUNCS
extern NCURSES_EXPORT(WINDOW *) _nc_curscr_of(SCREEN*);
extern NCURSES_EXPORT(WINDOW *) _nc_newscr_of(SCREEN*);
extern NCURSES_EXPORT(WINDOW *) _nc_stdscr_of(SCREEN*);
extern NCURSES_EXPORT(int) _nc_outc_wrapper(SCREEN*,int);
#if USE_REENTRANT
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_TABSIZE)(SCREEN*);
extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(longname)(SCREEN*);
#endif
#if NCURSES_EXT_FUNCS
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_set_tabsize)(SCREEN*, int);
#endif
/*
* We put the safe versions of various calls here as they are not published
* part of the API up to now
*/
extern NCURSES_EXPORT(TERMINAL*) NCURSES_SP_NAME(_nc_get_cur_term) (SCREEN *sp);
extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(_nc_makenew) (SCREEN*, int, int, int, int, int);
extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(_nc_reset_colors)(SCREEN*);
extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(_nc_printf_string)(SCREEN*, const char *, va_list);
extern NCURSES_EXPORT(chtype) NCURSES_SP_NAME(_nc_acs_char)(SCREEN*,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_curs_set)(SCREEN*,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_get_tty_mode)(SCREEN*,TTY*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_mcprint)(SCREEN*,char*, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_msec_cost)(SCREEN*, const char *, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_mvcur)(SCREEN*, int, int, int, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_outch)(SCREEN*, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_putchar)(SCREEN*, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_putp)(SCREEN*, const char *, const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_putp_flush)(SCREEN*, const char *, const char *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_resetty)(SCREEN*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_resize_term)(SCREEN*,int,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_ripoffline)(SCREEN*, int, int (*)(WINDOW *,int));
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_savetty)(SCREEN*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scr_init)(SCREEN*,const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scr_restore)(SCREEN*, const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scrolln)(SCREEN*, int, int, int, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_set_tty_mode)(SCREEN*, TTY*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_setupscreen)(SCREEN**, int, int, FILE *, int, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_tgetent)(SCREEN*,char*,const char *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_tigetnum)(SCREEN*,NCURSES_CONST char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_vid_attr)(SCREEN *, attr_t, NCURSES_COLOR_T, void *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_vidputs)(SCREEN*,chtype,int(*) (SCREEN*, int));
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_do_color)(SCREEN*, int, int, int, NCURSES_SP_OUTC);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_do_xmc_glitch)(SCREEN*, attr_t);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_flush)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_free_and_exit)(SCREEN*, int) GCC_NORETURN;
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_freeall)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_hash_map)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_init_acs)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_make_oldhash)(SCREEN*, int i);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_init)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_resume)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_wrap)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_init)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_resume)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_wrap)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_scroll_oldhash)(SCREEN*, int n, int top, int bot);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_scroll_optimize)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_set_buffer)(SCREEN*, FILE *, int);
extern NCURSES_EXPORT(void) _nc_cookie_init(SCREEN *sp);
#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_linedump)(SCREEN*);
#endif
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(wchar_t *) NCURSES_SP_NAME(_nc_wunctrl)(SCREEN*, cchar_t *);
#endif
#endif /* NCURSES_SP_FUNCS */
#if NCURSES_SP_FUNCS
#define safe_keyname NCURSES_SP_NAME(keyname)
#define safe_unctrl NCURSES_SP_NAME(unctrl)
#define safe_ungetch NCURSES_SP_NAME(ungetch)
#else
#define safe_keyname _nc_keyname
#define safe_unctrl _nc_unctrl
#define safe_ungetch _nc_ungetch
extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_keyname (SCREEN *, int);
extern NCURSES_EXPORT(int) _nc_ungetch (SCREEN *, int);
extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_unctrl (SCREEN *, chtype);
#endif
#ifdef EXP_XTERM_1005
NCURSES_EXPORT(int) _nc_conv_to_utf8(unsigned char *, unsigned, unsigned);
NCURSES_EXPORT(int) _nc_conv_to_utf32(unsigned *, const char *, unsigned);
#endif
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* CURSES_PRIV_H */
|
{
"pile_set_name": "Github"
}
|
<!--
****************************************************************************
* Copyright 2018-2019,2020 Thomas E. Dickey *
* Copyright 1998-2010,2017 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************
* @Id: menu_driver.3x,v 1.26 2020/02/02 23:34:34 tom Exp @
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<meta name="generator" content="Manpage converted by man2html - see https://invisible-island.net/scripts/readme.html#others_scripts">
<TITLE>menu_driver 3x</TITLE>
<link rel="author" href="mailto:bug-ncurses@gnu.org">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1 class="no-header">menu_driver 3x</H1>
<PRE>
<STRONG><A HREF="menu_driver.3x.html">menu_driver(3x)</A></STRONG> <STRONG><A HREF="menu_driver.3x.html">menu_driver(3x)</A></STRONG>
</PRE><H2><a name="h2-NAME">NAME</a></H2><PRE>
<STRONG>menu_driver</STRONG> - command-processing loop of the menu system
</PRE><H2><a name="h2-SYNOPSIS">SYNOPSIS</a></H2><PRE>
<STRONG>#include</STRONG> <STRONG><menu.h></STRONG>
int menu_driver(MENU *menu, int c);
</PRE><H2><a name="h2-DESCRIPTION">DESCRIPTION</a></H2><PRE>
Once a menu has been posted (displayed), you should funnel input events
to it through <STRONG>menu_driver</STRONG>. This routine has three major input cases:
<STRONG>o</STRONG> The input is a form navigation request. Navigation request codes
are constants defined in <STRONG><form.h></STRONG>, which are distinct from the key-
and character codes returned by <STRONG><A HREF="curs_getch.3x.html">wgetch(3x)</A></STRONG>.
<STRONG>o</STRONG> The input is a printable character. Printable characters (which
must be positive, less than 256) are checked according to the pro-
gram's locale settings.
<STRONG>o</STRONG> The input is the KEY_MOUSE special key associated with an mouse
event.
The menu driver requests are as follows:
REQ_LEFT_ITEM
Move left to an item.
REQ_RIGHT_ITEM
Move right to an item.
REQ_UP_ITEM
Move up to an item.
REQ_DOWN_ITEM
Move down to an item.
REQ_SCR_ULINE
Scroll up a line.
REQ_SCR_DLINE
Scroll down a line.
REQ_SCR_DPAGE
Scroll down a page.
REQ_SCR_UPAGE
Scroll up a page.
REQ_FIRST_ITEM
Move to the first item.
REQ_LAST_ITEM
Move to the last item.
REQ_NEXT_ITEM
Move to the next item.
REQ_PREV_ITEM
Move to the previous item.
REQ_TOGGLE_ITEM
Select/deselect an item.
REQ_CLEAR_PATTERN
Clear the menu pattern buffer.
REQ_BACK_PATTERN
Delete the previous character from the pattern buffer.
REQ_NEXT_MATCH
Move to the next item matching the pattern match.
REQ_PREV_MATCH
Move to the previous item matching the pattern match.
If the second argument is a printable character, the code appends it to
the pattern buffer and attempts to move to the next item matching the
new pattern. If there is no such match, <STRONG>menu_driver</STRONG> returns <STRONG>E_NO_MATCH</STRONG>
and deletes the appended character from the buffer.
If the second argument is one of the above pre-defined requests, the
corresponding action is performed.
</PRE><H3><a name="h3-MOUSE-HANDLING">MOUSE HANDLING</a></H3><PRE>
If the second argument is the KEY_MOUSE special key, the associated
mouse event is translated into one of the above pre-defined requests.
Currently only clicks in the user window (e.g., inside the menu display
area or the decoration window) are handled.
If you click above the display region of the menu:
<STRONG>o</STRONG> a REQ_SCR_ULINE is generated for a single click,
<STRONG>o</STRONG> a REQ_SCR_UPAGE is generated for a double-click and
<STRONG>o</STRONG> a REQ_FIRST_ITEM is generated for a triple-click.
If you click below the display region of the menu:
<STRONG>o</STRONG> a REQ_SCR_DLINE is generated for a single click,
<STRONG>o</STRONG> a REQ_SCR_DPAGE is generated for a double-click and
<STRONG>o</STRONG> a REQ_LAST_ITEM is generated for a triple-click.
If you click at an item inside the display area of the menu:
<STRONG>o</STRONG> the menu cursor is positioned to that item.
<STRONG>o</STRONG> If you double-click an item a REQ_TOGGLE_ITEM is generated and
<STRONG>E_UNKNOWN_COMMAND</STRONG> is returned. This return value makes sense,
because a double click usually means that an item-specific action
should be returned. It is exactly the purpose of this return value
to signal that an application specific command should be executed.
<STRONG>o</STRONG> If a translation into a request was done, <STRONG>menu_driver</STRONG> returns the
result of this request.
If you clicked outside the user window or the mouse event could not be
translated into a menu request an <STRONG>E_REQUEST_DENIED</STRONG> is returned.
</PRE><H3><a name="h3-APPLICATION-DEFINED-COMMANDS">APPLICATION-DEFINED COMMANDS</a></H3><PRE>
If the second argument is neither printable nor one of the above pre-
defined menu requests or KEY_MOUSE, the drive assumes it is an applica-
tion-specific command and returns <STRONG>E_UNKNOWN_COMMAND</STRONG>. Application-
defined commands should be defined relative to <STRONG>MAX_COMMAND</STRONG>, the maximum
value of these pre-defined requests.
</PRE><H2><a name="h2-RETURN-VALUE">RETURN VALUE</a></H2><PRE>
<STRONG>menu_driver</STRONG> return one of the following error codes:
<STRONG>E_OK</STRONG> The routine succeeded.
<STRONG>E_SYSTEM_ERROR</STRONG>
System error occurred (see <STRONG>errno(3)</STRONG>).
<STRONG>E_BAD_ARGUMENT</STRONG>
Routine detected an incorrect or out-of-range argument.
<STRONG>E_BAD_STATE</STRONG>
Routine was called from an initialization or termination function.
<STRONG>E_NOT_POSTED</STRONG>
The menu has not been posted.
<STRONG>E_UNKNOWN_COMMAND</STRONG>
The menu driver code saw an unknown request code.
<STRONG>E_NO_MATCH</STRONG>
Character failed to match.
<STRONG>E_REQUEST_DENIED</STRONG>
The menu driver could not process the request.
</PRE><H2><a name="h2-SEE-ALSO">SEE ALSO</a></H2><PRE>
<STRONG><A HREF="ncurses.3x.html">curses(3x)</A></STRONG>, <STRONG><A HREF="menu.3x.html">menu(3x)</A></STRONG>, <STRONG><A HREF="curs_getch.3x.html">getch(3x)</A></STRONG>.
</PRE><H2><a name="h2-NOTES">NOTES</a></H2><PRE>
The header file <STRONG><menu.h></STRONG> automatically includes the header files
<STRONG><curses.h></STRONG>.
</PRE><H2><a name="h2-PORTABILITY">PORTABILITY</a></H2><PRE>
These routines emulate the System V menu library. They were not sup-
ported on Version 7 or BSD versions. The support for mouse events is
ncurses specific.
</PRE><H2><a name="h2-AUTHORS">AUTHORS</a></H2><PRE>
Juergen Pfeifer. Manual pages and adaptation for new curses by Eric S.
Raymond.
<STRONG><A HREF="menu_driver.3x.html">menu_driver(3x)</A></STRONG>
</PRE>
<div class="nav">
<ul>
<li><a href="#h2-NAME">NAME</a></li>
<li><a href="#h2-SYNOPSIS">SYNOPSIS</a></li>
<li><a href="#h2-DESCRIPTION">DESCRIPTION</a>
<ul>
<li><a href="#h3-MOUSE-HANDLING">MOUSE HANDLING</a></li>
<li><a href="#h3-APPLICATION-DEFINED-COMMANDS">APPLICATION-DEFINED COMMANDS</a></li>
</ul>
</li>
<li><a href="#h2-RETURN-VALUE">RETURN VALUE</a></li>
<li><a href="#h2-SEE-ALSO">SEE ALSO</a></li>
<li><a href="#h2-NOTES">NOTES</a></li>
<li><a href="#h2-PORTABILITY">PORTABILITY</a></li>
<li><a href="#h2-AUTHORS">AUTHORS</a></li>
</ul>
</div>
</BODY>
</HTML>
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 1998-2010,2012 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
* and: Eric S. Raymond <esr@snark.thyrsus.com> *
* and: Juergen Pfeifer 1996-on *
* and: Thomas E. Dickey *
****************************************************************************/
/*
* lib_slkrefr.c
* Write SLK window to the (virtual) screen.
*/
#include <curses.priv.h>
#ifndef CUR
#define CUR SP_TERMTYPE
#endif
MODULE_ID("$Id: lib_slkrefr.c,v 1.27 2012/06/09 20:29:33 tom Exp $")
#ifdef USE_TERM_DRIVER
#define NumLabels InfoOf(SP_PARM).numlabels
#else
#define NumLabels num_labels
#endif
/*
* Paint the info line for the PC style SLK emulation.
*/
static void
slk_paint_info(WINDOW *win)
{
SCREEN *sp = _nc_screen_of(win);
if (win && sp && (sp->slk_format == 4)) {
int i;
(void) mvwhline(win, 0, 0, 0, getmaxx(win));
wmove(win, 0, 0);
for (i = 0; i < sp->_slk->maxlab; i++) {
mvwprintw(win, 0, sp->_slk->ent[i].ent_x, "F%d", i + 1);
}
}
}
/*
* Write the soft labels to the soft-key window.
*/
static void
slk_intern_refresh(SCREEN *sp)
{
int i;
int fmt;
SLK *slk;
int numlab;
if (sp == 0)
return;
slk = sp->_slk;
fmt = sp->slk_format;
numlab = NumLabels;
if (slk->hidden)
return;
for (i = 0; i < slk->labcnt; i++) {
if (slk->dirty || slk->ent[i].dirty) {
if (slk->ent[i].visible) {
if (numlab > 0 && SLK_STDFMT(fmt)) {
#ifdef USE_TERM_DRIVER
CallDriver_2(sp, hwlabel, i + 1, slk->ent[i].form_text);
#else
if (i < num_labels) {
TPUTS_TRACE("plab_norm");
putp(TPARM_2(plab_norm, i + 1, slk->ent[i].form_text));
}
#endif
} else {
if (fmt == 4)
slk_paint_info(slk->win);
wmove(slk->win, SLK_LINES(fmt) - 1, slk->ent[i].ent_x);
if (sp->_slk) {
(void) wattrset(slk->win, (int) AttrOf(sp->_slk->attr));
}
waddstr(slk->win, slk->ent[i].form_text);
/* if we simulate SLK's, it's looking much more
natural to use the current ATTRIBUTE also
for the label window */
(void) wattrset(slk->win, (int) WINDOW_ATTRS(StdScreen(sp)));
}
}
slk->ent[i].dirty = FALSE;
}
}
slk->dirty = FALSE;
if (numlab > 0) {
#ifdef USE_TERM_DRIVER
CallDriver_1(sp, hwlabelOnOff, slk->hidden ? FALSE : TRUE);
#else
if (slk->hidden) {
TPUTS_TRACE("label_off");
putp(label_off);
} else {
TPUTS_TRACE("label_on");
putp(label_on);
}
#endif
}
}
/*
* Refresh the soft labels.
*/
NCURSES_EXPORT(int)
NCURSES_SP_NAME(slk_noutrefresh) (NCURSES_SP_DCL0)
{
T((T_CALLED("slk_noutrefresh(%p)"), (void *) SP_PARM));
if (SP_PARM == 0 || SP_PARM->_slk == 0)
returnCode(ERR);
if (SP_PARM->_slk->hidden)
returnCode(OK);
slk_intern_refresh(SP_PARM);
returnCode(wnoutrefresh(SP_PARM->_slk->win));
}
#if NCURSES_SP_FUNCS
NCURSES_EXPORT(int)
slk_noutrefresh(void)
{
return NCURSES_SP_NAME(slk_noutrefresh) (CURRENT_SCREEN);
}
#endif
/*
* Refresh the soft labels.
*/
NCURSES_EXPORT(int)
NCURSES_SP_NAME(slk_refresh) (NCURSES_SP_DCL0)
{
T((T_CALLED("slk_refresh(%p)"), (void *) SP_PARM));
if (SP_PARM == 0 || SP_PARM->_slk == 0)
returnCode(ERR);
if (SP_PARM->_slk->hidden)
returnCode(OK);
slk_intern_refresh(SP_PARM);
returnCode(wrefresh(SP_PARM->_slk->win));
}
#if NCURSES_SP_FUNCS
NCURSES_EXPORT(int)
slk_refresh(void)
{
return NCURSES_SP_NAME(slk_refresh) (CURRENT_SCREEN);
}
#endif
|
{
"pile_set_name": "Github"
}
|
/****************************************************************
* *
* curvyCorners *
* ------------ *
* *
* This script generates rounded corners for your divs. *
* *
* Version 1.2.9 *
* Copyright (c) 2006 Cameron Cooke *
* By: Cameron Cooke and Tim Hutchison. *
* *
* *
* Website: http://www.curvycorners.net *
* Email: info@totalinfinity.com *
* Forum: http://www.curvycorners.net/forum/ *
* *
* *
* 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; either version 2.1 of the *
* License, or (at your option) any later version. *
* *
* This library 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 Lesser General Public *
* License for more details. *
* *
* You should have received a copy of the GNU Lesser *
* General Public License along with this library; *
* Inc., 59 Temple Place, Suite 330, Boston, *
* MA 02111-1307 USA *
* *
****************************************************************/
var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1; var isMoz = document.implementation && document.implementation.createDocument; var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false; function curvyCorners()
{ if(typeof(arguments[0]) != "object") throw newCurvyError("First parameter of curvyCorners() must be an object."); if(typeof(arguments[1]) != "object" && typeof(arguments[1]) != "string") throw newCurvyError("Second parameter of curvyCorners() must be an object or a class name."); if(typeof(arguments[1]) == "string")
{ var startIndex = 0; var boxCol = getElementsByClass(arguments[1]);}
else
{ var startIndex = 1; var boxCol = arguments;}
var curvyCornersCol = new Array(); if(arguments[0].validTags)
var validElements = arguments[0].validTags; else
var validElements = ["div"]; for(var i = startIndex, j = boxCol.length; i < j; i++)
{ var currentTag = boxCol[i].tagName.toLowerCase(); if(inArray(validElements, currentTag) !== false)
{ curvyCornersCol[curvyCornersCol.length] = new curvyObject(arguments[0], boxCol[i]);}
}
this.objects = curvyCornersCol; this.applyCornersToAll = function()
{ for(var x = 0, k = this.objects.length; x < k; x++)
{ this.objects[x].applyCorners();}
}
}
function curvyObject()
{ this.box = arguments[1]; this.settings = arguments[0]; this.topContainer = null; this.bottomContainer = null; this.masterCorners = new Array(); this.contentDIV = null; var boxHeight = get_style(this.box, "height", "height"); var boxWidth = get_style(this.box, "width", "width"); var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width"); var borderColour = get_style(this.box, "borderTopColor", "border-top-color"); var boxColour = get_style(this.box, "backgroundColor", "background-color"); var backgroundImage = get_style(this.box, "backgroundImage", "background-image"); var boxPosition = get_style(this.box, "position", "position"); var boxPadding = get_style(this.box, "paddingTop", "padding-top"); this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight)); this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth)); this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0)); this.boxColour = format_colour(boxColour); this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0)); this.borderColour = format_colour(borderColour); this.borderString = this.borderWidth + "px" + " solid " + this.borderColour; this.backgroundImage = ((backgroundImage != "none")? backgroundImage : ""); this.boxContent = this.box.innerHTML; if(boxPosition != "absolute") this.box.style.position = "relative"; this.box.style.padding = "0px"; if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%"; if(this.settings.autoPad == true && this.boxPadding > 0)
this.box.innerHTML = ""; this.applyCorners = function()
{ for(var t = 0; t < 2; t++)
{ switch(t)
{ case 0:
if(this.settings.tl || this.settings.tr)
{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0); newMainContainer.style.height = topMaxRadius + "px"; newMainContainer.style.top = 0 - topMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.topContainer = this.box.appendChild(newMainContainer);}
break; case 1:
if(this.settings.bl || this.settings.br)
{ var newMainContainer = document.createElement("DIV"); newMainContainer.style.width = "100%"; newMainContainer.style.fontSize = "1px"; newMainContainer.style.overflow = "hidden"; newMainContainer.style.position = "absolute"; newMainContainer.style.paddingLeft = this.borderWidth + "px"; newMainContainer.style.paddingRight = this.borderWidth + "px"; var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0); newMainContainer.style.height = botMaxRadius + "px"; newMainContainer.style.bottom = 0 - botMaxRadius + "px"; newMainContainer.style.left = 0 - this.borderWidth + "px"; this.bottomContainer = this.box.appendChild(newMainContainer);}
break;}
}
if(this.topContainer) this.box.style.borderTopWidth = "0px"; if(this.bottomContainer) this.box.style.borderBottomWidth = "0px"; var corners = ["tr", "tl", "br", "bl"]; for(var i in corners)
{ if(i > -1 < 4)
{ var cc = corners[i]; if(!this.settings[cc])
{ if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null))
{ var newCorner = document.createElement("DIV"); newCorner.style.position = "relative"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; if(this.backgroundImage == "")
newCorner.style.backgroundColor = this.boxColour; else
newCorner.style.backgroundImage = this.backgroundImage; switch(cc)
{ case "tl":
newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.left = -this.borderWidth + "px"; break; case "tr":
newCorner.style.height = topMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderTop = this.borderString; newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; newCorner.style.left = this.borderWidth + "px"; break; case "bl":
newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px"; newCorner.style.borderLeft = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = -this.borderWidth + "px"; newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break; case "br":
newCorner.style.height = botMaxRadius - this.borderWidth + "px"; newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px"; newCorner.style.borderRight = this.borderString; newCorner.style.borderBottom = this.borderString; newCorner.style.left = this.borderWidth + "px"
newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px"; break;}
}
}
else
{ if(this.masterCorners[this.settings[cc].radius])
{ var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);}
else
{ var newCorner = document.createElement("DIV"); newCorner.style.height = this.settings[cc].radius + "px"; newCorner.style.width = this.settings[cc].radius + "px"; newCorner.style.position = "absolute"; newCorner.style.fontSize = "1px"; newCorner.style.overflow = "hidden"; var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth); for(var intx = 0, j = this.settings[cc].radius; intx < j; intx++)
{ if((intx +1) >= borderRadius)
var y1 = -1; else
var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1); if(borderRadius != j)
{ if((intx) >= borderRadius)
var y2 = -1; else
var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2))); if((intx+1) >= j)
var y3 = -1; else
var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);}
if((intx) >= j)
var y4 = -1; else
var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2))); if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius); if(borderRadius != j)
{ for(var inty = (y1 + 1); inty < y2; inty++)
{ if(this.settings.antiAlias)
{ if(this.backgroundImage != "")
{ var borderFract = (pixelFraction(intx, inty, borderRadius) * 100); if(borderFract < 30)
{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);}
else
{ this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);}
}
else
{ var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius)); this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);}
}
}
if(this.settings.antiAlias)
{ if(y3 >= y2)
{ if (y2 == -1) y2 = 0; this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);}
}
else
{ if(y3 >= y1)
{ this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);}
}
var outsideColour = this.borderColour;}
else
{ var outsideColour = this.boxColour; var y3 = y1;}
if(this.settings.antiAlias)
{ for(var inty = (y3 + 1); inty < y4; inty++)
{ this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);}
}
}
this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);}
if(cc != "br")
{ for(var t = 0, k = newCorner.childNodes.length; t < k; t++)
{ var pixelBar = newCorner.childNodes[t]; var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px"))); var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px"))); var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px"))); if(cc == "tl" || cc == "bl"){ pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";}
if(cc == "tr" || cc == "tl"){ pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";}
switch(cc)
{ case "tr":
pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "tl":
pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px"; break; case "bl":
pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px"; break;}
}
}
}
if(newCorner)
{ switch(cc)
{ case "tl":
if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "tr":
if(newCorner.style.position == "absolute") newCorner.style.top = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.topContainer) this.topContainer.appendChild(newCorner); break; case "bl":
if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.left = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break; case "br":
if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px"; if(newCorner.style.position == "absolute") newCorner.style.right = "0px"; if(this.bottomContainer) this.bottomContainer.appendChild(newCorner); break;}
}
}
}
var radiusDiff = new Array(); radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius)
radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius); for(z in radiusDiff)
{ if(z == "t" || z == "b")
{ if(radiusDiff[z])
{ var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r"); var newFiller = document.createElement("DIV"); newFiller.style.height = radiusDiff[z] + "px"; newFiller.style.width = this.settings[smallerCornerType].radius+ "px"
newFiller.style.position = "absolute"; newFiller.style.fontSize = "1px"; newFiller.style.overflow = "hidden"; newFiller.style.backgroundColor = this.boxColour; switch(smallerCornerType)
{ case "tl":
newFiller.style.bottom = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.topContainer.appendChild(newFiller); break; case "tr":
newFiller.style.bottom = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.topContainer.appendChild(newFiller); break; case "bl":
newFiller.style.top = "0px"; newFiller.style.left = "0px"; newFiller.style.borderLeft = this.borderString; this.bottomContainer.appendChild(newFiller); break; case "br":
newFiller.style.top = "0px"; newFiller.style.right = "0px"; newFiller.style.borderRight = this.borderString; this.bottomContainer.appendChild(newFiller); break;}
}
var newFillerBar = document.createElement("DIV"); newFillerBar.style.position = "relative"; newFillerBar.style.fontSize = "1px"; newFillerBar.style.overflow = "hidden"; newFillerBar.style.backgroundColor = this.boxColour; newFillerBar.style.backgroundImage = this.backgroundImage; switch(z)
{ case "t":
if(this.topContainer)
{ if(this.settings.tl.radius && this.settings.tr.radius)
{ newFillerBar.style.height = topMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px"; newFillerBar.style.borderTop = this.borderString; if(this.backgroundImage != "")
newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px"; this.topContainer.appendChild(newFillerBar);}
this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";}
break; case "b":
if(this.bottomContainer)
{ if(this.settings.bl.radius && this.settings.br.radius)
{ newFillerBar.style.height = botMaxRadius - this.borderWidth + "px"; newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px"; newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px"; newFillerBar.style.borderBottom = this.borderString; if(this.backgroundImage != "")
newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px"; this.bottomContainer.appendChild(newFillerBar);}
}
break;}
}
}
if(this.settings.autoPad == true && this.boxPadding > 0)
{ var contentContainer = document.createElement("DIV"); contentContainer.style.position = "relative"; contentContainer.innerHTML = this.boxContent; contentContainer.className = "autoPadDiv"; var topPadding = Math.abs(topMaxRadius - this.boxPadding); var botPadding = Math.abs(botMaxRadius - this.boxPadding); if(topMaxRadius < this.boxPadding)
contentContainer.style.paddingTop = topPadding + "px"; if(botMaxRadius < this.boxPadding)
contentContainer.style.paddingBottom = botMaxRadius + "px"; contentContainer.style.paddingLeft = this.boxPadding + "px"; contentContainer.style.paddingRight = this.boxPadding + "px"; this.contentDIV = this.box.appendChild(contentContainer);}
}
this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius)
{ var pixel = document.createElement("DIV"); pixel.style.height = height + "px"; pixel.style.width = "1px"; pixel.style.position = "absolute"; pixel.style.fontSize = "1px"; pixel.style.overflow = "hidden"; var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius); if(image == -1 && this.backgroundImage != "")
{ pixel.style.backgroundImage = this.backgroundImage; pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";}
else
{ pixel.style.backgroundColor = colour;}
if (transAmount != 100)
setOpacity(pixel, transAmount); pixel.style.top = inty + "px"; pixel.style.left = intx + "px"; newCorner.appendChild(pixel);}
}
function insertAfter(parent, node, referenceNode)
{ parent.insertBefore(node, referenceNode.nextSibling);}
function BlendColour(Col1, Col2, Col1Fraction)
{ var red1 = parseInt(Col1.substr(1,2),16); var green1 = parseInt(Col1.substr(3,2),16); var blue1 = parseInt(Col1.substr(5,2),16); var red2 = parseInt(Col2.substr(1,2),16); var green2 = parseInt(Col2.substr(3,2),16); var blue2 = parseInt(Col2.substr(5,2),16); if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1; var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction))); if(endRed > 255) endRed = 255; if(endRed < 0) endRed = 0; var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction))); if(endGreen > 255) endGreen = 255; if(endGreen < 0) endGreen = 0; var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction))); if(endBlue > 255) endBlue = 255; if(endBlue < 0) endBlue = 0; return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);}
function IntToHex(strNum)
{ base = strNum / 16; rem = strNum % 16; base = base - (rem / 16); baseS = MakeHex(base); remS = MakeHex(rem); return baseS + '' + remS;}
function MakeHex(x)
{ if((x >= 0) && (x <= 9))
{ return x;}
else
{ switch(x)
{ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F";}
}
}
function pixelFraction(x, y, r)
{ var pixelfraction = 0; var xvalues = new Array(1); var yvalues = new Array(1); var point = 0; var whatsides = ""; var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2))); if ((intersect >= y) && (intersect < (y+1)))
{ whatsides = "Left"; xvalues[point] = 0; yvalues[point] = intersect - y; point = point + 1;}
var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2))); if ((intersect >= x) && (intersect < (x+1)))
{ whatsides = whatsides + "Top"; xvalues[point] = intersect - x; yvalues[point] = 1; point = point + 1;}
var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2))); if ((intersect >= y) && (intersect < (y+1)))
{ whatsides = whatsides + "Right"; xvalues[point] = 1; yvalues[point] = intersect - y; point = point + 1;}
var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2))); if ((intersect >= x) && (intersect < (x+1)))
{ whatsides = whatsides + "Bottom"; xvalues[point] = intersect - x; yvalues[point] = 0;}
switch (whatsides)
{ case "LeftRight":
pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2); break; case "TopRight":
pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2); break; case "TopBottom":
pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2); break; case "LeftBottom":
pixelfraction = (yvalues[0]*xvalues[1])/2; break; default:
pixelfraction = 1;}
return pixelfraction;}
function rgb2Hex(rgbColour)
{ try{ var rgbArray = rgb2Array(rgbColour); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);}
catch(e){ alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");}
return hexColour;}
function rgb2Array(rgbColour)
{ var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")")); var rgbArray = rgbValues.split(", "); return rgbArray;}
function setOpacity(obj, opacity)
{ opacity = (opacity == 100)?99.999:opacity; if(isSafari && obj.tagName != "IFRAME")
{ var rgbArray = rgb2Array(obj.style.backgroundColor); var red = parseInt(rgbArray[0]); var green = parseInt(rgbArray[1]); var blue = parseInt(rgbArray[2]); obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";}
else if(typeof(obj.style.opacity) != "undefined")
{ obj.style.opacity = opacity/100;}
else if(typeof(obj.style.MozOpacity) != "undefined")
{ obj.style.MozOpacity = opacity/100;}
else if(typeof(obj.style.filter) != "undefined")
{ obj.style.filter = "alpha(opacity:" + opacity + ")";}
else if(typeof(obj.style.KHTMLOpacity) != "undefined")
{ obj.style.KHTMLOpacity = opacity/100;}
}
function inArray(array, value)
{ for(var i = 0; i < array.length; i++){ if (array[i] === value) return i;}
return false;}
function inArrayKey(array, value)
{ for(key in array){ if(key === value) return true;}
return false;}
function addEvent(elm, evType, fn, useCapture) { if (elm.addEventListener) { elm.addEventListener(evType, fn, useCapture); return true;}
else if (elm.attachEvent) { var r = elm.attachEvent('on' + evType, fn); return r;}
else { elm['on' + evType] = fn;}
}
function removeEvent(obj, evType, fn, useCapture){ if (obj.removeEventListener){ obj.removeEventListener(evType, fn, useCapture); return true;} else if (obj.detachEvent){ var r = obj.detachEvent("on"+evType, fn); return r;} else { alert("Handler could not be removed");}
}
function format_colour(colour)
{ var returnColour = "#ffffff"; if(colour != "" && colour != "transparent")
{ if(colour.substr(0, 3) == "rgb")
{ returnColour = rgb2Hex(colour);}
else if(colour.length == 4)
{ returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);}
else
{ returnColour = colour;}
}
return returnColour;}
function get_style(obj, property, propertyNS)
{ try
{ if(obj.currentStyle)
{ var returnVal = eval("obj.currentStyle." + property);}
else
{ if(isSafari && obj.style.display == "none")
{ obj.style.display = ""; var wasHidden = true;}
var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS); if(isSafari && wasHidden)
{ obj.style.display = "none";}
}
}
catch(e)
{ }
return returnVal;}
function getElementsByClass(searchClass, node, tag)
{ var classElements = new Array(); if(node == null)
node = document; if(tag == null)
tag = '*'; var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)"); for (i = 0, j = 0; i < elsLen; i++)
{ if(pattern.test(els[i].className))
{ classElements[j] = els[i]; j++;}
}
return classElements;}
function newCurvyError(errorMessage)
{ return new Error("curvyCorners Error:\n" + errorMessage)
}
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 1998-2010,2011 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
* and: Eric S. Raymond <esr@snark.thyrsus.com> *
* and: Thomas E. Dickey 1996-on *
* and: Juergen Pfeifer *
****************************************************************************/
/*
* $Id: curses.priv.h,v 1.475 2011/01/22 21:10:19 tom Exp $
*
* curses.priv.h
*
* Header file for curses library objects which are private to
* the library.
*
*/
#ifndef CURSES_PRIV_H
#define CURSES_PRIV_H 1
/* *INDENT-OFF* */
#include <ncurses_dll.h>
#ifdef __cplusplus
extern "C" {
#endif
#include <ncurses_cfg.h>
#if USE_RCS_IDS
#define MODULE_ID(id) static const char Ident[] = id;
#else
#define MODULE_ID(id) /*nothing*/
#endif
#include <stddef.h> /* for offsetof */
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_SYS_BSDTYPES_H
#include <sys/bsdtypes.h> /* needed for ISC */
#endif
#if HAVE_LIMITS_H
# include <limits.h>
#elif HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include <assert.h>
#include <stdio.h>
#include <errno.h>
#ifndef PATH_MAX
# if defined(_POSIX_PATH_MAX)
# define PATH_MAX _POSIX_PATH_MAX
# elif defined(MAXPATHLEN)
# define PATH_MAX MAXPATHLEN
# else
# define PATH_MAX 255 /* the Posix minimum path-size */
# endif
#endif
#if DECL_ERRNO
extern int errno;
#endif
/* Some systems have a broken 'select()', but workable 'poll()'. Use that */
#if HAVE_WORKING_POLL
#define USE_FUNC_POLL 1
#if HAVE_POLL_H
#include <poll.h>
#else
#include <sys/poll.h>
#endif
#else
#define USE_FUNC_POLL 0
#endif
/* include signal.h before curses.h to work-around defect in glibc 2.1.3 */
#include <signal.h>
/* Alessandro Rubini's GPM (general-purpose mouse) */
#if HAVE_LIBGPM && HAVE_GPM_H
#define USE_GPM_SUPPORT 1
#else
#define USE_GPM_SUPPORT 0
#endif
/* QNX mouse support */
#if defined(__QNX__) && !defined(__QNXNTO__)
#define USE_QNX_MOUSE 1
#else
#define USE_QNX_MOUSE 0
#endif
/* EMX mouse support */
#ifdef __EMX__
#define USE_EMX_MOUSE 1
#else
#define USE_EMX_MOUSE 0
#endif
#define DEFAULT_MAXCLICK 166
#define EV_MAX 8 /* size of mouse circular event queue */
/*
* If we don't have signals to support it, don't add a sigwinch handler.
* In any case, resizing is an extended feature. Use it if we've got it.
*/
#if !NCURSES_EXT_FUNCS
#undef HAVE_SIZECHANGE
#define HAVE_SIZECHANGE 0
#endif
#if HAVE_SIZECHANGE && USE_SIGWINCH && defined(SIGWINCH)
#define USE_SIZECHANGE 1
#else
#define USE_SIZECHANGE 0
#undef USE_SIGWINCH
#define USE_SIGWINCH 0
#endif
/*
* If desired, one can configure this, disabling environment variables that
* point to custom terminfo/termcap locations.
*/
#ifdef USE_ROOT_ENVIRON
#define use_terminfo_vars() 1
#else
#define use_terminfo_vars() _nc_env_access()
extern NCURSES_EXPORT(int) _nc_env_access (void);
#endif
/*
* Not all platforms have memmove; some have an equivalent bcopy. (Some may
* have neither).
*/
#if USE_OK_BCOPY
#define memmove(d,s,n) bcopy(s,d,n)
#elif USE_MY_MEMMOVE
#define memmove(d,s,n) _nc_memmove(d,s,n)
extern NCURSES_EXPORT(void *) _nc_memmove (void *, const void *, size_t);
#endif
/*
* If we have va_copy(), use it for assigning va_list's.
*/
#if defined(HAVE___VA_COPY)
#define begin_va_copy(dst,src) __va_copy(dst, src)
#define end_va_copy(dst) va_end(dst)
#elif defined(va_copy) || defined(HAVE_VA_COPY)
#define begin_va_copy(dst,src) va_copy(dst, src)
#define end_va_copy(dst) va_end(dst)
#else
#define begin_va_copy(dst,src) (dst) = (src)
#define end_va_copy(dst) /* nothing */
#endif
/*
* Scroll hints are useless when hashmap is used
*/
#if !USE_SCROLL_HINTS
#if !USE_HASHMAP
#define USE_SCROLL_HINTS 1
#else
#define USE_SCROLL_HINTS 0
#endif
#endif
#if USE_SCROLL_HINTS
#define if_USE_SCROLL_HINTS(stmt) stmt
#else
#define if_USE_SCROLL_HINTS(stmt) /*nothing*/
#endif
/*
* Options for terminal drivers, etc...
*/
#ifdef USE_TERM_DRIVER
#define USE_SP_RIPOFF 1
#define USE_SP_TERMTYPE 1
#define USE_SP_WINDOWLIST 1
#endif
/*
* Note: ht/cbt expansion flakes out randomly under Linux 1.1.47, but only
* when we're throwing control codes at the screen at high volume. To see
* this, re-enable USE_HARD_TABS and run worm for a while. Other systems
* probably don't want to define this either due to uncertainties about tab
* delays and expansion in raw mode.
*/
#define TRIES struct tries
typedef TRIES {
TRIES *child; /* ptr to child. NULL if none */
TRIES *sibling; /* ptr to sibling. NULL if none */
unsigned char ch; /* character at this node */
unsigned short value; /* code of string so far. 0 if none. */
#undef TRIES
} TRIES;
/*
* Common/troublesome character definitions
*/
#define StringOf(ch) {ch, 0}
#define L_BRACE '{'
#define R_BRACE '}'
#define S_QUOTE '\''
#define D_QUOTE '"'
#define VT_ACSC "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~"
/*
* Structure for palette tables
*/
typedef struct
{
short red, green, blue; /* what color_content() returns */
short r, g, b; /* params to init_color() */
int init; /* true if we called init_color() */
}
color_t;
#define MAXCOLUMNS 135
#define MAXLINES 66
#define FIFO_SIZE MAXCOLUMNS+2 /* for nocbreak mode input */
#define ACS_LEN 128
#define WINDOWLIST struct _win_list
#if USE_WIDEC_SUPPORT
#define _nc_bkgd _bkgrnd
#else
#undef _XOPEN_SOURCE_EXTENDED
#undef _XPG5
#define _nc_bkgd _bkgd
#define wgetbkgrnd(win, wch) *wch = win->_bkgd
#define wbkgrnd wbkgd
#endif
#undef NCURSES_OPAQUE
#define NCURSES_INTERNALS 1
#define NCURSES_OPAQUE 0
#include <curses.h> /* we'll use -Ipath directive to get the right one! */
/*
* If curses.h did not expose the SCREEN-functions, then we do not need the
* parameter in the corresponding unextended functions.
*/
#define USE_SP_FUNC_SUPPORT NCURSES_SP_FUNCS
#define USE_EXT_SP_FUNC_SUPPORT (NCURSES_SP_FUNCS && NCURSES_EXT_FUNCS)
#if NCURSES_SP_FUNCS
#define SP_PARM sp /* use parameter */
#define NCURSES_SP_ARG SP_PARM
#define NCURSES_SP_DCL SCREEN *NCURSES_SP_ARG
#define NCURSES_SP_DCL0 NCURSES_SP_DCL
#define NCURSES_SP_ARGx NCURSES_SP_ARG,
#define NCURSES_SP_DCLx SCREEN *NCURSES_SP_ARGx
#else
#define SP_PARM SP /* use global variable */
#define NCURSES_SP_ARG
#define NCURSES_SP_DCL
#define NCURSES_SP_DCL0 void
#define NCURSES_SP_ARGx
#define NCURSES_SP_DCLx
#endif
#include <nc_panel.h>
#define IsPreScreen(sp) (((sp) != 0) && sp->_prescreen)
#define HasTerminal(sp) (((sp) != 0) && (0 != ((sp)->_term)))
#define IsValidScreen(sp) (HasTerminal(sp) && !IsPreScreen(sp))
#if BROKEN_LINKER || USE_REENTRANT
#define CurTerm _nc_prescreen._cur_term
#else
#define CurTerm cur_term
#endif
#if NCURSES_SP_FUNCS
#define TerminalOf(sp) ((sp) ? ((sp)->_term ? (sp)->_term : CurTerm) : CurTerm)
#else
#define TerminalOf(sp) CurTerm
#endif
#include <term.h>
/*
* Reduce dependency on cur_term global by using terminfo data from SCREEN's
* pointer to this data.
*/
#ifdef USE_SP_TERMTYPE
#undef CUR
#endif
#define SP_TERMTYPE TerminalOf(sp)->type.
#include <term_entry.h>
#include <nc_tparm.h>
/*
* Use these macros internally, to make tracing less verbose. But leave the
* option for compiling the tracing into the library.
*/
#if 1
#define ColorPair(n) NCURSES_BITS(n, 0)
#define PairNumber(a) (NCURSES_CAST(int,(((unsigned long)(a) & A_COLOR) >> NCURSES_ATTR_SHIFT)))
#else
#define ColorPair(pair) COLOR_PAIR(pair)
#define PairNumber(attr) PAIR_NUMBER(attr)
#endif
#define unColor(n) unColor2(AttrOf(n))
#define unColor2(a) ((a) & ALL_BUT_COLOR)
/*
* Extended-colors stores the color pair in a separate struct-member than the
* attributes. But for compatibility, we handle most cases where a program
* written for non-extended colors stores the color in the attributes by
* checking for a color pair in both places.
*/
#if NCURSES_EXT_COLORS
#define if_EXT_COLORS(stmt) stmt
#define SetPair(value,p) SetPair2((value).ext_color, AttrOf(value), p)
#define SetPair2(c,a,p) c = (p), \
a = (unColor2(a) | (A_COLOR & ColorPair(oldColor(c))))
#define GetPair(value) GetPair2((value).ext_color, AttrOf(value))
#define GetPair2(c,a) ((c) ? (c) : PairNumber(a))
#define oldColor(p) (((p) > 255) ? 255 : (p))
#define GET_WINDOW_PAIR(w) GetPair2((w)->_color, (w)->_attrs)
#define SET_WINDOW_PAIR(w,p) (w)->_color = (p)
#define SameAttrOf(a,b) (AttrOf(a) == AttrOf(b) && GetPair(a) == GetPair(b))
#if NCURSES_SP_FUNCS
#define VIDATTR(sp,attr,pair) NCURSES_SP_NAME(vid_attr)(sp, attr, pair, 0)
#else
#define VIDATTR(sp,attr,pair) vid_attr(attr, pair, 0)
#endif
#else /* !NCURSES_EXT_COLORS */
#define if_EXT_COLORS(stmt) /* nothing */
#define SetPair(value,p) RemAttr(value, A_COLOR), \
SetAttr(value, AttrOf(value) | (A_COLOR & (attr_t) ColorPair(p)))
#define GetPair(value) PairNumber(AttrOf(value))
#define GET_WINDOW_PAIR(w) PairNumber(WINDOW_ATTRS(w))
#define SET_WINDOW_PAIR(w,p) WINDOW_ATTRS(w) &= ALL_BUT_COLOR, \
WINDOW_ATTRS(w) |= (A_COLOR & (attr_t) ColorPair(p))
#define SameAttrOf(a,b) (AttrOf(a) == AttrOf(b))
#if NCURSES_SP_FUNCS
#define VIDATTR(sp,attr,pair) NCURSES_SP_NAME(vidattr)(sp, attr)
#else
#define VIDATTR(sp,attr,pair) vidattr(attr)
#endif
#endif /* NCURSES_EXT_COLORS */
#if NCURSES_NO_PADDING
#define GetNoPadding(sp) ((sp) ? (sp)->_no_padding : _nc_prescreen._no_padding)
#define SetNoPadding(sp) _nc_set_no_padding(sp)
extern NCURSES_EXPORT(void) _nc_set_no_padding(SCREEN *);
#else
#define GetNoPadding(sp) FALSE
#define SetNoPadding(sp) /*nothing*/
#endif
#define WINDOW_ATTRS(w) ((w)->_attrs)
#define SCREEN_ATTRS(s) (*((s)->_current_attr))
#define GET_SCREEN_PAIR(s) GetPair(SCREEN_ATTRS(s))
#define SET_SCREEN_PAIR(s,p) SetPair(SCREEN_ATTRS(s), p)
#if USE_REENTRANT || NCURSES_SP_FUNCS
NCURSES_EXPORT(int *) _nc_ptr_Lines (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Cols (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Tabsize (SCREEN *);
NCURSES_EXPORT(int *) _nc_ptr_Escdelay (SCREEN *);
#endif
#if USE_REENTRANT
#define ptrLines(sp) (sp ? &(sp->_LINES) : &(_nc_prescreen._LINES))
#define ptrCols(sp) (sp ? &(sp->_COLS) : &(_nc_prescreen._COLS))
#define ptrTabsize(sp) (sp ? &(sp->_TABSIZE) : &(_nc_prescreen._TABSIZE))
#define ptrEscdelay(sp) (sp ? &(sp->_ESCDELAY) : &(_nc_prescreen._ESCDELAY))
#define SET_LINES(value) *_nc_ptr_Lines(SP_PARM) = value
#define SET_COLS(value) *_nc_ptr_Cols(SP_PARM) = value
#define SET_TABSIZE(value) *_nc_ptr_Tabsize(SP_PARM) = value
#define SET_ESCDELAY(value) *_nc_ptr_Escdelay(SP_PARM) = value
#else
#define ptrLines(sp) &LINES
#define ptrCols(sp) &COLS
#define ptrTabsize(sp) &TABSIZE
#define ptrEscdelay(sp) &ESCDELAY
#define SET_LINES(value) LINES = value
#define SET_COLS(value) COLS = value
#define SET_TABSIZE(value) TABSIZE = value
#define SET_ESCDELAY(value) ESCDELAY = value
#endif
#define TR_MUTEX(data) _tracef("%s@%d: me:%08lX COUNT:%2u/%2d/%6d/%2d/%s%9u: " #data, \
__FILE__, __LINE__, \
(unsigned long) (pthread_self()), \
data.__data.__lock, \
data.__data.__count, \
data.__data.__owner, \
data.__data.__kind, \
(data.__data.__nusers > 5) ? " OOPS " : "", \
data.__data.__nusers)
#define TR_GLOBAL_MUTEX(name) TR_MUTEX(_nc_globals.mutex_##name)
#if USE_WEAK_SYMBOLS
#if defined(__GNUC__)
# if defined __USE_ISOC99
# define _cat_pragma(exp) _Pragma(#exp)
# define _weak_pragma(exp) _cat_pragma(weak name)
# else
# define _weak_pragma(exp)
# endif
# define _declare(name) __extension__ extern __typeof__(name) name
# define weak_symbol(name) _weak_pragma(name) _declare(name) __attribute__((weak))
#endif
#endif
#ifdef USE_PTHREADS
#if USE_REENTRANT
#include <pthread.h>
extern NCURSES_EXPORT(void) _nc_init_pthreads(void);
extern NCURSES_EXPORT(void) _nc_mutex_init(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_lock(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_trylock(pthread_mutex_t *);
extern NCURSES_EXPORT(int) _nc_mutex_unlock(pthread_mutex_t *);
#define _nc_lock_global(name) _nc_mutex_lock(&_nc_globals.mutex_##name)
#define _nc_try_global(name) _nc_mutex_trylock(&_nc_globals.mutex_##name)
#define _nc_unlock_global(name) _nc_mutex_unlock(&_nc_globals.mutex_##name)
#else
#error POSIX threads requires --enable-reentrant option
#endif
#ifdef USE_PTHREADS
# if USE_WEAK_SYMBOLS
weak_symbol(pthread_sigmask);
weak_symbol(pthread_kill);
weak_symbol(pthread_self);
weak_symbol(pthread_equal);
weak_symbol(pthread_mutex_init);
weak_symbol(pthread_mutex_lock);
weak_symbol(pthread_mutex_unlock);
weak_symbol(pthread_mutex_trylock);
weak_symbol(pthread_mutexattr_settype);
weak_symbol(pthread_mutexattr_init);
extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
# undef sigprocmask
# define sigprocmask _nc_sigprocmask
# endif
#endif
#if HAVE_NANOSLEEP
#undef HAVE_NANOSLEEP
#define HAVE_NANOSLEEP 0 /* nanosleep suspends all threads */
#endif
#else /* !USE_PTHREADS */
#if USE_PTHREADS_EINTR
# if USE_WEAK_SYMBOLS
#include <pthread.h>
weak_symbol(pthread_sigmask);
weak_symbol(pthread_kill);
weak_symbol(pthread_self);
weak_symbol(pthread_equal);
extern NCURSES_EXPORT(int) _nc_sigprocmask(int, const sigset_t *, sigset_t *);
# undef sigprocmask
# define sigprocmask _nc_sigprocmask
# endif
#endif /* USE_PTHREADS_EINTR */
#define _nc_init_pthreads() /* nothing */
#define _nc_mutex_init(obj) /* nothing */
#define _nc_lock_global(name) /* nothing */
#define _nc_try_global(name) 0
#define _nc_unlock_global(name) /* nothing */
#endif /* USE_PTHREADS */
/*
* When using sp-funcs, locks are targeted to SCREEN-level granularity.
* So the locking is done in the non-sp-func (which calls the sp-func) rather
* than in the sp-func itself.
*
* Use the _nc_nonsp_XXX functions in the function using "NCURSES_SP_NAME()".
* Use the _nc_sp_XXX functions in the function using "#if NCURSES_SP_FUNCS".
*/
#if NCURSES_SP_FUNCS
#define _nc_nonsp_lock_global(name) /* nothing */
#define _nc_nonsp_try_global(name) 0
#define _nc_nonsp_unlock_global(name) /* nothing */
#define _nc_sp_lock_global(name) _nc_lock_global(name)
#define _nc_sp_try_global(name) _nc_try_global(name)
#define _nc_sp_unlock_global(name) _nc_unlock_global(name)
#else
#define _nc_nonsp_lock_global(name) _nc_lock_global(name)
#define _nc_nonsp_try_global(name) _nc_try_global(name)
#define _nc_nonsp_unlock_global(name) _nc_unlock_global(name)
#define _nc_sp_lock_global(name) /* nothing */
#define _nc_sp_try_global(name) 0
#define _nc_sp_unlock_global(name) /* nothing */
#endif
#if HAVE_GETTIMEOFDAY
# define PRECISE_GETTIME 1
# define TimeType struct timeval
#else
# define PRECISE_GETTIME 0
# define TimeType time_t
#endif
/*
* Definitions for color pairs
*/
typedef unsigned colorpair_t; /* type big enough to store PAIR_OF() */
#define C_SHIFT 9 /* we need more bits than there are colors */
#define C_MASK ((1 << C_SHIFT) - 1)
#define PAIR_OF(fg, bg) (colorpair_t) ((((fg) & C_MASK) << C_SHIFT) | ((bg) & C_MASK))
#define FORE_OF(c) (((c) >> C_SHIFT) & C_MASK)
#define BACK_OF(c) ((c) & C_MASK)
#define isDefaultColor(c) ((c) >= COLOR_DEFAULT || (c) < 0)
#define COLOR_DEFAULT C_MASK
#if defined(USE_BUILD_CC) || (defined(USE_TERMLIB) && !defined(NEED_NCURSES_CH_T))
#undef NCURSES_CH_T /* this is not a termlib feature */
#define NCURSES_CH_T void /* ...but we need a pointer in SCREEN */
#endif /* USE_TERMLIB */
#ifndef USE_TERMLIB
struct ldat
{
NCURSES_CH_T *text; /* text of the line */
NCURSES_SIZE_T firstchar; /* first changed character in the line */
NCURSES_SIZE_T lastchar; /* last changed character in the line */
NCURSES_SIZE_T oldindex; /* index of the line at last update */
};
#endif /* USE_TERMLIB */
typedef enum {
M_XTERM = -1 /* use xterm's mouse tracking? */
,M_NONE = 0 /* no mouse device */
#if USE_GPM_SUPPORT
,M_GPM /* use GPM */
#endif
#if USE_SYSMOUSE
,M_SYSMOUSE /* FreeBSD sysmouse on console */
#endif
#ifdef USE_TERM_DRIVER
,M_TERM_DRIVER /* Win32 console, etc */
#endif
} MouseType;
/*
* Structures for scrolling.
*/
typedef struct {
unsigned long hashval;
int oldcount, newcount;
int oldindex, newindex;
} HASHMAP;
/*
* Structures for soft labels.
*/
struct _SLK;
#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
typedef struct
{
char *ent_text; /* text for the label */
char *form_text; /* formatted text (left/center/...) */
int ent_x; /* x coordinate of this field */
char dirty; /* this label has changed */
char visible; /* field is visible */
} slk_ent;
typedef struct _SLK {
bool dirty; /* all labels have changed */
bool hidden; /* soft labels are hidden */
WINDOW *win;
slk_ent *ent;
short maxlab; /* number of available labels */
short labcnt; /* number of allocated labels */
short maxlen; /* length of labels */
NCURSES_CH_T attr; /* soft label attribute */
} SLK;
#endif /* USE_TERMLIB */
typedef struct {
WINDOW *win; /* the window used in the hook */
int line; /* lines to take, < 0 => from bottom*/
int (*hook)(WINDOW *, int); /* callback for user */
} ripoff_t;
#if USE_GPM_SUPPORT
#undef buttons /* term.h defines this, and gpm uses it! */
#include <gpm.h>
#ifdef HAVE_LIBDL
/* link dynamically to GPM */
typedef int *TYPE_gpm_fd;
typedef int (*TYPE_Gpm_Open) (Gpm_Connect *, int);
typedef int (*TYPE_Gpm_Close) (void);
typedef int (*TYPE_Gpm_GetEvent) (Gpm_Event *);
#define my_gpm_fd SP_PARM->_mouse_gpm_fd
#define my_Gpm_Open SP_PARM->_mouse_Gpm_Open
#define my_Gpm_Close SP_PARM->_mouse_Gpm_Close
#define my_Gpm_GetEvent SP_PARM->_mouse_Gpm_GetEvent
#else
/* link statically to GPM */
#define my_gpm_fd &gpm_fd
#define my_Gpm_Open Gpm_Open
#define my_Gpm_Close Gpm_Close
#define my_Gpm_GetEvent Gpm_GetEvent
#endif /* HAVE_LIBDL */
#endif /* USE_GPM_SUPPORT */
typedef struct {
long sequence;
bool last_used;
char *fix_sgr0; /* this holds the filtered sgr0 string */
char *last_bufp; /* help with fix_sgr0 leak */
TERMINAL *last_term;
} TGETENT_CACHE;
#define TGETENT_MAX 4
/*
* State of tparm().
*/
#define STACKSIZE 20
typedef struct {
union {
int num;
char *str;
} data;
bool num_type;
} STACK_FRAME;
#define NUM_VARS 26
typedef struct {
#ifdef TRACE
const char *tname;
#endif
const char *tparam_base;
STACK_FRAME stack[STACKSIZE];
int stack_ptr;
char *out_buff;
size_t out_size;
size_t out_used;
char *fmt_buff;
size_t fmt_size;
int dynamic_var[NUM_VARS];
int static_vars[NUM_VARS];
} TPARM_STATE;
typedef struct {
char *text;
size_t size;
} TRACEBUF;
/*
* The filesystem database normally uses a single-letter for the lower level
* of directories. Use a hexadecimal code for filesystems which do not
* preserve mixed-case names.
*/
#if MIXEDCASE_FILENAMES
#define LEAF_FMT "%c"
#define LEAF_LEN 1
#else
#define LEAF_FMT "%02x"
#define LEAF_LEN 2
#endif
/*
* TRACEMSE_FMT is no longer than 80 columns, there are 5 numbers that
* could at most have 10 digits, and the mask contains no more than 32 bits
* with each bit representing less than 15 characters. Usually the whole
* string is less than 80 columns, but this buffer size is an absolute
* limit.
*/
#define TRACEMSE_MAX (80 + (5 * 10) + (32 * 15))
#define TRACEMSE_FMT "id %2d at (%2d, %2d, %2d) state %4lx = {" /* } */
#ifdef USE_TERM_DRIVER
struct DriverTCB; /* Terminal Control Block forward declaration */
#define INIT_TERM_DRIVER() _nc_globals.term_driver = _nc_get_driver
#else
#define INIT_TERM_DRIVER() /* nothing */
#endif
/*
* Global data which is not specific to a screen.
*/
typedef struct {
SIG_ATOMIC_T have_sigwinch;
SIG_ATOMIC_T cleanup_nested;
bool init_signals;
bool init_screen;
const char *comp_sourcename;
char *comp_termtype;
bool have_tic_directory;
bool keep_tic_directory;
const char *tic_directory;
char *dbi_list;
int dbi_size;
char *first_name;
char **keyname_table;
int slk_format;
char *safeprint_buf;
size_t safeprint_used;
TGETENT_CACHE tgetent_cache[TGETENT_MAX];
int tgetent_index;
long tgetent_sequence;
#ifndef USE_SP_WINDOWLIST
WINDOWLIST *_nc_windowlist;
#define WindowList(sp) _nc_globals._nc_windowlist
#endif
#if USE_HOME_TERMINFO
char *home_terminfo;
#endif
#if !USE_SAFE_SPRINTF
int safeprint_cols;
int safeprint_rows;
#endif
#ifdef USE_TERM_DRIVER
int (*term_driver)(struct DriverTCB*, const char*, int*);
#endif
#ifdef TRACE
bool init_trace;
char trace_fname[PATH_MAX];
int trace_level;
FILE *trace_fp;
char *tracearg_buf;
size_t tracearg_used;
TRACEBUF *tracebuf_ptr;
size_t tracebuf_used;
char tracechr_buf[40];
char *tracedmp_buf;
size_t tracedmp_used;
unsigned char *tracetry_buf;
size_t tracetry_used;
char traceatr_color_buf[2][80];
int traceatr_color_sel;
int traceatr_color_last;
#if !defined(USE_PTHREADS) && USE_REENTRANT
int nested_tracef;
#endif
#endif /* TRACE */
#ifdef USE_PTHREADS
pthread_mutex_t mutex_curses;
pthread_mutex_t mutex_tst_tracef;
pthread_mutex_t mutex_tracef;
int nested_tracef;
int use_pthreads;
#define _nc_use_pthreads _nc_globals.use_pthreads
#endif
#if USE_PTHREADS_EINTR
pthread_t read_thread; /* The reading thread */
#endif
} NCURSES_GLOBALS;
extern NCURSES_EXPORT_VAR(NCURSES_GLOBALS) _nc_globals;
#define N_RIPS 5
/*
* Global data which can be swept up into a SCREEN when one is created.
* It may be modified before the next SCREEN is created.
*/
typedef struct {
bool use_env;
bool filter_mode;
attr_t previous_attr;
#ifndef USE_SP_RIPOFF
ripoff_t rippedoff[N_RIPS];
ripoff_t *rsp;
#endif
TPARM_STATE tparm_state;
TTY *saved_tty; /* savetty/resetty information */
#if NCURSES_NO_PADDING
bool _no_padding; /* flag to set if padding disabled */
#endif
NCURSES_SP_OUTC _outch; /* output handler if not putc */
#if BROKEN_LINKER || USE_REENTRANT
chtype *real_acs_map;
int _LINES;
int _COLS;
int _TABSIZE;
int _ESCDELAY;
TERMINAL *_cur_term;
#ifdef TRACE
long _outchars;
const char *_tputs_trace;
#endif
#endif
} NCURSES_PRESCREEN;
/*
* Use screen-specific ripoff data (for softkeys) rather than global.
*/
#ifdef USE_SP_RIPOFF
#define safe_ripoff_sp (sp)->rsp
#define safe_ripoff_stack (sp)->rippedoff
#else
#define safe_ripoff_sp _nc_prescreen.rsp
#define safe_ripoff_stack _nc_prescreen.rippedoff
#endif
extern NCURSES_EXPORT_VAR(NCURSES_PRESCREEN) _nc_prescreen;
/*
* The SCREEN structure.
*/
struct screen {
int _ifd; /* input file ptr for screen */
FILE *_ofp; /* output file ptr for screen */
char *_setbuf; /* buffered I/O for output */
bool _filtered; /* filter() was called */
bool _buffered; /* setvbuf uses _setbuf data */
bool _prescreen; /* is in prescreen phase */
bool _use_env; /* LINES & COLS from environment? */
int _checkfd; /* filedesc for typeahead check */
TERMINAL *_term; /* terminal type information */
TTY _saved_tty; /* savetty/resetty information */
NCURSES_SIZE_T _lines; /* screen lines */
NCURSES_SIZE_T _columns; /* screen columns */
NCURSES_SIZE_T _lines_avail; /* lines available for stdscr */
NCURSES_SIZE_T _topstolen; /* lines stolen from top */
WINDOW *_curscr; /* current screen */
WINDOW *_newscr; /* virtual screen to be updated to */
WINDOW *_stdscr; /* screen's full-window context */
#define CurScreen(sp) (sp)->_curscr
#define NewScreen(sp) (sp)->_newscr
#define StdScreen(sp) (sp)->_stdscr
TRIES *_keytry; /* "Try" for use with keypad mode */
TRIES *_key_ok; /* Disabled keys via keyok(,FALSE) */
bool _tried; /* keypad mode was initialized */
bool _keypad_on; /* keypad mode is currently on */
bool _called_wgetch; /* check for recursion in wgetch() */
int _fifo[FIFO_SIZE]; /* input push-back buffer */
short _fifohead, /* head of fifo queue */
_fifotail, /* tail of fifo queue */
_fifopeek, /* where to peek for next char */
_fifohold; /* set if breakout marked */
int _endwin; /* are we out of window mode? */
NCURSES_CH_T *_current_attr; /* holds current attributes set */
int _coloron; /* is color enabled? */
int _color_defs; /* are colors modified */
int _cursor; /* visibility of the cursor */
int _cursrow; /* physical cursor row */
int _curscol; /* physical cursor column */
bool _notty; /* true if we cannot switch non-tty */
int _nl; /* True if NL -> CR/NL is on */
int _raw; /* True if in raw mode */
int _cbreak; /* 1 if in cbreak mode */
/* > 1 if in halfdelay mode */
int _echo; /* True if echo on */
int _use_meta; /* use the meta key? */
struct _SLK *_slk; /* ptr to soft key struct / NULL */
int slk_format; /* selected format for this screen */
/* cursor movement costs; units are 10ths of milliseconds */
#if NCURSES_NO_PADDING
bool _no_padding; /* flag to set if padding disabled */
#endif
int _char_padding; /* cost of character put */
int _cr_cost; /* cost of (carriage_return) */
int _cup_cost; /* cost of (cursor_address) */
int _home_cost; /* cost of (cursor_home) */
int _ll_cost; /* cost of (cursor_to_ll) */
#if USE_HARD_TABS
int _ht_cost; /* cost of (tab) */
int _cbt_cost; /* cost of (backtab) */
#endif /* USE_HARD_TABS */
int _cub1_cost; /* cost of (cursor_left) */
int _cuf1_cost; /* cost of (cursor_right) */
int _cud1_cost; /* cost of (cursor_down) */
int _cuu1_cost; /* cost of (cursor_up) */
int _cub_cost; /* cost of (parm_cursor_left) */
int _cuf_cost; /* cost of (parm_cursor_right) */
int _cud_cost; /* cost of (parm_cursor_down) */
int _cuu_cost; /* cost of (parm_cursor_up) */
int _hpa_cost; /* cost of (column_address) */
int _vpa_cost; /* cost of (row_address) */
/* used in tty_update.c, must be chars */
int _ed_cost; /* cost of (clr_eos) */
int _el_cost; /* cost of (clr_eol) */
int _el1_cost; /* cost of (clr_bol) */
int _dch1_cost; /* cost of (delete_character) */
int _ich1_cost; /* cost of (insert_character) */
int _dch_cost; /* cost of (parm_dch) */
int _ich_cost; /* cost of (parm_ich) */
int _ech_cost; /* cost of (erase_chars) */
int _rep_cost; /* cost of (repeat_char) */
int _hpa_ch_cost; /* cost of (column_address) */
int _cup_ch_cost; /* cost of (cursor_address) */
int _cuf_ch_cost; /* cost of (parm_cursor_right) */
int _inline_cost; /* cost of inline-move */
int _smir_cost; /* cost of (enter_insert_mode) */
int _rmir_cost; /* cost of (exit_insert_mode) */
int _ip_cost; /* cost of (insert_padding) */
/* used in lib_mvcur.c */
char * _address_cursor;
/* used in tty_update.c */
int _scrolling; /* 1 if terminal's smart enough to */
/* used in lib_color.c */
color_t *_color_table; /* screen's color palette */
int _color_count; /* count of colors in palette */
colorpair_t *_color_pairs; /* screen's color pair list */
int _pair_count; /* count of color pairs */
int _pair_limit; /* actual limit of color-pairs */
#if NCURSES_EXT_FUNCS
bool _default_color; /* use default colors */
bool _has_sgr_39_49; /* has ECMA default color support */
int _default_fg; /* assumed default foreground */
int _default_bg; /* assumed default background */
int _default_pairs; /* count pairs using default color */
#endif
chtype _ok_attributes; /* valid attributes for terminal */
chtype _xmc_suppress; /* attributes to suppress if xmc */
chtype _xmc_triggers; /* attributes to process if xmc */
chtype * _acs_map; /* the real alternate-charset map */
bool * _screen_acs_map;
/* used in lib_vidattr.c */
bool _use_rmso; /* true if we may use 'rmso' */
bool _use_rmul; /* true if we may use 'rmul' */
/*
* These data correspond to the state of the idcok() and idlok()
* functions. A caveat is in order here: the XSI and SVr4
* documentation specify that these functions apply to the window which
* is given as an argument. However, ncurses implements this logic
* only for the newscr/curscr update process, _not_ per-window.
*/
bool _nc_sp_idlok;
bool _nc_sp_idcok;
/*
* These are the data that support the mouse interface.
*/
bool _mouse_initialized;
MouseType _mouse_type;
int _maxclick;
bool (*_mouse_event) (SCREEN *);
bool (*_mouse_inline)(SCREEN *);
bool (*_mouse_parse) (SCREEN *, int);
void (*_mouse_resume)(SCREEN *);
void (*_mouse_wrap) (SCREEN *);
int _mouse_fd; /* file-descriptor, if any */
bool _mouse_active; /* true if initialized */
mmask_t _mouse_mask;
NCURSES_CONST char *_mouse_xtermcap; /* string to enable/disable mouse */
MEVENT _mouse_events[EV_MAX]; /* hold the last mouse event seen */
MEVENT *_mouse_eventp; /* next free slot in event queue */
#if USE_GPM_SUPPORT
bool _mouse_gpm_loaded;
bool _mouse_gpm_found;
#ifdef HAVE_LIBDL
void *_dlopen_gpm;
TYPE_gpm_fd _mouse_gpm_fd;
TYPE_Gpm_Open _mouse_Gpm_Open;
TYPE_Gpm_Close _mouse_Gpm_Close;
TYPE_Gpm_GetEvent _mouse_Gpm_GetEvent;
#endif
Gpm_Connect _mouse_gpm_connect;
#endif /* USE_GPM_SUPPORT */
#if USE_EMX_MOUSE
int _emxmouse_wfd;
int _emxmouse_thread;
int _emxmouse_activated;
char _emxmouse_buttons[4];
#endif
#if USE_SYSMOUSE
MEVENT _sysmouse_fifo[FIFO_SIZE];
int _sysmouse_head;
int _sysmouse_tail;
int _sysmouse_char_width; /* character width */
int _sysmouse_char_height; /* character height */
int _sysmouse_old_buttons;
int _sysmouse_new_buttons;
#endif
#ifdef USE_TERM_DRIVER
MEVENT _drv_mouse_fifo[FIFO_SIZE];
int _drv_mouse_head;
int _drv_mouse_tail;
int _drv_mouse_old_buttons;
int _drv_mouse_new_buttons;
#endif
/*
* This supports automatic resizing
*/
#if USE_SIZECHANGE
int (*_resize)(NCURSES_SP_DCLx int y, int x);
#endif
/*
* These are data that support the proper handling of the panel stack on an
* per screen basis.
*/
struct panelhook _panelHook;
bool _sig_winch;
SCREEN *_next_screen;
/* hashes for old and new lines */
unsigned long *oldhash, *newhash;
HASHMAP *hashtab;
int hashtab_len;
int *_oldnum_list;
int _oldnum_size;
bool _cleanup; /* cleanup after int/quit signal */
NCURSES_SP_OUTC _outch; /* output handler if not putc */
int _legacy_coding; /* see use_legacy_coding() */
#if USE_REENTRANT
char _ttytype[NAMESIZE];
int _ESCDELAY;
int _TABSIZE;
int _LINES;
int _COLS;
#ifdef TRACE
long _outchars;
const char *_tputs_trace;
#endif
#endif
#ifdef TRACE
char tracechr_buf[40];
char tracemse_buf[TRACEMSE_MAX];
#endif
#ifdef USE_SP_WINDOWLIST
WINDOWLIST* _windowlist;
#define WindowList(sp) (sp)->_windowlist
#endif
NCURSES_OUTC jump;
ripoff_t rippedoff[N_RIPS];
ripoff_t *rsp;
/*
* ncurses/ncursesw are the same up to this point.
*/
#if USE_WIDEC_SUPPORT
/* recent versions of 'screen' have partially-working support for
* UTF-8, but do not permit ACS at the same time (see tty_update.c).
*/
bool _screen_acs_fix;
#endif
};
extern NCURSES_EXPORT_VAR(SCREEN *) _nc_screen_chain;
extern NCURSES_EXPORT_VAR(SIG_ATOMIC_T) _nc_have_sigwinch;
WINDOWLIST {
WINDOWLIST *next;
SCREEN *screen; /* screen containing the window */
WINDOW win; /* WINDOW_EXT() needs to account for offset */
#ifdef NCURSES_WIDECHAR
char addch_work[(MB_LEN_MAX * 9) + 1];
unsigned addch_used; /* number of bytes in addch_work[] */
int addch_x; /* x-position for addch_work[] */
int addch_y; /* y-position for addch_work[] */
#endif
};
#define WINDOW_EXT(w,m) (((WINDOWLIST *)((void *)((char *)(w) - offsetof(WINDOWLIST, win))))->m)
#define SP_PRE_INIT(sp) \
sp->_cursrow = -1; \
sp->_curscol = -1; \
sp->_nl = TRUE; \
sp->_raw = FALSE; \
sp->_cbreak = 0; \
sp->_echo = TRUE; \
sp->_fifohead = -1; \
sp->_endwin = TRUE; \
sp->_cursor = -1; \
WindowList(sp) = 0; \
sp->_outch = NCURSES_SP_NAME(_nc_outch); \
sp->jump = 0 \
/* usually in <limits.h> */
#ifndef UCHAR_MAX
#define UCHAR_MAX 255
#endif
/* The terminfo source is assumed to be 7-bit ASCII */
#define is7bits(c) ((unsigned)(c) < 128)
/* Checks for isprint() should be done on 8-bit characters (non-wide) */
#define is8bits(c) ((unsigned)(c) <= UCHAR_MAX)
#ifndef min
#define min(a,b) ((a) > (b) ? (b) : (a))
#endif
#ifndef max
#define max(a,b) ((a) < (b) ? (b) : (a))
#endif
/* usually in <unistd.h> */
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
#define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
#define STDERR_FILENO 2
#endif
#ifndef EXIT_SUCCESS
#define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
#define EXIT_FAILURE 1
#endif
#ifndef R_OK
#define R_OK 4 /* Test for read permission. */
#endif
#ifndef W_OK
#define W_OK 2 /* Test for write permission. */
#endif
#ifndef X_OK
#define X_OK 1 /* Test for execute permission. */
#endif
#ifndef F_OK
#define F_OK 0 /* Test for existence. */
#endif
#if HAVE_FCNTL_H
#include <fcntl.h> /* may define O_BINARY */
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifdef TRACE
#if USE_REENTRANT
#define COUNT_OUTCHARS(n) _nc_count_outchars(n);
#else
#define COUNT_OUTCHARS(n) _nc_outchars += (n);
#endif
#else
#define COUNT_OUTCHARS(n) /* nothing */
#endif
#define RESET_OUTCHARS() COUNT_OUTCHARS(-_nc_outchars)
#define UChar(c) ((unsigned char)(c))
#define UShort(c) ((unsigned short)(c))
#define ChCharOf(c) ((c) & (chtype)A_CHARTEXT)
#define ChAttrOf(c) ((c) & (chtype)A_ATTRIBUTES)
#ifndef MB_LEN_MAX
#define MB_LEN_MAX 8 /* should be >= MB_CUR_MAX, but that may be a function */
#endif
#if USE_WIDEC_SUPPORT /* { */
#define isEILSEQ(status) (((size_t)status == (size_t)-1) && (errno == EILSEQ))
#define init_mb(state) memset(&state, 0, sizeof(state))
#if NCURSES_EXT_COLORS
#define NulColor , 0
#else
#define NulColor /* nothing */
#endif
#define NulChar 0,0,0,0 /* FIXME: see CCHARW_MAX */
#define CharOf(c) ((c).chars[0])
#define AttrOf(c) ((c).attr)
#define AddAttr(c,a) AttrOf(c) |= ((a) & A_ATTRIBUTES)
#define RemAttr(c,a) AttrOf(c) &= ~((a) & A_ATTRIBUTES)
#define SetAttr(c,a) AttrOf(c) = ((a) & A_ATTRIBUTES) | WidecExt(c)
#define NewChar2(c,a) { a, { c, NulChar } NulColor }
#define NewChar(ch) NewChar2(ChCharOf(ch), ChAttrOf(ch))
#if CCHARW_MAX == 5
#define CharEq(a,b) (((a).attr == (b).attr) \
&& (a).chars[0] == (b).chars[0] \
&& (a).chars[1] == (b).chars[1] \
&& (a).chars[2] == (b).chars[2] \
&& (a).chars[3] == (b).chars[3] \
&& (a).chars[4] == (b).chars[4] \
if_EXT_COLORS(&& (a).ext_color == (b).ext_color))
#else
#define CharEq(a,b) (!memcmp(&(a), &(b), sizeof(a)))
#endif
#define SetChar(ch,c,a) do { \
NCURSES_CH_T *_cp = &ch; \
memset(_cp, 0, sizeof(ch)); \
_cp->chars[0] = (wchar_t) (c); \
_cp->attr = (a); \
if_EXT_COLORS(SetPair(ch, PairNumber(a))); \
} while (0)
#define CHREF(wch) (&wch)
#define CHDEREF(wch) (*wch)
#define ARG_CH_T NCURSES_CH_T *
#define CARG_CH_T const NCURSES_CH_T *
#define PUTC_DATA char PUTC_buf[MB_LEN_MAX]; int PUTC_i, PUTC_n; \
mbstate_t PUT_st; wchar_t PUTC_ch
#define PUTC_INIT init_mb (PUT_st)
#define PUTC(ch,b) do { if(!isWidecExt(ch)) { \
if (Charable(ch)) { \
fputc(CharOf(ch), b); \
COUNT_OUTCHARS(1); \
} else { \
PUTC_INIT; \
for (PUTC_i = 0; PUTC_i < CCHARW_MAX; ++PUTC_i) { \
PUTC_ch = (ch).chars[PUTC_i]; \
if (PUTC_ch == L'\0') \
break; \
PUTC_n = (int) wcrtomb(PUTC_buf, \
(ch).chars[PUTC_i], &PUT_st); \
if (PUTC_n <= 0) { \
if (PUTC_ch && is8bits(PUTC_ch) && PUTC_i == 0) \
putc(PUTC_ch,b); \
break; \
} \
IGNORE_RC(fwrite(PUTC_buf, (unsigned) PUTC_n, 1, b)); \
} \
COUNT_OUTCHARS(PUTC_i); \
} } } while (0)
#define BLANK NewChar2(' ', WA_NORMAL)
#define ZEROS NewChar2('\0', WA_NORMAL)
#define ISBLANK(ch) ((ch).chars[0] == L' ' && (ch).chars[1] == L'\0')
/*
* Wide characters cannot be represented in the A_CHARTEXT mask of
* attr_t's but an application might have set a narrow character there.
* But even in that case, it would only be a printable character, or
* zero. Otherwise we can use those bits to tell if a cell is the
* first or extension part of a wide character.
*/
#define WidecExt(ch) (int) (AttrOf(ch) & A_CHARTEXT)
#define isWidecBase(ch) (WidecExt(ch) == 1)
#define isWidecExt(ch) (WidecExt(ch) > 1 && WidecExt(ch) < 32)
#define SetWidecExt(dst, ext) AttrOf(dst) &= ~A_CHARTEXT, \
AttrOf(dst) |= (attr_t) (ext + 1)
#define if_WIDEC(code) code
#define Charable(ch) ((SP_PARM != 0 && SP_PARM->_legacy_coding) \
|| (AttrOf(ch) & A_ALTCHARSET) \
|| (!isWidecExt(ch) && \
(ch).chars[1] == L'\0' && \
_nc_is_charable(CharOf(ch))))
#define L(ch) L ## ch
#else /* }{ */
#define CharOf(c) ChCharOf(c)
#define AttrOf(c) ChAttrOf(c)
#define AddAttr(c,a) c |= (a)
#define RemAttr(c,a) c &= ~((a) & A_ATTRIBUTES)
#define SetAttr(c,a) c = ((c) & ~A_ATTRIBUTES) | (a)
#define NewChar(ch) (ch)
#define NewChar2(c,a) ((c) | (a))
#define CharEq(a,b) ((a) == (b))
#define SetChar(ch,c,a) ch = (c) | (a)
#define CHREF(wch) wch
#define CHDEREF(wch) wch
#define ARG_CH_T NCURSES_CH_T
#define CARG_CH_T NCURSES_CH_T
#define PUTC_DATA int data = 0
#define PUTC(ch,b) do { data = CharOf(ch); putc(data,b); } while (0)
#define BLANK (' '|A_NORMAL)
#define ZEROS ('\0'|A_NORMAL)
#define ISBLANK(ch) (CharOf(ch) == ' ')
#define isWidecExt(ch) (0)
#define if_WIDEC(code) /* nothing */
#define L(ch) ch
#endif /* } */
#define AttrOfD(ch) AttrOf(CHDEREF(ch))
#define CharOfD(ch) CharOf(CHDEREF(ch))
#define SetChar2(wch,ch) SetChar(wch,ChCharOf(ch),ChAttrOf(ch))
#define BLANK_ATTR A_NORMAL
#define BLANK_TEXT L(' ')
#define CHANGED -1
#define LEGALYX(w, y, x) \
((w) != 0 && \
((x) >= 0 && (x) <= (w)->_maxx && \
(y) >= 0 && (y) <= (w)->_maxy))
#define CHANGED_CELL(line,col) \
if (line->firstchar == _NOCHANGE) \
line->firstchar = line->lastchar = (NCURSES_SIZE_T) col; \
else if ((col) < line->firstchar) \
line->firstchar = (NCURSES_SIZE_T) col; \
else if ((col) > line->lastchar) \
line->lastchar = (NCURSES_SIZE_T) col
#define CHANGED_RANGE(line,start,end) \
if (line->firstchar == _NOCHANGE \
|| line->firstchar > (start)) \
line->firstchar = (NCURSES_SIZE_T) start; \
if (line->lastchar == _NOCHANGE \
|| line->lastchar < (end)) \
line->lastchar = (NCURSES_SIZE_T) end
#define CHANGED_TO_EOL(line,start,end) \
if (line->firstchar == _NOCHANGE \
|| line->firstchar > (start)) \
line->firstchar = (NCURSES_SIZE_T) start; \
line->lastchar = (NCURSES_SIZE_T) end
#define SIZEOF(v) (sizeof(v)/sizeof(v[0]))
#define FreeIfNeeded(p) if ((p) != 0) free(p)
/* FreeAndNull() is not a comma-separated expression because some compilers
* do not accept a mixture of void with values.
*/
#define FreeAndNull(p) free(p); p = 0
#include <nc_alloc.h>
/*
* TTY bit definition for converting tabs to spaces.
*/
#ifdef TAB3
# define OFLAGS_TABS TAB3 /* POSIX specifies TAB3 */
#else
# ifdef XTABS
# define OFLAGS_TABS XTABS /* XTABS is usually the "same" */
# else
# ifdef OXTABS
# define OFLAGS_TABS OXTABS /* the traditional BSD equivalent */
# else
# define OFLAGS_TABS 0
# endif
# endif
#endif
/*
* Standardize/simplify common loops
*/
#define each_screen(p) p = _nc_screen_chain; p != 0; p = (p)->_next_screen
#define each_window(sp,p) p = WindowList(sp); p != 0; p = (p)->next
#define each_ripoff(p) p = safe_ripoff_stack; (p - safe_ripoff_stack) < N_RIPS; ++p
/*
* Prefixes for call/return points of library function traces. We use these to
* instrument the public functions so that the traces can be easily transformed
* into regression scripts.
*/
#define T_CALLED(fmt) "called {" fmt
#define T_CREATE(fmt) "create :" fmt
#define T_RETURN(fmt) "return }" fmt
#ifdef TRACE
#if USE_REENTRANT
#define TPUTS_TRACE(s) _nc_set_tputs_trace(s);
#else
#define TPUTS_TRACE(s) _nc_tputs_trace = s;
#endif
#define START_TRACE() \
if ((_nc_tracing & TRACE_MAXIMUM) == 0) { \
int t = _nc_getenv_num("NCURSES_TRACE"); \
if (t >= 0) \
trace((unsigned) t); \
}
/*
* Many of the _tracef() calls use static buffers; lock the trace state before
* trying to fill them.
*/
#if USE_REENTRANT
#define USE_TRACEF(mask) _nc_use_tracef(mask)
extern NCURSES_EXPORT(int) _nc_use_tracef (unsigned);
extern NCURSES_EXPORT(void) _nc_locked_tracef (const char *, ...) GCC_PRINTFLIKE(1,2);
#else
#define USE_TRACEF(mask) (_nc_tracing & (mask))
#define _nc_locked_tracef _tracef
#endif
#define TR(n, a) if (USE_TRACEF(n)) _nc_locked_tracef a
#define T(a) TR(TRACE_CALLS, a)
#define TRACE_RETURN(value,type) return _nc_retrace_##type(value)
#define TRACE_RETURN2(value,dst,src) return _nc_retrace_##dst##_##src(value)
#define TRACE_RETURN_SP(value,type) return _nc_retrace_##type(SP_PARM, value)
#define NonNull(s) ((s) != 0 ? s : "<null>")
#define returnAttr(code) TRACE_RETURN(code,attr_t)
#define returnBits(code) TRACE_RETURN(code,unsigned)
#define returnBool(code) TRACE_RETURN(code,bool)
#define returnCPtr(code) TRACE_RETURN(code,cptr)
#define returnCVoidPtr(code) TRACE_RETURN(code,cvoid_ptr)
#define returnChar(code) TRACE_RETURN(code,char)
#define returnChtype(code) TRACE_RETURN(code,chtype)
#define returnCode(code) TRACE_RETURN(code,int)
#define returnIntAttr(code) TRACE_RETURN2(code,int,attr_t)
#define returnMMask(code) TRACE_RETURN_SP(code,mmask_t)
#define returnPtr(code) TRACE_RETURN(code,ptr)
#define returnSP(code) TRACE_RETURN(code,sp)
#define returnVoid T((T_RETURN(""))); return
#define returnVoidPtr(code) TRACE_RETURN(code,void_ptr)
#define returnWin(code) TRACE_RETURN(code,win)
extern NCURSES_EXPORT(NCURSES_BOOL) _nc_retrace_bool (NCURSES_BOOL);
extern NCURSES_EXPORT(NCURSES_CONST void *) _nc_retrace_cvoid_ptr (NCURSES_CONST void *);
extern NCURSES_EXPORT(SCREEN *) _nc_retrace_sp (SCREEN *);
extern NCURSES_EXPORT(WINDOW *) _nc_retrace_win (WINDOW *);
extern NCURSES_EXPORT(attr_t) _nc_retrace_attr_t (attr_t);
extern NCURSES_EXPORT(char *) _nc_retrace_ptr (char *);
extern NCURSES_EXPORT(char *) _nc_trace_ttymode(TTY *tty);
extern NCURSES_EXPORT(char *) _nc_varargs (const char *, va_list);
extern NCURSES_EXPORT(chtype) _nc_retrace_chtype (chtype);
extern NCURSES_EXPORT(const char *) _nc_altcharset_name(attr_t, chtype);
extern NCURSES_EXPORT(const char *) _nc_retrace_cptr (const char *);
extern NCURSES_EXPORT(char) _nc_retrace_char (char);
extern NCURSES_EXPORT(int) _nc_retrace_int (int);
extern NCURSES_EXPORT(int) _nc_retrace_int_attr_t (attr_t);
extern NCURSES_EXPORT(mmask_t) _nc_retrace_mmask_t (SCREEN *, mmask_t);
extern NCURSES_EXPORT(unsigned) _nc_retrace_unsigned (unsigned);
extern NCURSES_EXPORT(void *) _nc_retrace_void_ptr (void *);
extern NCURSES_EXPORT(void) _nc_fifo_dump (SCREEN *);
#if USE_REENTRANT
NCURSES_WRAPPED_VAR(long, _nc_outchars);
NCURSES_WRAPPED_VAR(const char *, _nc_tputs_trace);
#define _nc_outchars NCURSES_PUBLIC_VAR(_nc_outchars())
#define _nc_tputs_trace NCURSES_PUBLIC_VAR(_nc_tputs_trace())
extern NCURSES_EXPORT(void) _nc_set_tputs_trace (const char *);
extern NCURSES_EXPORT(void) _nc_count_outchars (long);
#else
extern NCURSES_EXPORT_VAR(const char *) _nc_tputs_trace;
extern NCURSES_EXPORT_VAR(long) _nc_outchars;
#endif
extern NCURSES_EXPORT_VAR(unsigned) _nc_tracing;
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(const char *) _nc_viswbuf2 (int, const wchar_t *);
extern NCURSES_EXPORT(const char *) _nc_viswbufn (const wchar_t *, int);
#endif
extern NCURSES_EXPORT(const char *) _nc_viscbuf2 (int, const NCURSES_CH_T *, int);
extern NCURSES_EXPORT(const char *) _nc_viscbuf (const NCURSES_CH_T *, int);
#else /* !TRACE */
#define START_TRACE() /* nothing */
#define T(a)
#define TR(n, a)
#define TPUTS_TRACE(s)
#define returnAttr(code) return code
#define returnBits(code) return code
#define returnBool(code) return code
#define returnCPtr(code) return code
#define returnCVoidPtr(code) return code
#define returnChar(code) return ((char) code)
#define returnChtype(code) return code
#define returnCode(code) return code
#define returnIntAttr(code) return code
#define returnMMask(code) return code
#define returnPtr(code) return code
#define returnSP(code) return code
#define returnVoid return
#define returnVoidPtr(code) return code
#define returnWin(code) return code
#endif /* TRACE/!TRACE */
/*
* Workaround for defective implementation of gcc attribute warn_unused_result
*/
#if defined(__GNUC__) && defined(_FORTIFY_SOURCE)
#define IGNORE_RC(func) errno = (int) func
#else
#define IGNORE_RC(func) (void) func
#endif /* gcc workarounds */
/*
* Return-codes for tgetent() and friends.
*/
#define TGETENT_YES 1 /* entry is found */
#define TGETENT_NO 0 /* entry is not found */
#define TGETENT_ERR -1 /* an error occurred */
extern NCURSES_EXPORT(const char *) _nc_visbuf2 (int, const char *);
extern NCURSES_EXPORT(const char *) _nc_visbufn (const char *, int);
#define EMPTY_MODULE(name) \
extern NCURSES_EXPORT(void) name (void); \
NCURSES_EXPORT(void) name (void) { }
#define ALL_BUT_COLOR ((chtype)~(A_COLOR))
#define NONBLANK_ATTR (A_NORMAL|A_BOLD|A_DIM|A_BLINK)
#define XMC_CHANGES(c) ((c) & SP_PARM->_xmc_suppress)
#define toggle_attr_on(S,at) {\
if (PairNumber(at) > 0) {\
(S) = ((S) & ALL_BUT_COLOR) | (attr_t) (at);\
} else {\
(S) |= (attr_t) (at);\
}\
TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
#define toggle_attr_off(S,at) {\
if (PairNumber(at) > 0) {\
(S) &= ~(at|A_COLOR);\
} else {\
(S) &= ~(at);\
}\
TR(TRACE_ATTRS, ("new attribute is %s", _traceattr((S))));}
#define DelCharCost(sp,count) \
((parm_dch != 0) \
? sp->_dch_cost \
: ((delete_character != 0) \
? (sp->_dch1_cost * count) \
: INFINITY))
#define InsCharCost(sp,count) \
((parm_ich != 0) \
? sp->_ich_cost \
: ((enter_insert_mode && exit_insert_mode) \
? sp->_smir_cost + sp->_rmir_cost + (sp->_ip_cost * count) \
: ((insert_character != 0) \
? ((sp->_ich1_cost + sp->_ip_cost) * count) \
: INFINITY)))
#if USE_XMC_SUPPORT
#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
attr_t chg = AttrOf(SCREEN_ATTRS(sp)); \
VIDATTR(sp, AttrOf(c), GetPair(c)); \
if (magic_cookie_glitch > 0 \
&& XMC_CHANGES((chg ^ AttrOf(SCREEN_ATTRS(sp))))) { \
T(("%s @%d before glitch %d,%d", \
__FILE__, __LINE__, \
sp->_cursrow, \
sp->_curscol)); \
NCURSES_SP_NAME(_nc_do_xmc_glitch)(NCURSES_SP_ARGx chg); \
} \
}
#else
#define UpdateAttrs(sp,c) if (!SameAttrOf(SCREEN_ATTRS(sp), c)) { \
VIDATTR(sp, AttrOf(c), GetPair(c)); \
}
#endif
/*
* Macros to make additional parameter to implement wgetch_events()
*/
#ifdef NCURSES_WGETCH_EVENTS
#define EVENTLIST_0th(param) param
#define EVENTLIST_1st(param) param
#define EVENTLIST_2nd(param) , param
#define TWAIT_MASK (TW_ANY | TW_EVENT)
#else
#define EVENTLIST_0th(param) void
#define EVENTLIST_1st(param) /* nothing */
#define EVENTLIST_2nd(param) /* nothing */
#define TWAIT_MASK TW_ANY
#endif
#if NCURSES_EXPANDED && NCURSES_EXT_FUNCS
#undef toggle_attr_on
#define toggle_attr_on(S,at) _nc_toggle_attr_on(&(S), at)
extern NCURSES_EXPORT(void) _nc_toggle_attr_on (attr_t *, attr_t);
#undef toggle_attr_off
#define toggle_attr_off(S,at) _nc_toggle_attr_off(&(S), at)
extern NCURSES_EXPORT(void) _nc_toggle_attr_off (attr_t *, attr_t);
#undef DelCharCost
#define DelCharCost(sp, count) NCURSES_SP_NAME(_nc_DelCharCost)(NCURSES_SP_ARGx count)
#undef InsCharCost
#define InsCharCost(sp, count) NCURSES_SP_NAME(_nc_InsCharCost)(NCURSES_SP_ARGx count)
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_DelCharCost) (NCURSES_SP_DCLx int _c);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_InsCharCost) (NCURSES_SP_DCLx int _c);
#undef UpdateAttrs
#define UpdateAttrs(sp,c) NCURSES_SP_NAME(_nc_UpdateAttrs)(NCURSES_SP_ARGx CHREF(c))
#if USE_WIDEC_SUPPORT || defined(NEED_NCURSES_CH_T)
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx CARG_CH_T _c);
#else
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_UpdateAttrs) (NCURSES_SP_DCLx chtype c);
#endif
#if NCURSES_SP_FUNCS
extern NCURSES_EXPORT(int) _nc_DelCharCost (int);
extern NCURSES_EXPORT(int) _nc_InsCharCost (int);
extern NCURSES_EXPORT(void) _nc_UpdateAttrs (CARG_CH_T);
#endif /* NCURSES_SP_FUNCS */
#else
extern NCURSES_EXPORT(void) _nc_expanded (void);
#endif
#if !NCURSES_EXT_FUNCS
#define set_escdelay(value) ESCDELAY = value
#endif
#if !HAVE_GETCWD
#define getcwd(buf,len) getwd(buf)
#endif
/* charable.c */
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(bool) _nc_is_charable(wchar_t);
extern NCURSES_EXPORT(int) _nc_to_char(wint_t);
extern NCURSES_EXPORT(wint_t) _nc_to_widechar(int);
#endif
/* comp_captab.c */
typedef struct {
short nte_name; /* offset of name to hash on */
int nte_type; /* BOOLEAN, NUMBER or STRING */
short nte_index; /* index of associated variable in its array */
short nte_link; /* index in table of next hash, or -1 */
} name_table_data;
typedef struct
{
short from;
short to;
short source;
} alias_table_data;
/* doupdate.c */
#if USE_XMC_SUPPORT
extern NCURSES_EXPORT(void) _nc_do_xmc_glitch (attr_t);
#endif
/* hardscroll.c */
#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
extern NCURSES_EXPORT(void) _nc_linedump (void);
#endif
/* lib_acs.c */
extern NCURSES_EXPORT(void) _nc_init_acs (void); /* corresponds to traditional 'init_acs()' */
extern NCURSES_EXPORT(int) _nc_msec_cost (const char *const, int); /* used by 'tack' program */
/* lib_addch.c */
#if USE_WIDEC_SUPPORT
NCURSES_EXPORT(int) _nc_build_wch(WINDOW *win, ARG_CH_T ch);
#endif
/* lib_addstr.c */
#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(int) _nc_wchstrlen(const cchar_t *);
#endif
/* lib_color.c */
extern NCURSES_EXPORT(bool) _nc_reset_colors(void);
/* lib_getch.c */
extern NCURSES_EXPORT(int) _nc_wgetch(WINDOW *, int *, int EVENTLIST_2nd(_nc_eventlist *));
/* lib_insch.c */
extern NCURSES_EXPORT(int) _nc_insert_ch(SCREEN *, WINDOW *, chtype);
/* lib_mvcur.c */
#define INFINITY 1000000 /* cost: too high to use */
extern NCURSES_EXPORT(void) _nc_mvcur_init (void);
extern NCURSES_EXPORT(void) _nc_mvcur_resume (void);
extern NCURSES_EXPORT(void) _nc_mvcur_wrap (void);
extern NCURSES_EXPORT(int) _nc_scrolln (int, int, int, int);
extern NCURSES_EXPORT(void) _nc_screen_init (void);
extern NCURSES_EXPORT(void) _nc_screen_resume (void);
extern NCURSES_EXPORT(void) _nc_screen_wrap (void);
/* lib_mouse.c */
extern NCURSES_EXPORT(bool) _nc_has_mouse (SCREEN *);
/* lib_mvcur.c */
#define INFINITY 1000000 /* cost: too high to use */
#define BAUDBYTE 9 /* 9 = 7 bits + 1 parity + 1 stop */
/* lib_setup.c */
extern NCURSES_EXPORT(char *) _nc_get_locale(void);
extern NCURSES_EXPORT(int) _nc_unicode_locale(void);
extern NCURSES_EXPORT(int) _nc_locale_breaks_acs(TERMINAL *);
extern NCURSES_EXPORT(int) _nc_setupterm(NCURSES_CONST char *, int, int *, bool);
extern NCURSES_EXPORT(void) _nc_tinfo_cmdch(TERMINAL *, char);
/* lib_set_term.c */
extern NCURSES_EXPORT(int) _nc_ripoffline(int, int(*)(WINDOW*, int));
/* lib_tstp.c */
#if USE_SIGWINCH
extern NCURSES_EXPORT(int) _nc_handle_sigwinch(SCREEN *);
#else
#define _nc_handle_sigwinch(a) /* nothing */
#endif
/* lib_wacs.c */
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(void) _nc_init_wacs(void);
#endif
typedef struct {
char *s_head; /* beginning of the string (may be null) */
char *s_tail; /* end of the string (may be null) */
size_t s_size; /* current remaining size available */
size_t s_init; /* total size available */
} string_desc;
/* strings.c */
extern NCURSES_EXPORT(string_desc *) _nc_str_init (string_desc *, char *, size_t);
extern NCURSES_EXPORT(string_desc *) _nc_str_null (string_desc *, size_t);
extern NCURSES_EXPORT(string_desc *) _nc_str_copy (string_desc *, string_desc *);
extern NCURSES_EXPORT(bool) _nc_safe_strcat (string_desc *, const char *);
extern NCURSES_EXPORT(bool) _nc_safe_strcpy (string_desc *, const char *);
#if !HAVE_STRSTR
#define strstr _nc_strstr
extern NCURSES_EXPORT(char *) _nc_strstr (const char *, const char *);
#endif
/* safe_sprintf.c */
extern NCURSES_EXPORT(char *) _nc_printf_string (const char *, va_list);
/* tries.c */
extern NCURSES_EXPORT(int) _nc_add_to_try (TRIES **, const char *, unsigned);
extern NCURSES_EXPORT(char *) _nc_expand_try (TRIES *, unsigned, int *, size_t);
extern NCURSES_EXPORT(int) _nc_remove_key (TRIES **, unsigned);
extern NCURSES_EXPORT(int) _nc_remove_string (TRIES **, const char *);
/* elsewhere ... */
extern NCURSES_EXPORT(ENTRY *) _nc_delink_entry (ENTRY *, TERMTYPE *);
extern NCURSES_EXPORT(SCREEN *) _nc_screen_of (WINDOW *);
extern NCURSES_EXPORT(TERMINAL*) _nc_get_cur_term (void);
extern NCURSES_EXPORT(WINDOW *) _nc_makenew (int, int, int, int, int);
extern NCURSES_EXPORT(char *) _nc_trace_buf (int, size_t);
extern NCURSES_EXPORT(char *) _nc_trace_bufcat (int, const char *);
extern NCURSES_EXPORT(char *) _nc_tracechar (SCREEN *, int);
extern NCURSES_EXPORT(char *) _nc_tracemouse (SCREEN *, MEVENT const *);
extern NCURSES_EXPORT(int) _nc_access (const char *, int);
extern NCURSES_EXPORT(int) _nc_baudrate (int);
extern NCURSES_EXPORT(int) _nc_freewin (WINDOW *);
extern NCURSES_EXPORT(int) _nc_getenv_num (const char *);
extern NCURSES_EXPORT(int) _nc_keypad (SCREEN *, bool);
extern NCURSES_EXPORT(int) _nc_ospeed (int);
extern NCURSES_EXPORT(int) _nc_outch (int);
extern NCURSES_EXPORT(int) _nc_putp(const char *, const char *);
extern NCURSES_EXPORT(int) _nc_putp_flush(const char *, const char *);
extern NCURSES_EXPORT(int) _nc_read_termcap_entry (const char *const, TERMTYPE *const);
extern NCURSES_EXPORT(int) _nc_setupscreen (int, int, FILE *, bool, int);
extern NCURSES_EXPORT(int) _nc_setup_tinfo(const char *, TERMTYPE *);
extern NCURSES_EXPORT(int) _nc_timed_wait (SCREEN *, int, int, int * EVENTLIST_2nd(_nc_eventlist *));
extern NCURSES_EXPORT(void) _nc_do_color (short, short, bool, NCURSES_OUTC);
extern NCURSES_EXPORT(void) _nc_flush (void);
extern NCURSES_EXPORT(void) _nc_free_and_exit (int) GCC_NORETURN;
extern NCURSES_EXPORT(void) _nc_free_entry (ENTRY *, TERMTYPE *);
extern NCURSES_EXPORT(void) _nc_freeall (void);
extern NCURSES_EXPORT(void) _nc_hash_map (void);
extern NCURSES_EXPORT(void) _nc_init_keytry (SCREEN *);
extern NCURSES_EXPORT(void) _nc_keep_tic_dir (const char *);
extern NCURSES_EXPORT(void) _nc_make_oldhash (int i);
extern NCURSES_EXPORT(void) _nc_scroll_oldhash (int n, int top, int bot);
extern NCURSES_EXPORT(void) _nc_scroll_optimize (void);
extern NCURSES_EXPORT(void) _nc_set_buffer (FILE *, bool);
extern NCURSES_EXPORT(void) _nc_signal_handler (bool);
extern NCURSES_EXPORT(void) _nc_synchook (WINDOW *);
extern NCURSES_EXPORT(void) _nc_trace_tries (TRIES *);
#if NO_LEAKS
extern NCURSES_EXPORT(void) _nc_alloc_entry_leaks(void);
extern NCURSES_EXPORT(void) _nc_captoinfo_leaks(void);
extern NCURSES_EXPORT(void) _nc_codes_leaks(void);
extern NCURSES_EXPORT(void) _nc_comp_captab_leaks(void);
extern NCURSES_EXPORT(void) _nc_comp_scan_leaks(void);
extern NCURSES_EXPORT(void) _nc_keyname_leaks(void);
extern NCURSES_EXPORT(void) _nc_names_leaks(void);
extern NCURSES_EXPORT(void) _nc_tgetent_leaks(void);
#endif
#if !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(NCURSES_CH_T) _nc_render (WINDOW *, NCURSES_CH_T);
extern NCURSES_EXPORT(int) _nc_waddch_nosync (WINDOW *, const NCURSES_CH_T);
extern NCURSES_EXPORT(void) _nc_scroll_window (WINDOW *, int const, NCURSES_SIZE_T const, NCURSES_SIZE_T const, NCURSES_CH_T);
#endif
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(int) _nc_insert_wch(WINDOW *, const cchar_t *);
#endif
#if USE_WIDEC_SUPPORT && !(defined(USE_TERMLIB) || defined(USE_BUILD_CC))
extern NCURSES_EXPORT(size_t) _nc_wcrtomb (char *, wchar_t, mbstate_t *);
#endif
#if USE_SIZECHANGE
extern NCURSES_EXPORT(void) _nc_update_screensize (SCREEN *);
#endif
#if HAVE_RESIZETERM
extern NCURSES_EXPORT(void) _nc_resize_margins (WINDOW *);
#else
#define _nc_resize_margins(wp) /* nothing */
#endif
#ifdef NCURSES_WGETCH_EVENTS
extern NCURSES_EXPORT(int) _nc_eventlist_timeout(_nc_eventlist *);
#else
#define wgetch_events(win, evl) wgetch(win)
#define wgetnstr_events(win, str, maxlen, evl) wgetnstr(win, str, maxlen)
#endif
/*
* Wide-character macros to hide some platform-differences.
*/
#if USE_WIDEC_SUPPORT
#if HAVE_MBTOWC && HAVE_MBLEN
#define reset_mbytes(state) IGNORE_RC(mblen(NULL, 0)), IGNORE_RC(mbtowc(NULL, NULL, 0))
#define count_mbytes(buffer,length,state) mblen(buffer,length)
#define check_mbytes(wch,buffer,length,state) \
(int) mbtowc(&wch, buffer, length)
#define state_unused
#elif HAVE_MBRTOWC && HAVE_MBRLEN
#define reset_mbytes(state) init_mb(state)
#define count_mbytes(buffer,length,state) mbrlen(buffer,length,&state)
#define check_mbytes(wch,buffer,length,state) \
(int) mbrtowc(&wch, buffer, length, &state)
#else
make an error
#endif
#endif
/*
* Not everyone has vsscanf(), but we'd like to use it for scanw().
*/
#if !HAVE_VSSCANF
extern int vsscanf(const char *str, const char *format, va_list __arg);
#endif
/* scroll indices */
extern NCURSES_EXPORT_VAR(int *) _nc_oldnums;
#define USE_SETBUF_0 0
#define NC_BUFFERED(sp,flag) NCURSES_SP_NAME(_nc_set_buffer)(NCURSES_SP_ARGx sp->_ofp, flag)
#define NC_OUTPUT(sp) ((sp != 0) ? sp->_ofp : stdout)
/*
* On systems with a broken linker, define 'SP' as a function to force the
* linker to pull in the data-only module with 'SP'.
*/
#define _nc_alloc_screen_sp() typeCalloc(SCREEN, 1)
#if BROKEN_LINKER
#define SP _nc_screen()
extern NCURSES_EXPORT(SCREEN *) _nc_screen (void);
extern NCURSES_EXPORT(int) _nc_alloc_screen (void);
extern NCURSES_EXPORT(void) _nc_set_screen (SCREEN *);
#define CURRENT_SCREEN _nc_screen()
#else
/* current screen is private data; avoid possible linking conflicts too */
extern NCURSES_EXPORT_VAR(SCREEN *) SP;
#define CURRENT_SCREEN SP
#define _nc_alloc_screen() ((SP = _nc_alloc_screen_sp()) != 0)
#define _nc_set_screen(sp) SP = sp
#endif
#if NCURSES_SP_FUNCS
#define CURRENT_SCREEN_PRE (IsPreScreen(CURRENT_SCREEN) ? CURRENT_SCREEN : new_prescr())
#else
#define CURRENT_SCREEN_PRE CURRENT_SCREEN
#endif
/*
* We don't want to use the lines or columns capabilities internally, because
* if the application is running multiple screens under X, it's quite possible
* they could all have type xterm but have different sizes! So...
*/
#define screen_lines(sp) (sp)->_lines
#define screen_columns(sp) (sp)->_columns
extern NCURSES_EXPORT(int) _nc_slk_initialize (WINDOW *, int);
extern NCURSES_EXPORT(int) _nc_format_slks (NCURSES_SP_DCLx int _c);
/*
* Some constants related to SLK's
*/
#define MAX_SKEY_OLD 8 /* count of soft keys */
#define MAX_SKEY_LEN_OLD 8 /* max length of soft key text */
#define MAX_SKEY_PC 12 /* This is what most PC's have */
#define MAX_SKEY_LEN_PC 5
/* Macro to check whether or not we use a standard format */
#define SLK_STDFMT(fmt) (fmt < 3)
/* Macro to determine height of label window */
#define SLK_LINES(fmt) (SLK_STDFMT(fmt) ? 1 : ((fmt) - 2))
#define MAX_SKEY(fmt) (SLK_STDFMT(fmt)? MAX_SKEY_OLD : MAX_SKEY_PC)
#define MAX_SKEY_LEN(fmt) (SLK_STDFMT(fmt)? MAX_SKEY_LEN_OLD : MAX_SKEY_LEN_PC)
/*
* Common error messages
*/
#define MSG_NO_MEMORY "Out of memory"
#define MSG_NO_INPUTS "Premature EOF"
extern NCURSES_EXPORT(int) _nc_set_tty_mode(TTY *);
extern NCURSES_EXPORT(int) _nc_get_tty_mode(TTY *);
/* timed_wait flag definitions */
#define TW_NONE 0
#define TW_INPUT 1
#define TW_MOUSE 2
#define TW_ANY (TW_INPUT | TW_MOUSE)
#define TW_EVENT 4
#define SetSafeOutcWrapper(outc) \
SCREEN* sp = CURRENT_SCREEN; \
if (sp==0) { \
struct screen dummy; \
sp = &dummy; \
memset(sp,0,sizeof(struct screen)); \
sp->_outch = _nc_outc_wrapper; \
}\
sp->jump = outc
#ifdef USE_TERM_DRIVER
typedef void* TERM_HANDLE;
typedef struct _termInfo
{
bool caninit;
bool hascolor;
bool initcolor;
bool canchange;
int tabsize;
int maxcolors;
int maxpairs;
int nocolorvideo;
int numbuttons;
int numlabels;
int labelwidth;
int labelheight;
const color_t* defaultPalette;
} TerminalInfo;
typedef struct term_driver {
bool isTerminfo;
bool (*CanHandle)(struct DriverTCB*,const char*,int*);
void (*init)(struct DriverTCB*);
void (*release)(struct DriverTCB*);
int (*size)(struct DriverTCB*, int* Line, int *Cols);
int (*sgmode)(struct DriverTCB*, bool setFlag, TTY*);
chtype (*conattr)(struct DriverTCB*);
int (*hwcur)(struct DriverTCB*, int yold, int xold, int y, int x);
int (*mode)(struct DriverTCB*, bool progFlag, bool defFlag);
bool (*rescol)(struct DriverTCB*);
bool (*rescolors)(struct DriverTCB*);
void (*color)(struct DriverTCB*,bool fore, int color, int(*)(SCREEN*,int));
int (*doBeepOrFlash)(struct DriverTCB*, bool);
void (*initpair)(struct DriverTCB*,short,short,short);
void (*initcolor)(struct DriverTCB*,short,short,short,short);
void (*docolor)(struct DriverTCB*,short,short,bool,int(*)(SCREEN*,int));
void (*initmouse)(struct DriverTCB*);
int (*testmouse)(struct DriverTCB*,int);
void (*setfilter)(struct DriverTCB*);
void (*hwlabel)(struct DriverTCB*,int,char*);
void (*hwlabelOnOff)(struct DriverTCB*,bool);
int (*update)(struct DriverTCB*);
int (*defaultcolors)(struct DriverTCB*,int,int);
int (*print)(struct DriverTCB*,char*,int);
int (*getsize)(struct DriverTCB*,int*,int*);
int (*setsize)(struct DriverTCB*,int,int);
void (*initacs)(struct DriverTCB*,chtype*,chtype*);
void (*scinit)(SCREEN *);
void (*scexit)(SCREEN *);
int (*twait)(struct DriverTCB*,int,int,int* EVENTLIST_2nd(_nc_eventlist*));
int (*read)(struct DriverTCB*,int*);
int (*nap)(struct DriverTCB*,int);
int (*kpad)(struct DriverTCB*, bool);
int (*kyOk)(struct DriverTCB*, int, bool);
bool (*kyExist)(struct DriverTCB*, int);
} TERM_DRIVER;
typedef struct DriverTCB
{
TERMINAL term; /* needs to be the first Element !!! */
TERM_HANDLE inp; /* The input handle of the Terminal */
TERM_HANDLE out; /* The output handle of the Terminal in shell mode */
TERM_HANDLE hdl; /* The output handle of the Terminal in prog mode */
TERM_DRIVER* drv; /* The driver for that Terminal */
SCREEN* csp; /* The screen that owns that Terminal */
TerminalInfo info; /* Driver independent core capabilities of the Terminal */
void* prop; /* Driver dependent property storage to be used by the Driver */
long magic;
} TERMINAL_CONTROL_BLOCK;
#define NCDRV_MAGIC(id) (0x47110000 | (id&0xffff))
#define NCDRV_TINFO 0x01
#define NCDRV_WINCONSOLE 0x02
#define TCBOf(sp) ((TERMINAL_CONTROL_BLOCK*)(TerminalOf(sp)))
#define InfoOf(sp) TCBOf(sp)->info
#define CallDriver(sp,method) TCBOf(sp)->drv->method(TCBOf(sp))
#define CallDriver_1(sp,method,arg1) TCBOf(sp)->drv->method(TCBOf(sp),arg1)
#define CallDriver_2(sp,method,arg1,arg2) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2)
#define CallDriver_3(sp,method,arg1,arg2,arg3) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3)
#define CallDriver_4(sp,method,arg1,arg2,arg3,arg4) TCBOf(sp)->drv->method(TCBOf(sp),arg1,arg2,arg3,arg4)
extern NCURSES_EXPORT_VAR(const color_t*) _nc_cga_palette;
extern NCURSES_EXPORT_VAR(const color_t*) _nc_hls_palette;
extern NCURSES_EXPORT(int) _nc_get_driver(TERMINAL_CONTROL_BLOCK*, const char*, int*);
extern NCURSES_EXPORT(void) _nc_get_screensize_ex(SCREEN *, TERMINAL *, int *, int *);
#endif /* USE_TERM_DRIVER */
/*
* Entrypoints which are actually provided in the terminal driver, which would
* be an sp-name otherwise.
*/
#ifdef USE_TERM_DRIVER
#define TINFO_HAS_KEY _nc_tinfo_has_key
#define TINFO_DOUPDATE _nc_tinfo_doupdate
#define TINFO_MVCUR _nc_tinfo_mvcur
extern NCURSES_EXPORT(int) TINFO_HAS_KEY(SCREEN*, int);
extern NCURSES_EXPORT(int) TINFO_DOUPDATE(SCREEN *);
extern NCURSES_EXPORT(int) TINFO_MVCUR(SCREEN*, int, int, int, int);
#else
#define TINFO_HAS_KEY NCURSES_SP_NAME(has_key)
#define TINFO_DOUPDATE NCURSES_SP_NAME(doupdate)
#define TINFO_MVCUR NCURSES_SP_NAME(mvcur)
#endif
/*
* Entrypoints using an extra parameter with the terminal driver.
*/
#ifdef USE_TERM_DRIVER
extern NCURSES_EXPORT(void) _nc_get_screensize(SCREEN *, TERMINAL *, int *, int *);
extern NCURSES_EXPORT(int) _nc_setupterm_ex(TERMINAL **, NCURSES_CONST char *, int , int *, bool);
#define TINFO_GET_SIZE(sp, tp, lp, cp) \
_nc_get_screensize(sp, tp, lp, cp)
#define TINFO_SET_CURTERM(sp, tp) \
NCURSES_SP_NAME(set_curterm)(sp, tp)
#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
_nc_setupterm_ex(tpp, name, fd, err, reuse)
#else /* !USE_TERM_DRIVER */
extern NCURSES_EXPORT(void) _nc_get_screensize(SCREEN *, int *, int *);
#define TINFO_GET_SIZE(sp, tp, lp, cp) \
_nc_get_screensize(sp, lp, cp)
#define TINFO_SET_CURTERM(sp, tp) \
set_curterm(tp)
#define TINFO_SETUP_TERM(tpp, name, fd, err, reuse) \
_nc_setupterm(name, fd, err, reuse)
#endif /* !USE_TERM_DRIVER */
#ifdef USE_TERM_DRIVER
#ifdef __MINGW32__
#include <nc_mingw.h>
extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_WIN_DRIVER;
#endif
extern NCURSES_EXPORT_VAR(TERM_DRIVER) _nc_TINFO_DRIVER;
#endif
#ifdef USE_TERM_DRIVER
#define IsTermInfo(sp) (TCBOf(sp) && ((TCBOf(sp)->drv->isTerminfo)))
#else
#define IsTermInfo(sp) TRUE
#endif
#define HasTInfoTerminal(sp) ((0 != TerminalOf(sp)) && IsTermInfo(sp))
#define IsValidTIScreen(sp) (HasTInfoTerminal(sp))
/*
* Exported entrypoints beyond the published API
*/
#if NCURSES_SP_FUNCS
extern NCURSES_EXPORT(WINDOW *) _nc_curscr_of(SCREEN*);
extern NCURSES_EXPORT(WINDOW *) _nc_newscr_of(SCREEN*);
extern NCURSES_EXPORT(WINDOW *) _nc_stdscr_of(SCREEN*);
extern NCURSES_EXPORT(int) _nc_outc_wrapper(SCREEN*,int);
#if USE_REENTRANT
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_TABSIZE)(SCREEN*);
extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(longname)(SCREEN*);
#endif
#if NCURSES_EXT_FUNCS
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_set_tabsize)(SCREEN*, int);
#endif
/*
* We put the safe versions of various calls here as they are not published
* part of the API up to now
*/
extern NCURSES_EXPORT(TERMINAL*) NCURSES_SP_NAME(_nc_get_cur_term) (SCREEN *sp);
extern NCURSES_EXPORT(WINDOW *) NCURSES_SP_NAME(_nc_makenew) (SCREEN*, int, int, int, int, int);
extern NCURSES_EXPORT(bool) NCURSES_SP_NAME(_nc_reset_colors)(SCREEN*);
extern NCURSES_EXPORT(char *) NCURSES_SP_NAME(_nc_printf_string)(SCREEN*, const char *, va_list);
extern NCURSES_EXPORT(chtype) NCURSES_SP_NAME(_nc_acs_char)(SCREEN*,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_curs_set)(SCREEN*,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_get_tty_mode)(SCREEN*,TTY*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_mcprint)(SCREEN*,char*, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_msec_cost)(SCREEN*, const char *, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_outch)(SCREEN*, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_putp)(SCREEN*, const char *, const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_putp_flush)(SCREEN*, const char *, const char *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_resetty)(SCREEN*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_resize_term)(SCREEN*,int,int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_ripoffline)(SCREEN*, int, int (*)(WINDOW *,int));
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_savetty)(SCREEN*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scr_init)(SCREEN*,const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scr_restore)(SCREEN*, const char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_scrolln)(SCREEN*, int, int, int, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_set_tty_mode)(SCREEN*, TTY*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_setupscreen)(SCREEN**, int, int, FILE *, bool, int);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_tgetent)(SCREEN*,char*,const char *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_tigetnum)(SCREEN*,NCURSES_CONST char*);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_vid_attr)(SCREEN *, attr_t, short, void *);
extern NCURSES_EXPORT(int) NCURSES_SP_NAME(_nc_vidputs)(SCREEN*,chtype,int(*) (SCREEN*, int));
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_do_color)(SCREEN*, short, short, bool, NCURSES_SP_OUTC);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_do_xmc_glitch)(SCREEN*, attr_t);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_flush)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_free_and_exit)(SCREEN*, int) GCC_NORETURN;
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_freeall)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_hash_map)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_init_acs)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_make_oldhash)(SCREEN*, int i);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_init)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_resume)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_mvcur_wrap)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_init)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_resume)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_screen_wrap)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_scroll_oldhash)(SCREEN*, int n, int top, int bot);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_scroll_optimize)(SCREEN*);
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_set_buffer)(SCREEN*, FILE *, bool);
extern NCURSES_EXPORT(void) _nc_cookie_init(SCREEN *sp);
#if defined(TRACE) || defined(SCROLLDEBUG) || defined(HASHDEBUG)
extern NCURSES_EXPORT(void) NCURSES_SP_NAME(_nc_linedump)(SCREEN*);
#endif
#if USE_WIDEC_SUPPORT
extern NCURSES_EXPORT(wchar_t *) NCURSES_SP_NAME(_nc_wunctrl)(SCREEN*, cchar_t *);
#endif
#endif /* NCURSES_SP_FUNCS */
#if NCURSES_SP_FUNCS
#define safe_keyname NCURSES_SP_NAME(keyname)
#define safe_unctrl NCURSES_SP_NAME(unctrl)
#define safe_ungetch NCURSES_SP_NAME(ungetch)
#else
#define safe_keyname _nc_keyname
#define safe_unctrl _nc_unctrl
#define safe_ungetch _nc_ungetch
extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_keyname (SCREEN *, int);
extern NCURSES_EXPORT(int) _nc_ungetch (SCREEN *, int);
extern NCURSES_EXPORT(NCURSES_CONST char *) _nc_unctrl (SCREEN *, chtype);
#endif
#ifdef __cplusplus
}
#endif
/* *INDENT-ON* */
#endif /* CURSES_PRIV_H */
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 1998-2009,2010 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
* and: Eric S. Raymond <esr@snark.thyrsus.com> *
* and: Thomas E. Dickey 1996-on *
* and: Juergen Pfeifer *
****************************************************************************/
/*
** lib_mvwin.c
**
** The routine mvwin().
**
*/
#include <curses.priv.h>
MODULE_ID("$Id: lib_mvwin.c,v 1.18 2010/12/19 01:22:58 tom Exp $")
NCURSES_EXPORT(int)
mvwin(WINDOW *win, int by, int bx)
{
#if NCURSES_SP_FUNCS
SCREEN *sp = _nc_screen_of(win);
#endif
T((T_CALLED("mvwin(%p,%d,%d)"), (void *) win, by, bx));
if (!win || (win->_flags & _ISPAD))
returnCode(ERR);
/*
* mvwin() should only modify the indices. See test/demo_menus.c and
* test/movewindow.c for examples.
*/
#if 0
/* Copying subwindows is allowed, but it is expensive... */
if (win->_flags & _SUBWIN) {
int err = ERR;
WINDOW *parent = win->_parent;
if (parent) { /* Now comes the complicated and costly part, you should really
* try to avoid to move subwindows. Because a subwindow shares
* the text buffers with its parent, one can't do a simple
* memmove of the text buffers. One has to create a copy, then
* to relocate the subwindow and then to do a copy.
*/
if ((by - parent->_begy == win->_pary) &&
(bx - parent->_begx == win->_parx))
err = OK; /* we don't actually move */
else {
WINDOW *clone = dupwin(win);
if (clone) {
/* now we have the clone, so relocate win */
werase(win); /* Erase the original place */
/* fill with parents background */
wbkgrnd(win, CHREF(parent->_nc_bkgd));
wsyncup(win); /* Tell the parent(s) */
err = mvderwin(win,
by - parent->_begy,
bx - parent->_begx);
if (err != ERR) {
err = copywin(clone, win,
0, 0, 0, 0, win->_maxy, win->_maxx, 0);
if (ERR != err)
wsyncup(win);
}
if (ERR == delwin(clone))
err = ERR;
}
}
}
returnCode(err);
}
#endif
if (by + win->_maxy > screen_lines(SP_PARM) - 1
|| bx + win->_maxx > screen_columns(SP_PARM) - 1
|| by < 0
|| bx < 0)
returnCode(ERR);
/*
* Whether or not the window is moved, touch the window's contents so
* that a following call to 'wrefresh()' will paint the window at the
* new location. This ensures that if the caller has refreshed another
* window at the same location, that this one will be displayed.
*/
win->_begy = (NCURSES_SIZE_T) by;
win->_begx = (NCURSES_SIZE_T) bx;
returnCode(touchwin(win));
}
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Copyright (c) 1998-2007,2009 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************/
/****************************************************************************
* Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995 *
* and: Eric S. Raymond <esr@snark.thyrsus.com> *
* and: Juergen Pfeifer 1996-1999 *
* and: Thomas E. Dickey 1996-on *
****************************************************************************/
/*
* lib_slkclear.c
* Soft key routines.
* Remove soft labels from the screen.
*/
#include <curses.priv.h>
MODULE_ID("$Id: lib_slkclear.c,v 1.14 2009/11/07 16:27:05 tom Exp $")
NCURSES_EXPORT(int)
NCURSES_SP_NAME(slk_clear) (NCURSES_SP_DCL0)
{
int rc = ERR;
T((T_CALLED("slk_clear(%p)"), (void *) SP_PARM));
if (SP_PARM != 0 && SP_PARM->_slk != 0) {
SP_PARM->_slk->hidden = TRUE;
/* For simulated SLK's it looks much more natural to
inherit those attributes from the standard screen */
SP_PARM->_slk->win->_nc_bkgd = StdScreen(SP_PARM)->_nc_bkgd;
WINDOW_ATTRS(SP_PARM->_slk->win) = WINDOW_ATTRS(StdScreen(SP_PARM));
if (SP_PARM->_slk->win == StdScreen(SP_PARM)) {
rc = OK;
} else {
werase(SP_PARM->_slk->win);
rc = wrefresh(SP_PARM->_slk->win);
}
}
returnCode(rc);
}
#if NCURSES_SP_FUNCS
NCURSES_EXPORT(int)
slk_clear(void)
{
return NCURSES_SP_NAME(slk_clear) (CURRENT_SCREEN);
}
#endif
|
{
"pile_set_name": "Github"
}
|
/*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK 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 THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO 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 THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors:
* Gradient Systems
*/
#ifndef W_WEB_RETURNS_H
#define W_WEB_RETURNS_H
/*
* WEB_RETURNS table structure
*/
struct W_WEB_RETURNS_TBL {
ds_key_t wr_returned_date_sk;
ds_key_t wr_returned_time_sk;
ds_key_t wr_item_sk;
ds_key_t wr_refunded_customer_sk;
ds_key_t wr_refunded_cdemo_sk;
ds_key_t wr_refunded_hdemo_sk;
ds_key_t wr_refunded_addr_sk;
ds_key_t wr_returning_customer_sk;
ds_key_t wr_returning_cdemo_sk;
ds_key_t wr_returning_hdemo_sk;
ds_key_t wr_returning_addr_sk;
ds_key_t wr_web_page_sk;
ds_key_t wr_reason_sk;
ds_key_t wr_order_number;
ds_pricing_t wr_pricing;
};
int mk_w_web_returns(void *row, ds_key_t kIndex);
#endif
|
{
"pile_set_name": "Github"
}
|
export default {
'basic': 'Основні',
'advanced': 'Розширені',
'lab': 'Лабораторія',
'save': 'Зберігти та Застосувати',
'save-success-message': 'Налаштування збережено успішно',
'save-fail-message': 'Помилка при зберіганні налаштувань',
'discard': 'Відмінити',
'startup': 'Стартап',
'open-at-login': 'Запускати програму разом з запуском операційної системи',
'keep-window-state': 'Під час закриття додатка, зберігати розмір і положення вікна',
'auto-resume-all': 'Автоматично поновлювати всі невиконанні завдання',
'default-dir': 'Шлях за замовчуванням',
'mas-default-dir-tips': 'Через обмеження в App Store, рекомендовано встановити шлях за замовчення ~/Downloads',
'transfer-settings': 'Передача',
'transfer-speed-upload': 'Ліміт вивантаження',
'transfer-speed-download': 'Ліміт завантаження',
'transfer-speed-unlimited': 'Безлімітно',
'task-manage': 'Менеджер завдань',
'max-concurrent-downloads': 'Максимум активних завдань',
'max-connection-per-server': 'Максимум з\'єднання на сервер',
'new-task-show-downloading': 'Автоматично відображати завантаження після додавання завдання',
'no-confirm-before-delete-task': 'Перед видаленням завдання не потрібно підтверджувати',
'continue': 'Продовжити',
'task-completed-notify': 'Повідомлення після завершення завантаження',
'auto-purge-record': 'Автоматично чистити записи про завантаження перед закриттям додатка',
'ui': 'UI',
'appearance': 'Зовнішній вигляд',
'theme-auto': 'Автоматично',
'theme-light': 'Світлий',
'theme-dark': 'Темний',
'auto-hide-window': 'Автозахист вікон',
'run-mode': 'Виконати як',
'run-mode-standard': 'Стандартне застосування',
'run-mode-menu-bar': 'Застосування рядка меню',
'tray-speedometer': 'Лоток панелі меню показує швидкість у режимі реального часу',
'language': 'Мова',
'change-language': 'Змінити мову',
'hide-app-menu': 'Сховати меню додатка (Тільки для Windows та Linux)',
'proxy': 'Proxy',
'use-proxy': 'Застосувати Proxy',
'no-proxy-input-tips': 'Обхід налаштувань проксі для цих хостів та доменів, по одному на рядок',
'proxy-tips': 'Перегляньте посібник з проксі',
'bt-tracker': 'Tracker Сервер',
'bt-tracker-input-tips': 'Tracker сервера, один в рядок',
'bt-tracker-tips': 'Рекомендовано: ',
'sync-tracker-tips': 'Сінхронізуватись',
'auto-sync-tracker': 'Щодня оновлюйте список трекерів автоматично',
'port': 'Слухайте порти',
'bt-port': 'Порт прослуховування BT',
'dht-port': 'Порт прослуховування DHT',
'security': 'Безпека',
'rpc-secret': 'RPC Secret',
'rpc-secret-tips': 'Дивитись інструкцію RPC Secret',
'developer': 'Розробник',
'mock-user-agent': 'Макет User-Agent',
'app-log-path': 'Шлях до журналу додатка',
'download-session-path': 'Завантажити шлях сесії',
'factory-reset': 'Налаштування за замовчуванням',
'factory-reset-confirm': 'Ви впевненні, що бажаєте повернутись до налаштувань за замовчуванням?',
'lab-warning': '⚠️ Увімкнення функцій лабораторії може призвести до збою програми або втрати даних, вирішити на власний ризик!',
'download-protocol': 'Протоколи',
'protocols-default-client': 'Встановіть як клієнта за замовчуванням для таких протоколів',
'protocols-magnet': 'Magnet [ magnet:// ]',
'protocols-thunder': 'Thunder [ thunder:// ]',
'browser-extensions': 'Розширення',
'baidu-exporter': 'BaiduExporter',
'browser-extensions-tips': 'Надається спільнотою, ',
'baidu-exporter-help': 'Натисніть тут для використання',
'auto-update': 'Автоматичне оновлення',
'auto-check-update': 'Автоматично перевіряти оновлення',
'last-check-update-time': 'В останнє оновлення перевірялось'
}
|
{
"pile_set_name": "Github"
}
|
az: ադրբեջաներեն
az_AZ: 'ադրբեջաներեն (Ադրբեջան)'
az_Latn_AZ: 'ադրբեջաներեն (լատինական, Ադրբեջան)'
az_Latn: 'ադրբեջաներեն (լատինական)'
az_Cyrl_AZ: 'ադրբեջաներեն (կյուրեղագիր, Ադրբեջան)'
az_Cyrl: 'ադրբեջաներեն (կյուրեղագիր)'
sq: ալբաներեն
sq_AL: 'ալբաներեն (Ալբանիա)'
sq_XK: 'ալբաներեն (Կոսովո)'
sq_MK: 'ալբաներեն (Մակեդոնիա)'
am: ամհարերեն
am_ET: 'ամհարերեն (Եթովպիա)'
en: անգլերեն
en_US: 'անգլերեն (Ամերիկայի Միացյալ Նահանգներ)'
en_AS: 'անգլերեն (Ամերիկյան Սամոա)'
en_VI: 'անգլերեն (Ամերիկյան Վիրջինյան կղզիներ)'
en_AI: 'անգլերեն (Անգիլիա)'
en_AG: 'անգլերեն (Անտիգուա և Բարբուդա)'
en_AU: 'անգլերեն (Ավստրալիա)'
en_UM: 'անգլերեն (Արտաքին կղզիներ (ԱՄՆ))'
en_BS: 'անգլերեն (Բահամյան կղզիներ)'
en_BB: 'անգլերեն (Բարբադոս)'
en_BE: 'անգլերեն (Բելգիա)'
en_BZ: 'անգլերեն (Բելիզ)'
en_BM: 'անգլերեն (Բերմուդյան կղզիներ)'
en_BW: 'անգլերեն (Բոտսվանա)'
en_VG: 'անգլերեն (Բրիտանական Վիրջինյան կղզիներ)'
en_GM: 'անգլերեն (Գամբիա)'
en_GY: 'անգլերեն (Գայանա)'
en_GH: 'անգլերեն (Գանա)'
en_GG: 'անգլերեն (Գերնսի)'
en_GU: 'անգլերեն (Գուամ)'
en_GD: 'անգլերեն (Գրենադա)'
en_DG: 'անգլերեն (Դիեգո Գարսիա)'
en_DM: 'անգլերեն (Դոմինիկա)'
en_ZM: 'անգլերեն (Զամբիա)'
en_ZW: 'անգլերեն (Զիմբաբվե)'
en_ER: 'անգլերեն (Էրիտրեա)'
en_IE: 'անգլերեն (Իռլանդիա)'
en_LS: 'անգլերեն (Լեսոտո)'
en_LR: 'անգլերեն (Լիբերիա)'
en_CX: 'անգլերեն (Ծննդյան կղզի)'
en_CM: 'անգլերեն (Կամերուն)'
en_KY: 'անգլերեն (Կայմանյան կղզիներ)'
en_CA: 'անգլերեն (Կանադա)'
en_KI: 'անգլերեն (Կիրիբատի)'
en_CC: 'անգլերեն (Կոկոսյան (Քիլինգ) կղզիներ)'
en_CK: 'անգլերեն (Կուկի կղզիներ)'
en_SS: 'անգլերեն (Հարավային Սուդան)'
en_ZA: 'անգլերեն (Հարավաֆրիկյան Հանրապետություն)'
en_MP: 'անգլերեն (Հյուսիսային Մարիանյան կղզիներ)'
en_IO: 'անգլերեն (Հնդկական Օվկիանոսում Բրիտանական Տարածք)'
en_IN: 'անգլերեն (Հնդկաստան)'
en_HK: 'անգլերեն (Հոնկոնգի ՀՎՇ)'
en_MG: 'անգլերեն (Մադագասկար)'
en_MY: 'անգլերեն (Մալայզիա)'
en_MW: 'անգլերեն (Մալավի)'
en_MT: 'անգլերեն (Մալթա)'
en_MU: 'անգլերեն (Մավրիկիոս)'
en_MH: 'անգլերեն (Մարշալյան կղզիներ)'
en_IM: 'անգլերեն (Մեն կղզի)'
en_GB: 'անգլերեն (Միացյալ Թագավորություն)'
en_FM: 'անգլերեն (Միկրոնեզիա)'
en_MS: 'անգլերեն (Մոնտսերատ)'
en_NA: 'անգլերեն (Նամիբիա)'
en_NR: 'անգլերեն (Նաուրու)'
en_NG: 'անգլերեն (Նիգերիա)'
en_NU: 'անգլերեն (Նիուե)'
en_NZ: 'անգլերեն (Նոր Զելանդիա)'
en_NF: 'անգլերեն (Նորֆոլկ կղզի)'
en_UG: 'անգլերեն (Ուգանդա)'
en_MO: 'անգլերեն (Չինաստանի Մակաո ՀՎՇ)'
en_PW: 'անգլերեն (Պալաու)'
en_PK: 'անգլերեն (Պակիստան)'
en_PG: 'անգլերեն (Պապուա Նոր Գվինեա)'
en_PN: 'անգլերեն (Պիտկեռն կղզիներ)'
en_PR: 'անգլերեն (Պուերտո Ռիկո)'
en_JM: 'անգլերեն (Ջամայկա)'
en_JE: 'անգլերեն (Ջերսի)'
en_GI: 'անգլերեն (Ջիբրալթար)'
en_RW: 'անգլերեն (Ռուանդա)'
en_WS: 'անգլերեն (Սամոա)'
en_SC: 'անգլերեն (Սեյշելյան կղզիներ)'
en_LC: 'անգլերեն (Սենթ Լյուսիա)'
en_VC: 'անգլերեն (Սենթ Վիսենտ և Գրենադիններ)'
en_KN: 'անգլերեն (Սենթ Քիթս և Նևիս)'
en_SG: 'անգլերեն (Սինգապուր)'
en_SX: 'անգլերեն (Սինտ Մարտեն)'
en_SL: 'անգլերեն (Սյերա-Լեոնե)'
en_SB: 'անգլերեն (Սողոմոնյան կղզիներ)'
en_SD: 'անգլերեն (Սուդան)'
en_SH: 'անգլերեն (Սուրբ Հեղինեի կղզի)'
en_SZ: 'անգլերեն (Սվազիլենդ)'
en_VU: 'անգլերեն (Վանուատու)'
en_TZ: 'անգլերեն (Տանզանիա)'
en_TC: 'անգլերեն (Տերկս և Կայկոս կղզիներ)'
en_TK: 'անգլերեն (Տոկելաու)'
en_TO: 'անգլերեն (Տոնգա)'
en_TV: 'անգլերեն (Տուվալու)'
en_TT: 'անգլերեն (Տրինիդադ և Տոբագո)'
en_KE: 'անգլերեն (Քենիա)'
en_PH: 'անգլերեն (Ֆիլիպիններ)'
en_FJ: 'անգլերեն (Ֆիջի)'
en_FK: 'անգլերեն (Ֆոլկլենդյան կղզիներ)'
as: ասամերեն
as_IN: 'ասամերեն (Հնդկաստան)'
ar: արաբերեն
ar_DZ: 'արաբերեն (Ալժիր)'
ar_EH: 'արաբերեն (Արևմտյան Սահարա)'
ar_BH: 'արաբերեն (Բահրեյն)'
ar_EG: 'արաբերեն (Եգիպտոս)'
ar_YE: 'արաբերեն (Եմեն)'
ar_ER: 'արաբերեն (Էրիտրեա)'
ar_TN: 'արաբերեն (Թունիս)'
ar_IL: 'արաբերեն (Իսրայել)'
ar_IQ: 'արաբերեն (Իրաք)'
ar_LB: 'արաբերեն (Լիբանան)'
ar_LY: 'արաբերեն (Լիբիա)'
ar_QA: 'արաբերեն (Կատար)'
ar_KM: 'արաբերեն (Կոմորյան կղզիներ)'
ar_SS: 'արաբերեն (Հարավային Սուդան)'
ar_JO: 'արաբերեն (Հորդանան)'
ar_MR: 'արաբերեն (Մավրիտանիա)'
ar_MA: 'արաբերեն (Մարոկո)'
ar_AE: 'արաբերեն (Միացյալ Արաբական Էմիրություններ)'
ar_TD: 'արաբերեն (Չադ)'
ar_PS: 'արաբերեն (Պաղեստինյան տարածքներ)'
ar_DJ: 'արաբերեն (Ջիբուտի)'
ar_SA: 'արաբերեն (Սաուդյան Արաբիա)'
ar_SY: 'արաբերեն (Սիրիա)'
ar_SO: 'արաբերեն (Սոմալի)'
ar_SD: 'արաբերեն (Սուդան)'
ar_KW: 'արաբերեն (Քուվեյթ)'
ar_OM: 'արաբերեն (Օման)'
fy: 'արևմտյան ֆրիզերեն'
fy_NL: 'արևմտյան ֆրիզերեն (Նիդերլանդեր)'
ak: աքաներեն
ak_GH: 'աքաներեն (Գանա)'
af: աֆրիկաանս
af_ZA: 'աֆրիկաանս (Հարավաֆրիկյան Հանրապետություն)'
af_NA: 'աֆրիկաանս (Նամիբիա)'
bm: բամբարա
bm_Latn_ML: 'բամբարա (լատինական, Մալի)'
bm_Latn: 'բամբարա (լատինական)'
eu: բասկերեն
eu_ES: 'բասկերեն (Իսպանիա)'
be: բելառուսերեն
be_BY: 'բելառուսերեն (Բելառուս)'
bn: բենգալերեն
bn_BD: 'բենգալերեն (Բանգլադեշ)'
bn_IN: 'բենգալերեն (Հնդկաստան)'
my: բիրմայերեն
my_MM: 'բիրմայերեն (Մյանմա (Բիրմա))'
bs: բոսնիերեն
bs_BA: 'բոսնիերեն (Բոսնիա և Հերցեգովինա)'
bs_Latn_BA: 'բոսնիերեն (լատինական, Բոսնիա և Հերցեգովինա)'
bs_Latn: 'բոսնիերեն (լատինական)'
bs_Cyrl_BA: 'բոսնիերեն (կյուրեղագիր, Բոսնիա և Հերցեգովինա)'
bs_Cyrl: 'բոսնիերեն (կյուրեղագիր)'
bg: բուլղարերեն
bg_BG: 'բուլղարերեն (Բուլղարիա)'
br: բրետոներեն
br_FR: 'բրետոներեն (Ֆրանսիա)'
gl: գալիսերեն
gl_ES: 'գալիսերեն (Իսպանիա)'
lg: գանդա
lg_UG: 'գանդա (Ուգանդա)'
de: գերմաներեն
de_AT: 'գերմաներեն (Ավստրիա)'
de_BE: 'գերմաներեն (Բելգիա)'
de_DE: 'գերմաներեն (Գերմանիա)'
de_LI: 'գերմաներեն (Լիխտենշտեյն)'
de_LU: 'գերմաներեն (Լյուքսեմբուրգ)'
de_CH: 'գերմաներեն (Շվեյցարիա)'
gu: գուջարաթի
gu_IN: 'գուջարաթի (Հնդկաստան)'
da: դանիերեն
da_GL: 'դանիերեն (Գրենլանդիա)'
da_DK: 'դանիերեն (Դանիա)'
he: եբրայերեն
he_IL: 'եբրայերեն (Իսրայել)'
zu: զուլուսերեն
zu_ZA: 'զուլուսերեն (Հարավաֆրիկյան Հանրապետություն)'
eo: էսպերանտո
et: էստոներեն
et_EE: 'էստոներեն (Էստոնիա)'
ee: էվե
ee_GH: 'էվե (Գանա)'
ee_TG: 'էվե (Տոգո)'
ta: թամիլերեն
ta_IN: 'թամիլերեն (Հնդկաստան)'
ta_MY: 'թամիլերեն (Մալայզիա)'
ta_LK: 'թամիլերեն (Շրի Լանկա)'
ta_SG: 'թամիլերեն (Սինգապուր)'
th: թայերեն
th_TH: 'թայերեն (Թաիլանդ)'
te: թելուգու
te_IN: 'թելուգու (Հնդկաստան)'
ti: թիգրինիա
ti_ET: 'թիգրինիա (Եթովպիա)'
ti_ER: 'թիգրինիա (Էրիտրեա)'
tr: թուրքերեն
tr_TR: 'թուրքերեն (Թուրքիա)'
tr_CY: 'թուրքերեն (Կիպրոս)'
ig: իգբո
ig_NG: 'իգբո (Նիգերիա)'
id: ինդոնեզերեն
id_ID: 'ինդոնեզերեն (Ինդոնեզիա)'
ga: իռլանդերեն
ga_IE: 'իռլանդերեն (Իռլանդիա)'
is: իսլանդերեն
is_IS: 'իսլանդերեն (Իսլանդիա)'
es: իսպաներեն
es_US: 'իսպաներեն (Ամերիկայի Միացյալ Նահանգներ)'
es_AR: 'իսպաներեն (Արգենտինա)'
es_BO: 'իսպաներեն (Բոլիվիա)'
es_GT: 'իսպաներեն (Գվատեմալա)'
es_DO: 'իսպաներեն (Դոմինիկյան Հանրապետություն)'
es_EC: 'իսպաներեն (Էկվադոր)'
es_ES: 'իսպաներեն (Իսպանիա)'
es_IC: 'իսպաներեն (Կանարյան կղզիներ)'
es_CO: 'իսպաներեն (Կոլումբիա)'
es_CR: 'իսպաներեն (Կոստա-Ռիկա)'
es_CU: 'իսպաներեն (Կուբա)'
es_GQ: 'իսպաներեն (Հասարակածային Գվինեա)'
es_HN: 'իսպաներեն (Հոնդուրաս)'
es_MX: 'իսպաներեն (Մեքսիկա)'
es_NI: 'իսպաներեն (Նիկարագուա)'
es_UY: 'իսպաներեն (Ուրուգվայ)'
es_CL: 'իսպաներեն (Չիլի)'
es_PA: 'իսպաներեն (Պանամա)'
es_PY: 'իսպաներեն (Պարագվայ)'
es_PE: 'իսպաներեն (Պերու)'
es_PR: 'իսպաներեն (Պուերտո Ռիկո)'
es_SV: 'իսպաներեն (Սալվադոր)'
es_EA: 'իսպաներեն (Սեուտա և Մելիլյա)'
es_VE: 'իսպաներեն (Վենեսուելա)'
es_PH: 'իսպաներեն (Ֆիլիպիններ)'
it: իտալերեն
it_IT: 'իտալերեն (Իտալիա)'
it_CH: 'իտալերեն (Շվեյցարիա)'
it_SM: 'իտալերեն (Սան Մարինո)'
lo: լաոսերեն
lo_LA: 'լաոսերեն (Լաոս)'
lv: լատվիերեն
lv_LV: 'լատվիերեն (Լատվիա)'
pl: լեհերեն
pl_PL: 'լեհերեն (Լեհաստան)'
ln: լինգալա
ln_AO: 'լինգալա (Անգոլա)'
ln_CF: 'լինգալա (Կենտրոնական Աֆրիկյան Հանրապետություն)'
ln_CG: 'լինգալա (Կոնգո - Բրազավիլ)'
ln_CD: 'լինգալա (Կոնգո - Կինշասա)'
lt: լիտվերեն
lt_LT: 'լիտվերեն (Լիտվա)'
lb: լյուքսեմբուրգերեն
lb_LU: 'լյուքսեմբուրգերեն (Լյուքսեմբուրգ)'
lu: լուբա-կատանգա
lu_CD: 'լուբա-կատանգա (Կոնգո - Կինշասա)'
hr: խորվաթերեն
hr_BA: 'խորվաթերեն (Բոսնիա և Հերցեգովինա)'
hr_HR: 'խորվաթերեն (Խորվաթիա)'
kl: կալաալիսուտ
kl_GL: 'կալաալիսուտ (Գրենլանդիա)'
kn: կաննադա
kn_IN: 'կաննադա (Հնդկաստան)'
ca: կատալաներեն
ca_AD: 'կատալաներեն (Անդորա)'
ca_ES: 'կատալաներեն (Իսպանիա)'
ca_IT: 'կատալաներեն (Իտալիա)'
ca_FR: 'կատալաներեն (Ֆրանսիա)'
ki: կիկույու
ki_KE: 'կիկույու (Քենիա)'
kw: կոռներեն
kw_GB: 'կոռներեն (Միացյալ Թագավորություն)'
ko: կորեերեն
ko_KR: 'կորեերեն (Հարավային Կորեա)'
ko_KP: 'կորեերեն (Հյուսիսային Կորեա)'
hy: հայերեն
hy_AM: 'հայերեն (Հայաստան)'
ha: հաուսա
ha_GH: 'հաուսա (Գանա)'
ha_Latn_GH: 'հաուսա (լատինական, Գանա)'
ha_Latn_NE: 'հաուսա (լատինական, Նիգեր)'
ha_Latn_NG: 'հաուսա (լատինական, Նիգերիա)'
ha_Latn: 'հաուսա (լատինական)'
ha_NE: 'հաուսա (Նիգեր)'
ha_NG: 'հաուսա (Նիգերիա)'
hi: հինդի
hi_IN: 'հինդի (Հնդկաստան)'
nd: 'հյուսիսային նդեբելե'
nd_ZW: 'հյուսիսային նդեբելե (Զիմբաբվե)'
se: 'հյուսիսային սամի'
se_NO: 'հյուսիսային սամի (Նորվեգիա)'
se_SE: 'հյուսիսային սամի (Շվեդիա)'
se_FI: 'հյուսիսային սամի (Ֆինլանդիա)'
nl: հոլանդերեն
nl_AW: 'հոլանդերեն (Արուբա)'
nl_BE: 'հոլանդերեն (Բելգիա)'
nl_BQ: 'հոլանդերեն (Կարիբյան Նիդերլանդներ)'
nl_CW: 'հոլանդերեն (Կյուրասաո)'
nl_NL: 'հոլանդերեն (Նիդերլանդեր)'
nl_SX: 'հոլանդերեն (Սինտ Մարտեն)'
nl_SR: 'հոլանդերեն (Սուրինամ)'
el: հունարեն
el_CY: 'հունարեն (Կիպրոս)'
el_GR: 'հունարեն (Հունաստան)'
hu: հունգարերեն
hu_HU: 'հունգարերեն (Հունգարիա)'
kk: ղազախերեն
kk_Cyrl_KZ: 'ղազախերեն (կյուրեղագիր, Ղազախստան)'
kk_Cyrl: 'ղազախերեն (կյուրեղագիր)'
kk_KZ: 'ղազախերեն (Ղազախստան)'
ky: ղրղզերեն
ky_Cyrl_KG: 'ղրղզերեն (կյուրեղագիր, Ղրղզստան)'
ky_Cyrl: 'ղրղզերեն (կյուրեղագիր)'
ky_KG: 'ղրղզերեն (Ղրղզստան)'
ja: ճապոներեն
ja_JP: 'ճապոներեն (Ճապոնիա)'
mg: մալագասերեն
mg_MG: 'մալագասերեն (Մադագասկար)'
ml: մալայալամ
ml_IN: 'մալայալամ (Հնդկաստան)'
ms: մալայերեն
ms_BN: 'մալայերեն (Բրունեյ)'
ms_Latn_BN: 'մալայերեն (լատինական, Բրունեյ)'
ms_Latn_MY: 'մալայերեն (լատինական, Մալայզիա)'
ms_Latn_SG: 'մալայերեն (լատինական, Սինգապուր)'
ms_Latn: 'մալայերեն (լատինական)'
ms_MY: 'մալայերեն (Մալայզիա)'
ms_SG: 'մալայերեն (Սինգապուր)'
mt: մալթերեն
mt_MT: 'մալթերեն (Մալթա)'
mk: մակեդոներեն
mk_MK: 'մակեդոներեն (Մակեդոնիա)'
mr: մարաթի
mr_IN: 'մարաթի (Հնդկաստան)'
gv: մեներեն
gv_IM: 'մեներեն (Մեն կղզի)'
mn: մոնղոլերեն
mn_Cyrl_MN: 'մոնղոլերեն (կյուրեղագիր, Մոնղոլիա)'
mn_Cyrl: 'մոնղոլերեն (կյուրեղագիր)'
mn_MN: 'մոնղոլերեն (Մոնղոլիա)'
yo: յորուբա
yo_BJ: 'յորուբա (Բենին)'
yo_NG: 'յորուբա (Նիգերիա)'
ne: նեպալերեն
ne_IN: 'նեպալերեն (Հնդկաստան)'
ne_NP: 'նեպալերեն (Նեպալ)'
nb: 'նորվեգերեն բուկմոլ'
nb_NO: 'նորվեգերեն բուկմոլ (Նորվեգիա)'
nb_SJ: 'նորվեգերեն բուկմոլ (Սվալբարդ և Յան-Մայեն)'
nn: 'նորվեգերեն նյունորսկ'
nn_NO: 'նորվեգերեն նյունորսկ (Նորվեգիա)'
sn: շոնա
sn_ZW: 'շոնա (Զիմբաբվե)'
sv: շվեդերեն
sv_AX: 'շվեդերեն (Ալանդյան կղզիներ)'
sv_SE: 'շվեդերեն (Շվեդիա)'
sv_FI: 'շվեդերեն (Ֆինլանդիա)'
cy: ուելսերեն
cy_GB: 'ուելսերեն (Միացյալ Թագավորություն)'
uz: ուզբեկերեն
uz_Arab_AF: 'ուզբեկերեն (արաբական, Աֆղանստան)'
uz_Arab: 'ուզբեկերեն (արաբական)'
uz_AF: 'ուզբեկերեն (Աֆղանստան)'
uz_Latn_UZ: 'ուզբեկերեն (լատինական, Ուզբեկստան)'
uz_Latn: 'ուզբեկերեն (լատինական)'
uz_Cyrl_UZ: 'ուզբեկերեն (կյուրեղագիր, Ուզբեկստան)'
uz_Cyrl: 'ուզբեկերեն (կյուրեղագիր)'
uz_UZ: 'ուզբեկերեն (Ուզբեկստան)'
uk: ուկրաիներեն
uk_UA: 'ուկրաիներեն (Ուկրաինա)'
ug: ույղուրերեն
ug_Arab_CN: 'ույղուրերեն (արաբական, Չինաստան)'
ug_Arab: 'ույղուրերեն (արաբական)'
ug_CN: 'ույղուրերեն (Չինաստան)'
ur: ուրդու
ur_IN: 'ուրդու (Հնդկաստան)'
ur_PK: 'ուրդու (Պակիստան)'
cs: չեխերեն
cs_CZ: 'չեխերեն (Չեխիա)'
zh: չինարեն
zh_Hant_TW: 'չինարեն (ավանդական չինական, Թայվան)'
zh_Hant_HK: 'չինարեն (ավանդական չինական, Հոնկոնգի ՀՎՇ)'
zh_Hant_MO: 'չինարեն (ավանդական չինական, Չինաստանի Մակաո ՀՎՇ)'
zh_Hant: 'չինարեն (ավանդական չինական)'
zh_TW: 'չինարեն (Թայվան)'
zh_HK: 'չինարեն (Հոնկոնգի ՀՎՇ)'
zh_CN: 'չինարեն (Չինաստան)'
zh_MO: 'չինարեն (Չինաստանի Մակաո ՀՎՇ)'
zh_Hans_HK: 'չինարեն (պարզեցված չինական, Հոնկոնգի ՀՎՇ)'
zh_Hans_CN: 'չինարեն (պարզեցված չինական, Չինաստան)'
zh_Hans_MO: 'չինարեն (պարզեցված չինական, Չինաստանի Մակաո ՀՎՇ)'
zh_Hans_SG: 'չինարեն (պարզեցված չինական, Սինգապուր)'
zh_Hans: 'չինարեն (պարզեցված չինական)'
zh_SG: 'չինարեն (Սինգապուր)'
fa: պարսկերեն
fa_AF: 'պարսկերեն (Աֆղանստան)'
fa_IR: 'պարսկերեն (Իրան)'
pt: պորտուգալերեն
pt_AO: 'պորտուգալերեն (Անգոլա)'
pt_BR: 'պորտուգալերեն (Բրազիլիա)'
pt_GW: 'պորտուգալերեն (Գվինեա-Բիսաու)'
pt_TL: 'պորտուգալերեն (Թիմոր-Լեստե)'
pt_CV: 'պորտուգալերեն (Կաբո Վերդե)'
pt_MZ: 'պորտուգալերեն (Մոզամբիկ)'
pt_MO: 'պորտուգալերեն (Չինաստանի Մակաո ՀՎՇ)'
pt_PT: 'պորտուգալերեն (Պորտուգալիա)'
pt_ST: 'պորտուգալերեն (Սան Տոմե և Պրինսիպի)'
dz: ջոնգքհա
dz_BT: 'ջոնգքհա (Բութան)'
rm: ռոմանշերեն
rm_CH: 'ռոմանշերեն (Շվեյցարիա)'
ro: ռումիներեն
ro_MD: 'ռումիներեն (Մոլդովա)'
ro_RO: 'ռումիներեն (Ռումինիա)'
rn: ռունդի
rn_BI: 'ռունդի (Բուրունդի)'
ru: ռուսերեն
ru_BY: 'ռուսերեն (Բելառուս)'
ru_KZ: 'ռուսերեն (Ղազախստան)'
ru_KG: 'ռուսերեն (Ղրղզստան)'
ru_MD: 'ռուսերեն (Մոլդովա)'
ru_UA: 'ռուսերեն (Ուկրաինա)'
ru_RU: 'ռուսերեն (Ռուսաստան)'
sg: սանգո
sg_CF: 'սանգո (Կենտրոնական Աֆրիկյան Հանրապետություն)'
sr: սերբերեն
sr_BA: 'սերբերեն (Բոսնիա և Հերցեգովինա)'
sr_Latn_BA: 'սերբերեն (լատինական, Բոսնիա և Հերցեգովինա)'
sr_Latn_XK: 'սերբերեն (լատինական, Կոսովո)'
sr_Latn_ME: 'սերբերեն (լատինական, Չեռնոգորիա)'
sr_Latn_RS: 'սերբերեն (լատինական, Սերբիա)'
sr_Latn: 'սերբերեն (լատինական)'
sr_Cyrl_BA: 'սերբերեն (կյուրեղագիր, Բոսնիա և Հերցեգովինա)'
sr_Cyrl_XK: 'սերբերեն (կյուրեղագիր, Կոսովո)'
sr_Cyrl_ME: 'սերբերեն (կյուրեղագիր, Չեռնոգորիա)'
sr_Cyrl_RS: 'սերբերեն (կյուրեղագիր, Սերբիա)'
sr_Cyrl: 'սերբերեն (կյուրեղագիր)'
sr_XK: 'սերբերեն (Կոսովո)'
sr_ME: 'սերբերեն (Չեռնոգորիա)'
sr_RS: 'սերբերեն (Սերբիա)'
ii: 'սիխուան յի'
ii_CN: 'սիխուան յի (Չինաստան)'
si: սինհալերեն
si_LK: 'սինհալերեն (Շրի Լանկա)'
sk: սլովակերեն
sk_SK: 'սլովակերեն (Սլովակիա)'
sl: սլովեներեն
sl_SI: 'սլովեներեն (Սլովենիա)'
so: սոմալիերեն
so_ET: 'սոմալիերեն (Եթովպիա)'
so_DJ: 'սոմալիերեն (Ջիբուտի)'
so_SO: 'սոմալիերեն (Սոմալի)'
so_KE: 'սոմալիերեն (Քենիա)'
sw: սուահիլի
sw_UG: 'սուահիլի (Ուգանդա)'
sw_TZ: 'սուահիլի (Տանզանիա)'
sw_KE: 'սուահիլի (Քենիա)'
vi: վիետնամերեն
vi_VN: 'վիետնամերեն (Վիետնամ)'
ka: վրացերեն
ka_GE: 'վրացերեն (Վրաստան)'
bo: տիբեթերեն
bo_IN: 'տիբեթերեն (Հնդկաստան)'
bo_CN: 'տիբեթերեն (Չինաստան)'
to: տոնգա
to_TO: 'տոնգա (Տոնգա)'
pa: փենջաբերեն
pa_Arab_PK: 'փենջաբերեն (արաբական, Պակիստան)'
pa_Arab: 'փենջաբերեն (արաբական)'
pa_Guru_IN: 'փենջաբերեն (գուրմուխի, Հնդկաստան)'
pa_Guru: 'փենջաբերեն (գուրմուխի)'
pa_IN: 'փենջաբերեն (Հնդկաստան)'
pa_PK: 'փենջաբերեն (Պակիստան)'
ps: փուշթու
ps_AF: 'փուշթու (Աֆղանստան)'
ks: քաշմիրերեն
ks_Arab_IN: 'քաշմիրերեն (արաբական, Հնդկաստան)'
ks_Arab: 'քաշմիրերեն (արաբական)'
ks_IN: 'քաշմիրերեն (Հնդկաստան)'
qu: քեչուա
qu_BO: 'քեչուա (Բոլիվիա)'
qu_EC: 'քեչուա (Էկվադոր)'
qu_PE: 'քեչուա (Պերու)'
rw: քինյարվանդա
rw_RW: 'քինյարվանդա (Ռուանդա)'
km: քմերերեն
km_KH: 'քմերերեն (Կամբոջա)'
or: օրիյա
or_IN: 'օրիյա (Հնդկաստան)'
om: օրոմո
om_ET: 'օրոմո (Եթովպիա)'
om_KE: 'օրոմո (Քենիա)'
fo: ֆարյորերեն
fo_FO: 'ֆարյորերեն (Ֆարերյան կղզիներ)'
fi: ֆիններեն
fi_FI: 'ֆիններեն (Ֆինլանդիա)'
fr: ֆրանսերեն
fr_DZ: 'ֆրանսերեն (Ալժիր)'
fr_BE: 'ֆրանսերեն (Բելգիա)'
fr_BJ: 'ֆրանսերեն (Բենին)'
fr_BF: 'ֆրանսերեն (Բուրկինա Ֆասո)'
fr_BI: 'ֆրանսերեն (Բուրունդի)'
fr_GA: 'ֆրանսերեն (Գաբոն)'
fr_GP: 'ֆրանսերեն (Գվադելուպա)'
fr_GN: 'ֆրանսերեն (Գվինեա)'
fr_TN: 'ֆրանսերեն (Թունիս)'
fr_LU: 'ֆրանսերեն (Լյուքսեմբուրգ)'
fr_CM: 'ֆրանսերեն (Կամերուն)'
fr_CA: 'ֆրանսերեն (Կանադա)'
fr_CF: 'ֆրանսերեն (Կենտրոնական Աֆրիկյան Հանրապետություն)'
fr_KM: 'ֆրանսերեն (Կոմորյան կղզիներ)'
fr_CG: 'ֆրանսերեն (Կոնգո - Բրազավիլ)'
fr_CD: 'ֆրանսերեն (Կոնգո - Կինշասա)'
fr_HT: 'ֆրանսերեն (Հաիթի)'
fr_GQ: 'ֆրանսերեն (Հասարակածային Գվինեա)'
fr_MG: 'ֆրանսերեն (Մադագասկար)'
fr_ML: 'ֆրանսերեն (Մալի)'
fr_YT: 'ֆրանսերեն (Մայոտ)'
fr_MU: 'ֆրանսերեն (Մավրիկիոս)'
fr_MR: 'ֆրանսերեն (Մավրիտանիա)'
fr_MA: 'ֆրանսերեն (Մարոկո)'
fr_MQ: 'ֆրանսերեն (Մարտինիկա)'
fr_MC: 'ֆրանսերեն (Մոնակո)'
fr_NE: 'ֆրանսերեն (Նիգեր)'
fr_NC: 'ֆրանսերեն (Նոր Կալեդոնիա)'
fr_CH: 'ֆրանսերեն (Շվեյցարիա)'
fr_WF: 'ֆրանսերեն (Ուոլիս և Ֆուտունա)'
fr_TD: 'ֆրանսերեն (Չադ)'
fr_DJ: 'ֆրանսերեն (Ջիբուտի)'
fr_RE: 'ֆրանսերեն (Ռեյունիոն)'
fr_RW: 'ֆրանսերեն (Ռուանդա)'
fr_SC: 'ֆրանսերեն (Սեյշելյան կղզիներ)'
fr_MF: 'ֆրանսերեն (Սեն Մարտեն)'
fr_PM: 'ֆրանսերեն (Սեն Պիեր և Միկելոն)'
fr_SN: 'ֆրանսերեն (Սենեգալ)'
fr_SY: 'ֆրանսերեն (Սիրիա)'
fr_BL: 'ֆրանսերեն (Սուրբ Բարթողոմեոսի կղզի)'
fr_VU: 'ֆրանսերեն (Վանուատու)'
fr_TG: 'ֆրանսերեն (Տոգո)'
fr_CI: 'ֆրանսերեն (Փղոսկրի Ափ)'
fr_FR: 'ֆրանսերեն (Ֆրանսիա)'
fr_GF: 'ֆրանսերեն (Ֆրանսիական Գվիանա)'
fr_PF: 'ֆրանսերեն (Ֆրանսիական Պոլինեզիա)'
ff: Fulah
ff_CM: 'Fulah (Cameroon)'
ff_GN: 'Fulah (Guinea)'
ff_MR: 'Fulah (Mauritania)'
ff_SN: 'Fulah (Senegal)'
'no': Norwegian
no_NO: 'Norwegian (Norway)'
os: Ossetic
os_GE: 'Ossetic (Georgia)'
os_RU: 'Ossetic (Russia)'
gd: 'Scottish Gaelic'
gd_GB: 'Scottish Gaelic (United Kingdom)'
sh: Serbo-Croatian
sh_BA: 'Serbo-Croatian (Bosnia & Herzegovina)'
tl: Tagalog
tl_PH: 'Tagalog (Philippines)'
yi: Yiddish
|
{
"pile_set_name": "Github"
}
|
/* -------------------------------------------------------------------------- *
* OpenMMDrude *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit 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 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 "openmm/serialization/DrudeForceProxy.h"
#include "openmm/serialization/SerializationNode.h"
#include "openmm/Force.h"
#include "openmm/DrudeForce.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
DrudeForceProxy::DrudeForceProxy() : SerializationProxy("DrudeForce") {
}
void DrudeForceProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 1);
const DrudeForce& force = *reinterpret_cast<const DrudeForce*>(object);
SerializationNode& particles = node.createChildNode("Particles");
for (int i = 0; i < force.getNumParticles(); i++) {
int p, p1, p2, p3, p4;
double charge, polarizability, aniso12, aniso34;
force.getParticleParameters(i, p, p1, p2, p3, p4, charge, polarizability, aniso12, aniso34);
particles.createChildNode("Particle").setIntProperty("p", p).setIntProperty("p1", p1).setIntProperty("p2", p2).setIntProperty("p3", p3).setIntProperty("p4", p4)
.setDoubleProperty("charge", charge).setDoubleProperty("polarizability", polarizability).setDoubleProperty("a12", aniso12).setDoubleProperty("a34", aniso34);
}
SerializationNode& pairs = node.createChildNode("ScreenedPairs");
for (int i = 0; i < force.getNumScreenedPairs(); i++) {
int p1, p2;
double thole;
force.getScreenedPairParameters(i, p1, p2, thole);
pairs.createChildNode("Pair").setIntProperty("p1", p1).setIntProperty("p2", p2).setDoubleProperty("thole", thole);
}
}
void* DrudeForceProxy::deserialize(const SerializationNode& node) const {
if (node.getIntProperty("version") != 1)
throw OpenMMException("Unsupported version number");
DrudeForce* force = new DrudeForce();
try {
const SerializationNode& particles = node.getChildNode("Particles");
for (auto& particle : particles.getChildren())
force->addParticle(particle.getIntProperty("p"), particle.getIntProperty("p1"), particle.getIntProperty("p2"), particle.getIntProperty("p3"), particle.getIntProperty("p4"),
particle.getDoubleProperty("charge"), particle.getDoubleProperty("polarizability"), particle.getDoubleProperty("a12"), particle.getDoubleProperty("a34"));
const SerializationNode& pairs = node.getChildNode("ScreenedPairs");
for (auto& pair : pairs.getChildren())
force->addScreenedPair(pair.getIntProperty("p1"), pair.getIntProperty("p2"), pair.getDoubleProperty("thole"));
}
catch (...) {
delete force;
throw;
}
return force;
}
|
{
"pile_set_name": "Github"
}
|
British yachtsman Tony Bullimore's survival for four days in the icy Southern Ocean owes much to the high-tech safety equipment available to the modern sailor.
This year's London International Boat Show was crammed with gadgets such as the Emergency Position Indicating Radio Beacon (EPIRB). It costs 700 pounds ($1,176) but proved its worth by showing Bullimore's Australian rescuers where to look for him.
Bullimore's ordeal in the upturned hull of his yacht after it capsized in a solo round-the-world race is a far cry from the "Mediterranean marina" which was the centrepiece of this year's boat show at Earl's Court in west London.
Huge "Gin Palaces" abound but the show's organisers were keen to stress "messing about in boats" is not only for the rich.
The smallest vessel on show, the aptly-named Tadpole, was six foot (two metres) long and costs 297 pounds.
Around 800 boats were on display, 20 of them bobbing gently up and down in a giant indoor marina, built specially for the show, an annual event.
The 200,000 visitors had to wear slippers over their shoes to protect the polished decks if they wanted to go on board.
The British boating sector has a turnover of some two billion pounds and the boats on show were not just for dreaming about. Orders totalling millions of pounds were placed in the first week of the show, which ended on Sunday.
TRADITIONAL VERSUS HIGH-TECH EQUIPMENT
The halls were full of the paraphernalia of boating, with stands displaying traditional brass clocks and barometers competing with the latest in high-tech satellite navigation equipment.
If the latest in pump-action lavatories, the smoothest automatic winches or a machine that turns sea-water into drinking water is what you are after, this was the place to be.
Some firms demonstrated state-of-the-art sail materials, whose development owes much to the space programme. Others showed how traditional wooden "clinker" boat-building still has a place in the late 20th century.
The sunnier side of pleasure cruising was to the fore, but, topically, there were also tales of disaster and endeavour.
Among the speakers were a couple who 23 years ago spent four months drifting in the Pacific in a tiny inflatable life-raft.
Motor boats such as the sleek Sunseekers, the latest model of which, the Predator, sells for 1.8 million pounds, dominate one area, but most of the floorspace was dedicated to sailing.
SAILING REFLECTS BRITISH APPROACH TO THE SEA
This, says Tony Beechey, executive chairman of the British Marine Industries Federation, is in keeping with the British approach to the sea and reflects recent Olympic successes.
"Britons have always been more sail-oriented than power, maybe it is something to do with the climate...but we seem to have a stronger sailboat past," he told Reuters.
John Merricks, who with Ian Walker won a silver medal at the Atlanta Olympics in the 470 dinghy class, says boats need to keep evolving if sailing is to compete with other sports, even if this means his class is dropped after the 2000 games.
"It's harder to draw people into the sport with new outdoor activities competing against it," he said. "We need new, fast, exciting and colourful classes."
Many visitors made a beeline for the 49-er, recently selected as a new Olympic class and one of a new breed of "skiffs" --lightning-quick sailing dinghies which appear to fly across the water with both helmsman and crew suspended from trapezes.
They may cost just over 10,000 pounds, but Martin Wadhams of LDC Racing Sailboats which produces the space-age looking dinghy says fitness, skill and the agility of crews are what counts.
"The major thing about the boat is it brings the true spirit of the Olympics. It is going to spawn a new era in sailing." ($1=.5950 Pound)
|
{
"pile_set_name": "Github"
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:2.0.50727.5446
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace VolumeLight.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VolumeLight.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
# The MIT License
#
# Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:sorokh
#
# 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.
Back\ to\ List=Terug naar de lijst
Build\ History=Bouwhistoriek
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
"""
pygments.lexers._postgres_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Self-updating data files for PostgreSQL lexer.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Autogenerated: please edit them if you like wasting your time.
KEYWORDS = (
'ABORT',
'ABSOLUTE',
'ACCESS',
'ACTION',
'ADD',
'ADMIN',
'AFTER',
'AGGREGATE',
'ALL',
'ALSO',
'ALTER',
'ALWAYS',
'ANALYSE',
'ANALYZE',
'AND',
'ANY',
'ARRAY',
'AS',
'ASC',
'ASSERTION',
'ASSIGNMENT',
'ASYMMETRIC',
'AT',
'ATTRIBUTE',
'AUTHORIZATION',
'BACKWARD',
'BEFORE',
'BEGIN',
'BETWEEN',
'BIGINT',
'BINARY',
'BIT',
'BOOLEAN',
'BOTH',
'BY',
'CACHE',
'CALLED',
'CASCADE',
'CASCADED',
'CASE',
'CAST',
'CATALOG',
'CHAIN',
'CHAR',
'CHARACTER',
'CHARACTERISTICS',
'CHECK',
'CHECKPOINT',
'CLASS',
'CLOSE',
'CLUSTER',
'COALESCE',
'COLLATE',
'COLLATION',
'COLUMN',
'COMMENT',
'COMMENTS',
'COMMIT',
'COMMITTED',
'CONCURRENTLY',
'CONFIGURATION',
'CONNECTION',
'CONSTRAINT',
'CONSTRAINTS',
'CONTENT',
'CONTINUE',
'CONVERSION',
'COPY',
'COST',
'CREATE',
'CROSS',
'CSV',
'CURRENT',
'CURRENT_CATALOG',
'CURRENT_DATE',
'CURRENT_ROLE',
'CURRENT_SCHEMA',
'CURRENT_TIME',
'CURRENT_TIMESTAMP',
'CURRENT_USER',
'CURSOR',
'CYCLE',
'DATA',
'DATABASE',
'DAY',
'DEALLOCATE',
'DEC',
'DECIMAL',
'DECLARE',
'DEFAULT',
'DEFAULTS',
'DEFERRABLE',
'DEFERRED',
'DEFINER',
'DELETE',
'DELIMITER',
'DELIMITERS',
'DESC',
'DICTIONARY',
'DISABLE',
'DISCARD',
'DISTINCT',
'DO',
'DOCUMENT',
'DOMAIN',
'DOUBLE',
'DROP',
'EACH',
'ELSE',
'ENABLE',
'ENCODING',
'ENCRYPTED',
'END',
'ENUM',
'ESCAPE',
'EVENT',
'EXCEPT',
'EXCLUDE',
'EXCLUDING',
'EXCLUSIVE',
'EXECUTE',
'EXISTS',
'EXPLAIN',
'EXTENSION',
'EXTERNAL',
'EXTRACT',
'FALSE',
'FAMILY',
'FETCH',
'FILTER',
'FIRST',
'FLOAT',
'FOLLOWING',
'FOR',
'FORCE',
'FOREIGN',
'FORWARD',
'FREEZE',
'FROM',
'FULL',
'FUNCTION',
'FUNCTIONS',
'GLOBAL',
'GRANT',
'GRANTED',
'GREATEST',
'GROUP',
'HANDLER',
'HAVING',
'HEADER',
'HOLD',
'HOUR',
'IDENTITY',
'IF',
'ILIKE',
'IMMEDIATE',
'IMMUTABLE',
'IMPLICIT',
'IN',
'INCLUDING',
'INCREMENT',
'INDEX',
'INDEXES',
'INHERIT',
'INHERITS',
'INITIALLY',
'INLINE',
'INNER',
'INOUT',
'INPUT',
'INSENSITIVE',
'INSERT',
'INSTEAD',
'INT',
'INTEGER',
'INTERSECT',
'INTERVAL',
'INTO',
'INVOKER',
'IS',
'ISNULL',
'ISOLATION',
'JOIN',
'KEY',
'LABEL',
'LANGUAGE',
'LARGE',
'LAST',
'LATERAL',
'LC_COLLATE',
'LC_CTYPE',
'LEADING',
'LEAKPROOF',
'LEAST',
'LEFT',
'LEVEL',
'LIKE',
'LIMIT',
'LISTEN',
'LOAD',
'LOCAL',
'LOCALTIME',
'LOCALTIMESTAMP',
'LOCATION',
'LOCK',
'MAPPING',
'MATCH',
'MATERIALIZED',
'MAXVALUE',
'MINUTE',
'MINVALUE',
'MODE',
'MONTH',
'MOVE',
'NAME',
'NAMES',
'NATIONAL',
'NATURAL',
'NCHAR',
'NEXT',
'NO',
'NONE',
'NOT',
'NOTHING',
'NOTIFY',
'NOTNULL',
'NOWAIT',
'NULL',
'NULLIF',
'NULLS',
'NUMERIC',
'OBJECT',
'OF',
'OFF',
'OFFSET',
'OIDS',
'ON',
'ONLY',
'OPERATOR',
'OPTION',
'OPTIONS',
'OR',
'ORDER',
'ORDINALITY',
'OUT',
'OUTER',
'OVER',
'OVERLAPS',
'OVERLAY',
'OWNED',
'OWNER',
'PARSER',
'PARTIAL',
'PARTITION',
'PASSING',
'PASSWORD',
'PLACING',
'PLANS',
'POLICY',
'POSITION',
'PRECEDING',
'PRECISION',
'PREPARE',
'PREPARED',
'PRESERVE',
'PRIMARY',
'PRIOR',
'PRIVILEGES',
'PROCEDURAL',
'PROCEDURE',
'PROGRAM',
'QUOTE',
'RANGE',
'READ',
'REAL',
'REASSIGN',
'RECHECK',
'RECURSIVE',
'REF',
'REFERENCES',
'REFRESH',
'REINDEX',
'RELATIVE',
'RELEASE',
'RENAME',
'REPEATABLE',
'REPLACE',
'REPLICA',
'RESET',
'RESTART',
'RESTRICT',
'RETURNING',
'RETURNS',
'REVOKE',
'RIGHT',
'ROLE',
'ROLLBACK',
'ROW',
'ROWS',
'RULE',
'SAVEPOINT',
'SCHEMA',
'SCROLL',
'SEARCH',
'SECOND',
'SECURITY',
'SELECT',
'SEQUENCE',
'SEQUENCES',
'SERIALIZABLE',
'SERVER',
'SESSION',
'SESSION_USER',
'SET',
'SETOF',
'SHARE',
'SHOW',
'SIMILAR',
'SIMPLE',
'SMALLINT',
'SNAPSHOT',
'SOME',
'STABLE',
'STANDALONE',
'START',
'STATEMENT',
'STATISTICS',
'STDIN',
'STDOUT',
'STORAGE',
'STRICT',
'STRIP',
'SUBSTRING',
'SYMMETRIC',
'SYSID',
'SYSTEM',
'TABLE',
'TABLES',
'TABLESPACE',
'TEMP',
'TEMPLATE',
'TEMPORARY',
'TEXT',
'THEN',
'TIME',
'TIMESTAMP',
'TO',
'TRAILING',
'TRANSACTION',
'TREAT',
'TRIGGER',
'TRIM',
'TRUE',
'TRUNCATE',
'TRUSTED',
'TYPE',
'TYPES',
'UNBOUNDED',
'UNCOMMITTED',
'UNENCRYPTED',
'UNION',
'UNIQUE',
'UNKNOWN',
'UNLISTEN',
'UNLOGGED',
'UNTIL',
'UPDATE',
'USER',
'USING',
'VACUUM',
'VALID',
'VALIDATE',
'VALIDATOR',
'VALUE',
'VALUES',
'VARCHAR',
'VARIADIC',
'VARYING',
'VERBOSE',
'VERSION',
'VIEW',
'VIEWS',
'VOLATILE',
'WHEN',
'WHERE',
'WHITESPACE',
'WINDOW',
'WITH',
'WITHIN',
'WITHOUT',
'WORK',
'WRAPPER',
'WRITE',
'XML',
'XMLATTRIBUTES',
'XMLCONCAT',
'XMLELEMENT',
'XMLEXISTS',
'XMLFOREST',
'XMLPARSE',
'XMLPI',
'XMLROOT',
'XMLSERIALIZE',
'YEAR',
'YES',
'ZONE',
)
DATATYPES = (
'bigint',
'bigserial',
'bit',
'bit varying',
'bool',
'boolean',
'box',
'bytea',
'char',
'character',
'character varying',
'cidr',
'circle',
'date',
'decimal',
'double precision',
'float4',
'float8',
'inet',
'int',
'int2',
'int4',
'int8',
'integer',
'interval',
'json',
'jsonb',
'line',
'lseg',
'macaddr',
'money',
'numeric',
'path',
'pg_lsn',
'point',
'polygon',
'real',
'serial',
'serial2',
'serial4',
'serial8',
'smallint',
'smallserial',
'text',
'time',
'timestamp',
'timestamptz',
'timetz',
'tsquery',
'tsvector',
'txid_snapshot',
'uuid',
'varbit',
'varchar',
'with time zone',
'without time zone',
'xml',
)
PSEUDO_TYPES = (
'any',
'anyelement',
'anyarray',
'anynonarray',
'anyenum',
'anyrange',
'cstring',
'internal',
'language_handler',
'fdw_handler',
'record',
'trigger',
'void',
'opaque',
)
# Remove 'trigger' from types
PSEUDO_TYPES = tuple(sorted(set(PSEUDO_TYPES) - set(map(str.lower, KEYWORDS))))
PLPGSQL_KEYWORDS = (
'ALIAS', 'CONSTANT', 'DIAGNOSTICS', 'ELSIF', 'EXCEPTION', 'EXIT',
'FOREACH', 'GET', 'LOOP', 'NOTICE', 'OPEN', 'PERFORM', 'QUERY', 'RAISE',
'RETURN', 'REVERSE', 'SQLSTATE', 'WHILE',
)
if __name__ == '__main__': # pragma: no cover
import re
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
from pygments.util import format_lines
# One man's constant is another man's variable.
SOURCE_URL = 'https://github.com/postgres/postgres/raw/master'
KEYWORDS_URL = SOURCE_URL + '/doc/src/sgml/keywords.sgml'
DATATYPES_URL = SOURCE_URL + '/doc/src/sgml/datatype.sgml'
def update_myself():
data_file = list(urlopen(DATATYPES_URL))
datatypes = parse_datatypes(data_file)
pseudos = parse_pseudos(data_file)
keywords = parse_keywords(urlopen(KEYWORDS_URL))
update_consts(__file__, 'DATATYPES', datatypes)
update_consts(__file__, 'PSEUDO_TYPES', pseudos)
update_consts(__file__, 'KEYWORDS', keywords)
def parse_keywords(f):
kw = []
for m in re.finditer(
r'\s*<entry><token>([^<]+)</token></entry>\s*'
r'<entry>([^<]+)</entry>', f.read()):
kw.append(m.group(1))
if not kw:
raise ValueError('no keyword found')
kw.sort()
return kw
def parse_datatypes(f):
dt = set()
for line in f:
if '<sect1' in line:
break
if '<entry><type>' not in line:
continue
# Parse a string such as
# time [ (<replaceable>p</replaceable>) ] [ without time zone ]
# into types "time" and "without time zone"
# remove all the tags
line = re.sub("<replaceable>[^<]+</replaceable>", "", line)
line = re.sub("<[^>]+>", "", line)
# Drop the parts containing braces
for tmp in [t for tmp in line.split('[')
for t in tmp.split(']') if "(" not in t]:
for t in tmp.split(','):
t = t.strip()
if not t: continue
dt.add(" ".join(t.split()))
dt = list(dt)
dt.sort()
return dt
def parse_pseudos(f):
dt = []
re_start = re.compile(r'\s*<table id="datatype-pseudotypes-table">')
re_entry = re.compile(r'\s*<entry><type>([^<]+)</></entry>')
re_end = re.compile(r'\s*</table>')
f = iter(f)
for line in f:
if re_start.match(line) is not None:
break
else:
raise ValueError('pseudo datatypes table not found')
for line in f:
m = re_entry.match(line)
if m is not None:
dt.append(m.group(1))
if re_end.match(line) is not None:
break
else:
raise ValueError('end of pseudo datatypes table not found')
if not dt:
raise ValueError('pseudo datatypes not found')
return dt
def update_consts(filename, constname, content):
with open(filename) as f:
data = f.read()
# Line to start/end inserting
re_match = re.compile(r'^%s\s*=\s*\($.*?^\s*\)$' % constname, re.M | re.S)
m = re_match.search(data)
if not m:
raise ValueError('Could not find existing definition for %s' %
(constname,))
new_block = format_lines(constname, content)
data = data[:m.start()] + new_block + data[m.end():]
with open(filename, 'w') as f:
f.write(data)
update_myself()
|
{
"pile_set_name": "Github"
}
|
/*
MIT License
Copyright (c) 2019 Temainfo Sistemas
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.
*/
export enum MultiSelectErrorMessages {
NOTSIMPLE_AND_NOTKEYVALUE = 'You must pass the [keyValue] property when not using an ArrayString as DataSource',
NOTDETAIL_AND_WITHDETAILTAG = 'You have to declare the [detail] property',
DATAUNDEFINED = 'The property [data] and property [query] are Required when using a complex array object Example :' +
' <tl-multiselect [data]=\'source\' [query]=\'name\''
}
|
{
"pile_set_name": "Github"
}
|
I am re-reading [The Art of Learning](https://www.amazon.ca/Art-Learning-Journey-Optimal-Performance/dp/0743277465) by [Joshua Waitzkin](https://en.wikipedia.org/wiki/Joshua_Waitzkin), the chess prodigy who later became a world champion in competitive tai chi. In a chapter on keeping your concentration when the world around you is trying to split your attention, he has this small segment:
> The nature of your state of concentration will determine the first phase of your reaction [to an interruption] - if you are tense, with your fingers jammed in your ears and your whole body straining to fight off distraction, then you are in a _Hard Zone_ that demands a cooperative world for you to function. Like a dry twig, you are brittle, ready to snap under pressure. The alternative is for you to be quietly, intensely focused, apparently relaxed with a serene look on your face, but inside all the mental juices are churning. You flow with whatever comes, integrating every ripple of life into your creative moment. This _Soft Zone_ is resilient, like a flexible blade of grass that can move with and survive hurricane-force winds.
This, I think, we have all experienced before. We’ve focused when there was hassle around us - at airports, in busses, at school. All students eventually learn to deal with a minimum of chatter, or we wouldn’t spend so much time in cafes. However, I don’t think that many developers actively seek out louder cafes and environments as a way of increasing their focus.
> Mental resilience is arguable the most critical trait of a world-class performer, and it should be nurtured continuously.
We all know that working in cafes is a nice break from the office. But it also may be possible that it is a better place to work than the office. Have you tried? Spend a month in the noisiest cafe you can, and it will eventually cease to bother you. You’ll find a rhythm amidst the noise.
Nomadic developing (or remote work, or whatever you want to call it) is particularly suited to finding distracting places to work, with a two-fold purpose - first, to introduce social life into an otherwise barren AirBnB office environment; and secondly, to nurture signal out of the noise.
Me? I wrote this while blasting monk mantras through my headphones in the middle of a bright cafe, people walking behind me, two excessively loud girls with abrasive American accents talking next to me. Did I manage to focus? Yes. Do I feel comfortable with it? Yes. Is this better than my quiet office? Definitely yes - an hour ago, I was falling asleep.
Seek out chaos.
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<!--
* t
****************************************************************************
* Copyright (c) 1998-2006,2010 Free Software Foundation, 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, distribute with modifications, 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 ABOVE 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. *
* *
* Except as contained in this notice, the name(s) of the above copyright *
* holders shall not be used in advertising or otherwise to promote the *
* sale, use or other dealings in this Software without prior written *
* authorization. *
****************************************************************************
* @Id: form_page.3x,v 1.12 2010/12/04 18:40:45 tom Exp @
-->
<HTML>
<HEAD>
<TITLE>form_page 3x</TITLE>
<link rev=made href="mailto:bug-ncurses@gnu.org">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</HEAD>
<BODY>
<H1>form_page 3x</H1>
<HR>
<PRE>
<!-- Manpage converted by man2html 3.0.1 -->
<STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG> <STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG>
</PRE>
<H2>NAME</H2><PRE>
<STRONG>form_page</STRONG> - set and get form page number
</PRE>
<H2>SYNOPSIS</H2><PRE>
<STRONG>#include</STRONG> <STRONG><form.h></STRONG>
int set_current_field(FORM *form, FIELD *field);
FIELD *current_field(const FORM *);
int set_form_page(FORM *form, int n);
int form_page(const FORM *form);
int field_index(const FIELD *field);
</PRE>
<H2>DESCRIPTION</H2><PRE>
The function <STRONG>set_current</STRONG> <STRONG>field</STRONG> sets the current field of
the given form; <STRONG>current_field</STRONG> returns the current field of
the given form.
The function <STRONG>set_form_page</STRONG> sets the form's page number
(goes to page <EM>n</EM> of the form).
The function <STRONG>form_page</STRONG> returns the form's current page
number.
The function <STRONG>field_index</STRONG> returns the index of the field in
the field array of the form it is connected to. It returns
<STRONG>ERR</STRONG> if the argument is the null pointer or the field is
not connected.
</PRE>
<H2>RETURN VALUE</H2><PRE>
Except for <STRONG>form_page</STRONG>, each routine returns one of the fol-
lowing:
<STRONG>E_OK</STRONG> The routine succeeded.
<STRONG>E_BAD_ARGUMENT</STRONG>
Routine detected an incorrect or out-of-range argu-
ment.
<STRONG>E_BAD_STATE</STRONG>
Routine was called from an initialization or termina-
tion function.
<STRONG>E_INVALID_FIELD</STRONG>
Contents of a field are not valid.
<STRONG>E_REQUEST_DENIED</STRONG>
The form driver could not process the request.
<STRONG>E_SYSTEM_ERROR</STRONG>
System error occurred (see <STRONG>errno</STRONG>).
</PRE>
<H2>SEE ALSO</H2><PRE>
<STRONG><A HREF="ncurses.3x.html">curses(3x)</A></STRONG>, <STRONG><A HREF="form.3x.html">form(3x)</A></STRONG>.
</PRE>
<H2>NOTES</H2><PRE>
The header file <STRONG><form.h></STRONG> automatically includes the header
file <STRONG><curses.h></STRONG>.
</PRE>
<H2>PORTABILITY</H2><PRE>
These routines emulate the System V forms library. They
were not supported on Version 7 or BSD versions.
</PRE>
<H2>AUTHORS</H2><PRE>
Juergen Pfeifer. Manual pages and adaptation for new
curses by Eric S. Raymond.
<STRONG><A HREF="form_page.3x.html">form_page(3x)</A></STRONG>
</PRE>
<HR>
<ADDRESS>
Man(1) output converted with
<a href="http://www.oac.uci.edu/indiv/ehood/man2html.html">man2html</a>
</ADDRESS>
</BODY>
</HTML>
|
{
"pile_set_name": "Github"
}
|
## Объект `arguments`
В области видимости любой функции в JavaScript есть доступ к специальной переменной `arguments`. Эта переменная содержит в себе список всех аргументов, переданных данной функции.
> **Замечание:** В случае, если переменная `arguments` уже была объявлена в области видимости функции либо путём присвоения через выражение `var`, либо являясь формальным параметром, объект `arguments` не будет создан.
Объект `arguments` **не** является наследником `Array`. Он, конечно же, очень похож на массив и даже содержит свойство `length` — но он не наследует `Array.prototype`, а представляет собой `Object`.
По этой причине, у объекта `arguments` **отсутствуют** стандартные методы массивов, такие как `push`, `pop` или `slice`. Хотя итерация с использованием обычного цикла `for` по аргументам работает вполне корректно, вам придётся конвертировать этот объект в настоящий массив типа `Array`, чтобы применять к нему стандартные методы массивов.
### Конвертация в массив
Указанный код вернёт новый массив типа `Array`, содержащий все элементы объекта `arguments`.
Array.prototype.slice.call(arguments);
Эта конвертация занимает **много времени** и использовать её в критических частях кода **не рекомендуется**.
### Передача аргументов
Ниже представлен рекомендуемый способ передачи аргументов из одной функции в другую.
function foo() {
bar.apply(null, arguments);
}
function bar(a, b, c) {
// делаем здесь что-нибудь
}
Другой трюк — использовать и `call` и `apply` вместе, чтобы быстро создать несвязанную обёртку:
function Foo() {}
Foo.prototype.method = function(a, b, c) {
console.log(this, a, b, c);
};
// Создаём несвязанную версию "method"
// Она принимает параметры: this, arg1, arg2...argN
Foo.method = function() {
// Результат: Foo.prototype.method.call(this, arg1, arg2... argN)
Function.call.apply(Foo.prototype.method, arguments);
};
### Формальные аргументы и индексы аргументов
Объект `arguments` создаёт по *геттеру* и *сеттеру* и для всех своих свойств и для формальных параметров функции.
В результате, изменение формального параметра также изменит значение соответствующего свойства объекта `arguments` и наоборот.
function foo(a, b, c) {
arguments[0] = 2;
a; // 2
b = 4;
arguments[1]; // 4
var d = c;
d = 9;
c; // 3
}
foo(1, 2, 3);
### Мифы и правда о производительности
Объект `arguments` создаётся во всех случаях, лишь за двумя исключениями — когда он переопределён внутри функции (по имени) или когда одним из её параметров является переменная с таким именем. Неважно, используется при этом сам объект или нет.
*Геттеры* и *сеттеры* создаются **всегда**; так что их использование практически никак не влияет на производительность.
> **ES5 Замечание:** Эти *геттеры* и *сеттеры* не создаются в strict-режиме.
Однако, есть один момент, который может радикально понизить производительность современных движков JavaScript. Этот момент — использование `arguments.callee`.
function foo() {
arguments.callee; // сделать что-либо с этим объектом функции
arguments.callee.caller; // и с вызвавшим его объектом функции
}
function bigLoop() {
for(var i = 0; i < 100000; i++) {
foo(); // При обычных условиях должна бы была быть развёрнута...
}
}
В коде выше, функция `foo` не может [быть развёрнута][1] (а могла бы), потому что для корректной работы ей необходима ссылка и на себя и на вызвавший её объект. Это не только кладёт на лопатки механизм развёртывания, но и нарушает принцип инкапсуляции, поскольку функция становится зависима от конкретного контекста вызова.
**Крайне не рекомендуется** использовать `arguments.callee` или какое-либо из его свойств. **Никогда**.
> **ES5 Замечание:** В strict-режиме использование `arguments.callee` породит `TypeError`, поскольку его использование принято устаревшим.
[1]: http://en.wikipedia.org/wiki/Inlining
|
{
"pile_set_name": "Github"
}
|
digiCamControl - DSLR camera remote control open source software
Copyright (C) 2019 Duka Istvan
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 2012-2016 Broad Institute, 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.
*/
package org.broadinstitute.gatk.utils.commandline;
/**
* Represents a collection of parsed arguments for an argument source.
*
* Useful for printing out help documents.
*/
public abstract class ParsedArgs {
/**
* @return A compact description of the arguments from an provider/source.
*/
public abstract String getDescription();
}
|
{
"pile_set_name": "Github"
}
|
# Функциональное программирование
* Изучить книгу [Professor Frisby's Mostly Adequate Guide to Functional Programming](https://github.com/MostlyAdequate/mostly-adequate-guide) от Franklin Frisby (8-12 главы включительно).
* [Перевод](https://github.com/MostlyAdequate/mostly-adequate-guide-ru)
* Изучить книгу [Functional-Light JavaScript](https://github.com/getify/Functional-Light-JS) от Kyle Simpson (9-11 главы, плюс дополнения).
* Как реализовать функционал объектов через замыкания и наоборот? В чем преимущества каждого способа?
* Как можно создать приватные значения в функции? Как можно сделать их иммутабельными?
* Что такое категории? Что такое морфизмы?
* Что такое изоморфизм?
* Что такое функтор?
* Как можно избежать лишних проходов по массиву?
* Что такое ленивые вычисления? В чем преимущества и недостатки ленивых вычислений?
* Что такое трансдукция? Какие проблемы можно решить с помощью данного инструмента?
* Что такое pointed функтор?
* Что такое монады? Для чего они используются? Что делают приведенные ниже монады?
* `Maybe`
* `Either`
* `IO`
* Что такое ассоциативность?
* Что такое аппликативный функтор? Какова область его применения?
* Что делают приведенные ниже утилиты?
* `identity`
* `partial`/`partialRight`
* `prop`
* `curry`/`uncurry`
* `cond`
* `flatMap`/`chain`
* Immutability and state
* Может ли состояние программы быть иммутабельным?
* В чём проблема хранения состояния программы?
* Почему мутабельное состояние затрудняет соблюдение гарантии инвариантов на протяжении жизненного цикла программы?
* Почему мутабельность накладывает дополнительные требования к порядку выполнения функций? Как этого можно избежать?
* Опишите следующие модели состояния. Как их можно градировать по степени опасности?
* Невидимое клиенту изменяемое состояние
* Инкапсулированное изменяемое состояние
* Невидимое программисту изменяемое состояние
* Двухфазный цикл жизни
* Разделяемое между несколькими процессами изменяемое состояние
* Отсутствие изменяемого состояния
* Неинкапсулированное изменяемое состояние
* Управляемое изменяемое состояние
* Монотонное изменяемое состояние
### Ресурсы
* [Embracing Immutable Architecture](https://medium.com/react-weekly/embracing-immutable-architecture-dc04e3f08543)
* [Изменяемое состояние: опасности и борьба с ними](http://fprog.ru/2009/issue1/eugene-kirpichov-fighting-mutable-state/)
* [Immutable Data Structures and JavaScript](https://jlongster.com/Using-Immutable-Data-Structures-in-JavaScript#Immutable.js)
* [Mutability Leads to Suffering](https://hackernoon.com/mutability-leads-to-suffering-23671a0def6a)
* [The discussion thread about mutability](http://lambda-the-ultimate.org/node/724#comment-6580)
|
{
"pile_set_name": "Github"
}
|
Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell
Please consider promoting this project if you find it useful.
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"
}
|
<?php defined('SYSPATH') or die('No direct access allowed.');
/**
* В данном конфиге указываются возмо;ные права доступа
*
* Если пользователь не имеет прав администратора то при переходе в любой экшен контроллера
* он должен иметь на это права (если экшен не доступен для всех), поэтому
* если к экшенам контроллера предполагается разграничить права, то их необходимо описать в этом
* конфиге.
*/
// Наличие данного конфига не обязательно
return array(
// 'skeleton' => array( // Контроллер
// array(
// 'action' => 'index', // Экешн контроллера либо ключ для свободной проверки
// 'description' => 'View skeletons'
// )
// )
);
/**
* Проверка прав остуществляется ACL::check('skeleton.index')
*/
|
{
"pile_set_name": "Github"
}
|
# frozen_string_literal: true
#--
# Copyright (c) 2005-2018 David Heinemeier Hansson
#
# 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.
#++
require "securerandom"
require "active_support/dependencies/autoload"
require "active_support/version"
require "active_support/logger"
require "active_support/lazy_load_hooks"
require "active_support/core_ext/date_and_time/compatibility"
module ActiveSupport
extend ActiveSupport::Autoload
autoload :Concern
autoload :CurrentAttributes
autoload :Dependencies
autoload :DescendantsTracker
autoload :ExecutionWrapper
autoload :Executor
autoload :FileUpdateChecker
autoload :EventedFileUpdateChecker
autoload :LogSubscriber
autoload :Notifications
autoload :Reloader
eager_autoload do
autoload :BacktraceCleaner
autoload :ProxyObject
autoload :Benchmarkable
autoload :Cache
autoload :Callbacks
autoload :Configurable
autoload :Deprecation
autoload :Digest
autoload :Gzip
autoload :Inflector
autoload :JSON
autoload :KeyGenerator
autoload :MessageEncryptor
autoload :MessageVerifier
autoload :Multibyte
autoload :NumberHelper
autoload :OptionMerger
autoload :OrderedHash
autoload :OrderedOptions
autoload :StringInquirer
autoload :TaggedLogging
autoload :XmlMini
autoload :ArrayInquirer
end
autoload :Rescuable
autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
autoload :TestCase
def self.eager_load!
super
NumberHelper.eager_load!
end
cattr_accessor :test_order # :nodoc:
def self.to_time_preserves_timezone
DateAndTime::Compatibility.preserve_timezone
end
def self.to_time_preserves_timezone=(value)
DateAndTime::Compatibility.preserve_timezone = value
end
end
autoload :I18n, "active_support/i18n"
|
{
"pile_set_name": "Github"
}
|
Copyright (c) 2010 Darren Cauthon
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"
}
|
SUBROUTINE GP3D
C
C GP3D CREATES THE ETT (ELEMENT TEMPERATURE TABLE)
C
C THE GPTT AS PREPARED BY GP3B COMES TO THIS ROUTINE VIA SCRATCH
C DATA SET 1.
C
C DATA IN THE GPTT IS USED TOGETHER WITH DATA OBTAINED FROM TEMPP1,
C TEMPP2, TEMPP3, AND TEMPRB CARDS WHICH RESIDE ON GEOM3.
C
LOGICAL ANYGPT ,ANYET ,LFLAG ,ANY ,HEAT
INTEGER GEOM3 ,EQEXIN ,GEOM2 ,SLT ,ETT ,
1 SCR1 ,SCR2 ,BUF1 ,BUF2 ,BUF ,
2 FILE ,CARDID ,CARDDT ,STATUS ,PLOAD2 ,
3 TEMPD ,TEMPP1 ,TEMPP2 ,TEMPP3 ,TEMPRB ,
4 RD ,RDREW ,WRT ,WRTREW ,REW ,
5 NOREW ,Z ,FLAG ,TWOI ,DEFALT ,
6 NAM(2) ,RECORD ,GPTREC ,SETID ,OUTPT ,
7 SYSBUF ,OUTWDS ,ECTWDS ,ELEM ,BUF3
REAL RZ(1) ,RBUF(50) ,TGRID(32)
CHARACTER UFM*23
COMMON /XMSSG / UFM
COMMON /BLANK / NOGRAV ,NOLOAD ,NOTEMP
COMMON /SYSTEM/ KSYSTM(63)
COMMON /NAMES / RD ,RDREW ,WRT ,WRTREW ,REW ,
1 NOREW
COMMON /GP3COM/ GEOM3 ,EQEXIN ,GEOM2 ,SLT ,ETT ,
1 SCR1 ,SCR2 ,BUF1 ,BUF2 ,BUF(50) ,
2 CARDID(60),IDNO(30),CARDDT(60),MASK(60),STATUS(60)
3, NTYPES ,IPLOAD ,IGRAV ,PLOAD2(2),LOAD(2) ,
4 NOPLD2 ,TEMP(2) ,TEMPD(2) ,TEMPP1(2),TEMPP2(2),
5 TEMPP3(2),TEMPRB(2),BUF3
COMMON /GPTA1 / NELEM ,LAST ,INCR ,ELEM(1)
CZZ COMMON /ZZGP3X/ Z(1)
COMMON /ZZZZZZ/ Z(1)
EQUIVALENCE (RZ(1),Z(1)), (RBUF(1),BUF(1)), (DEFALT,DEFTMP),
1 (KSYSTM(1),SYSBUF), (KSYSTM(2),OUTPT),
2 (KSYSTM(56),IHEAT)
DATA NAM / 4HGP3D,4H /
C
C +---------------------+
C OPEN CORE I I Z(ILIST) = Z(1)
C I ET SET-LIST I
C DESIGN FOR I 2 WDS/ENTRY I
C I I Z(NLIST)
C GP3D +---------------------+
C I I Z(IGPTT)
C I GPT SET-LIST I
C I 3 WDS/ENTRY I
C I I Z(NGPTT)
C +---------------------+
C I I Z(IGPT) *
C I GPTT DATA I *
C I FOR CURRENT SETID I *
C I 2 WDS/ENTRY I *
C I I Z(NGPT) *
C +---------------------+ *
C I I Z(IET1) *
C I 2-DIMEN EL-TEMP I * THIS SPACE IS
C I FOR CURRENT SETID I * DYNAMIC FOR
C I 7 WDS/ENTRY I * EACH SET OF
C I I Z(NET1) * TEMPERATURE
C +---------------------+ * DATA.
C I I Z(IET2) *
C I 1-DIMEN EL-TEMP I *
C I FOR CURRENT SETID I *
C I 15 WDS/ENTRY I *
C I I Z(NET2) *
C +---------------------+ *
C I/////////////////////I *
C I/////////////////////I *
C +---------------------+
C I I Z(BUF1)
C I BUFFER 2 I
C I I
C +---------------------+
C I I Z(BUF2)
C I BUFFER 1 I
C I I Z(KORSZ)
C +---------------------+
C
C
C
C OPEN GEOM3, AND SCR1. READ IN TEMPP1, TEMPP2, TEMPP3, TEMPRB CARDS
C CONVERT AND WRITE THEM OUT ON SCR2.
C
HEAT = .FALSE.
IF (IHEAT .EQ. 1) HEAT = .TRUE.
LFLAG = .FALSE.
J = -1
NWORDS= 8
ILIST = 1
NLIST = 0
FILE = GEOM3
ANY = .FALSE.
CALL PRELOC (*820,Z(BUF1),GEOM3)
FILE = SCR2
CALL OPEN (*820,SCR2,Z(BUF2),WRTREW)
C
C PICK UP TEMPP1 CARDS
C
FILE = GEOM3
CALL LOCATE (*20,Z(BUF1),TEMPP1,FLAG)
ANY = .TRUE.
ASSIGN 10 TO IRETRN
BUF(7) = 0
BUF(8) = 1
10 CALL READ (*840,*20,GEOM3,BUF,6,0,FLAG)
GO TO 170
C
C PICK UP TEMPP2 CARDS
C
20 CALL LOCATE (*40,Z(BUF1),TEMPP2,FLAG)
ANY = .TRUE.
ASSIGN 30 TO IRETRN
30 CALL READ (*840,*40,GEOM3,BUF,8,0,FLAG)
GO TO 170
C
C PICK UP TEMPP3 CARDS (CONVERT THESE TO LOOK LIKE TEMPP1 CARDS)
C
40 CALL LOCATE (*140,Z(BUF1),TEMPP3,FLAG)
ANY = .TRUE.
ASSIGN 50 TO IRETRN
50 CALL READ (*840,*140,GEOM3,BUF,24,0,FLAG)
N = 25
DO 60 I = 1,11
N = N - 2
IF (RBUF(N).NE.0.0 .OR. RBUF(N+1).NE.0.0) GO TO 70
60 CONTINUE
70 N = N/2
T1 = RBUF(4)
T2 = RBUF(2*N+2)
IF (N .EQ. 1) GO TO 100
H = RBUF(2*N+1) - RBUF(3)
SUM= 0.0
N = N-1
DO 80 I = 1,N
TWOI = 2*I
FACTOR = RBUF(TWOI+3) - RBUF(TWOI+1)
IF (FACTOR .LE. 0.0) GO TO 120
SUM = SUM + (RBUF(TWOI+2) + RBUF(TWOI+4))*FACTOR
80 CONTINUE
TBAR = SUM/(2.0*H)
HOVER2 = H/2.0
SUM = 0.0
DO 90 I = 1,N
TWOI = 2*I
SUM = SUM + (RBUF(TWOI+3) - RBUF(TWOI+1) )*(3.0*
1 (RBUF(TWOI+1) - RBUF(3) - HOVER2)*
2 (RBUF(TWOI+4) + RBUF(TWOI+2) ) +
3 (RBUF(TWOI+2) + 2.0*RBUF(TWOI+4))*
4 (RBUF(TWOI+3) - RBUF(TWOI+1) ))
90 CONTINUE
TPRIME = 2.0*SUM/H**3
GO TO 110
C
100 TBAR = RBUF(4)
TPRIME = 0.0
C
110 RBUF(3) = TBAR
RBUF(4) = TPRIME
RBUF(5) = T1
RBUF(6) = T2
BUF(7) = 0
BUF(8) = 1
GO TO 170
C
C BAD DATA ON A TEMPP3 CARD
C
120 WRITE (OUTPT,130) UFM,BUF(1),BUF(2)
130 FORMAT (A23,' 4010, TEMPP3 BULK DATA CARD WITH SET ID =',I8,
1 ' AND ELEMENT ID =',I8, /27X,
2 'DOES NOT HAVE ASCENDING VALUES SPECIFIED FOR Z.')
LFLAG = .TRUE.
GO TO 50
C
C END OF 8 WORD CARDS. WRITE EOR ON SCR2 AND DO TEMPRB CARDS NOW.
C
140 CALL WRITE (SCR2,0,0,1)
NWORDS = 16
CALL LOCATE (*160,Z(BUF1),TEMPRB,FLAG)
ANY = .TRUE.
ASSIGN 150 TO IRETRN
150 CALL READ (*840,*160,GEOM3,BUF,16,0,FLAG)
GO TO 170
C
C WRITE EOR ON SCR2. SCR2 THEN WILL HAVE 2 RECORDS (1 OR BOTH EMPTY)
C
160 CALL WRITE (SCR2,0,0,1)
CALL CLOSE (GEOM3,REW )
CALL CLOSE (SCR2 ,REW )
GO TO 230
C
C INTERNAL SUBROUTINE TO BUILD SET LIST FROM TEMPERATURE CARD DATA
C FIND SET-ID OR ADD IT TO LIST IN SORT, BUMP COUNT AND WRITE CARD.
C
170 IF (J .EQ. -1) GO TO 210
IF (BUF(1) .EQ. Z(J)) GO TO 180
IF (BUF(1).GT.Z(J) .AND. J.EQ.NLIST-1) GO TO 210
C
C LOOK FOR MATCHING SETID OR FIND WHERE NEW SETID BELONGS
C
CALL BISLOC (*190,BUF(1),Z(ILIST),2,NLIST/2,J)
C
C MATCH WAS FOUND (ILIST ASSUMED TO BE EQUAL TO 1)
C
180 Z(J+1) = Z(J+1) + NWORDS
GO TO 220
C
C ADD THIS NEW SETID INTO LIST
C
190 IF (BUF(1) .GT. Z(J)) J = J + 2
C
C PUSH Z(J) THRU Z(NLIST) DOWN TWO WORDS TO MAKE ROOM FOR NEW SETID
C
I = NLIST + 2
DO 200 K = J,NLIST
Z(I) = Z(I-2)
I = I - 1
200 CONTINUE
GO TO 211
C
C ADD NEW SETID TO LIST
C
210 J = J + 2
211 Z(J) = BUF(1)
NLIST = NLIST + 2
Z(J+1)= NWORDS
C
C WRITE OUT THE DATA CARD ON THE SCRATCH FILE FOR LATER USE
C
220 CALL WRITE (SCR2,BUF,NWORDS,0)
GO TO IRETRN, (10,30,50,150)
C
C READ IN GPTT HEADER RECORD FROM SCR1
C
230 IGPTT = NLIST + 1
NGPTT = IGPTT
FILE = SCR1
IF (NOTEMP .NE. 1) GO TO 250
CALL OPEN (*820,SCR1,Z(BUF1),RDREW)
CALL READ (*840,*240,SCR1,Z(IGPTT),BUF2-IGPTT,1,FLAG)
CALL MESAGE (-8,0,NAM)
240 NGPTT = NLIST + FLAG
IGPTT = IGPTT + 2
NSETS = (NGPTT - IGPTT + 1)/3
C
C DETERMINE NUMBER OF RECORDS OF EXTERNAL INDEX TEMP DATA
C FOLLOWING HEADER RECORD.
C
IRECS = 0
IF (NSETS) 247,247,241
241 DO 244 I = IGPTT,NGPTT,3
IRECS = MAX0(Z(I+2),IRECS)
244 CONTINUE
247 CONTINUE
CALL CLOSE (SCR1,NOREW)
C
C OPEN ETT, PUT OUT HEADER RECORD WITH THE 3 WORD SET ENTRIES.
C
250 IF (NOTEMP.NE.1 .AND. .NOT.ANY) GO TO 810
NOTEMP = 1
FILE = ETT
CALL OPEN (*820,ETT,Z(BUF2),WRTREW)
CALL FNAME (ETT,BUF)
CALL WRITE (ETT,BUF,2,0)
LIST1 = ILIST
LIST2 = IGPTT
RECORD= 0
260 IF (LIST1.GT.NLIST-1 .AND. LIST2.LE.NGPTT-2) GO TO 290
IF (LIST1.LE.NLIST-1 .AND. LIST2.GT.NGPTT-2) GO TO 270
IF (LIST1.GT.NLIST-1 .AND. LIST2.GT.NGPTT-2) GO TO 330
C
IF (Z(LIST1) - Z(LIST2)) 270,280,290
C
C SET-ID OF LIST1 IS .LT. SET-ID OF LIST2 OR LIST2 IS ALL USED.
C
270 BUF(1) = Z(LIST1)
BUF(2) = -1
LIST1 = LIST1 + 2
GO TO 300
C
C SET-ID OF LIST1 IS .EQ. SET-ID OF LIST2.
C
280 BUF(1) = Z(LIST2 )
BUF(2) = Z(LIST2+1)
LIST1 = LIST1 + 2
LIST2 = LIST2 + 3
GO TO 300
C
C SET-ID OF LIST2 IS .LT. SET-ID OF LIST1 OR LIST1 IS ALL USED.
C
290 BUF(1) = Z(LIST2 )
BUF(2) = Z(LIST2+1)
LIST2 = LIST2 + 3
IF (Z(LIST2-1) .EQ. 0) GO TO 310
C
C WRITE 3-WORD SET-ID ENTRY IN HEADER
C
300 RECORD = RECORD + 1
BUF(3) = RECORD
GO TO 320
310 BUF(3) = 0
320 CALL WRITE (ETT,BUF,3,0)
GO TO 260
C
C HEADER RECORD IS COMPLETE. WRITE EOR AND CLOSE WITH NOREWIND.
C
330 CALL WRITE (ETT,0,0,1)
CALL CLOSE (ETT,NOREW)
C
C FOR EACH SET DEFINED IN THE EL-TEMP SET LIST AND OR THE GRID-TEMP
C SET LIST PASS GEOM2 USING LOCATE FOR ALL THE ELEMENTS FOR
C WHICH ETT TEMP DATA OUTPUT IS POSSIBLE.
C IF ANY ELEMENTS CONCERNED ARE PRESENT THEN SELECT FROM THE TEMP
C DATA AVAILABLE THAT WHICH IS APPLICABLE AND OUTPUT THE DATA ON THE
C ETT IN THE FOLLOWING FORMAT.
C
C CONTENTS OF 1 RECORD OF THE OUTPUT FILE ETT. EACH RECORD CONTAINS
C DATA FOR 1 SET.
C
C SET-ID
C ELEMENT TYPE * * * * * * * * * *
C NUMBER OF TEMPERATURE DATA VALUES/EL-ID *
C EL-ID * *
C TEMP-VALUE * *
C . * EL-ID *
C . * ENTRY *
C . * * ELEMENT-TYPE
C LAST-TEMP-VALUE* * ENTRY
C * (1 OR MORE EL-ID *
C * ENTRIES PER EL-TYPE * (1 OR MORE
C * ENTRY) * PER RECORD)
C EL-ID * *
C TEMP-VALUE * *
C . * EL-ID *
C . * ENTRY *
C . * *
C LAST-TEMP-VALUE* *
C 0 * * * * * * * * * *
C
C IN THE ABOVE IF THE ELEMENT HAS NO SPECIAL DATA, A NEGATIVE
C ELEMENT ID IS INSERTED FOLLOWED BY NO TEMPERATURE DATA.
C
C NOW GATHER THE DATA AVAILABLE FOR A SET FROM SCR1 AND OR SCR2.
C
GPTREC = 1
LIST1 = ILIST
LIST2 = IGPTT
340 ANYGPT = .FALSE.
ANYET = .FALSE.
IGPT = 0
NGPT = 0
IET1 = 0
NET1 = 0
IET2 = 0
NET2 = 0
IF (LIST1 .GT. NLIST-1) GO TO 350
IF (LIST2 .LE. NGPTT-2) GO TO 360
GO TO 370
350 IF (LIST2 .LE. NGPTT-2) GO TO 390
GO TO 770
C
360 IF (Z(LIST1) - Z(LIST2)) 370,380,390
C
C NEXT SET-ID HAS ONLY EL-TEMP DATA
C
370 SETID = Z(LIST1)
DEFALT = -1
ANYET = .TRUE.
NWORDS = Z(LIST1+1)
LIST1 = LIST1 + 2
GO TO 400
C
C NEXT SET-ID HAS BOTH GRID-TEMP AND EL-TEMP DATA
C
380 SETID = Z(LIST2 )
DEFALT = Z(LIST2+1)
ANYET = .TRUE.
INREC = Z(LIST2+2)
IF (INREC .GT. 0) ANYGPT = .TRUE.
NWORDS = Z(LIST1+1)
LIST1 = LIST1 + 2
LIST2 = LIST2 + 3
GO TO 400
C
C NEXT SET-ID HAS ONLY GRID-TEMP DATA
C
390 SETID = Z(LIST2 )
DEFALT = Z(LIST2+1)
INREC = Z(LIST2+2)
IF (INREC .GT. 0) ANYGPT = .TRUE.
LIST2 = LIST2 + 3
GO TO 400
C
C AT THIS POINT READ IN ANY GRID-TEMP DATA AND/OR ANY EL-TEMP DATA.
C SORT THE EL-TEMP DATA ON EL-ID. THE GRID-TEMP DATA IS SORTED ON
C GRIDS
C
400 IGPT = NGPTT + 1
NGPT = IGPT
IF (.NOT.ANYGPT) GO TO 460
FILE = SCR1
CALL OPEN (*820,SCR1,Z(BUF1),RD)
C
C POSITION GPTT TO DESIRED GRID-POINT-TEMP SET AND READ IT IN.
C
MOVE = INREC - GPTREC
IF (MOVE) 410,440,420
410 CALL REWIND (SCR1)
MOVE = INREC
420 DO 430 I = 1,MOVE
CALL FWDREC (*840,SCR1)
430 CONTINUE
440 GPTREC = INREC + 1
CALL READ (*840,*450,SCR1,Z(IGPT),BUF2-IGPT,1,FLAG)
CALL MESAGE (-8,0,NAM)
450 NGPT = IGPT + FLAG - 1
CALL CLOSE (SCR1,NOREW)
C
C READ IN EL-TEMP DATA PERTAINING TO THIS SET-ID
C
460 IF (.NOT.ANYET) GO TO 520
IF (NGPT+NWORDS .GE. BUF2) CALL MESAGE (-8,0,NAM)
FILE = SCR2
CALL OPEN (*820,SCR2,Z(BUF1),RDREW)
IET1 = NGPT + 1
NET1 = NGPT
470 CALL READ (*840,*490,SCR2,BUF,8,0,FLAG)
IF (BUF(1) .NE. SETID) GO TO 470
DO 480 I = 2,8
NET1 = NET1 + 1
480 Z(NET1) = BUF(I)
NWORDS = NWORDS - 8
IF (NWORDS .NE. 0) GO TO 470
CALL FWDREC (*820,SCR2)
490 IET2 = NET1 + 1
NET2 = NET1
500 CALL READ (*840,*520,SCR2,BUF,16,0,FLAG)
IF (BUF(1) .NE. SETID) GO TO 500
DO 510 I = 2,16
NET2 = NET2 + 1
510 Z(NET2) = BUF(I)
NWORDS = NWORDS - 16
IF (NWORDS .NE. 0) GO TO 500
C
C ALL DATA IS NOW IN CORE FOR THIS SET-ID
C
520 CALL CLOSE (SCR2,REW)
IF (.NOT.ANYET .AND. .NOT.ANYGPT) GO TO 340
C
C SORT THE 7-WORD TEMP CARDS ON ID AND CHECK FOR DUPLICATE ID S
C AMONG ALL THE ELEMENT TEMPERATURE DATA
C
IF (IET1 .LT. NET1) CALL SORT (0,0, 7,1,Z(IET1),NET1-IET1+1)
IF (IET2 .LT. NET2) CALL SORT (0,0,15,1,Z(IET2),NET2-IET2+1)
C
LET1 = (NET1 - IET1 + 1)/7
LET2 = (NET2 - IET2 + 1)/15
LGPT = (NGPT - IGPT + 1)/2
LFLAG = .FALSE.
IF (LET1 .LE. 1) GO TO 560
ID = Z(IET1)
J = IET1 + 7
DO 550 I = J,NET1,7
IF (ID .NE. Z(I)) GO TO 540
C
C ERROR - TWO OR MORE ID-S EQUAL IN TEMPERATURE DATA WITHIN A SET.
C
WRITE (OUTPT,530) UFM,SETID,ID
530 FORMAT (A23,' 4011, ELEMENT TEMPERATURE SET',I9,' CONTAINS ',
1 'MULTIPLE TEMPERATURE DATA SPECIFIED FOR ELEMENT ID',I9)
LFLAG = .TRUE.
540 ID = Z(I)
550 CONTINUE
560 IF (LET2 .LE. 1) GO TO 590
ID = Z(IET2)
J = IET2 + 15
DO 580 I = J,NET2,15
IF (ID .NE. Z(I)) GO TO 570
WRITE (OUTPT,530) UFM,SETID,ID
LFLAG = .TRUE.
570 ID = Z(I)
580 CONTINUE
C
C OPEN GEOM2, PREPARE TO PASS GEOM2, AND OUTPUT A RECORD OF THE ETT.
C
590 FILE = GEOM2
CALL PRELOC (*820,Z(BUF1),GEOM2)
C
C OPEN ETT TO PUT OUT DATA-RECORD FOR THIS SET AND WRITE SETID,
C
FILE = ETT
CALL OPEN (*820,ETT,Z(BUF2),WRT)
CALL WRITE (ETT,SETID,1,0)
C
C RUN THROUGH POSSIBLE TEMPERATURE DEPENDENT ELEMENTS ON GEOM2.
C
FILE = GEOM2
595 CALL ECTLOC (*760,FILE,BUF,I)
C
C OK DATA FOR A CARD TYPE HAS BEEN FOUND. WRITE EL-TYPE AND
C DATA FOR A CARD TYPE FOUND.
C
BUF(1) = ELEM(I+2)
BUF(2) = ELEM(I+14) - 1
IELTYP = BUF(1)
C
C WRITE ELEMENT TYPE HEADER
C
CALL WRITE (ETT,BUF,2,0)
IF (ELEM(I+13) .EQ. 0) GO TO 740
JTEMP = ELEM(I+13)
OUTWDS = ELEM(I+14)
ECTWDS = ELEM(I+ 5)
IGRID = ELEM(I+12)
NGRID = IGRID + ELEM(I+9) - 1
FGRIDS = 0.0
600 CALL READ (*840,*740,GEOM2,BUF,ECTWDS,0,FLAG)
C
C ON FIRST PASS COUNT NUMBER OF NON-ZERO GRIDS
C
IF (FGRIDS) 605,601,605
601 DO 603 J = IGRID,NGRID
IF (BUF(J) .NE. 0) FGRIDS = FGRIDS + 1.0
603 CONTINUE
605 CONTINUE
C
C SELECT DATA TO BE OUTPUT
C
IF (.NOT.ANYET) GO TO 650
GO TO (610,620,650,650), JTEMP
C
C 1 - DIMENSIONAL ELEMENT-TEMP DATA MAY BE AVAIL.
C
610 IF (LET2 .LT. 1) GO TO 650
CALL BISLOC (*650,BUF(1),Z(IET2),15,LET2,J)
J = IET2 + J
C
C AVERAGE T-BAR-A AND T-BAR-B IF THIS IS A ROD, CONROD, OR TUBE
C
IF (IELTYP.NE.1 .AND. IELTYP.NE.3 .AND. IELTYP.NE.10) GO TO 630
RBUF(2) = (RZ(J) + RZ(J+1))/2.0
GO TO 730
C
C 2 - DIMENSIONAL ELEMENT-TEMP DATA MAY BE AVAIL.
C
620 IF (LET1 .LT. 1) GO TO 650
CALL BISLOC (*650,BUF(1),Z(IET1),7,LET1,J)
J = IET1 + J
630 DO 640 K = 2,OUTWDS
BUF(K) = Z(J)
J = J + 1
640 CONTINUE
GO TO 730
C
C CHECK FOR GRID-POINT-TEMP-DATA
C
650 IF (.NOT.ANYGPT) GO TO 700
C
C GRID-POINT-TEMP-DATA IS AVAILABLE FOR SOME OR ALL GRID POINTS.
C
ANY = .FALSE.
RTEMP = 0.0
II = 0
DO 670 K = IGRID,NGRID
II = II + 1
IF (BUF(K)) 655,665,655
655 CALL BISLOC (*660,BUF(K),Z(IGPT),2,LGPT,J)
J = IGPT + J
RTEMP = RTEMP + RZ(J)
IF (II .GT. 32) CALL MESAGE (-61,0,0)
TGRID(II) = RZ(J)
ANY = .TRUE.
GO TO 670
660 IF (DEFALT .EQ. -1) GO TO 710
RTEMP = RTEMP + DEFTMP
TGRID(II) = DEFTMP
GO TO 670
C
C UNDEFINED GRID-POINT
C
665 TGRID(II) = 0
670 CONTINUE
C
C IF NOTHING BUT DEFAULT DATA THEN WRITE NOTHING SINCE THE
C DEFAULT IS IN THE HEADER RECORD.
C
IF (.NOT.ANY) GO TO 735
C
C IF BAR ELEMENT PUT GRID TEMPS INTO BUFFER FOR T-BAR-A AND T-BAR-B
C
IF (IELTYP .NE. 34) GO TO 675
RBUF(2) = TGRID(1)
RBUF(3) = TGRID(2)
J = 4
GO TO 676
C
675 RBUF(2) = RTEMP/FGRIDS
J = 3
IF (JTEMP .EQ. 4) J = 2
C
676 IF (JTEMP .LT. 3) GO TO 690
DO 680 K = 1,II
RBUF(J) = TGRID(K)
680 J = J + 1
690 IF (J .GT. OUTWDS) GO TO 730
BUF(J) = 0
J = J + 1
GO TO 690
C
C NO GRID-POINT-TEMP-DATA. VERIFY THAT THERE IS A DEFAULT TEMP.
C
700 IF (DEFALT .NE. -1) GO TO 735
C
C ERROR NO TEMP DATA OR DEFALT OF ANY KIND FOR THIS ID.
C
710 LFLAG = .TRUE.
WRITE (OUTPT,720) UFM,SETID,BUF(1)
720 FORMAT (A23,' 4012, THERE IS NO ELEMENT, GRID POINT, OR DEFAULT',
1 ' TEMPERATURE DATA FOR', /30X,'TEMPERATURE SET',I12,
2 ', WITH RESPECT TO ELEMENT ID =',I8)
GO TO 735
C
C OUTPUT ELEMENT-TEMPERATURE DATA FOR 1 ELEMENT OF THIS TYPE IN SET
C
730 CALL WRITE (ETT,BUF,OUTWDS,0)
GO TO 600
C
C OUTPUT A NEGATIVE ELEMENT ID SINCE THERE IS NO DATA AVAILABLE.
C
735 ID = -BUF(1)
CALL WRITE (ETT,ID,1,0)
GO TO 600
C
C END OF ELEMENTS FOR THIS EL-TYPE. WRITE ZERO ON ETT
C
740 CALL WRITE (ETT,0,1,0)
GO TO 595
760 CONTINUE
C
C ETT-RECORD IS COMPLETE FOR THIS SET. WRITE EOR AND PROCESS NEXT
C SET.
C
CALL WRITE (ETT,0,0,1)
CALL CLOSE (ETT,NOREW)
GO TO 340
C
C ETT IS COMPLETE
C
770 IF (LFLAG) CALL MESAGE (-61,0,0)
C
C WRITE TRAILER FOR ETT
C
BUF(1) = ETT
BUF(7) = 7
DO 775 I = 2,6
775 BUF(I) = 0
C
C OPEN ETT AND APPEND GPTT SECTION OF TEMP DATA IN INTERNAL NOTATION
C
FILE = ETT
CALL OPEN (*820,ETT,Z(BUF2),WRT)
IF (.NOT.ANYGPT .AND. .NOT.HEAT) GO TO 800
C
C OPEN SCR1 AND SKIP THE TEMPERATURE DATA HAVING EXTERNAL INDICES
C
FILE = SCR1
CALL GOPEN (SCR1,Z(BUF1),RDREW)
IF (IRECS) 790,790,780
780 DO 785 I = 1,IRECS
CALL FWDREC (*840,SCR1)
785 CONTINUE
C
C COPY BALANCE OF SCR1 TO ETT
C
790 CALL READ (*800,*795,SCR1,Z,BUF2-1,0,FLAG)
CALL WRITE (ETT,Z,BUF2-1,0)
GO TO 790
795 CALL WRITE (ETT,Z,FLAG,1)
GO TO 790
800 CALL CLOSE (SCR1,REW)
CALL CLOSE (ETT, REW)
CALL WRTTRL (BUF)
C
C THERE WAS NO GPTT DATA AND ALSO NO ETT DATA. THUS RETURN HAVING
C CREATED NO ETT DATA SET.
C
810 RETURN
C
C ERROR CONDITIONS ON FILES
C
C
C FILE NOT IN FIST OR PURGED
C
820 J = -1
GO TO 850
C
C EOF HIT WHILE READING FILE
C
840 J = -2
850 CALL MESAGE (J,FILE,NAM)
RETURN
END
|
{
"pile_set_name": "Github"
}
|
/*
* Legal Notice
*
* This document and associated source code (the "Work") is a part of a
* benchmark specification maintained by the TPC.
*
* The TPC reserves all right, title, and interest to the Work as provided
* under U.S. and international laws, including without limitation all patent
* and trademark rights therein.
*
* No Warranty
*
* 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION
* CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE
* AUTHORS AND DEVELOPERS OF THE WORK 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 THE WORK.
* 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO
* ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO 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 THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD
* ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
*
* Contributors
* - Doug Johnson
*/
#include "main/CommissionRateTable.h"
#include <cstring>
using namespace TPCE;
CCommissionRateTable::CCommissionRateTable(const CommissionRateDataFile_t &dataFile)
: FixedTable<CommissionRateDataFile_t, COMMISSION_RATE_ROW>(dataFile) {
}
CCommissionRateTable::~CCommissionRateTable() {
}
void CCommissionRateTable::LoadTableRow() {
const CommissionRateDataFileRecord &dataRecord(df[recordIdx]);
tableRow.CR_C_TIER = dataRecord.CR_C_TIER();
strncpy(tableRow.CR_EX_ID, dataRecord.CR_EX_ID_CSTR(), sizeof(tableRow.CR_EX_ID));
tableRow.CR_FROM_QTY = dataRecord.CR_FROM_QTY();
tableRow.CR_RATE = dataRecord.CR_RATE();
tableRow.CR_TO_QTY = dataRecord.CR_TO_QTY();
strncpy(tableRow.CR_TT_ID, dataRecord.CR_TT_ID_CSTR(), sizeof(tableRow.CR_TT_ID));
}
|
{
"pile_set_name": "Github"
}
|
/*
* _______ _ _ _____ ____
* |__ __| | | | |/ ____| _ \
* | | ___ ___ _ __ _ _| | | | (___ | |_) |
* | |/ _ \/ _ \ '_ \| | | | | | |\___ \| _ <
* | | __/ __/ | | | |_| | |__| |____) | |_) |
* |_|\___|\___|_| |_|\__, |\____/|_____/|____/
* __/ |
* |___/
*
* TeenyUSB - light weight usb stack for micro controllers
*
* Copyright (c) 2020 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_DEF_H__
#define __TEENY_USB_DEF_H__
#include "stdint.h"
#define USB_LEN_DEV_QUALIFIER_DESC 0x0A
#define USB_LEN_DEV_DESC 0x12
#define USB_LEN_CFG_DESC 0x09
#define USB_LEN_IF_DESC 0x09
#define USB_LEN_EP_DESC 0x07
#define USB_LEN_OTG_DESC 0x03
#define USB_LEN_LANGID_STR_DESC 0x04
#define USB_LEN_OTHER_SPEED_DESC_SIZ 0x09
#define USB_LEN_IF_ASSOC_DESC 0x08
#define USB_LEN_FUNCTION_DESC 0x03
#define USBD_IDX_LANGID_STR 0x00
#define USBD_IDX_MFC_STR 0x01
#define USBD_IDX_PRODUCT_STR 0x02
#define USBD_IDX_SERIAL_STR 0x03
#define USBD_IDX_CONFIG_STR 0x04
#define USBD_IDX_INTERFACE_STR 0x05
#define USB_REQ_TYPE_STANDARD 0x00
#define USB_REQ_TYPE_CLASS 0x20
#define USB_REQ_TYPE_VENDOR 0x40
#define USB_REQ_TYPE_MASK 0x60
#define USB_REQ_RECIPIENT_DEVICE 0x00
#define USB_REQ_RECIPIENT_INTERFACE 0x01
#define USB_REQ_RECIPIENT_ENDPOINT 0x02
#define USB_REQ_RECIPIENT_MASK 0x03
#define USB_REQ_GET_STATUS 0x00
#define USB_REQ_CLEAR_FEATURE 0x01
#define USB_REQ_SET_FEATURE 0x03
#define USB_REQ_SET_ADDRESS 0x05
#define USB_REQ_GET_DESCRIPTOR 0x06
#define USB_REQ_SET_DESCRIPTOR 0x07
#define USB_REQ_GET_CONFIGURATION 0x08
#define USB_REQ_SET_CONFIGURATION 0x09
#define USB_REQ_GET_INTERFACE 0x0A
#define USB_REQ_SET_INTERFACE 0x0B
#define USB_REQ_SYNCH_FRAME 0x0C
#define USB_DESC_TYPE_DEVICE 1
#define USB_DESC_TYPE_CONFIGURATION 2
#define USB_DESC_TYPE_STRING 3
#define USB_DESC_TYPE_INTERFACE 4
#define USB_DESC_TYPE_ENDPOINT 5
#define USB_DESC_TYPE_DEVICE_QUALIFIER 6
#define USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION 7
#define USB_DESC_TYPE_BOS 0x0F
#define USB_DESC_TYPE_DEVICE_CAPABILITY 16
#define USB_DEVICE_DESCRIPTOR_TYPE 0x01
#define USB_CONFIGURATION_DESCRIPTOR_TYPE 0x02
#define USB_STRING_DESCRIPTOR_TYPE 0x03
#define USB_INTERFACE_DESCRIPTOR_TYPE 0x04
#define USB_ENDPOINT_DESCRIPTOR_TYPE 0x05
#define USB_IAD_DESCRIPTOR_TYPE 0x0B
#define USB_HUB_DESCRIPTOR_TYPE 0x29
#define USB_HID_DESCRIPTOR_TYPE 0x21
#define USB_REPORT_DESCRIPTOR_TYPE 0x22
#define USB_DESC_TYPE_REPORT 0x22
#define USB_FUCNTION_DESCRIPTOR_TYPE 0x24
#define USB_CLASS_DEVICE 0x00
#define USB_CLASS_AUDIO 0x01
#define USB_CLASS_CDC 0x02
#define USB_CLASS_HID 0x03
#define USB_CLASS_PHYSICAL 0x05
#define USB_CLASS_IMAGE 0x06
#define USB_CLASS_PRINTER 0x07
#define USB_CLASS_MASS_STORAGE 0x08
#define USB_CLASS_HUB 0x09
#define USB_CLASS_CDC_DATA 0x0a
#define USB_CLASS_SMART_CARD 0x0b
#define USB_CLASS_SECURITY 0x0d
#define USB_CLASS_VIDEO 0x0e
#define USB_CLASS_HEALTHCARE 0x0f
#define USB_CLASS_DIAG_DEVICE 0xdc
#define USB_CLASS_WIRELESS 0xe0
#define USB_CLASS_MISC 0xef
#define USB_CLASS_APP_SPECIFIC 0xfe
#define USB_CLASS_VEND_SPECIFIC 0xff
#define USB_CONFIG_REMOTE_WAKEUP 2
#define USB_CONFIG_SELF_POWERED 1
#define USB_FEATURE_EP_HALT 0
#define USB_FEATURE_REMOTE_WAKEUP 1
#define USB_FEATURE_TEST_MODE 2
#define USB_STATUS_REMOTE_WAKEUP 0x0002
#define USB_DEVICE_CAPABITY_TYPE 0x10
#define USB_HS_MAX_PACKET_SIZE 512
#define USB_FS_MAX_PACKET_SIZE 64
#define USB_MAX_EP0_SIZE 64
/* Device Status */
#define USBD_STATE_DEFAULT 1
#define USBD_STATE_ADDRESSED 2
#define USBD_STATE_CONFIGURED 3
#define USBD_STATE_SUSPENDED 4
/* EP0 State */
#define USBD_EP0_IDLE 0
#define USBD_EP0_SETUP 1
#define USBD_EP0_DATA_IN 2
#define USBD_EP0_DATA_OUT 3
#define USBD_EP0_STATUS_IN 4
#define USBD_EP0_STATUS_OUT 5
#define USBD_EP0_STALL 6
#define USBD_EP_TYPE_CTRL 0
#define USBD_EP_TYPE_ISOC 1
#define USBD_EP_TYPE_BULK 2
#define USBD_EP_TYPE_INTR 3
#define USBD_EP_TYPE_MASK 3
#ifndef SWAPBYTE
#define SWAPBYTE(addr) (((uint16_t)(*((uint8_t *)(addr)))) + \
(((uint16_t)(*(((uint8_t *)(addr)) + 1))) << 8))
#endif
#ifndef LO_BYTE
#define LO_BYTE(x) ((uint8_t)(x & 0x00FF))
#endif
#ifndef HI_BYTE
#define HI_BYTE(x) ((uint8_t)((x & 0xFF00) >>8))
#endif
#ifndef MIN
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#if defined ( __GNUC__ )
#ifndef __weak
#define __weak __attribute__((weak))
#endif /* __weak */
#ifndef __packed
#define __packed __attribute__((__packed__))
#endif /* __packed */
#elif defined(__CC_ARM)
#else
// unknown compiler
#define __weak
#endif /* __GNUC__ */
#define WEAK __weak
/* In HS mode and when the DMA is used, all variables and data structures dealing
with the DMA during the transaction process should be 4-bytes aligned */
#if defined (__GNUC__) /* GNU Compiler */
#define __ALIGN_END __attribute__ ((aligned (4)))
#define __ALIGN_BEGIN
#else
#define __ALIGN_END
#if defined (__CC_ARM) /* ARM Compiler */
#define __ALIGN_BEGIN __align(4)
#elif defined (__ICCARM__) /* IAR Compiler */
#define __ALIGN_BEGIN
#elif defined (__TASKING__) /* TASKING Compiler */
#define __ALIGN_BEGIN __align(4)
#else
#define __ALIGN_BEGIN
#endif /* __CC_ARM */
#endif /* __GNUC__ */
#define STATIC_ASSERT4(COND,MSG) typedef char static_assertion_##MSG[(!!(COND))*2-1];
#define STATIC_ASSERT3(X,L) STATIC_ASSERT4(X,_at_line_##L)
#define STATIC_ASSERT2(X,L) STATIC_ASSERT3(X,L)
#define STATIC_ASSERT(X) STATIC_ASSERT2(X,__LINE__)
#if defined (__GNUC__)
#define __PACK_BEGIN
#define __PACK_END __packed
#elif defined(__CC_ARM)
#define __PACK_BEGIN __packed
#define __PACK_END
#else
#define __PACK_BEGIN
#define __PACK_END
#endif
typedef __PACK_BEGIN struct _usb_device_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize;
uint16_t idVendor;
uint16_t idProduct;
uint16_t bcdDevice;
uint8_t iManufacturer;
uint8_t iProduct;
uint8_t iSerialNumber;
uint8_t bNumConfigurations;
} __PACK_END usb_device_descriptor_t;
STATIC_ASSERT(sizeof(usb_device_descriptor_t) == USB_LEN_DEV_DESC)
typedef __PACK_BEGIN struct _usb_device_qualifier_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t bcdUSB;
uint8_t bDeviceClass;
uint8_t bDeviceSubClass;
uint8_t bDeviceProtocol;
uint8_t bMaxPacketSize;
uint8_t bNumConfigurations;
uint8_t bReserved;
} __PACK_END usb_device_qualifier_descriptor_t;
STATIC_ASSERT(sizeof(usb_device_qualifier_descriptor_t) == USB_LEN_DEV_QUALIFIER_DESC)
typedef __PACK_BEGIN struct _usb_config_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint16_t wTotalLength;
uint8_t bNumInterfaces;
uint8_t bConfigurationValue;
uint8_t iConfiguration;
uint8_t bmAttributes;
uint8_t bMaxPower;
} __PACK_END usb_config_descriptor_t;
STATIC_ASSERT(sizeof(usb_config_descriptor_t) == USB_LEN_CFG_DESC)
typedef __PACK_BEGIN struct _usb_interface_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bInterfaceNumber;
uint8_t bAlternateSetting;
uint8_t bNumEndpoints;
uint8_t bInterfaceClass;
uint8_t bInterfaceSubClass;
uint8_t bInterfaceProtocol;
uint8_t iInterface;
} __PACK_END usb_interface_descriptor_t;
STATIC_ASSERT(sizeof(usb_interface_descriptor_t) == USB_LEN_IF_DESC)
typedef __PACK_BEGIN struct _usb_endpoint_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bEndpointAddress;
uint8_t bmAttributes;
uint16_t wMaxPacketSize;
uint8_t bInterval;
} __PACK_END usb_endpoint_descriptor_t;
STATIC_ASSERT(sizeof(usb_endpoint_descriptor_t) == USB_LEN_EP_DESC)
typedef __PACK_BEGIN struct _usb_interface_association_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bFirstInterface;
uint8_t bInterfaceCount;
uint8_t bFunctionClass;
uint8_t bFunctionSubClass;
uint8_t bFunctionProtocol;
uint8_t iFunction;
} __PACK_END usb_interface_association_descriptor_t;
STATIC_ASSERT(sizeof(usb_interface_association_descriptor_t) == USB_LEN_IF_ASSOC_DESC)
typedef __PACK_BEGIN struct _usb_function_descriptor {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubtype;
} __PACK_END usb_function_descriptor_t;
STATIC_ASSERT(sizeof(usb_function_descriptor_t) == USB_LEN_FUNCTION_DESC)
/* Macros: */
/** Flag used to send data, to indicate that the core will send zero length packet as need */
#define TUSB_TXF_ZLP ((uint8_t)0x80)
/** Flag used to send data, to indicate that the core will send 1 packet pre frame in high speed periodic endpoint */
#define TUSB_TXF_MC1 ((uint8_t)0x00)
/** Flag used to send data, to indicate that the core will send 2 packet pre frame in high speed periodic endpoint */
#define TUSB_TXF_MC2 ((uint8_t)0x01)
/** Flag used to send data, to indicate that the core will send 3 packet pre frame in high speed periodic endpoint */
#define TUSB_TXF_MC3 ((uint8_t)0x02)
#define TUSB_DBG_LEVEL_DEBUG 1
#define TUSB_DBG_LEVEL_WARNING 2
#define TUSB_DBG_LEVEL_ERROR 3
#define TUSB_DBG_LEVEL_NONE 4
/** USB port speed high speed */
#define PORT_SPEED_HIGH 0U
/** USB port speed full speed */
#define PORT_SPEED_FULL 1U
/** USB port speed low speed */
#define PORT_SPEED_LOW 2U
#endif
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
* Core Library Version 1.7, August 2004
* Copyright (c) 1995-2004 Exact Computation Project
* All rights reserved.
*
* This file is part of CORE (http://cs.nyu.edu/exact/core/).
* 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 3 of the License, or (at your option) any later version.
*
* Licensees holding a valid commercial license may use this file in
* accordance with the commercial license agreement provided with the
* software.
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*
* $URL$
* $Id$
***************************************************************************/
/******************************************************************
* Core Library Version 1.7, August 2004
* Copyright (c) 1995-2002 Exact Computation Project
*
* File: LinearAlgebra.h
* Synopsis:
* Linear Algebra Extension of Core Library introducing
* class Vector
* class Matrix
*
* Written by
* Shubin Zhao (shubinz@cs.nyu.edu) (2001)
*
* WWW URL: http://cs.nyu.edu/exact/
* Email: exact@cs.nyu.edu
*
* $Id$
*****************************************************************/
#ifndef CORE_LINEAR_ALGEBRA_H
#define CORE_LINEAR_ALGEBRA_H
#ifndef CORE_LEVEL
# define CORE_LEVEL 3
#endif
#include <cstdarg>
#include <CGAL/CORE/CORE.h>
class Vector;
class Matrix;
////////////////////////////////////////////////////////////////////////
// Class Vector
// Generic vectors
// Operations implemented: addition, subtraction, dot product
////////////////////////////////////////////////////////////////////////
class Vector {
private:
int dim;
double* _rep;
public:
class RangeException { };
class ArithmeticException { };
explicit Vector(int);
Vector();
Vector(double, double);
Vector(double, double, double);
Vector(const Vector&);
Vector(int, double *);
~Vector();
const Vector& operator=(const Vector&);
bool operator==(const Vector&);
bool operator!=(const Vector&);
const Vector& operator+=(const Vector&);
const Vector& operator-=(const Vector&);
const Vector& operator*=(double);
const double& operator[](int) const;
double& operator[](int);
double norm() const;
double maxnorm() const;
double infnorm() const;
double dimension() const {return dim;}
bool isZero() const;
Vector cross(const Vector &v) const;
static Vector crossProduct(int, ...);
friend Vector operator+(const Vector&, const Vector&);
friend Vector operator-(const Vector&, const Vector&);
friend Vector operator-(const Vector&);
friend Vector operator*(const Vector&, double);
friend Vector operator*(double, const Vector&);
friend Vector operator*(const Matrix&, const Vector&);
friend Vector operator*(const Vector&, const Matrix&);
friend double dotProduct(const Vector&, const Vector&);
friend std::istream& operator>>(std::istream&, Vector&);
friend std::ostream& operator<<(std::ostream&, const Vector&);
};
////////////////////////////////////////////////////////////////////////
// Class Matrix
// Generic matrices
// Operations implemented: addition, subtraction, multiplication
////////////////////////////////////////////////////////////////////////
class Matrix {
private:
int dim1, dim2;
double* _rep;
public:
class RangeException { };
class ArithmeticException { };
explicit Matrix(int);
Matrix(int, int);
Matrix(int, int, double *);
Matrix(double, double,
double, double);
Matrix(double, double, double,
double, double, double,
double, double, double);
Matrix(const Matrix&);
~Matrix();
Matrix& operator=(const Matrix&);
bool operator==(const Matrix&);
bool operator!=(const Matrix&);
const Matrix& operator+=(const Matrix&);
const Matrix& operator-=(const Matrix&);
const Matrix& operator*=(double);
const double& operator()(int, int) const;
double& operator()(int, int);
// added by chen li
// const Vector& row(int i) const;
// const Vector& col(int i) const;
Matrix matrixAlgebraRemainder(int, int) const;
double valueAlgebraRemainder(int, int) const;
const Matrix& transpose();
double determinant() const;
int dimension_1() const { return dim1; }
int dimension_2() const { return dim2; }
friend Matrix operator+(const Matrix&, const Matrix&);
friend Matrix operator-(const Matrix&, const Matrix&);
friend Matrix operator*(const Matrix&, double);
friend Matrix operator*(double, const Matrix&);
friend Vector operator*(const Vector&, const Matrix&);
friend Vector operator*(const Matrix&, const Vector&);
friend Matrix operator*(const Matrix&, const Matrix&);
friend Matrix transpose(const Matrix&);
friend double det(const double a, const double b,
const double c, const double d);
friend double det(const Vector u, const Vector & v); // u,v are 2d vectors
friend std::istream& operator>>(std::istream&, Matrix&);
friend std::ostream& operator<<(std::ostream&, const Matrix&);
}; //Matrix
#endif
|
{
"pile_set_name": "Github"
}
|
// Хранилище глобальных переменных.
//
// ПараметрыПриложения - Соответствие - хранилище переменных, где:
// * Ключ - Строка - имя переменной в формате "ИмяБиблиотеки.ИмяПеременной";
// * Значение - Произвольный - значение переменной.
//
// Инициализация (на примере СообщенияДляЖурналаРегистрации):
// ИмяПараметра = "СтандартныеПодсистемы.СообщенияДляЖурналаРегистрации";
// Если ПараметрыПриложения[ИмяПараметра] = Неопределено Тогда
// ПараметрыПриложения.Вставить(ИмяПараметра, Новый СписокЗначений);
// КонецЕсли;
//
// Использование (на примере СообщенияДляЖурналаРегистрации):
// ПараметрыПриложения["СтандартныеПодсистемы.СообщенияДляЖурналаРегистрации"].Добавить(...);
// ПараметрыПриложения["СтандартныеПодсистемы.СообщенияДляЖурналаРегистрации"] = ...;
Перем УИ_ПараметрыПриложения Экспорт;
//@skip-warning
&После("ПриНачалеРаботыСистемы")
Процедура УИ_ПриНачалеРаботыСистемы()
ПараметрыСтартаСеанса=УИ_ОбщегоНазначенияВызовСервера.ПараметрыСтартаСеанса();
Если ПараметрыСтартаСеанса.ДобавленыПраваНаРасширение Тогда
ЗавершитьРаботуСистемы(Ложь, Истина);
КонецЕсли;
УИ_ПараметрыПриложения.Вставить("НомерСеанса", ПараметрыСтартаСеанса.НомерСеанса);
КонецПроцедуры
&После("ПриЗавершенииРаботыСистемы")
Процедура УИ_ПриЗавершенииРаботыСистемы()
УИ_РедакторКодаКлиент.УдалитьБибилиотекуРедактораКодаСДиска();
КонецПроцедуры
УИ_ПараметрыПриложения = Новый Соответствие;
|
{
"pile_set_name": "Github"
}
|
<header>ADSL Клиентски модул</header>
Този модул ви позволява да конфигурирате RP-PPPoE ADSL клиентска програма,
която се използва за свързване в Мрежата посредством Ethernet-свързан
ADSL модем поддържащ PPPoE (PPP през Ethernet) протокол. Той няма да
работи с USB свързани ADSL модеми нито с тези намиращи се в мостово състояние. <p>
Преди да го използвате трябва да имате сметка към ADSL доставчик,
и модема ви да бъде свързан към неизползван Ethernet интерфейс на вашата Linux
система. Този интерфейс трябва да е видим за ядрото и не трябва да има
IP адрес. <p>
<hr>
|
{
"pile_set_name": "Github"
}
|
/**
* MIT License
* <p>
* Copyright (c) 2017 James
* <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>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <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 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.
*/
package me.zbl.mediator;
/**
* 派对成员
*/
public interface PartyMember {
void joinParty(Party party);
void partyActivity(Activity activity);
void act(Activity activity);
}
|
{
"pile_set_name": "Github"
}
|
#
# a
#
b
#
# a
#
|
{
"pile_set_name": "Github"
}
|
;******************** (C) COPYRIGHT 2011 STMicroelectronics ********************
;* File Name : startup_stm32f10x_ld.s
;* Author : MCD Application Team
;* Version : V3.5.0
;* Date : 11-March-2011
;* Description : STM32F10x Low Density Devices vector table for EWARM
;* toolchain.
;* This module performs:
;* - Set the initial SP
;* - Configure the clock system
;* - Set the initial PC == __iar_program_start,
;* - Set the vector table entries with the exceptions ISR
;* address.
;* After Reset the Cortex-M3 processor is in Thread mode,
;* priority is Privileged, and the Stack is set to Main.
;********************************************************************************
;* 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.
;*******************************************************************************
;
;
; The modules in this file are included in the libraries, and may be replaced
; by any user-defined modules that define the PUBLIC symbol _program_start or
; a user defined start symbol.
; To override the cstartup defined in the library, simply add your modified
; version to the workbench project.
;
; The vector table is normally located at address 0.
; When debugging in RAM, it can be located in RAM, aligned to at least 2^6.
; The name "__vector_table" has special meaning for C-SPY:
; it is where the SP start value is found, and the NVIC vector
; table register (VTOR) is initialized to this address if != 0.
;
; Cortex-M version
;
MODULE ?cstartup
;; Forward declaration of sections.
SECTION CSTACK:DATA:NOROOT(3)
SECTION .intvec:CODE:NOROOT(2)
EXTERN __iar_program_start
EXTERN SystemInit
PUBLIC __vector_table
DATA
__vector_table
DCD sfe(CSTACK)
DCD Reset_Handler ; Reset Handler
DCD NMI_Handler ; NMI Handler
DCD HardFault_Handler ; Hard Fault Handler
DCD MemManage_Handler ; MPU Fault Handler
DCD BusFault_Handler ; Bus Fault Handler
DCD UsageFault_Handler ; Usage Fault Handler
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD SVC_Handler ; SVCall Handler
DCD DebugMon_Handler ; Debug Monitor Handler
DCD 0 ; Reserved
DCD PendSV_Handler ; PendSV Handler
DCD SysTick_Handler ; SysTick Handler
; External Interrupts
DCD WWDG_IRQHandler ; Window Watchdog
DCD PVD_IRQHandler ; PVD through EXTI Line detect
DCD TAMPER_IRQHandler ; Tamper
DCD RTC_IRQHandler ; RTC
DCD FLASH_IRQHandler ; Flash
DCD RCC_IRQHandler ; RCC
DCD EXTI0_IRQHandler ; EXTI Line 0
DCD EXTI1_IRQHandler ; EXTI Line 1
DCD EXTI2_IRQHandler ; EXTI Line 2
DCD EXTI3_IRQHandler ; EXTI Line 3
DCD EXTI4_IRQHandler ; EXTI Line 4
DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1
DCD DMA1_Channel2_IRQHandler ; DMA1 Channel 2
DCD DMA1_Channel3_IRQHandler ; DMA1 Channel 3
DCD DMA1_Channel4_IRQHandler ; DMA1 Channel 4
DCD DMA1_Channel5_IRQHandler ; DMA1 Channel 5
DCD DMA1_Channel6_IRQHandler ; DMA1 Channel 6
DCD DMA1_Channel7_IRQHandler ; DMA1 Channel 7
DCD ADC1_2_IRQHandler ; ADC1 & ADC2
DCD USB_HP_CAN1_TX_IRQHandler ; USB High Priority or CAN1 TX
DCD USB_LP_CAN1_RX0_IRQHandler ; USB Low Priority or CAN1 RX0
DCD CAN1_RX1_IRQHandler ; CAN1 RX1
DCD CAN1_SCE_IRQHandler ; CAN1 SCE
DCD EXTI9_5_IRQHandler ; EXTI Line 9..5
DCD TIM1_BRK_IRQHandler ; TIM1 Break
DCD TIM1_UP_IRQHandler ; TIM1 Update
DCD TIM1_TRG_COM_IRQHandler ; TIM1 Trigger and Commutation
DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare
DCD TIM2_IRQHandler ; TIM2
DCD TIM3_IRQHandler ; TIM3
DCD 0 ; Reserved
DCD I2C1_EV_IRQHandler ; I2C1 Event
DCD I2C1_ER_IRQHandler ; I2C1 Error
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD SPI1_IRQHandler ; SPI1
DCD 0 ; Reserved
DCD USART1_IRQHandler ; USART1
DCD USART2_IRQHandler ; USART2
DCD 0 ; Reserved
DCD EXTI15_10_IRQHandler ; EXTI Line 15..10
DCD RTCAlarm_IRQHandler ; RTC Alarm through EXTI Line
DCD USBWakeUp_IRQHandler ; USB Wakeup from suspend
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Default interrupt handlers.
;;
THUMB
PUBWEAK Reset_Handler
SECTION .text:CODE:REORDER(2)
Reset_Handler
LDR R0, =SystemInit
BLX R0
LDR R0, =__iar_program_start
BX R0
PUBWEAK NMI_Handler
SECTION .text:CODE:REORDER(1)
NMI_Handler
B NMI_Handler
PUBWEAK HardFault_Handler
SECTION .text:CODE:REORDER(1)
HardFault_Handler
B HardFault_Handler
PUBWEAK MemManage_Handler
SECTION .text:CODE:REORDER(1)
MemManage_Handler
B MemManage_Handler
PUBWEAK BusFault_Handler
SECTION .text:CODE:REORDER(1)
BusFault_Handler
B BusFault_Handler
PUBWEAK UsageFault_Handler
SECTION .text:CODE:REORDER(1)
UsageFault_Handler
B UsageFault_Handler
PUBWEAK SVC_Handler
SECTION .text:CODE:REORDER(1)
SVC_Handler
B SVC_Handler
PUBWEAK DebugMon_Handler
SECTION .text:CODE:REORDER(1)
DebugMon_Handler
B DebugMon_Handler
PUBWEAK PendSV_Handler
SECTION .text:CODE:REORDER(1)
PendSV_Handler
B PendSV_Handler
PUBWEAK SysTick_Handler
SECTION .text:CODE:REORDER(1)
SysTick_Handler
B SysTick_Handler
PUBWEAK WWDG_IRQHandler
SECTION .text:CODE:REORDER(1)
WWDG_IRQHandler
B WWDG_IRQHandler
PUBWEAK PVD_IRQHandler
SECTION .text:CODE:REORDER(1)
PVD_IRQHandler
B PVD_IRQHandler
PUBWEAK TAMPER_IRQHandler
SECTION .text:CODE:REORDER(1)
TAMPER_IRQHandler
B TAMPER_IRQHandler
PUBWEAK RTC_IRQHandler
SECTION .text:CODE:REORDER(1)
RTC_IRQHandler
B RTC_IRQHandler
PUBWEAK FLASH_IRQHandler
SECTION .text:CODE:REORDER(1)
FLASH_IRQHandler
B FLASH_IRQHandler
PUBWEAK RCC_IRQHandler
SECTION .text:CODE:REORDER(1)
RCC_IRQHandler
B RCC_IRQHandler
PUBWEAK EXTI0_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI0_IRQHandler
B EXTI0_IRQHandler
PUBWEAK EXTI1_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI1_IRQHandler
B EXTI1_IRQHandler
PUBWEAK EXTI2_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI2_IRQHandler
B EXTI2_IRQHandler
PUBWEAK EXTI3_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI3_IRQHandler
B EXTI3_IRQHandler
PUBWEAK EXTI4_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI4_IRQHandler
B EXTI4_IRQHandler
PUBWEAK DMA1_Channel1_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel1_IRQHandler
B DMA1_Channel1_IRQHandler
PUBWEAK DMA1_Channel2_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel2_IRQHandler
B DMA1_Channel2_IRQHandler
PUBWEAK DMA1_Channel3_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel3_IRQHandler
B DMA1_Channel3_IRQHandler
PUBWEAK DMA1_Channel4_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel4_IRQHandler
B DMA1_Channel4_IRQHandler
PUBWEAK DMA1_Channel5_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel5_IRQHandler
B DMA1_Channel5_IRQHandler
PUBWEAK DMA1_Channel6_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel6_IRQHandler
B DMA1_Channel6_IRQHandler
PUBWEAK DMA1_Channel7_IRQHandler
SECTION .text:CODE:REORDER(1)
DMA1_Channel7_IRQHandler
B DMA1_Channel7_IRQHandler
PUBWEAK ADC1_2_IRQHandler
SECTION .text:CODE:REORDER(1)
ADC1_2_IRQHandler
B ADC1_2_IRQHandler
PUBWEAK USB_HP_CAN1_TX_IRQHandler
SECTION .text:CODE:REORDER(1)
USB_HP_CAN1_TX_IRQHandler
B USB_HP_CAN1_TX_IRQHandler
PUBWEAK USB_LP_CAN1_RX0_IRQHandler
SECTION .text:CODE:REORDER(1)
USB_LP_CAN1_RX0_IRQHandler
B USB_LP_CAN1_RX0_IRQHandler
PUBWEAK CAN1_RX1_IRQHandler
SECTION .text:CODE:REORDER(1)
CAN1_RX1_IRQHandler
B CAN1_RX1_IRQHandler
PUBWEAK CAN1_SCE_IRQHandler
SECTION .text:CODE:REORDER(1)
CAN1_SCE_IRQHandler
B CAN1_SCE_IRQHandler
PUBWEAK EXTI9_5_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI9_5_IRQHandler
B EXTI9_5_IRQHandler
PUBWEAK TIM1_BRK_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM1_BRK_IRQHandler
B TIM1_BRK_IRQHandler
PUBWEAK TIM1_UP_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM1_UP_IRQHandler
B TIM1_UP_IRQHandler
PUBWEAK TIM1_TRG_COM_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM1_TRG_COM_IRQHandler
B TIM1_TRG_COM_IRQHandler
PUBWEAK TIM1_CC_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM1_CC_IRQHandler
B TIM1_CC_IRQHandler
PUBWEAK TIM2_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM2_IRQHandler
B TIM2_IRQHandler
PUBWEAK TIM3_IRQHandler
SECTION .text:CODE:REORDER(1)
TIM3_IRQHandler
B TIM3_IRQHandler
PUBWEAK I2C1_EV_IRQHandler
SECTION .text:CODE:REORDER(1)
I2C1_EV_IRQHandler
B I2C1_EV_IRQHandler
PUBWEAK I2C1_ER_IRQHandler
SECTION .text:CODE:REORDER(1)
I2C1_ER_IRQHandler
B I2C1_ER_IRQHandler
PUBWEAK SPI1_IRQHandler
SECTION .text:CODE:REORDER(1)
SPI1_IRQHandler
B SPI1_IRQHandler
PUBWEAK USART1_IRQHandler
SECTION .text:CODE:REORDER(1)
USART1_IRQHandler
B USART1_IRQHandler
PUBWEAK USART2_IRQHandler
SECTION .text:CODE:REORDER(1)
USART2_IRQHandler
B USART2_IRQHandler
PUBWEAK EXTI15_10_IRQHandler
SECTION .text:CODE:REORDER(1)
EXTI15_10_IRQHandler
B EXTI15_10_IRQHandler
PUBWEAK RTCAlarm_IRQHandler
SECTION .text:CODE:REORDER(1)
RTCAlarm_IRQHandler
B RTCAlarm_IRQHandler
PUBWEAK USBWakeUp_IRQHandler
SECTION .text:CODE:REORDER(1)
USBWakeUp_IRQHandler
B USBWakeUp_IRQHandler
END
/******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
|
{
"pile_set_name": "Github"
}
|
/*
FreeRTOS+TCP V2.2.2
Copyright (C) 2017 Amazon.com, Inc. or its affiliates. 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.
http://aws.amazon.com/freertos
http://www.FreeRTOS.org
*/
/*****************************************************************************
*
* See the following URL for an explanation of this file:
* http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/Embedded_Compiler_Porting.html
*
*****************************************************************************/
__attribute__( (packed) );
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.