text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
bitcoin trading software reviews India
binary banc & ten options Malaysia
crypto trading cfd calculator India
is bitcoin trading profitable India
online crypto trading bot South Africa
resolute crypto trading is it safe South Africa
bitcoin trading bot platform India
how to hedge forex with binary options Malaysia
should i invest in gold or bitcoin Malaysia
10000 invested in bitcoin in 2010 Singapore
a comprehensive guide to recover money lost to binary options Singapore
how old to do binary options India
crypto trading and holding Malaysia
can hedge funds invest in bitcoin Singapore
crypto asset trading platforms Malaysia
bitcoin investment codecanyon India
list of binary option companies Singapore
binary options gold cars Malaysia
teamalliance live nadex binary options training Malaysia
binary option on bitcoin Singapore
what is the binary options market Malaysia
best binary option app in nigeria South Africa
banks trading bitcoin futures India
was bitcoin a good investment Singapore
appli trading crypto South Africa
forex.com web trading platform account login different from mt4 account? Singapore
how to apply binary operands on optionals in ios swifts Singapore
legit bitcoin mining without investment India
cheap crypto trading bot Malaysia
best bitcoin trading bot reddit Singapore
abu dhabi bitcoin investment India
investing in bitcoin short term India
strong in capital markets, brokerage space and trading platform in resume Singapore
the option pro reviews Singapore
deep learning bitcoin trading bot Singapore
what is the best pennystock trading platform South Africa
invest a small amount of money in bitcoin Malaysia
binary options indicator download Malaysia
signal trading vip bitcoin India
ox trading platform India
best bitcoin to invest into South Africa
hedge funds are quietly investing in bitcoin South Africa
can binary options make you rich Malaysia
top capital options South Africa
c trading platform Singapore
cryptocurrency binary option us brokers Malaysia
guide to crypto day trading South Africa
paper trading app crypto itunes India
win loss binary options count Malaysia
bitcoin trading hours in india South Africa
bitcoin investment trust assets India
best website to invest in bitcoin South Africa
markets world binary options trading Malaysia
i want to trade binary options South Africa
marketsworld trading platform Malaysia
binary options pro signals review Singapore
crypto trading sites fox logo Malaysia
bitcoin trading suggestions South Africa
bitcoin investing for profit Singapore
largest us online stock trading platform South Africa
how to start bitcoin trading uk Singapore
binary option brokers using paypal Singapore
crypto trading robot review South Africa
binary option auto trading youtube India
china banned crypto trading Malaysia
trading platform with database access India
black scholes fair values of binary options India
if i have a forex account what trading platform do i use Malaysia
thinkorswim free trading platform India
united states binary options brokers Malaysia
best way to invest in fractional bitcoin India
binary option halal apa haram South Africa
nadex out of money binary options Singapore
best binary options copy trading Malaysia
apex futures trading platform Malaysia
binary options trading platform download Malaysia
is bitcoin the best cryptocurrency to invest in Malaysia
compounding calculaotr binary options India
ig com binary options Singapore
tr binary options real Malaysia
touch binary options strategy Malaysia
vanguard trading platform? Malaysia
best ios crypto trading app Malaysia
does the irs treat bitcoin trading as currency trading? Singapore
barclay bank warned about binary options trading India
top binary options canada South Africa
digital currency trading platform Malaysia
how does trading in bitcoin work South Africa
michael freeman binary options strategy Malaysia
castro edwin crypto trading India
best savings account bitcoin trading South Africa
binary options podcast South Africa
day trading platform canada Singapore
best cypto trading platform Singapore
bitcoin trading on stock market Singapore
eu ban binary options alternative India
how do i invest in bitcoin nz Singapore
how will bitcoin futures trading affect price India
real time stock trading platform South Africa
stocks to invest in for exposure to bitcoin surge South Africa
reliable binary options strategy Singapore
the dividend machine scam South Africa
aig bitcoin investments India
binary options in c India
open a binary option account South Africa
open source bitcoin trading platform Singapore
forex trading platform ranking Singapore
what trading platform or broker has the fastest option trading executions Malaysia
best bitcoin trading app australia Singapore
trading platform with kucoinm South Africa
why no bitcoin trading in new york India
forex.com trading platform download India
365 binary option regulated South Africa
trade binary options like a pro Singapore
which day-trading platform has scope to buy bitcoins India
usd e-wallet for bitcoin trading South Africa
bitcoin sv not trading Malaysia
etf that invest in bitcoin India
iq option app Malaysia
binary option trader life site youtube.com South Africa
cours bitcoin euro investing Singapore
binary option nairaland 2018 South Africa
boundary binary options India
como se hace trading con bitcoin South Africa
c binary serialization optional field Malaysia
crypto day trading taxes vs crypto holding India
reddit day trading platform India
tax on bitcoin trading india Malaysia
trading bitcoin easy steps South Africa
launch crypto trading South Africa
united binary options Singapore
was bitcoin a successful investment India
binary options trading community India
schwab binary options Malaysia
best research on binary options Malaysia
investir em bitcoin passo a passo Singapore
trading platform lending sblc Singapore
binary options candlestick strategy pdf Malaysia
best bitcoin trading account Malaysia
the greeks crypto trading Malaysia
is crypto insider trading illegal Singapore
best app online trading platform no minimum Malaysia
what trading platform do professionals use Malaysia
comparing different bitcoin trading platforms Singapore
como investir em bitcoin passo a passo 2019 Malaysia
omega options scam Malaysia
binary option minimum deposit South Africa
crypto trading bots 2019 India
investir em bitcoins Singapore
reviews on bitcoin platform automated trading platform India
cboe binary options s& Malaysia
tradestation how do i know what version of the trading platform i am running Singapore
sec suspends bitcoin trading Malaysia
figuring out net profit from bitcoins trading Malaysia
bitcoin trading at right now India
eli5 bitcoin trading Malaysia
how good is charles schwab's trading platform Singapore
nadex binary optiona Malaysia
best bitcoin trading alls South Africa
how do you invest in bitcoin in uk India
stock market binary options South Africa
binary options trading nadex youtube India
bitcoin trading without verification South Africa
fidelity mobile trading platform South Africa
invest in bitcoin 2020 novemen ber India
binary options calculator download India
bird view binary options Malaysia
stock trading classes near me South Africa
is bitcoin always trading Singapore
binary option robot review forum Singapore
bitcoin currenc investment or commodity Singapore
how to start a bitcoin investment company Singapore
trik trading di vip bitcoin Singapore
other investment like bitcoin Singapore
us binary options no deposit bonus Singapore
winning binary options trading strategy South Africa
how to see linked accounts in thinkorswim trading platform South Africa
trading bitcoin sv in us South Africa
free trading platform for charting Malaysia
bitcoin cash investing com Malaysia
onetwotrade binary options South Africa
binary options demo youtube Malaysia
binary options us trading low minimum deposit Malaysia
bitcoin gold investment app South Africa
bests and easiest crypto currency trading platform Malaysia
advanced bitcoin trading book India
free binary options indicator software Malaysia
bitcoin momentum hashrate trading view Singapore
best companies to trade options South Africa
make bitcoins daily investment Malaysia
trading crypto on kraken Malaysia
binary options industry growth Singapore
binary option trader forum India
what is a good trading platform India
bitcoin trading vlaue South Africa
trend following binary options system Singapore
bitcoin trading neat South Africa
bitcoin investing denver co India
closing time for bitcoin trading Malaysia
index binary options South Africa
cardano trading platform Singapore
what is bitcoin trading and how does it work India
fxglory binary options Malaysia
static replicatin of binary options Singapore
bitcoin investment trust and bitcoin cash South Africa
tb binary options India
ai based bitcoin trading India
et binary options Malaysia
binary options brokers for us residents 2020 South Africa
bitcoin vs ethereum price prediction investment advice South Africa
jp 90 day beginner routine video Malaysia
best trading platform nerdwallet Singapore
metatrader 5 binary options advisors South Africa
how much money do i need to invest in bitcoin Malaysia
order flow trading platform India
advanced bitcoin trading India
low cost trading platform ratings Malaysia
binary option money management excel South Africa
why aren't there many binary options in usa? Singapore
invest in companies using bitcoin India
who is successfully algo trading bitcoin South Africa
is robinhood a good trading platform? Singapore
is buying bitcoin a smart investment India
how nadex binary options works South Africa
voyager trading bitcoin South Africa
binary options credit card Malaysia
sa crypto trading platforms Malaysia
most up to date cyrpto trading platform Malaysia
professional forex trading platform India
non repainting binary options indicator Malaysia
crypto tradings hiring manager South Africa
bitcoin trading newsletter Singapore
how can i maintain high liquidity in crypto trading South Africa
alpari binary option trading download South Africa
1 min binary options united states South Africa
veltyco fx binary options Malaysia
binary options binary promo code South Africa
bitcoin trading tutorial pdf Singapore
the binary succession South Africa
mirror trading crypto Malaysia
top bitcoin trading website India
bitcoin investment facts India
demo binary options united states South Africa
binary option 10 minimum deposit India
best investment after bitcoin India
sierra charts bitcoin trading South Africa
best binary options platform usa South Africa
how to trade binary options using mt4 South Africa
graphics binary options India
salt crypto trading price South Africa
brokers binary option in usa Malaysia
tips for binary options trading India
which exchanges are trading bitcoin cash Singapore
bitcoin trading gui Singapore
us bitcoin margain trading Singapore
investing vs trading bitcoin South Africa
nadex binary options api India
why bitcoin is a good investment Singapore
how many gbs of data does the tws trading platform use per month South Africa
trading view for bitcoin Singapore
how to trade binary options book South Africa
bitcoin investment loss tax deduction India
does bitcoin count as day trading South Africa
binary options strategy for beginners binary option trading strategy publisher Singapore
what happened to binary options trading advertising South Africa
rends in crypto strategy and trading Malaysia
binary options xls Malaysia
bitcoin trading exhcnage Malaysia
tickmill trading platform Singapore
investment opportunities like bitcoin Singapore
how does yahoo determine opening time for bitcoin trading South Africa
app for bitcoin trading demo South Africa
is bitcoin a good investment december 2018 Singapore
how much is the minimum you can invest in bitcoin Singapore
market world binary Malaysia
how to join binary options South Africa
bill gates bitcoin wealth investment Singapore
options trading canada Malaysia
make bitcoins daily investment Malaysia
how do brokers make money on binary options India
24option scam South Africa
binary options no deposit limit India
tac software for binary options Singapore
boconcept uk Singapore
gdm-binary options Malaysia
best crypto futures trading Singapore
is crypto trading a con South Africa
binary options long term strategy South Africa
marketsworld trading platform Singapore
crypto trading cheat sheet India
bitcoin investment calculator in 2010 Singapore
yahoo answes investing in bitcoin South Africa
binary options price action strategy pdf India
try binary options for free India
is bitcoin gold a good investment reddit Malaysia
binary options social trading network Singapore
how tio invest in bitcoins India
equity options trading platform and uk and south africa India
dave ramsey investing in bitcoin Malaysia
most profitable binary options strategy India
forex binary options meaning South Africa
crypto trading bot gdax Malaysia
bitcoin ira better investment Singapore
which trading platform sells vegn etf South Africa
bitcoin trading software quora India
free trading platform for cryptocurrency South Africa
australian options trading platform Singapore
zerodha trading platform Singapore
trade binary options with metatrader South Africa
bitcoin trading apps 2017 South Africa
website for bitcoin trading Malaysia
is trading binary options legal in uk Singapore
artificial intelligence stock trading platform South Africa
god strategy binary options pdf Malaysia
bitcoin trading app shark tank India
best us trading bitcoin Malaysia
trading bitcoin for stock taxable Singapore
bond large trading platform Singapore
bitcoin if you invested 2010 India
binary options algorithm software India
is rightbtc a scam trading platform India
bitcoin trading platform gdex India
what bitcoin indicators should i have on trading view Singapore
binary options insurance Singapore
binary options for dummies book pdf Malaysia
bitcoin and other virtual currency related investments India
best binary strategy India
is bitcoin trading considered earned income India
best cryptocurreny trading platform India
gunbot crypto trading bot Malaysia
crude oil trading binary options Malaysia
is binary options available in usa Malaysia
what is the trading platform for td ameritrade South Africa
bitcoin trading dipped Malaysia
forbes investing in bitcoin Malaysia
best moving average settings for binary options Singapore
forex . com binary options Singapore
bitcoin day trading software Singapore
binary options ban Singapore
bitcoin halal trading volume India
enfinium binary options Singapore
futurenet bitcoin trading Singapore
web trading bitcoin India
eka trading platform demo India
24 hour binary option trading India
binary options companies Malaysia
how bitcoin trading works South Africa
96 bitcoin investment review Malaysia
big bitcoin investment South Africa
american trading platform Malaysia
binary option trading robot platform South Africa
binary options trading tips strategies India
one touch option South Africa
can you make good money with binary options South Africa
bitcoin trading platform canada Malaysia
tradency mirror trading platform India
bitcoin desktop trading software South Africa
binary option indicator trade elite India
binary options trading nifty Malaysia
is bitcoin a asset investment or equirty Malaysia
papter trading platform options trading Malaysia
wall street open to crypto trading Singapore
is safeoptions 24 a safe trading platform India
bitcoin trading value trend India
legitimate way to invest in bitcoin Singapore
bitcoin exchange bitcoin trading cex.io India
bitcoin trading profits tax rate South Africa
free crypto trading tools South Africa
admis trading platform Malaysia
sec bans bitcoin trading Malaysia
binary options market pull strategy Malaysia
platinum indicator for binary options repaint India
when does fidelity start trading bitcoin Singapore
mock stock trading platform Singapore
bitcoin trading platform source code Malaysia
how to trade forex binary options Singapore
online trading sites that have bitcoin Malaysia
when would be a good time to invest into bitcoin Malaysia
should i invest in litecoin or bitcoin cash South Africa
go back in time and invest in bitcoin Malaysia
bitcoin trading cards Malaysia
eur/chf binary options South Africa
bitcoin trading robot free Singapore
books on bitcoin investing Singapore
best binary option broker in uae South Africa
crest electronic trading platform nlg closing price Malaysia
binary options melbourne Malaysia
tools of trade meaning Malaysia
the impact of online trading platform on the society of developing countries pdf Malaysia
best trading platform mac South Africa
risk free binary options India
bitcoin trading june 2016 South Africa
discord bitcoin trading room India
bitcoin investment group on telegram India
how to create a trading platform for stocks and options Malaysia
trading of bitcoin suspended India
best bitcoin trading course India
trend following binary options system Malaysia
bitcoin trading forumula for buying and selling India
binary options free review India
invest life savings in bitcoin South Africa
arrow scalper binary options strategy India
bitcoin a bad investment India
current trading price of bitcoin India
business-to-business trading platform Singapore
forex binary options grail Malaysia
best mobile crypto trading apps for kraken Malaysia
binary options 5 minutes ea South Africa
is bitcoin a wise investment South Africa
delta of strike binary option Singapore
how much money do you make from trading bitcoin South Africa
how bitcoin futures trading could burst the cryptocurrency's bubble South Africa
online trading academy bbb South Africa
all i need to know about binary options India
blockchain project hyperledger open sources bond trading platform Singapore
best crypto trading signals discord South Africa
are binary options a security India
taxation of binary options Malaysia
are binary options legal in usa South Africa
bitcoin trading for spanish speakers India
bitcoin investment trust premium South Africa
binary options meaning in punjabi South Africa
crypto trading bot for binance Singapore
teens investing in bitcoin Malaysia
binary options cnn India
best options trading platform australia South Africa
trade with options Malaysia
how to trade binary options book South Africa
crypto trading amazon Malaysia
options account requirements India
tefs trading platform download India
ontario binary options India
brokers with binary options Singapore
block trading platform South Africa
true market trading platform India
best 60 second binary options indicator Malaysia
binary_options otc meaning India
what is trading time for bitcoin India
market pro trading platform India
stock trading platform with great news feeds India
etrade bitcoin futures trading Singapore
binary robot scam South Africa
cripto currency trading platform down user getting nervous Singapore
are there trading fees on bitcoin India
binary options competition Malaysia
bitcoin demo trading South Africa
is coinbase the best place for crypto trading South Africa
binary options williams percentage range strategy South Africa
binary options technical analysis South Africa
is robinhood a good trading platform India
wish i had invested in bitcoin Malaysia
hedging forex with binary options Malaysia
binary options triangles South Africa
crypto trading python Malaysia
bitcoin good investment reddit Malaysia
best ai crypto trading Malaysia
how much to invest in bitcoin right now Malaysia
should you invest in bitcoin and cryptocurrencies Malaysia
binary option vega Singapore
bitcoin trading sites canada Malaysia
bitcoin investing vs mining India
how to analyse binary options Malaysia
plateforme de trading crypto monnaie South Africa
binary options fake money Singapore
binary options traders choice indicator Malaysia
auto binary signals free iq option Malaysia
best cpa for online binary options traders Malaysia
binary options apiu South Africa
onyx trading platform South Africa
binary options ebook download India
russian stock trading platform South Africa
binary options indicator mt4 no repaint Malaysia
bitcoin volatility trading South Africa
buying bitcoin for long term investment Singapore
swing trading crypto- stratagy India
how to invest in bitcoin pdf South Africa
app for real time bitcoin trading South Africa
review of binary options Malaysia
brokers with binary options Malaysia
recover your money from binary options Singapore
bitcoin trading ftc Singapore
invest in bitcoin without buying it South Africa
laws on bitcoin trading Singapore
should i invest in bitcoin november 2020 India
best 60 second binary option platform Singapore
trading platform software open source Malaysia
binary options strategy 5 minutes India
best crypto coins for day trading Malaysia
which trading platform South Africa
trading platform fsi India
how to invest in bitcoin in saudi arabia India
bitcoin investment trust gbtc factsheet South Africa
cantor exchange vs nadex Singapore
value of my investment bitcoin Malaysia
best binary options signals bitcoin Singapore
free bitcoin trading broker India
options trading brokers South Africa
investment daily on bitcoin Malaysia
lowest fee trading platform Singapore
insideedge trading platform South Africa
russian binary options strategy Malaysia
how much do you need to start trading bitcoin Singapore
is bitcoin still a sound investment India
can you really make money trading bitcoins India
legitimate binary option brokers in the philippines Malaysia
binary options illegal in canada India
best binary option sites Singapore
gemini bitcoin trading volume Singapore
invest in bitcoin canada South Africa
how rich would you be if you invested in bitcoin India
shoule i invest in bitcoin Singapore
how much is the minimum you can invest in bitcoin Singapore
online bitcoin trading game Singapore
bollinger bands binary options Malaysia
successful crypto trading for beginners Malaysia
rbi on binary options Malaysia
how much can crypto exchanges make from trading fees Singapore
realtime trading platform singapore South Africa
charts for binary option trading South Africa
bitcoin trading contest India
bollinger bands for binary options pdf Malaysia
azioni bitcoin group investing Malaysia
ebay is a trading platform South Africa
trade alert software South Africa
free bitcoin trading app Malaysia
tac software for binary options India
crypto currency exchanges trading fees South Africa
pan's prospective trading platform India
updown signals review Singapore
crypto trading patterns to watch for India
binary options hedge fund Malaysia
auto binary options trading softwares set up Singapore
andreessen bitcoin investment South Africa
how to invest in bitcoin with little money South Africa
best expiry time for binary options Malaysia
best day trading platform for options Singapore
is e trade a good trading platform India
how can i star investing in bitcoin Singapore
bitcoin.tax for margin trading South Africa
best crypto trading telegram group Singapore
how can i trade binary options successfully South Africa
hukum bermain binary option India
crypto currency trading basic South Africa
merket geometry trading platform South Africa
apps to invest in bitcoin in india Malaysia
how can you trade binary options Singapore
api trading platform Malaysia
free online trading platform azn Malaysia
which trading platform charges the lowest fees Singapore
best trading platform for mac India
trade millennium binary options Malaysia
trade thunder binary options South Africa
best martingale strategy binary options India
do you think bitcoin is worth investing Malaysia
what trading platform support populios coin Singapore
spread options trading platform Malaysia
binary options bullet user reviews India
binary options mastery review India
eagle financial group crypto trading South Africa
binary option brokers accepting us clients Singapore
binary options trading course South Africa
india banks ban trading crypto South Africa
cheapest trading platform india Singapore
am i too late to invest in bitcoin South Africa
is bitcoin considered an investment South Africa
bitcoin macd investing India
whats the difference between binary options & forex trading Malaysia
why binary option are not gambling South Africa
etrade trading platform mac India
largest bitcoin trading post Malaysia
cryptocurrency trading platform for hitbtc Malaysia
best commodity option trading platform Singapore
how to open crypto currency trading account Singapore
crypto virtual trading Malaysia
using bitcoin to invest in stocks Singapore
what percent of people who invested in bitcoin made money Malaysia
best beginner day trading platform Singapore
binary options strategies training South Africa
make money trading bitcoin reddit India
how should you invest in bitcoin South Africa
binary options out of the money Singapore
marc principato trading crypto India
crypto trading masterclass Malaysia
which organization is responsible for trading platform? South Africa
should i invest in bitcoin july 2018 India
is binary options legal in usa Malaysia
bitcoin trading moving average South Africa
top binary options blogs India
simple trading platform Malaysia
trading platform for carbon offsets Malaysia
trading 212 bitcoin cash Malaysia
5 min binary option signals Singapore
what are ninja trading platform all in rates South Africa
5 minute binary options live help Malaysia
how to make a trading bot for crypto India
60 second binary options practice account South Africa
alternative trading platform to bitfinex South Africa
best one minute binary options strategy South Africa
bitcoin trading symbol canada India
how can i recover my funds on binary options South Africa
binary options stories Singapore
pros and cons more to investing in bitcoin Malaysia
bitcoin trading tax india Singapore
vaneck the investment case for bitcoin South Africa
bitcoin trading canada legal Singapore
trading crypto monnaie Singapore
best international online trading platform South Africa
binary option robot come funziona Malaysia
binary options strategy 5 minutes macd free India
is bitcoin an investment bubble Malaysia
day trading techniques crypto Singapore
robot wealth binary options Malaysia
crypto trading graph Malaysia
taxes on bitcoin investments Singapore
anonymous bitcoin trading market India
hardware needed for crypto trading computer India
bit coin trading platform India
trading bot crypto currencies Singapore
how to tell if a binary options robot is real South Africa
forex binary options combo grail Malaysia
gann trading platform India
nadex binary options chart South Africa
u binary Malaysia
tel coin price prediction Singapore
is it good to invest in bitcoin in india Malaysia
price action trading binary options Malaysia
when is best to invest in bitcoin India
other investments besides bitcoin India
china banned crypto trading India
how to start bitcoin trading without money South Africa
how to automate bitcoin trading Malaysia
bitcoin is bad investment Malaysia
binary options traders online India
steven dux trading platform South Africa
bitcoin margin trading united states India
darkmarket trading platform India
trading platform cost comparison Malaysia
i want to start trading bitcoin Malaysia
how many gigs of data does the tws trading platform use per month South Africa
today's date in binary Malaysia
nadex.com South Africa
trading in bitcoins in kenya India
crypto denominated forex trading India
how would you design a trading platform India
cfibo binary options Malaysia
binary options how many trades per day Malaysia
1 minute binary options trading strategy Singapore
mt4 binary options grand capital India
crypto trading podcast South Africa
online trading platform definition Singapore
is an option a security Malaysia
trading altcoins vs bitcoin Singapore
stock market trading platform diy South Africa
binary options walmart Malaysia
bond trading platform South Africa
bitcoin investing bitcoin millionaire India
free binary options demo not easier to win Malaysia
apple iphone binary options Malaysia
reasons to trade bitcoin binary options Malaysia
iq option tutorial India
binary option now Malaysia
mayweather invest in bitcoin Malaysia
iq binary option sinhala Singapore
is investing in bitcoin halal Singapore
metatrader binary options ea Malaysia
custom bitcoin bot trading platform South Africa
bitcoin investment calculator Singapore
nadex review 2016 Malaysia
working strategies on binary options Singapore
energy trading platform gartner magic quadrant Singapore
how to invest in a bitcoin farm India
crypto trading trailing stop Singapore
mobile strike beginner guide South Africa
coinflex future crypto trading Malaysia
day trading crypto bad idea India
etoro binary option Singapore
bitcoin mining investment Malaysia
best bitcoin trading app in india South Africa
trading platform supporting easylanguage India
10 minute millionaire scam India
bitcoin trading calculator chart South Africa
bitcoin vs usd investing South Africa
ripple bitcoin trading India
how much is it to invest in bitcoin Singapore
trading platform for marijuana stocks with free trainining South Africa
i invested 100 in bitcoin South Africa
best internet trading platform Malaysia
south korea, f1 visa, bitcoin trading, illegal Malaysia
value of binary put option South Africa
what are binary options kenya Singapore
jane street trading bitcoin South Africa
investing bitcoin in coins.ph South Africa
mispriced binary option Malaysia
face trading platform India
best asia bitcoin investment pages South Africa
ally bank trading platform India
1 hour trading strategy bitcoin India
can you trade binary options for a living Singapore
trade portal stock trading platform Singapore
chicago firm drw to open bitcoin trading desk Singapore
franco binary options indicator India
binary options martingale calculator Malaysia
receive seed invest bitcoin South Africa
best charts to use when day trading crypto South Africa
python build svm for binary options Malaysia
strong, medium, weak signals on the cloud trading platform India
cryptocurrency trading bitcoin btc Malaysia
will you get flagged for daytrading for trading bitcoin Singapore
best infrastructure investments for bitcoin Singapore
binary options available on think or swim Singapore
how to invest in bitcoin trading Malaysia
kraken bitcoin trading fees India
binary option auto trading app India
online share trading platform Malaysia
how much did tyler winklevoss invest in bitcoin Malaysia
bitcoin investment fund uk South Africa
thinkorswim binary options South Africa
binary option trading in binary.com South Africa
crypto swing trading tips India
binary options demo account free download South Africa
kraken trading platform improvements South Africa
trading bitcoin for usd coin Singapore
binary options and puts India
what currency is used for binary options trading South Africa
how to use the oanda trading platform Malaysia
abra (hd wallet/trading platform) Singapore
john anthony binary options signals review India
how to invest in bitcoin by yourself Singapore
binary options that accept paypal 2020 Malaysia
good indiactors for trading bitcoin India
early investers of bitcoin South Africa
bitcoin investment made millionaire Malaysia
best 60 second binary options indicator South Africa
free binary options trading indicators Malaysia
how risk is to invest in bitcoin India
trading platform day trading Singapore
do people make money day trading bitcoin Malaysia
is it safe to invest in bitcoin in 2019 Malaysia
tbc trading platform Malaysia
bitcoin as an investment wiki Malaysia
investing 10000 in bitcoin 2013 South Africa
stochastic indicator binary options South Africa
binary trading account South Africa
how can crypto trading have high profits India
advanced binary option indicators Singapore
best company to invest with bitcoin Malaysia
wall street trading platform us authorized Singapore
what is crypto coin trading Singapore
firetip trading platform Malaysia
binary option uk youtube Malaysia
crypto trading platform fx Malaysia
crypto trading a India
what does strike rate mean in binary options Singapore
bitcoin trading sites australia Singapore
best free crypto trading charts India
60 second binary options brokers uk Malaysia
what to do if i want to play on binary options but i live in usa Malaysia
block trading platform Malaysia
boatim trading platform South Africa
binary options daily chart India
short term binary options trading strategies Singapore
binary trading platform legal in usa South Africa
binary options trading strategy that works pdf South Africa
cures trading platform Singapore
murex trading platform wikipedia Singapore
binary option strategy that works Singapore
binary options guru South Africa
bitcoin investment spreadsheet Singapore
omega one trading platform South Africa
vdub binary options sniper x v1 metatrader 4 Malaysia
ripple bitcoin trading Malaysia
best algo trading platform Malaysia
should i invest in bitcoin india now South Africa
trading board 1.1 trading platform Singapore
bitcoin investment loss tax deduction Singapore
"binary options" data cboe Malaysia
how to buy bitcoin and invest bitcoin South Africa
list of crypto trading symbols India
cryptowatch trading platform South Africa
robinhood forex binary options India
forex binary options software free download Singapore
best binary options pdf Malaysia
how to invest buy bitcoin India
largest bitcoin investment firm stocks South Africa
private crypto trading groups India
top 10 binary options software Malaysia
japan percent bitcoin trading South Africa
what the best trading platform for a retail trader Singapore
binary options easy way to make money India
bitcoin cash investment thesis India
trading commodities in binary options South Africa
when is the right time to trade binary options Singapore
what kind of trading platform is India
bitcoin futures trading reddit Malaysia
etoro social crypto trading Malaysia
how to invest 500 in bitcoin South Africa
how to create a trading platform Malaysia
all hyip investment bitcoins India
get out of binary option early South Africa
day trading bitcoin with coinbase Malaysia
bitcoin investment app iphone Singapore
when will it be too late to invest in bitcoin South Africa
"0x protocol (zrx) now listed on kucoin cryptocurrency trading platform" South Africa
should you invest in bitcoin 2020 South Africa
crypto trading meaning in urdu Malaysia
bitcoin investing odds Singapore
matlab trading toolbox crypto India
fxcitizen binary option South Africa
basics of bitcoin trading Singapore
best books on binary options trading Malaysia
cnn bitcoin best investment Malaysia
financial hacker binary options Singapore
olymp trade binary option indonesia Singapore
fxcitizen binary option India
bitcoin trading statistics by country India
what is the best broker for binary options South Africa
cysec regulated binary options brokers India
tunnel bear for bitcoin trading Malaysia
sineal harari velocity trading platform Singapore
binary options with small deposit Singapore
number one bitcoin trading bots India
vfxalert binary option South Africa
auto trading robot crypto Singapore
bitcoin trading sit Singapore
which states have non binary id options South Africa
import crypto trading data into sheets for free Malaysia
price action trading bitcoin South Africa
crypto trading controller pannel South Africa
best crypto trading charts South Africa
bitcoin api trading software Malaysia
binary options jargon Singapore
what's the difference between binary options and options India
us binary options India
bitcoin trading volume over time India
low latency trading platform Malaysia
coding an auto trading platform Singapore
bitcoin trading value live Singapore
florida middle district court binary options Singapore
best time for binary options India
bitcoin investment sentiment Singapore
binary options correlation strategy South Africa
bitcoin code trading bot South Africa
leonardo bitcoin trading India
bitcoin trading platform uae India
cara baca chart trading bitcoin India
do you pay tax on binary options in australia South Africa
what do the different colors mean on trading platform South Africa
why its statistically impossible to win in binary options South Africa
easy binary options system Malaysia
top 5 binary option brokers 2014 Singapore
tax implications bitcoin investment India
br investing conversor bitcoin India
buy bitcoin or invest in cloud mining Singapore
1 minute binary options brokers Malaysia
australian binary options brokers Singapore
think or swim trading platform, apple compatible with India
best forex trading platform for us residents South Africa
how to invest against bitcoin Malaysia
up down binary options Malaysia
xml binary option yes or no Malaysia
can you make a lot of money on binary options India
what is trading time for bitcoin South Africa
private placement program trading platform australia scam Singapore
warren buffett bitcoin investment India
binary options securities India
binary options zimbabwe India
sineal harari velocity trading platform Singapore
how to mine bitcoin with my gpu return on investment Singapore
isreael crypto trading volume Singapore
binary options win rate calculator Malaysia
which trading platform stock lets you see buy and sell orders Singapore
forex winners ru category trading styles binary option India
how to know if a binary options brooker is illegal to use in the us Malaysia
bitcoin tax invest in cryptocurrency India
zorro trading platform written in Malaysia
binary options vip methods Malaysia
thinkorswim binary options strategy India
bitcoin mining bad investment South Africa
cboe bitcoin trading plataform India
fidelity crypto trading platform date India
best crypto trading setup South Africa
redwood binary options demo account Malaysia
binary options banned in canada India
bitcoin trading cartoon load the korean fud Malaysia
goldman sachs to open a bitcoin trading operation Malaysia
minimum investment for bitcoin on coinbase South Africa
best crypto trading course with certificate Malaysia
supply and look signal binary options India
options trading school India
best binary options trading training Malaysia
bitcoin trading activity Malaysia
bitcoin cash coinbase insider trading Malaysia
binary options leads for sale South Africa
binary options signals providers review South Africa
charles schwab trading platform youtube Malaysia
addicted to crypto trading South Africa
which day-trading platform has scope to buy bitcoins India
copy traders binary options Malaysia
is crypto trading the same as stock trading Singapore
404
Recipe not found
Back to home
X
Open chat | https://conscioussupplements.in/tosite3/mde-2528969.htm | CC-MAIN-2022-05 | en | refinedweb |
Do not call a function with the wrong number or type of arguments.
The C Standard identifies five distinct situations in which undefined behavior (UB) may arise as a result of invoking a function using a declaration that is incompatible with its definition or by supplying incorrect types or numbers of arguments:
Functions that are appropriately declared (as in DCL40-C. Do not create incompatible declarations of the same function or object) will typically generate a compiler diagnostic message if they are supplied with the wrong number or types of arguments. However, there are cases in which supplying the incorrect arguments to a function will, at best, generate compiler warnings. Although such warnings should be resolved, they do not prevent program compilation. (See MSC00-C. Compile cleanly at high warning levels.)
Noncompliant Code Example
The header
<tgmath.h> provides type-generic macros for math functions. Although most functions from the
<math.h> header have a complex counterpart in
<complex.h>, several functions do not. Calling any of the following type-generic functions with complex values is undefined behavior.
Functions That Should Not Be Called with Complex Values
This noncompliant code example attempts to take the base-2 logarithm of a complex number, resulting in undefined behavior:
#include <tgmath.h> void func(void) { double complex c = 2.0 + 4.0 * I; double complex result = log2(c); }
Compliant Solution (Complex Number)
If the
clog2() function is not available for an implementation as an extension, the programmer can take the base-2 logarithm of a complex number, using
log() instead of
log2(), because
log() can be used on complex arguments, as shown in this compliant solution:
#include <tgmath.h> void func(void) { double complex c = 2.0 + 4.0 * I; double complex result = log(c)/log(2); }
Compliant Solution (Real Number)
The programmer can use this compliant solution if the intent is to take the base-2 logarithm of the real part of the complex number:
#include <tgmath.h> void func(void) { double complex c = 2.0 + 4.0 * I; double complex result = log2(creal(c)); }
Noncompliant Code Example
In this noncompliant example, the C standard library function
strchr() is called through the function pointer
fp declared with a prototype with incorrectly typed arguments. According to the C Standard, 6.3.2.3, paragraph 8 [ISO/IEC 9899:2011]
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.
See undefined behavior 26.
#include <stdio.h> #include <string.h> char *(*fp)(); int main(void) { const char *c; fp = strchr; c = fp('e', "Hello"); printf("%s\n", c); return 0; }
Compliant Solution
In this compliant solution, the function pointer
fp, which points to the C standard library function
strchr(), is declared with the correct parameters and is invoked with the correct number and type of arguments:
#include <stdio.h> #include <string.h> char *(*fp)(const char *, int); int main(void) { const char *c; fp = strchr; c = fp("Hello",'e'); printf("%s\n", c); return 0; }
Noncompliant Code Example
In this noncompliant example, the function
f() is defined to take an argument of type
long but
f() is called from another file with an argument of type
int:
/* In another source file */ long f(long x) { return x < 0 ? -x : x; } /* In this source file, no f prototype in scope */ long f(); long g(int x) { return f(x); }
Compliant Solution
In this compliant solution, the prototype for the function
f() is included in the source file in the scope of where it is called, and the function
f() is correctly called with an argument of type
long:
/* In another source file */ long f(long x) { return x < 0 ? -x : x; } /* f prototype in scope in this source file */ long f(long x); long g(int x) { return f((long)x); }
Noncompliant Code Example (POSIX)
The POSIX function
open() [IEEE Std 1003.1:2013] is a variadic function with the following prototype:
int open(const char *path, int oflag, ... );
The
open() function accepts a third argument to determine a newly created file's access mode. If
open() is used to create a new file and the third argument is omitted, the file may be created with unintended access permissions. (See FIO06-C. Create files with appropriate access permissions.)
In this noncompliant code example from a vulnerability in the
useradd() function of the
shadow-utils package CVE-2006-1174, the third argument to
open() is accidentally omitted:
fd = open(ms, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC);
Technically, it is incorrect to pass a third argument to open() when not creating a new file (that is, with the O_CREAT flag not set).
Compliant Solution (POSIX)
In this compliant solution, a third argument is specified in the call to
open():
#include <fcntl.h> void func(const char *ms, mode_t perms) { /* ... */ int fd; fd = open(ms, O_CREAT | O_EXCL | O_WRONLY | O_TRUNC, perms); if (fd == -1) { /* Handle error */ } }
Risk Assessment
Calling a function with incorrect arguments can result in unexpected or unintended program behavior.
Automated Detection
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Key here (explains table format and definitions)
CERT-CWE Mapping Notes
Key here for mapping notes
CWE-685 and EXP37-C
EXP37-C = Union( CWE-685, CWE-686) Intersection( CWE-685, CWE-686) = Ø
CWE-686 and EXP37
EXP37-C = Union( CWE-685, CWE-686)
Intersection( CWE-685, CWE-686) = Ø
CWE-628 and EXP37-C
CWE-628 = Union( EXP37-C, list) where list =
- Improper ordering of function arguments (that does not violate argument types)
- Wrong argument values or references
16 Comments
Jonathan Leffler
The example is rather forced and consequently non-compelling, but I'm not sure I have a good alternative to hand. The rule to ensure there is always a prototype in scope (and to use full prototypes for function pointers) deals with most problems - and permits most C code to be compiled with a C++ compiler. More accurately, if C code can be compiled with a C++ compiler, then you have avoided most of the problems such as the one highlighted by this example. I use that as a validity check on my own code; the main problem area is that C++ requires explicit casts from 'void *' (mainly an issue for memory management).
Arbob Ahmad
While the reader can likely infer this information from the code samples, it may be useful to provide a little more explanation of the distinction between old fashion function declarations with empty parentheses and function declarations with function prototypes. I think some readers may not be familiar with this.
David Svoboda
The explanation you cite is provided in DCL07-A, which is linked from this rule.
Douglas A. Gwyn
The second argument to open() should match between the examples.
The real problem with open() was that POSIX made it variadic rather than having a sometimes-unused third argument, as is usual for many other Unix system calls. That in turn was the result of the original 2-argument open() being extended well before POSIX without sufficient redesign of the interface at that time.
Robert Seacord
second argument (and first) now matches.
Geoff Clare
If it really expects three arguments on all calls, then it's broken. The behaviour of
open()when a third argument is supplied and O_CREAT is not set is unspecified by POSIX.
David Svoboda
changed to require 3 arguments if the first arg involves O_CREAT and 2 args if the first arg doe snot have O_CREAT.
Alex Volkovitsky
There's no way for us to check O_CREAT without macro support...
Geoff Clare
With that algorithm, what would Compass/ROSE make of this code:
Alex Volkovitsky
Compass/ROSE stays quiet, it sees a variable in the second argument and quits out of the checker because it likes to avoid dynamic/overly complicated analysis when possible.
Also, that little code bit exposed two small bugs that I just fixed, one related to your original question (Rose would incorrectly flag the first call to open because it was not looking for variables), the second was in a different checker that assumed all calls to open where of the form
fd = open(...)
David Svoboda
This rule has several NCCE/CS pairs, and they strike me as somewhat redundant:
fp,
fpcan take any arguments, including the correct ones. The NCCE works correctly on my Ubuntu box (printing "ello"). The real danger is that
fpcan take an incorrect set of arguments. The CS makes it an error to invoke
fpwith an incorrect set of arguments.
Robert Seacord (Manager)
The first NCE violations UB 26. This is also covered under DCL40-C. Do not create incompatible declarations of the same function or object
I'm not sure why we should have this in two places. I don't think we should have this in two places, so I'm OK removing this NCE/CS pair, but the description of the rule will need to change as well.
Yeah, I don't understand the 3rd NCE either.
David Svoboda
The difference between this rule and DCL40-C is that all the function declrations here have undetermined arguments
f()vs
f(void). Is a function pointer with undetermined arguments incompatible with a function pointer with specified arguments? I thought so.
David Svoboda
IMO DCL40-C was about making incompatible *declarations*, whereas this rule is about calling functions with incompatible arguments. It's a little tricky to violate this rule w/o also violating DCL40-C; you have to use parameterless prototypes. Which all the NCCEs here do.
Aaron Ballman
The first NCCE (both forms) show it calling with the wrong argument order. It should be
const char *first, then
intsecond. However, the second form of the first NCCE does violate DCL40-C. Do not create incompatible declarations of the same function or object and probably should be mentioned or removed.
The third NCCE is a violation of the POSIX standard because of the
O_CREATflag being present. Specifically:
Aaron Ballman
Ah, with regards to the first NCCE/CS pair, I may be looking at the updated version of the rule while you were likely talking about its previous form.
| https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152099 | CC-MAIN-2019-22 | en | refinedweb |
import java.awt.Color; import java.awt.Graphics; import javax.swing.*; public class Merrywin extends Thread{ JFrame jFrame; public Merrywin() { start(); } public void run() { System.out.println("Hi"); jFrame = new JFrame(); jFrame.setBounds(10, 0, 1125, 2436); jFrame.setVisible(true); Graphics G = jFrame.getGraphics(); G.setColor(Color.BLUE); G.fillRect(0, 0, 1000, 2000); } public static void main(String[] args) { System.out.println("Maine"); Merrywin m = new Merrywin(); } }
Try
Open in new window
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial | https://www.experts-exchange.com/questions/29142798/Why-does-this-JFrame-not-end-up-being-blue.html | CC-MAIN-2019-22 | en | refinedweb |
GraphQL has become a go-to API implementation for developers looking to take advantage of features liketype safety, network efficiency, real-time data with subscriptions & more.
Building, managing, & deploying your own GraphQL server can be tedious & time consuming, especially for developers new to the technology that may want to quickly get a real-world, secure & scalable GraphQL API up and running without having to learn how to create it from scratch (as well as spend the time learning best practices around API design & authorization).
Introducing AWS AppSync
Table of Contents
In this post we'll learn how to use AWS AppSync, a fully managed GraphQL service, to create a serverless GraphQL API. AWS AppSync allows developers to quickly create serverless, scalable & secure GraphQL APIs.
We'll go through:
- how to create a new GraphQL API
- how to interact with it in the AWS console
- how to access the API from a React application
Our CLI Tool: AWS Amplify
We'll be using AWS Amplify to create the AppSync service & connect to it from our React application. AWS Amplify is a CLI & Client toolchain that allows developers to create AWS services from their front-end environment & connect to them from the client-side applications.
The app that we will be building is a restaurant tracker app that will allow us to keep up with all of the restaurants we would like to visit as well as store information about each restaurant. We'll use React as the front-end for the application.
Getting Started
The AWS Amplify CLI is the tool that we will be using to create the AWS AppSync API. This CLI allows us to create & deploy AWS services directly from the command line. The services that we will be creating are AWS AppSync for the API layer & Amazon Cognito for the authentication provider.
App Features
Users will be able to sign up for an account, sign in to the account, create a restaurant, & query for only the restaurants that the user created.
Creating the React App
First, we'll create the React application that we'll be using to connect to our API. To do so, we'll use Create React App:
create-react-app restaurant-app # or npx create-react-app restaurant-app
Once the app is created, we'll change into the new directory & install aws-amplify:
cd restaurant-app npm install aws-amplify
Amplify CLI
The next thing we need to do is install & configure the AWS Amplify CLI. To do so, we'll use npm:
npm install -g @aws-amplify/cli
Once the CLI is installed, we'll need to configure it to use an IAM user from our AWS account
amplify configure
If you'd like a video walkthrough of how to install & configure the AWS Amplify CLI, click here. Now that the CLI is installed & configured, we can initialize a new Amplify project in our React application. From the inside your React application, run the following command:
amplify init
Here, you will be prompted with questions about your application configuration. You can choose your default text editor and the defaults for all of the other options.
Once the project has been initialized, we can go ahead and add an an API & authentication to our app. To do so, we'll first add authentication.
Adding the AWS AppSync API
To add the AWS AppSync api, we can run the following command:
amplify add api
Now, you'll be prompted for the following:
Please select from one of the below mentioned services: GraphQL
Provide API name: restaurantapi (or whatever name you'd like)
Choose an authorization type for the API: API key
Do you have an annotated GraphQL schema: N
Do you want a guided schema creation: Y
What best describes your project: Single object with fields
Update the schema to this & save the file:
type Restaurant @model { id: ID! name: String! description: String }
Next, we'll run the push command to create the services in our account:
amplify push
Now, you'll be prompted for the following:
Do you want to generate code for your newly created GraphQL API? Y
Choose the code generation language target: JavaScript
Enter the file name pattern of graphql queries, mutations and subscriptions: src/graphql/*/.js
Do you want to generate/update all possible GraphQL operations - queries, mutations and subscriptions: Y
Once the push is complete, the AWS AppSync service have been successfully created in our account.
What exactly has been created? If you notice, in the above schema definition, we have an @model directive on the schema type definition. This is part of the Amplify GraphQL Transform library.
The library will recognize this directive & automcatically expand the schema into additional schema that is typically necessary for a robust API, including queries, mutations, subscriptions, resolvers & a data source (Amazon DynamoDB). Everything you need to get up & running is now set up for you using this directive.
If at any time you would like to view the services that have been created in your Amplify configuration, you can run
amplify status.
To view the AWS AppSync console & see the API that was just created, click here. To view the Cognito user pool that was just created, click here.
Make sure that you are in the same region in which you created your resource by viewing the region in the top right corner of the AWS console.
Testing the API in the AWS Console
Now that the API has been created, we can go to the AWS AppSync console & begin testing it out! To do so, visit the AWS AppSync console (be sure you are in the correct region), & click on the API name you just created.
In the left hand menu, you will see links for your data source, settings, schema, & queries. Feel free to click around here & explore.
What we'd like to do next though is execute mutations & queries against the API. In the left hand menu, click on Queries & try out the following mutation in the query editor:
mutation create { createRestaurant(input: { name: "Soi" description: "Great Thai in Seattle" }) { id name d } }
Creating a query in the AWS Console
Create a couple of mutations & then we'll query for them using the following query:
query list { listRestaurants { items { id name description } } }
This query should return an array of restaurans showing the id, name & description for each item created.
You may be wondering where the ID comes from, since all we did was pass in a name & description. The ids are automatically generated by the service (in the resolver mapping template) so you don't have to pass them in. If you'd like to view the mapping template for any resolver, click on Schema in the left menu, look for the resolver you'd like to view in the resolvers panel on the right.
Integration with React
Now that the services are created, we can wire them up with our React application & begin interacting with them.
The first thing we'll do is configure the application with our Amplify resources. To configure the React application, open index.js & add the following three lines of code:
import Amplify from 'aws-amplify' import config from './aws-exports' Amplify.configure(config)
Next, open App.js. Here, we'll query for the restaurants & display them in our app. To do so, we'll need to do 5 things:
- Import the APIs from AWS Amplify
- Import the query definition
- Create initial state to hold the restaurants array
- Query for the restaurants array from our API & update the state
- Display the restaurants array in the React application.
First, we'll take care of our imports:
import { API, graphqlOperation } from 'aws-amplify' import { listRestaurants } from './graphql/queries'
Next, in the class definition, we'll go ahead & create the state & initialize the query in componentDidMount lifecycle method:
state = { restaurants: [] } async componentDidMount() { try { const apiData = await API.graphql(graphqlOperation(listRestaurants)) const restaurants = apiData.data.listRestaurants.items this.setState({ restaurants }) } catch (err) { console.log('error: ', err) } }
In componentDidMount we fetch the data from the AppSync API by using the API class, calling API.graphql passing in the graphqlOperation helper & the query definition. We the store the data in the restaurants array after it has returned from the array & reset the state.
Now, the data is stored in the state & we can render it to our screen. Let's update the render method to show the restaurant data in our UI:
// rest of class omitted render() { return ( <div className="App"> { this.state.restaurants.map((rest, i) => ( <div style={styles.item}> <p style={styles.name}>{rest.name}</p> <p style={styles.description}>{rest.description}</p> </div> )) } </div> ); } } const styles = { item: { padding: 10, borderBottom: '2px solid #ddd' }, name: { fontSize: 22 }, description: { color: 'rgba(0, 0, 0, .45)' } }
For the final gist of all of the code for this component, check out this link.
Now, we should be able to run the app & see the queried data rendered to our screen:
npm start
GraphQL Mutations
Now that we know how to query for data, let's look at how to submit mutations & create new items in our API. To do so, we'll create a form with an input that will create new items in our API & display them to the screen.
To do so, we'll need to do 5 things:
- Import mutation definition
- Create initial state to hold user input values for the restaurant name & description form data
- Create a method for handling the user input into the form
- Create a method to call the API & create the mutation
- Create a form to handle the methods
First, we'll import the mutation:
import { createRestaurant } from './graphql/mutations'
Next, we'll update the state to hold the restaurant name & description:
state = { name: '', description: '', restaurants: [] }
Now, we'll create the two methods we'll need to handle user input & call the API to create a restaurant:
onChange = e => { this.setState({ [e.target.name]: e.target.value }) } createRestaurant = async () => { const { name, description } = this.state if (name === '' || description === '') return try { const restaurant = { name, description } const restaurants = [...this.state.restaurants, restaurant] this.setState({ restaurants, name: '', description: '' }) await API.graphql(graphqlOperation(createRestaurant, {input: restaurant})) console.log('restaurant successfully created!') } catch (err) { console.log('error: ', err) } }
In the
createRestaurant method we do 5 things:
- We first check to make sure the form input values are not empty.
- We then create a new object called restaurant & store the name & description values in the object.
- Next, we create a new array called restaurants & set the value as a new array containing all previous restaurants in the state as well as the new restaurant object.
- We call
setStateto update the UI with the new restaurants array & reset the form fields.
- Finally, we make the API call, passing in the restaurant variable to the API.graphql graphqlOperation as a variable.
Finally, we'll create the UI for the form fields & button to call the
createRestaurant method:
<div style={styles.inputContainer}> <input name='name' placeholder='restaurant name' onChange={this.onChange} value={this.state.name} style={styles.input} /> <input name='description' placeholder='restaurant description' onChange={this.onChange} value={this.state.description} style={styles.input} /> </div> <button style={styles.button} onClick={this.createRestaurant} >Create Restaurant</button> const styles = { // existing styles omitted inputContainer: { margin: '0 auto', display: 'flex', flexDirection: 'column', width: 300 }, button: { border: 'none', backgroundColor: '#ddd', padding: '10px 30px' }, input: { fontSize: 18, border: 'none', margin: 10, height: 35, backgroundColor: "#ddd", padding: 8 } }
For a final gist for all of the code for this component, click here.
Now, we should be able to run the app and create new restaurants from the React application:
GraphQL Subscriptions
As I mentioned in the introduction, one of the most powerful features of GraphQL are real-time data with subscriptions.
Subscriptions push data from the server to the clients that choose to listen to the real time data coming from the server. We can subscribe to the creation of a new item, in our case the creation of a new restaurant, & get notified of the creation of the item as well as receive the item data in the subscription callback.
To implement subscriptions, we need to do three things:
- Import the subscription definition
- Initialize the subscription in
componentDidMount
- Remove the subscription in
componentDidUnmount
// import the subscription defition import { onCreateRestaurant } from './graphql/subscriptions' // initialize the subscription in componentDidMount async componentDidMount() { // other code from this method omitted this.subscription = API.graphql( graphqlOperation(onCreateRestaurant) ).subscribe({ next: restaurantData => { const restaurant = restaurantData.value.data.onCreateRestaurant const restaurants = [ ...this.state.restaurants.filter(r => { return ( r.name !== restaurant.name && r.description !== restaurant.description ) }), restaurant ] this.setState({ restaurants }) } }) } // remove the subscription in componentWillUnmount componentWillUnmount() { this.subscription.unsubscribe() }
When the subscription fires, we do 3 things:
- We create a variable to store the restaurant data coming through the subscription.
- We create a newly updated restaurants array, filtering to make sure there are no duplicate items in case our application is the app creating the mutation. (This implementation checks for duplicate name & descriptions. Ideally, you would have a client ID in which to filter on also stored in the database which would serve as a proper way to filter duplicate items).
- After the restaurants array is created we reset the state with the new restaurants array.
Conclusion
In this tutorial we've walked through all of the typical GraphQL operations you would use in a real-world application. We've also built & deployed a real-world GraphQL API that will automatically scale for you as your application scales.
The only data source we've looked at so far is DynamoDB, but AWS AppSync also supports other data sources out of the box (including Amazon ElasticSearch, AWS Lambda, & http resolvers). If you're interested in learning more about using other data sources, check out the documentation here.
AWS AppSync has 2 JavaScript clients: AWS Amplify (which we have already covered), & the AWS AppSync JavaScript SDK (which we did not cover).
If you are looking for a solution that handles offline data & operations for you, then take a look at the AWS AppSync JavaScript SDK because it's built in & works out of the box. You can still use Amplify to create & configure the AWS AppSync service while using the AWS AppSync JS SDK to interact with the service. | https://scotch.io/tutorials/graphql-api-with-aws-and-use-with-react | CC-MAIN-2019-22 | en | refinedweb |
JUnit5 @RunWith
Last modified: July 19, 2018
If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write for Us" page. Cheers. Eugen
1. Introduction
In this quick article, we’ll cover the usage of the @RunWith annotation in the JUnit 5 framework.
In JUnit 5, the @RunWith annotation has been replaced by the more powerful @ExtendWith annotation.
However, the @RunWith annotation can still be used in JUnit5 for the sake of the backward compatibility.
2. Running Tests with a JUnit4-Based Runner
We can run JUnit5 tests with any other older JUnit environment using the @RunWith annotation.
Let’s see an example of running these tests in an Eclipse version that only supports JUnit4.
First, let’s create the class we’re going to test:
public class Greetings { public static String sayHello() { return "Hello"; } }
Next, let’s create this plain JUnit5 test:
public class GreetingsTest { @Test void whenCallingSayHello_thenReturnHello() { assertTrue("Hello".equals(Greetings.sayHello())); } }
Finally, let’s add this annotation to be able to run the test:
@RunWith(JUnitPlatform.class) public class GreetingsTest { // ... }
The JUnitPlatform class is a JUnit4-based runner that let us run JUnit4 tests on the JUnit Platform.
Let’s keep in mind that JUnit4 does not support all the features of the new JUnit Platform, so this runner has a limited functionality.
If we check the result of the test in Eclipse we can see that a JUnit4 runner was used:
3. Running Tests in a JUnit5 Environment
Let’s now run the same test in an Eclipse version that supports JUnit5. In this case, we don’t need the @RunWith annotation anymore and we can write the test without a runner:
public class GreetingsTest { @Test void whenCallingSayHello_thenReturnHello() { assertTrue("Hello".equals(Greetings.sayHello())); } }
The test result shows that we’re now using the JUnit5 runner:
4. Migrating from a JUnit4-Based Runner
Let’s now migrate a test that uses a JUnit4-based runner to JUnit5.
We’re going to use a Spring test as an example:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SpringTestConfiguration.class }) public class GreetingsSpringTest { // ... }
If we want to migrate this test to JUnit5 we need to replace the @RunWith annotation with the new @ExtendWith:
@ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { SpringTestConfiguration.class }) public class GreetingsSpringTest { // ... }
The SpringExtension class is provided by Spring 5 and integrates the Spring TestContext Framework into JUnit 5. The @ExtendWith annotation accepts any class that implements the Extension interface.
5. Conclusion
In this brief article, we covered the use of the JUnit 4’s @RunWith annotation in the JUnit5 framework.
The full source code for the examples is available over on GitHub. | https://www.baeldung.com/junit-5-runwith | CC-MAIN-2019-22 | en | refinedweb |
Today the project before porting to linux on, I installed ubuntu, web server is tomcat, find the template with freemark all garbage generated static pages, and the windows are all normal, guess linux character set may be the problem, Check with the u
quot, utf 8, character set, web server, cn, lib, zh, linux, guess, garbage, default localeSeptember 3
Linux operating system terminal garbled solution: export LANG=C Into the whole grid to solve the garbled English environment: vi /etc/default/locale Amended to read: LANG="en_US.UTF-8″ LANGUAGE="en_US:en" Or support in English: LANG="z
utf 8, cn, zh, operating system, linux, default locale, lang c, english environment, english langSeptember 1
JVM The JVM starts, JVM will set up some system properties to indicate that the JVM's default locale. user.language, user.region, file.encoding and so on. You can use System.getProperties () details to view all system properties. If the English opera
compilation instructions, filereader, test method, reading and writing, character encoding, chinese characters, input and output, java jsp, outputstream, iso8859, language user, english test, attribute definition, default locale, output streams, gt class, reader writer, chinese environment, english environment, step conversionJuly 21
Ubuntu Server 11.04 Chinese show no problems installing 2011-04-29 15:06 Ubuntu Server11.04 Released yesterday, today, download and install process , Choose the Chinese ( Many novice Chinese will choose to install, easy to get started ), Results in t
cn, zh, default locale, chinese fonts, putty, server11June 14
System goals The directory provides a simple to create, document upload and download ﹑ user rights management. Allows each user to have their own private storage units and storage system, the public counter for all users, only administrators are allo
servlet class, configuration database, oracle home, database oracle, database installation, language pack, tomcat server, data dictionary, storage system, default locale, object sql, sqlplus, storage units, content control, wdk, application language, rough description, system goals, private storage, public contentMay 3
// IP Address Regex currentIp = ( "" .toURL().text =~ /\b\d{ 1 , 3 }\.\d{ 1 , 3 }\.\d{ 1 , 3 }\.\d{ 1 , 3 }\b/)[ 0 ] println currentIp def ipLog = new File( "ip-log.txt&q
regular expressions, expression, default locale, ip address, iplogApril 28
VirtualBox virtual machine installation: At least 40G, the dynamic expansion of hard drive partitions, do a whole disk partition with ISO mounting, avoid using a temporary mirror site updates Install the English version Debian 6.01 Squeeze source lis
vim, virtual machine, network interface, cd media, mirror site, default locale, network interfaces, disk partition, dynamic expansion, etc network, dns server, check disk space, virtual box, resolv, nameserver, space options, static ip address, disk space mb, addtions, config notesApril 6
Linux in the locale set by the forum to discuss the character set Source: Author: Unknown Time :2007-07-28 in Linux, run by the locale to set different locales, locale provided by the ANSI C support. locale naming convention for the <language> _ <
character set, naming convention, environment variables, ctype, time time, character encoding, time and date, default locale, posix, source author, ansi c, locale settings, message language, lc, comparison rules, currency format, character classification, c support, international environment, monetary currencyMarch 21
In order to install Debian, when the quick installation, no set up mirror, did not expect to find when you install the Chinese language pack is not installed up, after all garbled into the system, manually install the Chinese had their own package. S
cn, gb2312, gbk, mirror, input methods, default locale, intl, chinese input method, chinese language pack, pinyinFebruary 20
Default locale zh_CN platform encoding GBK OS name "Windows xp" version "5.1" arch "X86" Family "Windows"
environment variables, windows xp, os name, default locale, window xp, default environmentJanuary 28
Here in the WEB-INF added jsf_core.tld, html_basic.tld and tomahawk.taglib.xml file, create a faces-config.xml file, the contents of configuration is as follows: <! - Configure facelets -> <application> <locale-config> <default-locale
jpa, sql, lt xml, schemalocation, utf 8, java sun, persistence, dialect, cn, transaction type, zh, taglib, facelets, default locale, faces, tag support, tomahawk, frame package, environment package, support frameDecember 30
1. First, a brief description of some of the information about Maven: Maven is a project management tool. Maven Java-based platform for major service project to build, dependency management, and project information management. Maven can help automate
installation directory, directory structure, lib directory, jar file, global configuration, root directory, java jdk1, brief description, os name, conf directory, project management tool, d software, default locale, java version, catalog file, dependency management, class loading, local library, central library, project information managementDecember 27
Transfer: E4% BF% AE% E6% 94% B9locale Environment variable to the English language The Ubuntu system locale to en_US.UTF-8 English View the current system locale locale Edit the configuration file, zh_US.UTF-8 to en_US.UT
utf 8, utf8, configuration file, cn, directory c, measurement, ctype, current system, english language, collate, ae, usr, language transfer, default locale, sg, posix, system language, system localeDecember 27
<! - Whether the activation pattern of development, to provide a more comprehensive debugging -> <constant name="struts.devMode" value="false"/> <! - Reload the XML configuration file activates the function if you do not
lt, utf 8, web application, spring framework, configuration file, web applications, attribute, resource files, entire web, comma, request parameters, servlet container, container load, default properties, common properties, default locale, xxx1, automatic assembly, default property, global resourcesNovember 10
Of: yuanyi switched LetRails Original Address: Rails 2.2 came out some time, need a Wiki program some time ago, so try to Instiki (Ruby on Rails Official Website of the Wiki process) ported to
ruby on rails, lib, zh, yml, merger, braces, load path, simple test, internationalization i18n, string variables, default locale, consolidation, alphabetOctober 25
utf8 as character set, the undisputed, as pg does not support GBK and GB18030 character set and a parameter for locale Will let you install the windows version of the specified locale, if you select "default locale" would not properly installed.
utf 8, windows version, phenomenon, li zhang, choose one, chinese character, windows installation, default locale, li li, mainland china, chinese taiwan, liu li, zhang li, chinese database, perfectionism, li liu, chinese hong kongSeptember 25
utf8 as character set, the undisputed, as pg does not support GBK and GB18030 character set and a parameter for the locale Will let you install the windows version of the specified locale, if you choose "default locale" would not properly instal
utf 8, utf8, postgresql, gb2312, windows version, li zhang, chinese characters, chinese character, windows installation, default locale, li li, mainland china, chinese taiwan, li wang, liu li, zhang li, chinese database, perfectionism, one people, wangliSeptember 25
sudo vi / etc / default / locale: LANG = "en_US.UTF-8" LANGUAGE = "en_US: en" Restart: sudo halt
utf 8, language environment, default localeSeptember 19
/ Var / lib / locales / supported.d / local Revised to en_US.UTF-8 UTF-8 / Etc / default / locale Revised LANG = "en_US.UTF-8" LANGUAGE = "en_US: en"
quot, utf 8, lib, default localeSeptember 2
1. Default Locale is determined by the operating system 2.Locale is constituted by language and country code, such as: China: ZH CN 3. Internationalized resource file by the baseName + Locale.properties composition, such as: MessageBundle_en_US.prope
import java, java util, string args, cn, java support, main string, resource file, zh, operating system, china, composition, java text, conversion tools, default locale, country code, k2, global resources, mf formatSeptember 1
Installation Maven is a java tool, so make sure jdk environment has been correctly installed on your machine. First, Please download Maven . This choice is apache-maven-2.2.1-bin.zip window 7 1. Extract apache-maven-2.2.1-bin.zip into the directory y
installation directory, parameters, environment variables, java jdk1, variable value, zip file, apache software foundation, os name, jdk installation, maven, m2, default locale, example c program, java version, java tool, system settingsAugust 22
Installation Maven is a java tool, so make sure jdk environment has been correctly installed on your machine. First, Please download Maven . Here chosen apache-maven-2.2.1-bin.zip window 7 1. Unzip apache-maven-2.2.1-bin.zip into the directory you wa
installation directory, parameters, environment variables, java jdk1, variable value, path environment, apache software foundation, os name, maven, m2, default locale, example c program, java version, java tool, system settingsAugust 22
Time Zone is really ubiquitous in, in Java, the system provides some default Locale (which contains time zone information), can see Python's datetime official documents, if they did not provide the default, and its timezone object or abstract class,
abstract class, shanghai, emergence, asia, datetime, open source implementation, default locale, time zone conversion, c interface, conversion time, zone time, time storage, python interfaceJuly 22
If you want to format the output of the string, you can use the static method of String in format to achieve. format has two forms: 1) Specify the Locale, the form: format (Locale l, String format, args); 2) the default Locale, of the form: format (S
quot, string format, parentheses, hex, minus sign, floating point, static method, format string, java string, default locale, hexadecimal, digits, conversion method, octal, biginteger, 12345, format index, band 8, index logo, logo descriptionJuly 1
1, create ibatis profile SqlMapConfig.xml <? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE sqlMapConfig PUBLIC "- / / ibatis.apache.org / / DTD SQL Map Config 2.0 / / EN" "-
suffix, ibatis, lt xml, utf 8, web application, gt 2, doctype, gt 3, cn, web applications, struts apache, dtds, apache software foundation, i18n, default locale, dynamic method invocation, factory managementJune 25
Have long known that international, to know i18n, do not know why. Original internationalization (international), the word length is 20, and then whichever sum of the letters, the letter omitted the middle of just 18. Locale selected as the internati
lt, priority, ruby on rails, cn, lib, zh, yml, basic knowledge, load path, profiles, translations, default config, word length, internationalization i18n, default locale, international solutionJune 7
Reprinted: 3DStruts2 struts.configuration (default: org.apache.struts2.config.DefaultConfiguration) Struts 2 configuration file specified load the config
implementation class, configuration file, lib directory, attribute, resource files, internationalization, virtual machine, configuration interface, interface class, realization, application information, locale default, default locale, automatic assembly, default class, model values, crude solution, assembly model, factory assembly, c11April 24
Maven2.2.1 installation method 1, in the Apache website Maven2, Download Address:, I downloaded version is: maven-2.2.1-bin.zip. 2, the maven-2.2.1-bin.zip unzip to D: \ Program Files \ Maven 3, configure the env
apache, variable name, environment variables, java jdk1, variable value, environment variable, command line type, windows xp, os name, maven, m2, default locale, java version, new button, zip unzip, midpointApril 21
Default Magento has only English language pack, so if you want to also show the Chinese, it is necessary to install the Chinese language pack. Steps: 1. First, download the English package to extract to Mage
scope, storage, english language, china, default config, default locale, chinese language pack, chinese store, chinese code, options tab, app design, app localeApril 3
displaytag.properties file is located in the org.displaytag.properties displaytag-1.x.jar under Open this file, copy and save to make consequential amendments to the classes directory, you can display the form View the table settings accordingly Java
lt, java code, jsp, displaytag, localization, default locale, consequential amendments, span class, table settings, pdf export, decorators, csv excel, page sort, group size, banner placement, excel xml, table css, banner group, bottom position, header tableApril 1
1.maven2 Installation 1, first of all to the official website of:, I chose the version as the latest version of the maven2.0.4 2, set the environment variable: Maven2 Once downloaded, I will extract it into my co
variable name, directory structure, webapp, lib, system variables, environment variables, mvn, root directory, java jdk1, variable value, windows xp, dos window, os name, value parameter, maven, default locale, java version, source c, variable properties, creating webMarch 29
This file is the struts2 framework of the global property file is automatically loaded file. This file contains a series of key-value pairs. The file can configured in struts.xml file, use the constant element. The following is the configuration file
web application, spring framework, parameter values, configuration file, web applications, attribute, configuration manager, key value, value pairs, configuration interface, request parameters, default configuration, interface class, property values, default locale, automatic assembly, detection mechanism, false values, default property, global propertyMarch 20
Baidu left and right google. Finally found a way to achieve the Chinese errors, refer to the post as Because it is a simple procedure, suggesting that the error with or can, and
gt 2, lt 2, ruby, cn, generators, google, plug ins, sword, zh, tree master, original version, zip package, dos window, i18n, plugin directory, default locale, version errorMarch 6
We build the first WINODWS WIN32 compilation process, this process is complete display a dialog box with a question mark, the contents of the dialog box is now the system time. First, open MASM32Editor (can be found on the desktop icon), enter the fo
lib, environment variables, environment variable, dos window, helloworld, dialog box, dup, question mark, default locale, system time, desktop icon, reference system, asm, null null, gdi32, kernel32, user32, masm32, correct environment, winodwsFebruary 17
The central role of context is the ApplicationContext interface, which is derived from the BeanFactory interface. At the same time, context also provides the following features: 1) MessageSource, providing access to international news 2) resource acc
implementation, web application, conjunction, interface, internationalization, string code, i18n, application layer, default locale, loc, international newsMay 5
Struts2 constant at a glance: struts.configuration This attribute specifies the Struts 2 configuration file loads the configuration file manager. The default value of the property org.apache.Struts2.config.DefaultConfiguration, which is Struts 2 defa
web application, spring framework, parameter values, configuration file, web applications, attribute, configuration manager, configuration interface, request parameters, multipart form data, default configuration, interface class, property values, jakarta, default locale, mime type, automatic assembly, detection mechanism, false values, default propertyJuly 31
extjs contentElsite:file: C: set mobile60.8.19467;8088 net net_Kksyyhtmhttp: t.cn RZR5CRChttp: 58.213.129.204 infoms ccwj.jspheep: 38:9090 jsphttp: to access iav99.comjs request url 加密 | http://www.quweiji.com/tag/default-locale/ | CC-MAIN-2019-22 | en | refinedweb |
In this Google flutter code example we are going to learn how to use Expanded 'expandedicExpanded(), ); } }
expanded.dart
import 'package:flutter/material.dart'; class BasicExpanded extends StatelessWidget { //A widget that expands a child of a Row, Column, or Flex. //Using an Expanded widget makes a child of a Row, Column, or Flex expand to fill the available space in //the main axis (e.g., horizontally for a Row or vertically for a Column). @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Expanded Widget")), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ //Expanded here give the Inducesmile text the remaining available space Text("Google.com", style: TextStyle(fontSize: 25)), Expanded( child: Center( child: Text("Inducesmile.com", style: TextStyle(fontSize: 25)))), Text("Flutter.dev", style: TextStyle(fontSize: 25)), ], ), ), ); } }
If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below. | https://inducesmile.com/google-flutter/how-to-use-expanded-widget-in-flutter/ | CC-MAIN-2019-22 | en | refinedweb |
Program to implement t-test
The t test (also called Student’s T Test) compares two averages (means) and tells if they are different from each other. The t-test also tells how significant the differences are. In other words it lets you know if those differences could have happened by chance. t-test can be calculated by using formula :
where,
x̄1 is the mean of first data set
x̄2 is the mean of second data set
S12 is the standard deviation of first data set
S22 is the standard deviation of second data set
N1 is the number of elements in the first data set
N2 is the number of elements in the second data set
Examples :
Input : arr1[] = {10, 20, 30, 40, 50} arr2[] = {1, 29, 46, 78, 99} Output : -1.09789 Input : arr1[] = {5, 20, 40, 80, 100, 120} arr2[] = {1, 29, 46, 78, 99} Output : 0.399518
Explanation :
In example 1, x̄1 = 30, x̄2 = 50.6, S12 = 15.8114, S12 = 38.8626
using the formula, t-test = -1.09789
Below is the implementation of t-test.
C++
Java
Python3
# Python 3 Program to implement t-test.
from math import sqrt
# Function to find mean.
def Mean(arr, n):
sum = 0
for i in range(0, n, 1):
sum = sum + arr[i]
return sum / n
# Function to find standard
# deviation of given array.
def standardDeviation(arr, n):
sum = 0
for i in range(0, n, 1):
sum = (sum + (arr[i] – Mean(arr, n)) *
(arr[i] – Mean(arr, n)))
return sqrt(sum / (n – 1))
# Function to find t-test of
# two set of statistical data.
def tTest(arr1, n, arr2, m):
mean1 = Mean(arr1, n)
mean2 = Mean(arr2, m)
sd1 = standardDeviation(arr1, n)
sd2 = standardDeviation(arr2, m)
# Formula to find t-test
# of two set of data.
t_test = (mean1 – mean2) / sqrt((sd1 * sd1) / n +
(sd2 * sd2) / m)
return t_test
# Driver Code
if __name__ == ‘__main__’:
arr1 = [10, 20, 30, 40, 50]
# Calculate size of first array.
n = len(arr1)
arr2 = [1, 29, 46, 78, 99]
# Calculate size of second array.
m = len(arr2)
# Function call.
print(‘{0:.6}’.format(tTest(arr1, n, arr2, m)))
# This code is contributed by
# Surendra_Gangwar
C#
PHP
Output:
-1.09789
Recommended Posts:
- Program to implement standard error of mean
- Program to implement standard deviation of grouped data
- Implement two stacks in an array
- Program for harmonic mean of numbers
- Program for product of array
- Python program to add two matrices
- Program to find covariance
- Program for Mean Absolute Deviation
- Program for Coefficient of variation
- Program for K Most Recently Used (MRU) Apps
- Program for array rotation
- Program to check if an array is bitonic or not
- Program to calculate Bitonicity of an Array
- Program to find the Hidden Number
-, nitin mittal, SURENDRA_GANGWAR | https://www.geeksforgeeks.org/program-implement-t-test/ | CC-MAIN-2019-22 | en | refinedweb |
in reply to Re: Re: Factorsin thread Vampire Numbers
# Calculate the least non-negative remainder when an integer a
# is divided by a positive integer b.
sub mod {
my ($a, $b) = @_;
my $c = $a % $b;
return $c if ($a >= 0);
return 0 if ($c == 0);
return ($c + $b);
}
# Calculate a^b (mod c), where a,b and c are integers and a,b>=0, c>=1
+
sub mpow {
my ($a, $b, $c) = @_;
my ($x, $y, $z) = ($a, $b, 1);
while ($y > 0) {
while ($y % 2 == 0) {
$y = $y / 2;
$x = $x**2 % $c;
}
$y--;
$z = mod($z * $x, $c);
}
return $z;
}
# Shanks-Tonelli algorithm to calculate y^2 = a (mod p) for p an odd p
+rime
sub tonelli {
my ($a, $p) = @_;
my ($b, $e, $g, $h, $i, $m, $n, $q, $r, $s, $t, $x, $y, $z);
$q = $p - 1;
$t = mpow($a, $q/2, $p);
return 0 if ($t = $q); # a is a quadratic non-residue mod p
$s = $q;
$e = 0;
while ($s % 2 == 0) {
$s = $s/2;
$e++;
}
# p-1 = s * 2^e;
$x = mpow($a, ++$s/2, $p);
$b = mpow($a, $s, $p);
return $x if ($b == 1);
$n = 2;
RES: while ($n >= 2) {
$t = mpow($n, $q/2, $p);
last RES if ($t == $q);
} continue {
$n++;
}
# n is the least quadratic non-residue mod p
$g = mpow($n, $s, $p);
$r = $e;
OUT: {
do {
$y = $b;
$m = 0;
IN: while ($m <= $r-1) {
last IN if ($y == 1);
$y = $y**2 % $p;
} continue {
$m++;
}
return $x if ($m == 0);
$z = $r - $m - 1;
$h = $g;
for ($i = 1; $i < $z; $i++) {$h = $h**2 % $p;}
$x = ($x * $h) % $p;
$b = ($b * $h**2) % $p;
$g = $h**2 % $p;
$r = $m;
} while 1;
}
}
[download]
#! = . | http://www.perlmonks.org/?node_id=174242 | CC-MAIN-2017-26 | en | refinedweb |
I. 🙂. 🙂:
- Type definitions
- Utilities for calculating the corresponding digits (I took the liberty of calling it the Hash, abusing the term) of a text string
- Input: constructing a WordMap from the word list file
- Output: a pretty printer for phrases
- The core algorithm: calculating and printing the result
Since I anticipate most of the readers are not familiar with Haskell, I’ll give an almost line-by-line explanation on the code.
Let’s start with the type definitions.
3.1 Type definitions
type Digit = Int
type Word = String
type Phrase = [Word]
type WordMap = [Digit] -> Set Word
type Phraser = WordMap -> [Digit] -> [Phrase]:
— The characters on each key in a telephone keypad
keypad = [ “0”, “1”, “2abc”, “3def”, “4ghi”
, “5jkl”, “6mno”, “7pqrs”, “8tuv”, “9wxyz” ]
charHash finds the Hash (i.e. corresponding digit) of a character. It does this by finding the index of the element of keypad that contains this character. If no index is found, -1 is returned, meaning that this character is not in the keypad.
— Converts a character to its corresponding digit in the keypad.
charHash :: Char -> Digit
charHash ch = case findIndex (elem (toLower ch)) keypad of.
— Converts a String to its corresponding digit sequence.
strHash :: String -> [Digit]
strHash str = map charHash str.
readWords :: IO [Word]
readWords = do h <- openFile “words.txt” ReadMode
contents <- hGetContents h
return (words contents)
We construct the WordMap by inserting Words into it, one at a time. Hence the following function:
— 🙂 ). Output
I wrote a mini pretty printer for Phrases. Instead of inserting “–” between two words, I decide to just capitalize the first letter of each word. This way, all entries are printed with the same width, and are much easier on the eyes (to me at least).
— Capitalizes the first letter in a word
cap1 :: Word -> Word
cap1 “” = “”
cap1 (x:xs) = toUpper x : map toLower xs
cap1 is defined by pattern matching: If the input is empty, then the output is also empty. Otherwise suppose the first character in the input is x, and the rest of the input is a String xs, we just turn x into upper case and everything in xs into lower case. x:y means a list whose head is x and the remainder is y.
Given a Phrase (a list of Words) p, we show it by properly capitalizing each Word in p (that’s what map cap1 p does) and concatenating the results:
— Prints a Phrase
showPhrase :: Phrase -> String
showPhrase p = concat (map cap1 p)
Given a list of Phrases, we show it by separating the elements with TAB:
— Prints a list of Phrases
showPhrases :: [Phrase] -> String
showPhrases ps = concat (intersperse “\t” (map showPhrase ps))
3.5 Core algorithm
Now comes the exciting stuff. allPhrases is the function for calculating all possible ways to phrase a digit sequence (remember that Phraser is a synonym of (WordMap -> [Digit] -> [Phrase]).
—) ]
Compare this piece of code with our informal definition of P( s ) shown earlier:
P( empty sequence ) = { empty sequence }
P( s ) = { w++p | s1 is non-empty, s1++s2 == s, w is in P1( s1 ) and p is in P( s2 ) }
Do we see the correspondence? It’s pretty clear to me. This is what I love about Haskell most: being able to produce high-level code close to your algorithm description!
The last thing is to hook up I/O with the)
4. Sample runs
To phrase a phone # foo, just execute run allPhrases “foo”. For example,
run allPhrases “6423946369”
gives you:
There are 160 solutions:
6423946369 6423946Do9 6423946Fox 642394Of69 64239I6369
64239I6Do9 64239I6Fox 64239IOf69 64239Go369 64239GoDo9
64239GoFox 64239In369 64239InDo9 64239InFox 6423Who369
6423WhoDo9 6423WhoFox 6423Wind69 6423Wine69 6423Window
64A3946369 64A3946Do9 64A3946Fox 64A394Of69 64A39I6369
64A39I6Do9 64A39I6Fox 64A39IOf69 64A39Go369 64A39GoDo9
64A39GoFox 64A39In369 64A39InDo9 64A39InFox 64A3Who369
64A3WhoDo9 64A3WhoFox 64A3Wind69 64A3Wine69 64A3Window
64Be946369 64Be946Do9 64Be946Fox 64Be94Of69 64Be9I6369
64Be9I6Do9 64Be9I6Fox 64Be9IOf69 64Be9Go369 64Be9GoDo9
64Be9GoFox 64Be9In369 64Be9InDo9 64Be9InFox 64BeWho369
64BeWhoDo9 64BeWhoFox 64BeWind69 64BeWine69 64BeWindow
6I23946369 6I23946Do9 6I23946Fox 6I2394Of69 6I239I6369
6I239I6Do9 6I239I6Fox 6I239IOf69 6I239Go369 6I239GoDo9
6I239GoFox 6I239In369 6I239InDo9 6I239InFox 6I23Who369
6I23WhoDo9 6I23WhoFox 6I23Wind69 6I23Wine69 6I23Window
6IA3946369 6IA3946Do9 6IA3946Fox 6IA394Of69 6IA39I6369
6IA39I6Do9 6IA39I6Fox 6IA39IOf69 6IA39Go369 6IA39GoDo9
6IA39GoFox 6IA39In369 6IA39InDo9 6IA39InFox 6IA3Who369
6IA3WhoDo9 6IA3WhoFox 6IA3Wind69 6IA3Wine69 6IA3Window
6IBe946369 6IBe946Do9 6IBe946Fox 6IBe94Of69 6IBe9I6369
6IBe9I6Do9 6IBe9I6Fox 6IBe9IOf69 6IBe9Go369 6IBe9GoDo9
6IBe9GoFox 6IBe9In369 6IBe9InDo9 6IBe9InFox 6IBeWho369
6IBeWhoDo9 6IBeWhoFox 6IBeWind69 6IBeWine69 6IBeWindow
6Ice946369 6Ice946Do9 6Ice946Fox 6Ice94Of69 6Ice9I6369
6Ice9I6Do9 6Ice9I6Fox 6Ice9IOf69 6Ice9Go369 6Ice9GoDo9
6Ice9GoFox 6Ice9In369 6Ice9InDo9 6Ice9InFox 6IceWho369
6IceWhoDo9 6IceWhoFox 6IceWind69 6IceWine69 6IceWindow
Nice946369 Nice946Do9 Nice946Fox Nice94Of69 Nice9I6369
Nice9I6Do9 Nice9I6Fox Nice9IOf69 Nice9Go369 Nice9GoDo9
Nice9GoFox Nice9In369 Nice9InDo9 Nice9InFox NiceWho369
NiceWhoDo9 NiceWhoFox NiceWind69 NiceWine69 NiceWindow
This is all cool, except that the list contains so many entries with many numbers in it. No problem, given an arbitrary Phraser, we can easily restrict it by filtering the result it produces. Behold the power of higher-order functions (in C#, these are functions that take delegates as parameters or return delegates):
— Restricts a Phraser by a predicate
restrict :: (Phrase -> Bool) -> Phraser -> Phraser
restrict pred phraser = \wordMap ds ->
filter pred (phraser wordMap ds)
Now suppose we are only interested in phrases that contain no more than 2 digits. We just define a predicate that tells us if a phrase satisfies this test:
atMost2Digits :: Phrase -> Bool
atMost2Digits ph = length (filter isDigit (showPhrase ph)) <= 2
Then we can use this predicate to restrict the original Phraser. For example,
run (restrict atMost2Digits allPhrases) “6423946369”
gives us:
There are 24 solutions:
64BeWhoFox 64BeWindow 6IA3WhoFox 6IA3Window 6IBe9GoFox
6IBe9InFox 6IBeWhoDo9 6IBeWhoFox 6IBeWindow 6Ice9GoFox
6Ice9InFox 6IceWhoDo9 6IceWhoFox 6IceWindow Nice9I6Fox
Nice9GoDo9 Nice9GoFox Nice9InDo9 Nice9InFox NiceWhoDo9
NiceWhoFox NiceWind69 NiceWine69 NiceWindow
Isn’t this modular?
5. Ways to optimize
How would I go about optimizing my program? First let’s see where the time is spent. In this algorithm, most of the time the program is either updating the word map or looking up from it. In this simple implementation, inserting to the word map is an O(1) operation, which is good. However, looking up takes O(n) time, where n is the number of keys in the map. This seriously impedes the performance.
I have two ideas for reducing the complexity, both not difficult to implement. The first is to change the implementation of WordMap from a function to a Hash table, that will make both inserting and looking-up nearly O(1) (assuming a good Hash function). This alone should dramatically speed things up.
My second idea goes further and uses a trie instead of a Hash. This would yield guaranteed O(1) access time. It will also cut down the space footprint because keys share storage in a trie. (To find out the details, read more about the trie data structure here.)
Both optimizations will make the code look more complex, but not very much.
6. What has Microsoft got to do with functional programming?
Well, there are some eminent functional programmers at Microsoft, including Eric Meijer and Wolfram Schulte, who designed the much anticipated Xen programming language together. More to the point, Xen (rumors are that it’s called X omega now) incorporates a lot of cool ideas from functional programming to C# in order to support seamless programming of XML, SQL, and objects.
The next version of C# (the one in Whidbey) was also influenced by functional programming. One example is the addition of anonymous methods.
And, the most widely used Haskell compiler is called GHC, which is freely available and supported (among others) by researchers at Microsoft Research,
VERY nice. I was halfway with my own C++ based solution just now but since I’ve looked at your algorithm and code, I’m too tainted to even continue 🙂
Functional language are cool, but can you give us any idea about actual performance?
Dear Tene,
The performance is not bad at all. It took a couple of seconds to find the 160 solutions in my example. What matters is the complexity of the algorithm. With the optimization I proposed, the performance can still be drastically improved.
Thanks for your reply, is there a chance to get a more precise idea of what give haskell against C++ or C#?
I mean "a couple of seconds" on an unknown system is a bit short to get an idea of the perf 😉
Another interresting aspect is how "unreadable" become optimized code?
Dear Tene,
It’s not easy to give a short answer to your questions. I suggest you check out this guide:.
I came up with a similar (divide and conquer) algorithm… but with a few different optimizations (sort-of)…
Using regular expressions , I created a small lookup table… of the word – word in numbers – weight (length of word).. At the same time, I also checked to see if the word as a number was in the original number.. this created an incredibly smaller set of words to check. A filter basically. Take care of the larger O(n) sequence FIRST and then you only have to iterate an O(n) on a considerably smaller set. THEN I divided into
(head) (found sequence) (tail) recursion route.. and by ALSO filtering the small table by weight, it created an even smaller subset, and in a lot of cases, eliminated the candidates completely…
I havent compiled this as I am OOF and dont have a compiler handy (:: sigh ::)
The trick is dealing with the head and tail having multiple matches that converge on the found sequence. But I think it lends to an efficient algorithm.. especially if you want to run several numbers over the same word set.
Is there something wrong with my crazy thinking? 🙂 I welcome suggestions…
jake *(@)* developstuff.com
Jake
I’ve posted my optimized version of the solution <a href=> here</a> and I’ve also made <a href=>a web page</a> from which you can enter a phone number or sequence of letters to run the algorithm and see the results.
(fixed urls)
I’ve posted my optimized version of the solution and I’ve also made a web page from which you can enter a phone number or sequence of letters to run the algorithm. 🙂.
Just to give some background, the C# implementation takes on the order of 200 ms to find all 160 solutions (actually more because I expanded my dictionary, the original contest had nice-win-fox as a result, so I added win to the dictionary and another I believe), and only a slightly longer amount of time to parse the results down based on the maxDigits calculation.
PingBack from
PingBack from | https://blogs.msdn.microsoft.com/the1/2004/04/02/my-own-solution-to-my-programming-challenge/ | CC-MAIN-2017-26 | en | refinedweb |
I'm setting up ProGuard for my Android project. My project also uses GSON.
I've researched ProGuard configurations for compatibility with GSON and Android and came across this example offered by google-gson.
ProGuard config copied below:
##---------------Begin: proguard configuration common for all Android apps ----------
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-repackageclasses ''
-dontnote com.android.vending.licensing.ILicensingService
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
();
}
# Preserve all native method names and the names of their classes.
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembernames class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
# Preserve static fields of inner classes of R classes that might be accessed
# through introspection.
-keepclassmembers class **.R$* {
public static <fields>;
}
# Preserve the special static methods that are required in all enumeration classes.
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep public class * {
public protected *;
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
##---------------End: proguard configuration common for all Android apps ----------
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
##---------------End: proguard configuration for Gson ----------
I think most of those settings you have there are already included in the Android SDK by default.
So you can remove most of them, just leaving in the section devoted to GSON.
I am developing in Eclipse using Android SDK Tools 22.6.3 & whatever version of ProGuard ships with that.
Here's what I'm using for GSON 2.2.4 (as per their example):
##---------------Begin: proguard configuration for Gson ---------- # Gson uses generic type information stored in a class file when working with fields. Proguard # removes such information by default, so configure it to keep all of it. -keepattributes Signature # Gson specific classes -keep class sun.misc.Unsafe { *; } #-keep class com.google.gson.stream.** { *; } # Application classes that will be serialized/deserialized over Gson # -keep class mypersonalclass.data.model.** { *; }
It looks exactly the same as what you have, except I don't need the line about the annotations.
You can see I've commented out some classes that I added myself. If you serialize/deserialize your own classes, you need to declare them here in place of the reference to
mypersonalclass.data.model. This is really important, as you don't want ProGuard to obfuscate the field or class names that GSON uses for serialization.
I always leave those types of comments in there, so I know how to configure the next library or app. | https://codedump.io/share/dEJAwHfU1uqi/1/proguard-for-android-and-gson | CC-MAIN-2017-26 | en | refinedweb |
I have the following mapping in ObjectFactory.Initialize
method:
ObjectFactory.Initialize
expression.For<IFoo>().Singleton()
.Use<SomeFoo>()
.Ctor<string>("url").Is(<fetch from config>)
.Ctor<string>("username").Is(<fetch from config>)
This ensures that my
Ok, I have a singleton class GraphMaster which contains a
number of system-wide values. I have a subclass GraphObject :
GraphMaster which has graph specific data. By subclassing, I can
access members of either the global class or subclass. And by using a
singleton class, I can change the global variables anywhere and have them
be reflected in all the subclasses.
GraphMaster
GraphObject :
GraphMaster
I have a service in my application which is a singleton.My
application is being bloated with the use of spring framework.
I am confused over to use the singleton service as
1:
Plain Old Singleton [Access them statically when required]
OR
as a
2: Spring singleton bean. [Use DI to inject when
required]
Which approach is correct ?
There is a pattern that I use from time to time, but I'm not quite sure
what it is called. I was hoping that the SO community could help me
out.
The pattern is pretty simple, and consists of two parts:
A factory method that creates objects based on the arguments
passed in.
Objects created by the factory.
So far
this is just a standard "factory" p
I'm calling my custom factory that I created (PhotoServiceFactory),
which is a singleton that allows me to get at a specific custom service
type back (in this case FacebookService). FacebookService is also a
singleton. In FacebookService I've exposed an instance of
FacebookAlbumPhoto through a property. I did this because then I don't
have to have a ton of the same code over and over again c
I have the following error in my code
Assignment has more
non-singleton rhs dimensions than non-singleton
This is
the code:
string =['d:facefaceffw' int2str(r) '_'
int2str(Sel(nSelRow,t)) '.bmp']; A = imread(string); B =
im2double(A); Train_Dat(:,:,s)=B;
When I updated the code we got new err
My goal ist to reference a function into an singleton/object
body!
#
This result is my goal:
var
singletonObj_1 = (function () { return {
custom_fn1 : function(){...}, custom_fn2 :
function(){...} <<-- *But Imported }})();
So after importing, i am able to call
I have two services, one that calls another. Both are marked as
singletons as follows:
[ServiceBehavior(InstanceContextMode
= InstanceContextMode.Single, ConcurrencyMode =
ConcurrencyMode.Multiple)]public class Service : IService
And I set these up with a ServiceHost as follows:
ServiceHost serviceHost = new ServiceHost(singleto
I've tried putting the remote interface of another Singleton bean into
another. However, the remote object will always be null. Is there any other
way I could get around it?
@Singletonpublic class
SingletonBean1 implements SingletonBean1Remote { @EJB
SingletonBean2Remote singletonBean2Remote; ... public
SingletonBean1() { ...
I started to develop my singleton class but I have a problem.What
I want to do is have a search objects containing the values of the search
form that I could use in several views.I want to have the ability to
get the singleton in any view in order to perform the search or build the
search form.So I have a set of values with a boolean for each to know
if the variable has been i | http://bighow.org/tags/Singleton/1 | CC-MAIN-2017-26 | en | refinedweb |
I have an array that is initialised like:
Element[] array = {new Element(1),new Element(2),new Element(3)};
I would like to convert this array into an object of the ArrayList class.
ArrayList<Element> arraylist = ???;
I am sure I have done this before, but the solution is sitting just at the edge of my memory.
new ArrayList<Element>(Arrays.asList(array)).
I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<>. For the sake of this example lets say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression?
List<Person> people = PopulateList(); people.OrderBy(???? => ?????)
If you mean an in-place sort (i.e. the list is updated):
people.Sort((x, y) => string.Compare(x.LastName, y.LastName));
If you mean a new list:
var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional
This causes a compile-time exception:
public sealed class ValidatesAttribute<T> : Attribute { } [Validates<string>] public static class StringValidation { }
I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.
Does anyone know why generic types cannot derive from
Attribute? Any theories?
Well, I can't answer why it's not available, but I can confirm that it's not a CLI issue. The CLI spec doesn't mention it (as far as I can see) and if you use IL directly you can create a generic attribute. The part of the C# 3 spec that bans it - section 10.1.4 "Class base specification" doesn't give any justification.
The annotated ECMA C# 2 spec doesn't give any helpful information either, although it does provide an example of what's not allowed.
My copy of the annotated C# 3 spec should arrive tomorrow... I'll see if that gives any more information. Anyway, it's definitely a language decision rather than a runtime one.
EDIT: Answer from Eric Lippert (paraphrased): no particular reason, except to avoid complexity in both the language and compiler for a use case which doesn't add much value.:
int(); }; int
int :-)
Due to the implementation of Java Generics you can't have code like this. How can I implement this while maintaining type safety?
public class GenSet<E> { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; } }? Thanks in advance.
I have to ask a question in return: is your GenSet "checked" or "unchecked"? What does that mean?
checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection(java.util.Collection, java.lang.Class)
-> in that case, you should write
private E[] a @SuppressWarnings({"unchecked"}) public GenSet(Class<E> c, int s) { // Use Array native method to create array of a type only known at run time a = (E[]) Array.newInstance(c,s); } E get(int i) { return a[i]; }
unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.
-> in that case, you should write
private Object[] a public GenSet(int s) { a = new Object[s]; } @SuppressWarnings({"unchecked"}) E get(int i) { return (E) a[i]; }
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.
Can. | http://boso.herokuapp.com/generics | CC-MAIN-2017-26 | en | refinedweb |
Perfect for buttons, logos and nav/tab bars. Easy to extend, style and integrate into your project.
Main advantages over
react-native-icons
- You can use your own custom icon sets. Supports SVG via Fontello or regular icon fonts.
- You can use native
TabBarIOS.
- You can use icons inline with
Textcomponents as emojis or to create buttons.
- You can use the icon as an image if a native component requires it (such as
NavigatorIOS).
- Most common use cases is JavaScript only and thus enables wider possibilities of styling (and is easier to integrate with your project).
- No need to define
widthand
heightstyles.
- Presentational stuff like size and color can be defined in your stylesheet instead of via a property (if you want to).
- Icons scale with accessibility settings (unless disabled).
Pst! Migrating from
react-native-icons? Scroll down for more information.
Bundled Icon Sets)
Installation
- Run:
$ npm install react-native-vector-icons --save
- For each platform (iOS/Android/Windows) you plan to use, follow one of the options for the corresponding platform.
iOS
Option: Manually
If you want to use any of the bundled icons, you need to add the icon fonts to your Xcode project. Just follow these steps:
- Browse to
node_modules/react-native-vector-iconsand drag the folder
Fonts(or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder.
- Edit.
Option: With CocoaPods.
Option: With
rnpm
$ react-native link
Note: Some users are having trouble using this method, try one of the others if you are too.
Android
Option: With Gradle (recommended)"
Option: Manually
- Copy the contents in the
Fontsfolder to
android/app/src/main/assets/fonts(note lowercase font folder).
Integrating library for
getImageSource and
ToolbarAndroid support
These steps are optional and only needed if you want to use the
Icon.getImageSource function or using custom icons in the
Icon.ToolbarAndroid component.
Edit
android/settings.gradleto look like this (without the +):
rootProject.name = 'MyApp' include ':app' + include ':react-native-vector-icons' + project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
Edit-vector-icons') }
Edit your
MainApplication.java(deep in
android/app/src/main/java/...) to look like this (note two places to edit):
package com.myapp; + import com.oblador.vectoricons.VectorIconsPackage; .... @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage() + , new VectorIconsPackage() ); } }
Note: If you're using React Native (Android) <= 0.17, follow this instructions
Option: With
rnpm
$ react-native link
Note: Some users are having trouble using this method, try one of the others if you are too.
OSX via
react-native-desktop
- Browse to
node_modules/react-native-vector-iconsand drag the folder
Fontsto your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create folder references" is checked.
- Edit.
Windows via
react-native-windows
- Open your solution in Visual Studio, right click the Assets folder in your solution, click Add Existing.
- Browse to the
node_modules\react-native-vector-icons\Fontsfolder, select the required font files
- Click the Add drop-down and select Add as Link.
- Set Copy To Output Directory property of each font file to Copy if newer
Note: you need to recompile your project after adding new fonts.
Web (with webpack) include: path.resolve(__dirname, "node_modules/react-native-vector-icons"), },
Then consume those files in your JavaScript entry point to get the bundled url and inject a style tag in your page:
// generate required css import fontAwesome from "react-native-vector-icons/Fonts/FontAwesome.ttf" const reactNativeVectorIconsRequiredStyles = "@font-face { src:url("+fontAwesome+");font-family: FontAwesome; }" // create stylesheet const style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet){ style.styleSheet.cssText = reactNativeVectorIconsRequiredStyles; } else { style.appendChild(document.createTextNode(reactNativeVectorIconsRequiredStyles)); } // inject stylesheet document.head.appendChild(style);
Icon Component
You can either use one of the bundled icons above or roll your own custom font.
import Icon from 'react-native-vector-icons/FontAwesome'; const myIcon = (<Icon name="rocket" size={30})
Properties
Any Text property and the following:
Styling Component
A convenience component for creating buttons with an icon on the left side.
import Icon from 'react-native-vector-icons/FontAwesome'; const myButton = ( <Icon.Button <Text style={{fontFamily: 'Arial', fontSize: 15}}>Login with Facebook</Text> </Icon.Button> );
Properties
Any
Text,
TouchableHighlight or
TouchableWithoutFeedback property in addition to these:
Usage as PNG image/source object.
Usage with TabBarIOS.
Usage with Navigator.
Usage with ToolbarAndroid.
Custom Fonts.
import { createIconSet } from 'react-native-vector-icons'; const glyphMap = { 'icon-name': 1234, test: '∆' }; const Icon = createIconSet(glyphMap, 'FontName');
createIconSetFromFontello(config[, fontFamily[, fontFile]])
Convenience method to create a custom font based on a fontello config file. Don't forget to import the font as described above and drop the
config.json somewhere convenient in your project.
import { createIconSetFromFontello } from 'react-native-vector-icons'; import fontelloConfig from './config.json'; const Icon = createIconSetFromFontello(fontelloConfig);
createIconSetFromIcoMoon(config[, fontFamily[, fontFile]])
import { createIconSetFromIcoMoon } from 'react-native-vector-icons'; import icoMoonConfig from './config.json'; const Icon = createIconSetFromIcoMoon(icoMoonConfig);.
Animation
React Native comes with an amazing animation library called
Animated. To use it with an icon, simply create an animated component with this line:
const AnimatedIcon = Animated.createAnimatedComponent(Icon). You can also use the higher level animation library react-native-animatable.
Examples
IconExplorer
Try the
IconExplorer project in
Examples/IconExplorer folder, there you can also search for any icon.
Basic Example
import Icon from 'react-native-vector-icons/Ionicons'; function ExampleView(props) { return (<Icon name="ios-person" size={30}); }
TabBarIOS
Full example in
TabBarExample project in
Examples/TabBarExample folder.
import { View, Text, TabBarIOS } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; function TabBarView(props) { return ( <TabBarIOS> <Icon.TabBarItem <View style={styles.tabContent}><Text>Home Tab</Text></View> </Icon.TabBarItem> </TabBarIOS> ); }
ToolbarAndroid
import Icon from 'react-native-vector-icons/Ionicons'; function ToolbarView(props) { return ( <Icon.ToolbarAndroid ); }
Inline Icons
import { Text } from 'react-native'; import Icon from 'react-native-vector-icons/Ionicons'; function ExampleView(props) { return (<Text>Lorem <Icon name="ios-book" color="#4F8EF7" /> Ipsum</Text>); }
Community examples
- react-native-dribbble-app
- voximplant react-native-demo
- product-kitty (blog post)
- react-native-netflix
Generating your own icon set from a CSS file
If you already have a icon font with associated CSS file then you can easily generate a icon set with the
generate-icon script.
Example usage:
./node_modules/.bin/generate-icon path/to/styles.css --componentName=MyIcon --fontFamily=myicon > Components/MyIcon.js
Options
Changelog
Migrating:
import Icon from 'react-native-vector-icons/RNIMigration';
Troubleshooting
The icons show up as a crossed out box on Android
- Make sure you've copied the font to
android/app/src/main/assets/fonts.
- Delete the
android/app/buildfolder.
- Recompile the project.
Red screen with "Unrecognized font family" error on iOS
- Make sure you've added manually the reference of your
.ttfon your xcodeproj
Resourcesfolder.
- Check that the font you are trying to use appears in
Info.plist, if you've added the whole folder and it's blue in color, then you need to add it to the path.
- Check that the font is copied in the Copy Bundle Resources in Build Phases.
- Recompile the project.
Android build fails on Windows for no good reason.
License
This project is licenced under the MIT License.
Any bundled fonts are copyright to their respective authors and mostly under MIT or SIL OFL.
Add to your project
npm i --save react-native-vector-icons | http://nativerepo.com/i/oblador/react-native-vector-icons | CC-MAIN-2017-26 | en | refinedweb |
(very) approximately 1000 bytes in size. They are stored using a Microsoft proprietary binary format, and are created and modified using Windows API COM (Component Object Model) functions.
The remainder of this topic describes the fields in the short-cut, how to create a short-cut, and a sample program that creates short-cuts. Because this is a Windows API article, this topic concludes by discussing how to create short-cuts in other languages that don't offer direct COM support. Short-cut creation is discussed using Visual Basic and Ubercode - these discussions are relevant because they show that COM and the Windows API are truly language-independent concepts, then click on Shortcut in the Properties dialog. The short-cut properties look like this (the exact details vary with different versions of Windows):
The short-cut dialog shows the most important fields, but bear in mind short-cuts have extra fields that are not shown in the dialog. Here is the complete list of fields:
ShowWindow()
SW_SHOWNORMAL (1)
SW_SHOWMAXIMIZED (3)
SW_SHOWMINNOACTIVE (7)
Other values are ignored by Windows. Also note that some target files ignore this information because they define their preferred window size when they start.
Most of the fields in this list can be set by code when the short-cut file is created. This is shown next.
Short-cuts are created using the Windows COM (Component Object Model) library. Functions in the COM library are available to programs written in C, C++, VBScript,()
/*
-------------------------------------------------------------------
Description:
Creates the actual 'lnk' file (assumes COM has been initialized).
Parameters:
pszTargetfile - File name of the link's target.
pszTargetargs - Command line arguments passed to link's target.
pszLinkfile - File name of the actual link file being created.
pszDescription - Description of the linked item.
iShowmode - ShowWindow() constant for the link's target.
pszCurdir - Working directory of the active link.
pszIconfile - File name of the icon file used for the link.
iIconindex - Index of the icon in the icon file.
Returns:
HRESULT value >= 0 for success, < 0 for failure.
--------------------------------------------------------------------
*/
static HRESULT CreateShortCut(LPSTR pszTargetfile, LPSTR pszTargetargs,
LPSTR pszLinkfile, LPSTR pszDescription,
int iShowmode, LPSTR pszCurdir,
LPSTR pszIconfile, int iIconindex)
{
HRESULT hRes; /* Returned COM result code */
IShellLink* pShellLink; /* IShellLink object pointer */
IPersistFile* pPersistFile; /* IPersistFile object pointer */
WORD wszLinkfile[MAX_PATH]; /* pszLinkfile as Unicode
string */
int iWideCharsWritten; /* Number of wide characters
written */
hRes = E_INVALIDARG;
if (
(pszTargetfile != NULL) && (strlen(pszTargetfile) > 0) &&
(pszTargetargs != NULL) &&
(pszLinkfile != NULL) && (strlen(pszLinkfile) > 0) &&
(pszDescription != NULL) &&
(iShowmode >= 0) &&
(pszCurdir != NULL) &&
(pszIconfile != NULL) &&
*/
&pShellLink); /* Returns a pointer to the IShellLink
object */
if (SUCCEEDED(hRes))
{
/* Set the fields in the IShellLink object */
hRes = pShellLink->lpVtbl->SetPath(pShellLink,
pszTargetfile);
hRes = pShellLink->lpVtbl->SetArguments(pShellLink,
pszTargetargs);
if (strlen(pszDescription) > 0)
{
hRes = pShellLink->lpVtbl->SetDescription(pShellLink,
pszDescription);
}
if (iShowmode > 0)
{
hRes = pShellLink->lpVtbl->SetShowCmd(pShellLink,
iShowmode);
}
if (strlen(pszCurdir) > 0)
{
hRes = pShellLink->lpVtbl->SetWorkingDirectory(pShellLink,
pszCurdir);
}
if (strlen(pszIconfile) > 0 && iIconindex >= 0)
{
hRes = pShellLink->lpVtbl->SetIconLocation(pShellLink,
pszIconfile, iIconindex);
}
/* Use the IPersistFile object to save the shell link */
hRes = pShellLink->lpVtbl->QueryInterface(
pShellLink, /* existing IShellLink object */
&IID_IPersistFile, /* pre-defined interface of the
IPersistFile object */
&pPersistFile); /* returns a pointer to the
IPersistFile object */
if (SUCCEEDED(hRes))
{
iWideCharsWritten = MultiByteToWideChar(CP_ACP, 0,
pszLinkfile, -1,
wszLinkfile, MAX_PATH);
hRes = pPersistFile->lpVtbl->Save(pPersistFile,
wszLinkfile, TRUE);
pPersistFile->lpVtbl->Release(pPersistFile);
}
pShellLink->lpVtbl->Release(pShellLink);
}
}
return (hRes);
}
The code works as follows. Firstly the inputs are validated, to avoid program errors caused by NULL pointers or missing arguments. Assuming the inputs are valid, CoCreateInstance() is called to create the IShellLink object.
NULL
If IShellLink was successfully created, the fields in the short-cut can be set. This is done by SetPath(), SetArguments(), SetDescription(), SetShowCmd(), SetWorkingDirectory(), and SetIconLocation(). Some of these fields are optional, for example if no description was passed into the function, SetDescription() is not called.
SetPath()
SetArguments()
SetDescription()
SetShowCmd()
SetWorkingDirectory()
SetIconLocation()
After setting the fields, the short-cut exists only in memory. The next step is to use QueryInterface() to create the IPersistFile object. The call to QueryInterface() (instead of CoCreateInstance()) connects IPersistFile to the IShellLink object. This means IPersistFile knows what to save when it is told to write to a file.
After IPersistFile was created, the name of the short-cut file (pszLinkfile) is converted to a Unicode string. Then IPersistFile's Save() method is called, which saves the short-cut to an actual file. The end result is the short-cut
This topic also includes a sample program for creating short-cuts, provided as C source code. The file has no external dependencies other than the Windows API, so it can be compiled by creating a new console-mode project, adding the source file and compiling it. The compiled program makelink.exe should run under any version of Windows, from Windows 95 onwards. When the sample program is run without any parameters, it shows a help screen as follows:
The help screen shows how the program is called up. For example if you type:
makelink c:\windows\notepad.exe "" mylink.lnk ""
this creates a short-cut file mylink.lnk in the current directory. The empty strings "" represent the arguments and description which are not required. When mylink.lnk is double-clicked, it runs the Notepad program. As another example if you type:
makelink c:\windows\write.exe c:\windows\tips.txt mylink.lnk ""
this creates a short-cut file mylink.lnk in the current directory. When activated, the short-cut will run the Windows write.exe program and make it open the Windows tips file.
If you read through the source code of the sample program, you will see the following functions:
ShowHelp()
ShowError()
GetArguments()
main()
It is interesting to see how short-cut are created using other computer languages. The main complication is that not all languages allow direct calls to the COM library. Programs in these languages must either provide link creation code as an inbuilt function in the language, or must use other techniques to access the COM library.
For example Ubercode is a modern computer language with ease-of-use as its main objective. Ubercode syntax is as simple as possible, consistent with being useful for real-world applications, and consistent with being compilable to Windows EXE files and allowing simple distribution to other computers. To implement short-cuts, Ubercode includes built-in library functions that directly permit the creation of short-cuts. Here is a sample program:
Ubercode 1 class MakeShortCut
public function main()
var
linkfile:string[*]
result:integer(0:MAXINT)
code
linkfile <- "mylink.lnk"
result <- FileCreateShortcut("c:\windows\notepad.exe",
"", linkfile, "")
if SUCCEEDED(result) then
call Msgbox("MakeShortCut",
"Return code = " + Str(result) + NL +
"Successfully created " + linkfile)
else
call Sound("")
call Msgbox("MakeShortCut",
"Return code = " + Str(result) + NL +
"Could not create " + linkfile)
end if
end function
end class
As can be seen, Ubercode syntax is similar to JavaScript and to C#. The program consists of a single class MakeShortCut containing a single function main. The class is therefore a main class that compiles to an EXE file. The code in function main works as follows:
MakeShortCut
main
First the name of the short-cut file is copied to a string variable, then FileCreateShortcut() is called. This is an inbuilt library function that takes the same argument as the makelink program shown previously (Ubercode allows functions to have optional arguments). After FileCreateShortcut() returns, the result of the call is checked, and a success or failure message is shown. When the program terminates, the short-cut file will exist on disk.
FileCreateShortcut()
If you want to experiment more with this code and with the Ubercode Developer Environment, it can be downloaded from the Ubercode website.
Most versions of Microsoft Visual Basic provide direct access to the COM library, so short-cuts can be created using Visual Basic. Here is a program that creates a short-cut. This example is loosely based on the Microsoft Windows Script Technologies help file v5.6, under the topic Creating a shortcut. This example has been tested with VBScript v5.6, and should also run under Visual Basic version 5 and version 6:
' Make sure variables are declared.
option explicit
' Routine to create "mylink.lnk" on the Windows desktop.
sub CreateShortCut()
dim objShell, strDesktopPath, objLink
set objShell = CreateObject("WScript.Shell")
strDesktopPath = objShell.SpecialFolders("Desktop")
set objLink =
objShell.CreateShortcut(strDesktopPath & "\mylink.lnk")
objLink.Arguments = "c:\windows\tips.txt"
objLink.Description = "Shortcut to Notepad.exe"
objLink.TargetPath = "c:\windows\notepad.exe"
objLink.WindowStyle = 1
objLink.WorkingDirectory = "c:\windows"
objLink.Save
end sub
' Program starts running here.
call CreateShortCut()
This works as follows. The program starts running at the first line of module-level code (i.e. code not in a function or subroutine), which is the line of code call CreateShortCut(). The CreateShortCut() routine declares its variables, then creates the COM object objShell using "WScript.Shell". The string variable strDesktopPath is initialized with the full path to the Windows desktop. The call objShell.CreateShortcut creates an actual IShellLink object which is stored in the objLink variable. The fields of objLink are set, and these fields have the same meanings and values as in the short-cut properties dialog shown previously. Refer to the section
To run the example, save the code to a file with the extension .vbs, for example makelink.vbs. Open a command window and type wscript makelink.vbs to run it. After the Visual Basic file finishes running, the short-cut mylink.lnk should exist on the Windows desktop. If double-clicked, the short-cut will run Windows Notepad, and open the Windows tips file.
This article discussed the uses of short-cuts and their internal structure. It showed a C function for creating a short-cut and provided C source code for a command-line program that creates short-cuts. The article then discussed short-cut creation using other languages. The purpose of the discussion was to show COM functions are available in the same way as other Windows API functions - there is nothing special about COM that requires it to be called from C++ or from Microsoft scripting languages.
I hope you enjoyed the article. Any suggestions or feedback is welcome.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
I've made some changes to the CreateShortCut function for: support UNICODE, remove the use of the virtual-table's pointer and, enable default values for some of the parameters. I've changed the order of the second and the third parameter, since the most important parameters are the files' names. So that, we can call the function only with the files' names and, get default values for the other parameters.
CreateShortCut
Here is the changed function:
HRESULT CreateShortCut(LPCTSTR pszTargetfile, LPCTSTR pszLinkfile,
LPCTSTR pszTargetargs, LPCTSTR pszDescription,
int iShowmode, LPCTSTR pszCurdir,
LPCTSTR pszIconfile, int iIconindex)
{
HRESULT hRes; /* Returned COM result code */
IShellLink* pShellLink; /* IShellLink object pointer */
IPersistFile* pPersistFile; /* IPersistFile object pointer */
hRes = E_INVALIDARG;
if (
(pszTargetfile != NULL) && (_tcslen(pszTargetfile) > 0) &&
(pszLinkfile != NULL) && (_tcslen(pszLinkfile) > 0) &&
(iShowmode >= 0) &&
*/
(LPVOID*)&pShellLink); /* Returns a pointer to the IShellLink object */
if (SUCCEEDED(hRes))
{
/* Set the fields in the IShellLink object */
hRes = pShellLink->SetPath(pszTargetfile);
hRes = pShellLink->SetArguments(pszTargetargs != NULL ? pszTargetargs : _T(""));
if (pszDescription != NULL && _tcslen(pszDescription) > 0)
{
hRes = pShellLink->SetDescription(pszDescription);
}
if (iShowmode > 0)
{
hRes = pShellLink->SetShowCmd(iShowmode);
}
if (pszCurdir != NULL && _tcslen(pszCurdir) > 0)
{
hRes = pShellLink->SetWorkingDirectory(pszCurdir);
}
if (pszIconfile != NULL && _tcslen(pszIconfile) > 0 && iIconindex >= 0)
{
hRes = pShellLink->SetIconLocation(pszIconfile, iIconindex);
}
/* Use the IPersistFile object to save the shell link */
hRes = pShellLink->QueryInterface(
IID_IPersistFile, /* pre-defined interface of the IPersistFile object */
(void**)&pPersistFile); /* returns a pointer to the IPersistFile object */
if (SUCCEEDED(hRes))
{
hRes = pPersistFile->Save(pszLinkfile, TRUE);
pPersistFile->Release();
}
pShellLink->Release();
}
}
return (hRes);
}
For the header file, we can add the following forward declaration:
HRESULT CreateShortCut(LPCTSTR pszTargetfile, LPCTSTR pszLinkfile,
LPCTSTR pszTargetargs = NULL, LPCTSTR pszDescription = NULL,
int iShowmode = SW_SHOWNORMAL, LPCTSTR pszCurdir = NULL,
LPCTSTR pszIconfile = NULL, int iIconindex = 0);
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/11467/How-to-create-short-cuts-link-files?msg=1215475 | CC-MAIN-2017-26 | en | refinedweb |
Upgrading to Mountain Lion has been a terrible experience so far. After
upgrading, bash commands didn't even work in the terminal so I had them
back into my path variable. Memcached also stopped working.
Anyways, when I try to use my cakephp application on my local
environment with MAMP, I get a cakephp error saying my caching isn't
configured correctly. Not surprisingly, class_e
I
I was wondering if there was a way to know where the script stopped (ie:
file + line), which would be useful for debugging or for removing stupid
'exit' calls lost somewhere in the code.
Thanks in advance
I am developing web application using (C#) and (ASP.NET Web API) and MS
SQL 2008 R2 and hosting on IIS7 in Windows Server 2008, All APIs return
data in JSON
When i call any API from any web browser and
refresh the page to call again before the first call finishes it give me
warning in the event viewer and after 0 to 5 minutes the worker process in
the II7 stopped for about 2 minutes
I am getting error : Unfortunately App has Stopped
By using
below code, i am trying to call RestaurantActivity by using click on
Restaurant Button.
AndroidDashboardDesignActivity.java:
public class AndroidDashboardDesignActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState)
{ super.onCreate(save
I want to download and parse an XML code from the internet and I have no
problems with the version 2.3.3. Everything runs perfect!
But
when I start the version 4.1.2 (AVD) I got following error:
Unfortunately, myProject has stopped.
At this line:
HttpResponse httpResponse = httpClient.execute(httpPost)
What is the problem
Back again with another rookie question. While working on a function for
my homework project I found that my menu wouldn't exit when I press X, it
worked just an hour ago and I haven't changed anything in main(). I
commented out all the code in my functions just to be sure that nothing in
a function interfered. I just can't find any problem and would be grateful
for any help.
int
#include<stdio.h>#include<conio.h>#include<string.h>char *createP(int);int main(){ int n,i; char str[100]; printf("int n =
"); scanf("%d",&n); printf("string str = ");
scanf("%s",&str); if(n>40) return -1; for(i=0;i<strlen(str);i++) | http://bighow.org/tags/stopped/1 | CC-MAIN-2017-26 | en | refinedweb |
On iOS, views always have an underlying layer. There is a very strong relationship between the view and its layer, and the view derives most of its data from the layer object directly. There are also standalone layers – for example,
AVCaptureVideoPreviewLayer and
CAShapeLayer – that present content on the screen without being attached to a view. In either case, there is a layer involved. Still, the layers that are attached to views and the standalone layers behave slightly differently.
If you change almost any property of a standalone layer, it will make a brief animation from the old value to the new value.1 However, if you change the same property of a view’s layer, it just changes from one frame to the next. Despite it being layers involved in both cases, the default layer behavior of implicit animations doesn’t apply when the layer is attached to a view.
An explanation as to why this is happening can be found in the Core Animation Programming Guide in the section “How to Animate Layer-Backed Views”:
The UIView class disables layer animations by default but reenables them inside animation blocks
That is the behavior that we are seeing; when a property is changed outside of an animation block, there is no animation, but when the property is changed inside of an animation, there is an animation. The answer to the question of how this is happening is both simple and elegant and speaks well to how views and layers were designed to work together.
Whenever an animatable layer property changes, the layer looks for the appropriate ‘action’ to run for that property change. An action in Core Animation terminology is a more general term for an animation.2 The layer searches for an action in a very well-documented manner, consisting of five steps. The first step is the most interesting when looking at the interaction between the view and the layer:
The layer asks its delegate to provide an action for the property that was changed by sending the
actionForLayer:forKey: message to its delegate. The delegate can respond with one out of three things:
- It can respond with an action object, in which case the layer will use that action.
- It can respond with
nilto tell the layer to keep looking elsewhere.
- It can respond with the
NSNullobject to tell the layer that no action should run and that the search should be terminated.
What makes this so interesting is that, for a layer that is backing a view, the view is always the delegate:
In iOS, if the layer is associated with a UIView object, this property must be set to the view that owns the layer.
What may have seemed complicated a minute ago is all of a sudden very simple: the view returns
NSNull whenever the layer asks for an action, except when the property change happened inside of an animation block. But don’t just take my word for it. It’s very easy to verify that this is the case. Simply ask the view to provide an action for a layer property that would normally animate, for example, 'position’:
NSLog(@"outside animation block: %@", [myView actionForLayer:myView.layer forKey:@"position"]); [UIView animateWithDuration:0.3 animations:^{ NSLog(@"inside animation block: %@", [myView actionForLayer:myView.layer forKey:@"position"]); }];
Running the above code shows that the view returns the NSNull object outside of the block and returns a CABasicAnimation inside of the block. Elegant, isn’t it? Note that the description of NSNull prints with angle brackets, just like other objects, (“
<null>”) and that nil prints with parenthesis (“
(null)”):
outside animation block: <null> inside animation block: <CABasicAnimation: 0x8c2ff10>
For backing layers, the search for an action doesn’t go further than the first step.3 For standalone layers, there are four more steps that you can read more about in the documentation for
actionForKey: on CALayer.
Learning from UIKit
I’m sure that we can all agree that UIView animation is a really nice API with its concise, declarative style. And the fact that it’s using Core Animation to perform these animations gives us an opportunity to dig deep and see how UIKit uses Core Animation. There may even be some good practices and neat tricks to pick up along the way :)
When a property changes inside of an animation block, the view returns a basic animation to the layer and that animation gets added to the layer via the regular
addAnimation:forKey: method, just like an explicit animation would. Once again, don’t just take my word for it. Let’s verify.
The interaction between views and layers is rather easy to inspect, all thanks to the
+layerClass class method on UIView. It determines what class is used when creating the backing layer of the view. By subclassing UIView and returning a custom layer class, we can override
addAnimation:forKey: in that layer subclass and log to see that it gets called. The only thing we need to remember is to always call super so that we don’t alter the behavior that we are trying to inspect:
@interface DRInspectionLayer : CALayer @end @implementation DRInspectionLayer - (void)addAnimation:(CAAnimation *)anim forKey:(NSString *)key { NSLog(@"adding animation: %@", [anim debugDescription]); [super addAnimation:anim forKey:key]; } @end @interface DRInspectionView : UIView @end @implementation DRInspectionView + (Class)layerClass { return [DRInspectionLayer class]; } @end
By logging the debug description of the animation, we don’t only see that it gets called as expected, but we also see how the animation is constructed:
<CABasicAnimation:0x8c73680; delegate = <UIViewAnimationState: 0x8e91fa0>; fillMode = both; timingFunction = easeInEaseOut; duration = 0.3; fromValue = NSPoint: {5, 5}; keyPath = position >
At the time when the animation is added to the layer, the new value of the property hasn’t yet been changed. The animation is constructed to make good use of this by only specifying an explicit
fromValue (the current value). A quick glance at the CABasicAnimation documentation reminds us what this means for the interpolation of the animation:
fromValueis non-
nil. Interpolates between
fromValueand the current presentation value of the property.
This is how I like to work with explicit animations as well, by changing the property to the new value and then adding the animation object to the layer:
CABasicAnimation *fadeIn = [CABasicAnimation animationWithKeyPath:@"opacity"]; fadeIn.duration = 0.75; fadeIn.fromValue = @0; myLayer.opacity = 1.0; // change the model value ... // ... and add the animation object [myLayer addAnimation:fadeIn forKey:@"fade in slowly"];
I find it to be very clean, and you don’t have to do anything extra when the animation is removed. If the animation starts after a delay, you can use a backward fill mode (or the 'both’ fill mode), just like the animation that UIKit created.
You may have seen the animation delegate and wondered what that class is for. Looking at a class dump, we can see that it’s mostly maintaining state about the animations (duration, delay, repeat count, etc.). We can also see that it pushes and pops to a stack to be able to get the correct state when nesting one animation block inside of another. All of that is mostly an implementation detail and not very interesting unless you are trying to write your own block-based animation API (which is actually quite a fun idea).
However, it is interesting to see that the delegate implements
animationDidStart: and
animationDidStop:finished: and passes that information on to its own delegate. We can log the delegate’s delegate to see that it is of another private class: UIViewAnimationBlockDelegate. Looking at its class dump, we can see that it is a very small class with a single responsibility: responding to the animation delegate callbacks and executing the corresponding blocks. This is something that we can easily add to our own Core Animation code if we prefer blocks over delegate callbacks:
@interface DRAnimationBlockDelegate : NSObject @property (copy) void(^start)(void); @property (copy) void(^stop)(BOOL); +(instancetype)animationDelegateWithBeginning:(void(^)(void))beginning completion:(void(^)(BOOL finished))completion; @end @implementation DRAnimationBlockDelegate + (instancetype)animationDelegateWithBeginning:(void (^)(void))beginning completion:(void (^)(BOOL))completion { DRAnimationBlockDelegate *result = [DRAnimationBlockDelegate new]; result.start = beginning; result.stop = completion; return result; } - (void)animationDidStart:(CAAnimation *)anim { if (self.start) { self.start(); } self.start = nil; } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { if (self.stop) { self.stop(flag); } self.stop = nil; } @end
Depending on personal preference, a block-based callback style, like this, may fit you better than implementing the delegate callbacks in your code:
fadeIn.delegate = [DRAnimationBlockDelegate animationDelegateWithBeginning:^{ NSLog(@"beginning to fade in"); } completion:^(BOOL finished) { NSLog(@"did fade %@", finished ? @"to the end" : @"but was cancelled"); }];
Custom Block-Based Animation APIs
Once you know about the
actionForKey: mechanism, UIView animations are a lot less magical than they might first seem. In fact, there isn’t really anything stopping us from writing our own block-based animation APIs that are tailored to our needs. The one I’m designing will be used to draw attention to a view by animating the change inside of the block with a very aggressive timing curve, and then slowly animate back to the original value. You could say that it makes the view 'pop.’4 Unlike a regular animation block with the
UIViewAnimationOptionAutoreverse option, I’m also changing the model value back to what it was before, since that’s what the animation conceptually does. Using the custom animation API will look like this:
[UIView DR_popAnimationWithDuration:0.7 animations:^{ myView.transform = CGAffineTransformMakeRotation(M_PI_2); }];
When we are done, it is going to look like this (animating the position, size, color, and rotation of four different views):
To start with, we need to get the delegate callback when a layer property changes. Since we can’t know what layers are going to change beforehand, I have chosen to swizzle
actionForLayer:forKey: in a category on UIView:
@implementation UIView (DR_CustomBlockAnimations) + (void)load { SEL originalSelector = @selector(actionForLayer:forKey:); SEL extendedSelector = @selector(DR_actionForLayer:forKey:); Method originalMethod = class_getInstanceMethod(self, originalSelector); Method extendedMethod = class_getInstanceMethod(self, extendedSelector); NSAssert(originalMethod, @"original method should exist"); NSAssert(extendedMethod, @"exchanged method should exist"); if(class_addMethod(self, originalSelector, method_getImplementation(extendedMethod), method_getTypeEncoding(extendedMethod))) { class_replaceMethod(self, extendedSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, extendedMethod); } }
To make sure that we don’t break any other code that relies on the
actionForLayer:forKey: callback, we use a static variable to determine if this is our custom animation context or not. It could have been just a
BOOL for this single use, but a context is more flexible if we would like to write more code like this in the future:
static void *DR_currentAnimationContext = NULL; static void *DR_popAnimationContext = &DR_popAnimationContext; - (id<CAAction>)DR_actionForLayer:(CALayer *)layer forKey:(NSString *)event { if (DR_currentAnimationContext == DR_popAnimationContext) { // our custom code here... } // call the original implementation return [self DR_actionForLayer:layer forKey:event]; // yes, they are swizzled }
In our implementation, we will make sure to set the animation context before executing the animation block, and then restore the context afterward:
+ (void)DR_popAnimationWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations { DR_currentAnimationContext = DR_popAnimationContext; // execute the animations (which will trigger callbacks to the swizzled delegate method) animations(); /* more code to come */ DR_currentAnimationContext = NULL; }
If all we wanted to do was to add a basic animation from the old value to the new, then we could do so directly from within the delegate callback. But since we want more control of the animation, we need to use a keyframe animation. A keyframe animation requires all of the values to be known, and in our case, the new value hasn’t been set so we can’t know it yet.
Interestingly, iOS 7 added a block-based animation API that encounters the same obstacle. Using the same inspection technique as above, we can see how it overcomes that obstacle. For each keyframe, the view returns
nil when the property is changed, but saves the necessary state so that the CAKeyframeAnimation object can be created after all the keyframe blocks have executed.
Inspired by that approach, we can create a small class that stores the information that we need to create the animation: what layer was modified, what key path was changed, and what the old value was:
@interface DRSavedPopAnimationState : NSObject @property (strong) CALayer *layer; @property (copy) NSString *keyPath; @property (strong) id oldValue; + (instancetype)savedStateWithLayer:(CALayer *)layer keyPath:(NSString *)keyPath; @end @implementation DRSavedPopAnimationState + (instancetype)savedStateWithLayer:(CALayer *)layer keyPath:(NSString *)keyPath { DRSavedPopAnimationState *savedState = [DRSavedPopAnimationState new]; savedState.layer = layer; savedState.keyPath = keyPath; savedState.oldValue = [layer valueForKeyPath:keyPath]; return savedState; } @end
Then, in our swizzled delegate callback, we simply store the state for the property that changed in a static mutable array:
if (DR_currentAnimationContext == DR_popAnimationContext) { [[UIView DR_savedPopAnimationStates] addObject:[DRSavedPopAnimationState savedStateWithLayer:layer keyPath:event]]; // no implicit animation (it will be added later) return (id<CAAction>)[NSNull null]; }
After the animation block has executed, all the properties have been changed and their states have been saved. Now, we can enumerate over the saved state and create the keyframe animations:
+ (void)DR_popAnimationWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations { DR_currentAnimationContext = DR_popAnimationContext; // do the animation (which will trigger callbacks to the swizzled delegate method) animations(); [[self DR_savedPopAnimationStates] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { DRSavedPopAnimationState *savedState = (DRSavedPopAnimationState *)obj; CALayer *layer = savedState.layer; NSString *keyPath = savedState.keyPath; id oldValue = savedState.oldValue; id newValue = [layer valueForKeyPath:keyPath]; CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:keyPath]; CGFloat easing = 0.2; CAMediaTimingFunction *easeIn = [CAMediaTimingFunction functionWithControlPoints:1.0 :0.0 :(1.0-easing) :1.0]; CAMediaTimingFunction *easeOut = [CAMediaTimingFunction functionWithControlPoints:easing :0.0 :0.0 :1.0]; anim.duration = duration; anim.keyTimes = @[@0, @(0.35), @1]; anim.values = @[oldValue, newValue, oldValue]; anim.timingFunctions = @[easeIn, easeOut]; // back to old value without an animation [CATransaction begin]; [CATransaction setDisableActions:YES]; [layer setValue:oldValue forKeyPath:keyPath]; [CATransaction commit]; // animate the "pop" [layer addAnimation:anim forKey:keyPath]; }]; // clean up (remove all the stored state) [[self DR_savedPopAnimationStates] removeAllObjects]; DR_currentAnimationContext = nil; }
Note that the old model value was set on the layer so that the model and the presentation match when the animation finishes and is removed.
Creating your own API like this is not going to be a good fit for every case, but if you are doing the same animation in many places throughout your app, it can help clean up your code and reduce duplication. Even if you never end up using it, having walked through it once demystifies the UIView block animation APIs, especially if you are comfortable with Core Animation.
Other Animation Inspiration
I’d like to leave you with a completely different approach to a higher-level animation API: the UIImageView animation. On the surface, it barely resembles a traditional animation API. All that you are doing is specifying an array of images and a duration, and telling the image view to start animating. Behind that abstraction, it results in a discrete keyframe animation of the contents property being added to the image view’s layer:
<CAKeyframeAnimation:0x8e5b020; removedOnCompletion = 0; delegate = <_UIImageViewExtendedStorage: 0x8e49230>; duration = 2.5; repeatCount = 2.14748e+09; calculationMode = discrete; values = ( "<CGImage 0x8d6ce80>", "<CGImage 0x8d6d2d0>", "<CGImage 0x8d5cd30>" ); keyPath = contents >
Animation APIs can come in many different forms, and the same applies to the animation APIs you write yourself.
Almost all layer properties are implicitly animatable. You will see that their brief descriptions in the documentation end with 'animatable.’ This applies to pretty much any numeric property, such as the position, size, color, and opacity, and even for boolean properties like isHidden and doubleSided. Properties that are paths are animatable but do not support implicit animations. ↩
Technically, it is a protocol and could be pretty much anything, but in practice you are talking about an animation of some sort. ↩
At least I have never seen a case where the view returns
nilso that the search for an action continues. ↩
Not to be confused with Facebook’s new framework. ↩ | https://www.objc.io/issues/12-animations/view-layer-synergy/ | CC-MAIN-2017-26 | en | refinedweb |
Syntax bug, in 1.8.5? return not (some expr) <-- syntax error vsreturn (not (some expr)) <-- fine
Discussion in 'Ruby' started by Good Night Moon, client_encoding, stores fine but queries don't return unicodeIrmen de Jong, Dec 1, 2003, in forum: Python
- Replies:
- 0
- Views:
- 351
- Irmen de Jong
- Dec 1, 2003
extend for loop syntax with if expr like listcomp&genexp ?Bengt Richter, Jul 12, 2005, in forum: Python
- Replies:
- 6
- Views:
- 347
- Paul Rubin
- Jul 14, 2005
Using explicit constructors for C++0x "return { expr };"Johannes Schaub (litb), Sep 27, 2010, in forum: C++
- Replies:
- 10
- Views:
- 763
- Francesco S. Carta
- Oct 1, 2010
invalid argument in IE, yet everything fine in FireFox, no syntax error reported, Jul 16, 2005, in forum: Javascript
- Replies:
- 1
- Views:
- 131
- Jc
- Jul 16, 2005
Expr syntax?, with { blah : foo }, Dec 1, 2005, in forum: Javascript
- Replies:
- 4
- Views:
- 146
- Thomas 'PointedEars' Lahn
- Dec 2, 2005 | http://www.thecodingforums.com/threads/syntax-bug-in-1-8-5-return-not-some-expr-syntax-error-vsreturn-not-some-expr-fine.842629/ | CC-MAIN-2015-06 | en | refinedweb |
Skip navigation links
java.lang.Object
oracle.iam.reconciliation.profileconfig.vo.ChilddataType
public class ChilddataType
Java class for childdata-type complex type.
The following schema fragment specifies the expected content contained within this class.
<complexType name="childdata_type"> <complexContent> <restriction base="{}anyType"> <sequence> <element name="childform" type="{}form-recondetails-type" maxOccurs="unbounded" minOccurs="0"/> </sequence> </restriction> </complexContent> </complexType>
public ChilddataType()
public java.util.List getChildform()
This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is not a
set method for the childform property.
For example, to add a new item, do as follows:
getChildform().add(newItem);
Objects of the following type(s) are allowed in the list
FormRecondetailsType
Skip navigation links | http://docs.oracle.com/cd/E28280_01/apirefs.1111/e17334/oracle/iam/reconciliation/profileconfig/vo/ChilddataType.html | CC-MAIN-2015-06 | en | refinedweb |
15 November 2007 19:32 [Source: ICIS news]
TORONTO (ICIS news)--Foster Wheeler has been retained to work on proposed expansion projects at the Kern refinery in Bakersfield, California, the US petrochemicals engineering firm said on Thursday.
?xml:namespace>
Foster was hired by NTR Acquisition, which earlier this month announced plans to acquire Kern.
NTR plans to convert the facility into a world-class heavy crude oil refinery, expand conversion capacity and improve product yield.
Foster did not disclose specific capacity or financial details.
According to its website, the Kern refinery currently makes diesel, gasoline, jet fuel, fuel oil and aliphatic solvents, mainly | http://www.icis.com/Articles/2007/11/15/9079184/foster-wins-work-for-us-kern-refinery-expansion.html | CC-MAIN-2015-06 | en | refinedweb |
21 March 2008 17:03 [Source: ICIS news]
WASHINGTON (?xml:namespace>
Kevin Swift, chief economist for the American Chemistry Council (ACC), said that the latest hard economic data “all point to recession”.
“Housing activity continues to fall and will likely fall further as builders need to reduce inventories,” Swift said in his weekly review of economic trends.
“Industrial production fell during February and the regional survey points to continued weakness in March,” he noted.
“All four of the measures used by the NBER Data Committee to determine business cycle peaks and troughs are in decline,” he added, referring to the National Bureau of Economic Research, the widely respected non-profit business and commerce analytical group.
The four key measures cited by the bureau are personal income, which peaked in September; employment, down since December; industrial production, in decline since January; and manufacturing and wholesale-retail sales, down from a peak in November.
The decline in those four measures “is consistent with a recession”, Swift said.
In addition, he noted, the Conference Board’s index of leading economic indicators has declined for the fifth consecutive month, “which also is consistent with past recessions”.
“Inflation at the producer level remains elevated and underlying trends have intensified as a result of the weakness in the dollar and the commodities boom,” Swift said. “This suggests adverse implications for corporate profit margins and consumer purchasing power.”
In the chemicals industry, Swift said that overall production slipped in February, and with the exception of pharmaceuticals, the sector’s output has been soft for several months.
However, Swift noted that often by the time a US economic recession is officially recognised by NBER and other conservative analysts, the recession has probably been in play for some time and may already be ending.
For example, he cited the 13-week moving average of railcar loadings of chemical products, “which indicates recent improving activity”. The 13-week railcar loadings for chemicals, regarded as a more reliable indicator than the weekly loadings numbers, is up 3.4% over the same 13-week period | http://www.icis.com/Articles/2008/03/21/9110295/us-in-recession-top-us-chemical-economist.html | CC-MAIN-2015-06 | en | refinedweb |
Copyright © 1998 material in this draft was previously part of the XSL Working Draft. intended to be "feature complete". The Working Group plans to use future drafts to stabilize the current functionality; it does not intend to add any new functionality in version 1.0.
The XSL WG and the XML Linking WG have agreed to unify XSLT expressions and XPointers [XPointer]. A common core semantic model for querying has been agreed upon, and this draft follows this model (see [6.1 Location Paths]). However, further changes particularily in the syntax will probably be necessary.
This is part of the Style activity. [7.4 Conflict Resolution for Template Rules]. includes an expression language (see [6 Expressions and Patterns]) that is used for selecting elements for processing, for conditional processing and for generating text. The expression language is not a complete programming language. XSLT provides an extension mechanism to allow access from the expression language to a complete programming language such as ECMAScript or Java. XSLT does not require support for any programming language. Therefore XSLT stylesheets that must be portable across all XSLT implementations cannot depend on this extension mechanism.
A stylesheet is represented by an
xsl:stylesheet
element in an XML document.
xsl:transform is allowed as
a synonym for
xsl:stylesheet.
XSLT processors must use the XML namespaces mechanism [XML Names] for both source documents and stylesheets. All XSLT
defined elements, that is those specified in this document with a
prefix of
xsl:, will only be recognized by the XSLT
processor if they belong to a namespace with the URI; XSLT defined
elements are recognized only in the stylesheet not in the source
document.
The
xsl:stylesheet element may contain the following types
of elements:
xsl:import
xsl:include
xsl:strip-space
xsl:preserve-space
xsl:key
xsl:functions
xsl:locale
xsl:attribute-set
xsl:variable
xsl:param-variable
xsl:template
This example shows the structure of a stylesheet. Ellipses
(
...) indicate where attribute values or content have
been omitted. Although this example shows one of each type of allowed
element, stylesheets may contain zero or more of each of these
elements.
<?xml version="1.0"?> <xsl:stylesheet xmlns: <xsl:import <xsl:include <xsl:strip-space <xsl:preserve-space <xsl:key <xsl:functions ... </xsl:functions> <xsl:locale ... </xsl:locale> <xsl:attribute-set ... </xsl:attribute-set> <xsl:variable...</xsl:variable> <xsl:param-variable...</xsl:param-variable> .
An XSLT processor must treat any namespace whose URI starts with
the in the same way as
the XSLT 1.0 namespace
() except that it must
recover from errors as follows:
Unrecognized attributes on elements in the XSLT namespace must be ignored
Unrecognized top-level XSLT elements must be ignored along with their content
Error reporting for unrecognized XSLT elements in templates must be lazy: in other words it's not an error to have an unrecognized XSLT element unless the element is actually instantiated
Similarly error reporting for bad expression syntax must be lazy: it's not an error to have bad expression syntax in an attribute on some element unless the element containing the bad syntax is instantiated
Ed. Note: What happens with stylesheets that mix XSLT namespaces with different versions?
Thus any XSLT 1.0 processor must be able to process the following stylesheet without error:
<xsl:stylesheet xmlns: <xsl:template >
XSLT operates on an XML document, whether a stylesheet or a source document, as a tree. Any two stylesheets or source documents that have the same tree will be processed the same by XSLT. The XML document resulting from the tree construction process is also a tree. This section describes how XSLT models an XML document as a tree. This model is conceptual only and does not mandate any particular implementation.
XML documents operated on by XSLT must conform to the XML namespaces specification [XML Names].
The tree contains nodes. There are seven kinds of node:
root nodes
element nodes
text nodes
attribute nodes
namespace nodes
processing instruction nodes
comment nodes
Neither processing instruction nodes nor comment nodes are included in the tree for the stylesheet.
For every type of node there is a way of determining a string value for a node of that type. For some types of node, the value is part of the node; for other types of node, the value is computed from the value of descendant nodes.
Issue (data-entity): Should XSLT provide support for external data entities and notations?
Issue (entity-ref): Should XSLT provide support for entity references?
Issue (dtd): Should XSLT provide support for DTDs in the data model?
The root node is the root of the tree. It does not occur anywhere else in the tree. It has a single child which is the element node for the document element of the document.
The value of the root node is the value of the document element.
There is an element node for every element in the document. An element has an expanded name consisting of a local name and a possibly null URI reference (see [XML Names]); the URI reference will be null if the element type name has no prefix and there is no default namespace in scope. A relative URI reference should be resolved into an absolute URI during namespace processing.
The children of an element node are the element nodes, comment nodes, processing instruction nodes and text nodes for its content. Entity references to both internal and external entities are expanded. Character references are resolved.
The descendants of an element node are the children of the element node and the descendants of the children that are element nodes.
The value of an element node is the string that results from concatenating all characters that are descendants of the element node in the order in which they occur in the document.
The set of all element nodes in a document can be ordered according to the order of the start-tags of the elements in the document; this is known as document order.
Ed. Note: Need a definition of document order that handles arbitrary node types, including attributes.
An element object may have a unique identifier (ID). This is the
value of the attribute which must be treated as not having a
unique ID.
NOTE: If a document does not have a DTD, then no element in the document will have a unique ID..
Each element node has an associated set of attribute nodes..
An attribute node has an expanded name and has a string value. The expanded name consists of a local name and a possibly null URI (see [XML Names]); the URI will be null if the specified attribute name did not have a prefix. The value is the normalized value as specified by the XML Recommendation [XML]. An attribute whose normalized value is a zero-length string is not treated specially: it results in an attribute node whose value is a zero-length string.
There are no attribute nodes for attributes that declare namespaces (see [XML Names]).
Issue (external-dtd): Should we specify something about how we expect XSLT processors to process external DTDs and parameter entities? For example, what happens if an attribute default is declared in an external DTD?
Each element has an associated set of namespace nodes, one for each namespace prefix that is in scope for the element and one for the default namespace if one is in scope for the element. This means that an element will have a namespace node:
for every attribute on the element whose name starts with
xmlns:;
for every attribute on an ancestor element whose name starts
xmlns: unless the element itself or a nearer ancestor
redeclares the prefix;
for an
xmlns attribute, unless its value is the empty
string.
NOTE: An attribute
xmlns="""undeclares" the default namespace (see [XML Names]).
A namespace node has a name which is a string giving the prefix. This is empty if the namespace node is for the default namespace. A namespace node also has a value which is the namespace URI. If the namespace declaration specifies a relative URI, then the resolved absolute URI is used as the value.
When writing an element node in the result tree out as XML, an XSLT processor must add sufficient namespace-declaring attributes to the start-tag to ensure that if a tree were recreated from the XML, then the set of namespace nodes on the element node in the recreated tree would be equal to or a superset of the set of namespace nodes of the element node in the result tree.
NOTE: The semantics of a document type may treat parts of attribute values or data content as namespace prefixes. The presence of namespace nodes ensures that the semantics can be preserved when the tree is written out as XML.
There is a processing instruction node for every processing instruction.
Ed. Note: What about processing instructions in the internal subset or elsewhere in the DTD?
A processing instruction has a name. This is a string equal to
the processing instruction's target. It also has a value. This is a
string equal to the part of the processing instruction following the
target and any whitespace. It does not include the terminating
?>.
There is a comment node for every comment.
Ed. Note: What about comments in the internal subset or elsewhere in the DTD?
A comment has a value. This is a string equal to the text of the
comment not including the opening
<!-- or the closing
-->.
Character data is grouped into text nodes. As much character data as possible is grouped into each text node: a text node never has an immediately following or preceding sibling that is a text node. The value of a text node is the character data.
Each character within a CDATA section is treated as character data.
Thus
<![CDATA[<]]> in the source document will
treated the same as
<. Both will result in a
single
< character in a text node in the tree.
NOTE: When a text node that contains a
<character is written out as XML, the
<character must be escaped by, for example, using
<, or including it in a CDATA section.
Characters inside comments or processing instructions are not character data. Line-endings in external entities are normalized to #xA as specified in the XML Recommendation [XML].
After the tree.
Ed. Note: Clarify how these declarations interact with each other and with xsl:import. not specified, then the
result tree must be output as XML. If the
result-ns
attribute is specified, all elements in the result tree must belong to
the namespace identified by this prefix (the result
namespace).
When an XSLT processor outputs the result tree as a sequence of bytes that represents the result tree in XML, it must do so in such a way that the sequence of bytes is a well-formed XML document conforming to the XML Namespaces Recommendation [XML Names] and that if a new tree was constructed from the sequence of bytes as specified in [4 Data Model],>
The
xsl:stylesheet element can include.
Ed. Note: The XSL WG and the XML Linking WG have agreed to unify XSLT expressions and XPointers. A common core semantic model for querying has been agreed upon, and this draft follows this model. However, further changes particularily in the syntax will probably be necessary.
Expressions are used in XSLT for a variety of purposes including:
An expression is evaluated to yield an object which has one of the following types:
Expression evaluation occurs with respect to a context, which consists of:
The context node is always a member of the context node list. The variable bindings consist of a mapping from variable names to variable values. The value of a variable is an object which can have any of the types which are possible for the value of an expression.
The variable bindings, node key function, extension functions and namespace declarations used to evaluate a subexpression are always the same as those used to evaluate the containing expression. The context node and context node list used to evaluate a subexpression is sometimes different from the context node and context node list used to evaluate the containing expression. When the evaluation of a kind of expression is described, it will always be explicitly stated if the context node and node list change for the evaluation of subexpressions; if nothing is said about the context node and context node list, they remain unchanged for the evaluation of subexpressions of that kind of expression.
The node key function takes a pair of strings (a key name and a key value) and a document and returns a set of nodes (the nodes in the document that have a key with the specified name and value).
In XSLT, expressions occur in attribute values. The grammar
specified in this section applies to the attribute value after XML 1.0
normalization. So, for example, if the grammar uses the character
< this must not appear in the XML source for the
stylesheet as
< but must be quoted according to XML
1.0 rules by, for example, entering it as
<.
A top-level expression (an expression not occurring within an expression) gets its context as follows:
the context node comes from the current node
the context node list comes from the current node list
the variable bindings are the bindings in scope on the element which has the attribute in which the expression occurs (see [13 Variables and Parameters])
the node key function is specified by top-level
xsl:key elements (see [6.4.1 Declaring Keys])
the implementations of extension functions are provided by
top-level
xsl:functions elements (see [6.4.2 Declaring Extension Functions]), and may also be provided externally to the
stylesheet by means not specified by XSLT
the set of namespace declarations are those in scope on the
element which has the attribute in which the expression occurs; the default
namespace (as declared by
xmlns) is not part of this
set which are used to filter lists of nodes.
Certain contexts in XSLT make use of a pattern..
In the following grammar, the nonterminals QName and NCName are defined in [XML Names], and S is defined in [XML].
Expressions (including patterns and location paths) are parsed by first dividing up the character string to be parsed into tokens and then parsing the resulting sequence of tokens. Whitespace can be freely used between tokens. The tokenization process is described in [6.2.9 Lexical Structure]. [6.1.4 Abbreviated Syntax]).
Here are some examples of location paths using the unabbreviated syntax:
from-children(para) selects the
para element children of the context node
from-children(*) selects all element
children of the context node
from-children(text()) selects all text
node children of the context node
from-children(node()) selects all the
children of the context node, whatever their node type
from-attributes(name) selects the
name attribute of the context node
from-attributes(*) selects all the
attributes of the context node
from-descendants(para) selects the
para element descendants of the context node
from-ancestors(div) selects all
div
ancestors of the context node
from-ancestors-or-self(div) selects the
div ancestors of the context node and, if the context node is a
div element, the context node as well
from-descendants-or-self(para) selects the
para element descendants of the context node and, if the context node is
a
para element, the context node as well
from-self(para) selects the context node if it is a
para element, and otherwise selects nothing
from-children(chapter)/from-descendants(para)
selects the
para element descendants of the
chapter element children of the context node
from-children(*)/from-children(para) selects
all
para grandchildren of the context node
/ selects the document root (which is
always the parent of the document element)
/from-descendants(para) selects all the
para elements in the same document as the context node
/from-descendants(olist)/from-children(item)
selects all the
item elements in the same document as the
context node that have an
olist parent
from-children(para[position()=1]) selects the first
para child of the context node
from-children(para[position()=last()]) selects the last
para child of the context node
from-children(para[position()=last()-1]) selects
the last but one
para child of the context node
from-children(para[position()>1]) selects all
the
para children of the context node other than the
first
para child of the context node
from-following-siblings(chapter[position()=1])
selects the next
chapter sibling of the context node
from-preceding-siblings(chapter[position()=1])
selects the previous
chapter sibling of the
context node
/from-descendants(figure[position()=42]) selects
the forty-second
figure element in the
document
/from-children(doc)/from-children(chapter[position()=5])/from-children(section[position()=2])
selects the second
section of the fifth
chapter of the
doc document element
from-children(para[from-attributes(type)="warning"])
selects all
para children of the context node that have a
type attribute with value
warning
from-children(para[from-attributes(type)="warning"][position()=5])
selects the fifth
para child of the context node that has a
type attribute with value
warning
from-children(para[position()=5][from-attributes(type)="warning"])
selects the fifth
para child of the context node if that child has
a
type attribute with value
warning
from-children(chapter[from-children(title)="Introduction"])
selects the
chapter children of the context node whose first
title child has value equal to
Introduction
from-children(chapter[from-children(title)])
selects the
chapter children of the context node that have one
or more
title children
from-children(chapter[from-children(title[from-self(*)="Introduction"])])
selects the
chapter children of the context node any of whose
title children has value equal to
Introduction
from-children(*[from-self(chapter) or
from-self(appendix)]) selects the
chapter and
appendix children of the context node
from-children(*[from-self(chapter) or
from-self(appendix)][position()=last()]) selects the last
chapter or
appendix child of the
context node
There are two kinds of location path: relative location paths and absolute
the second step are unioned together. The set of nodes identified by
the composition of the steps is this union. For example,
from-children(div)/from-children(para) selects the
para element children of the
div element
children of the context node, or, in other words, the
para element grandchildren that have
div
parents.
An absolute location path consists of
/ optionally
followed by a relative location path. A
/ by itself
selects the root node of the document containing the context node. If
it is followed by a relative location path, then the location path
selects the set of nodes that would be selected by the relative
location path relative to the root node of the document containing the
context node.
A location step consists of
an axis identifier;
a node test;
zero or more predicates.
The axis identifier selects an initial list of nodes relative to the context node. The initial list of nodes is filtered first by the node test; the result of filtering by the node test is then filtered by the first predicate; the result of that is then filtered by the next predicate and so on. The node test selects nodes from the initial list based on the node type and node name. Each predicate selects nodes that satisfy a condition specified by an arbitrary expression. The result of the location step is the set of nodes that are members of the list that results from filtering the initial list by the node test and all the predicates. Note that although a location step selects a set of nodes, an axis selects a list of nodes and the predicates operate on a list of nodes.
The axis identifier is followed by the node test and predicates in
parentheses. For example,
from-descendants(para) selects the
descendants of the context node that are
para elements:
from-descendants specifies the axis, and
para
is a test that is true for elements with name
para. Each
predicate is specified as an expression in square brackets.
An axis identifies a list of nodes based on the kind of tree relationship that the nodes have to the context node. For example, the children of the context node are one axis, the ancestors of the context node are another axis. Note that an axis identifies an ordered list, not a set. The order of nodes in an axis is in the direction away from the context node.
The following axes are defined:
the
children axis contains the children of the
context node in document order
the
descendants axis contains the descendants of
the context node in document order
the
parent axis contains the parent of the
context node, if there is one
Ed. Note: Is the parent of an attribute node the element that the attribute is on?
the
following-siblings axis contains the
following siblings of the context node in document order
the
preceding-siblings axis contains the
preceding siblings of the context node in reverse document order; the first
preceding sibling is first on the axis; the sibling preceding that
node is the second on the axis and so on.
the
following axis contains all nodes in the same
document as the context node that are after the context node in document order;
the nodes are ordered in document order
Issue (following-axis): Is the
followingaxis needed?
Issue (following-start): Should the
followingaxis include the descendants of the context node?
the
preceding axis contains all nodes in the same
document as the context node that are before the context node in document order;
the nodes are ordered in reverse document order
Issue (preceding-axis): Is the
precedingaxis needed?
the
ancestors axis contains the ancestors of the
context node; the nodes are ordered in reverse document order; thus the
parent is the first node on the axis, and the parent's parent is the
second node on the axis
the
attributes axis contains the attributes of
the context node; the order of nodes on this axis is
implementation-defined
the
self axis contains just the context node
itself
the
ancestors-or-self axis contains the context node
and ancestors of the context node in reverse document order; thus the context node
is the first node on the axis, and the context node's parent the
second
the
descendants-or-self axis contains the context node
and the descendants of the context node in document order; thus the context node
is the first node on the axis, and the first child of the context node is
the second node on the axis
In an axis identifier the name of the axis is preceded by
from- to distinguish it from a function name.
A node test that is a QName tests whether the node is an
element or attribute with the specified name. For example,
from-attributes(href) selects the
href
attribute of the context node; if the context node has no
href
attribute, it will select an empty set of nodes.
A QName in the node test
is expanded into a local name and a possibly null URI. This expansion
is done using the namespace declarations from the expression context.
This is the same way expansion is done for element type names in start
and end-tags except that the default namespace declared with
xmlns is not used: if the QName does not have a prefix, then
the URI is null (this is the same way attribute names are expanded).
The expanded names are then compared for equality. Two expanded names
are equal if they have the same local part, and either both have no
URI or both have the same URI.
A node test
* is true for any element or
attribute node. For example,
from-children(*) will
select all element children of the context node, and
from-attributes(*) will select all attributes of the
context node.
A node test can have the form NCName
:*. In this case the
prefix is expanded in the same way as with a QName using the context namespace
declarations. The node test will be true for an element or attribute
whose expanded name has the URI to which the prefix expands, whatever
the local part of the name.
The node test
text() is true for any text node. For
example
from-children(text()) will select the text node
children of the context node. Similarly, the node test
comment() is true for any comment node, and the node test
pi() is true for any processing instruction. The
pi() test may have an argument that is Literal; in this case it is true for any
processing instruction that has a name equal to the value of the Literal.
A node test
node() is true for any node.
A predicate filters a list of nodes to produce a new list of nodes. For each node in the list to be filtered, the PredicateExpr is evaluated with that node as the context node and with the complete list of nodes to be filtered as the context node list; if PredicateExpr evaluates to true for that node, the node is included in the new list; otherwise it is not included.
A PredicateExpr is evaluated by
evaluating the Expr and converting the result
to a boolean. If the result is a number, the result will be converted
to true if the number is equal to the position of the context node in
the context node list and will be converted to false otherwise; if the
result is not a number, then the result will be converted as if by a
call to the
boolean() function. Thus a location path
para[3] is equivalent to
para[position()=3].
Here are some examples of location paths using whose first
title child has value equal to
Introduction
chapter[title] selects the
chapter
children of the context node that have one or more
title
children
chapter[title[.="Introduction"]] selects the
chapter children of the context node any of whose
title children has value equal to
Introduction
employee[@secretary and @assistant] selects all
the
employee children of the context node that have both a
secretary attribute and an
assistant
attribute
The most important abbreviation is that when the axis is the
children axis, the
from-children and surrounding
parentheses can be omitted. In effect the
children axis
is the default axis. For example, a location path
div/para
is short for
from-children(div)/from-children(para).
There's also an abbreviation for the attributes axis. Instead of
using
from-attributes and parentheses around the node
test, the node test can be preceded by
@ to indicate the
attributes axis. For example, a location path
para[@type="warning"] is short for
from-children(para[from-attributes(type)="warning"]) and
so selects
para children with a
type
attribute with value equal to
warning.
// is short for
/from-descendants-or-self(node())/. For example,
//para is short for
/from-descendants-or-self(node())/from-children(para) and so
will select any
para element in the document (even a
para element that is a document element will be selected by
//para since the document element node is a child of the
root node);
div//para is short for
div/from-descendants-or-self(node())/from-children(para) and
so will select all
para descendants of
div
children.
A location step of
. is short for
from-self(node()). This is particularly useful in
conjunction with
//. For example, the location path
.//para is short for
from-self(node())/from-descendants-or-self(node())/from-children(para)
and so will select all
para descendant elements of the
context node.
Similarly a location step of
.. is short for
from-parent(node()). For example,
../title
is short for
from-parent(node())/from-children(title) and
so will select the
title children of the parent of the
context node.
A VariableReference evaluates to the value to which the variable name is bound in the set of variable bindings in the context.
Parentheses may be used for grouping.
A location path can be used as an expression. The expression returns the set of nodes selected by the path.
The
| operator computes the union of its operands
which must be node-sets.
Square brackets are used to filter expressions in the same way that they are used in location paths. It is an error if the expression to be filtered does not evaluate to a node-set. The context node list used for evaluating the expression in square brackets is the node-set to be filtered listed in document order.
The
/ operator and
// operators combine
an arbitrary expression and a relative location path. It is an error
if the expression does not evaluate to a node-set. The
/
operator does composition in the same way as when
/ is
used in a location path. As in location paths,
// is
short for
/from-descendants-or-self(node())/.
There are no types of objects that can be converted to node-sets. It is an error if evaluating a NodeSetExpr yields an object that is not a node-set.
The
last() function returns the number of nodes in
the context node list. The
position() function returns
the position of the context node in the context node list. The first
position is 1, and so the last position will be equal to
The
count() function returns the number of nodes in the
argument node-set.
The
id() and
idref() functions select
elements by their unique ID (see [4.2.1 Unique IDs]).
id() converts its argument to a string and returns a
node-set containing the element in the same document as the context
node with unique ID equal to that string, if there is such an element,
and otherwise returns an empty node-set.
idref()
requires that its argument be a node-set; for each node in the
node-set, the value is split into a whitespace-separated list of
tokens;
idref() returns a node-set containing the
elements in the same document as the context node that have a unique
ID equal to any of the tokens in the value of any of the nodes in the
node-set. For example,
id("foo") selects the element with unique ID
foo
id("foo")/from-children(para[position()=5]) selects
the fifth
para child of the element with unique ID
foo
Ed. Note: No way to get an ID in another document. Can workaround with xsl:for-each. Maybe add optional second argument which gives document.
Issue (id-inverse): Should there be a way to get back from an element to the elements that reference it (eg by IDREF attributes)?
The
key() and
keyref() functions select a
set of nodes using the node key function in the expression evaluation
context. Both functions have a string as the first argument that
specifies the name of the key and have an expression as the second
argument.
key() has a second argument that is a string
and returns a node-set containing the nodes in the same document as
the context node that have a value for the named key equal to this
string.
keyref() has a second argument that is a node-set
and returns a node-set containing the nodes in the same document as
the context node that have a value for the named key equal to the
value of any of the nodes in the argument node-set. See [6.4.1 Declaring Keys] for how to declare a key.
The
doc() and
docref() functions allow
access to XML documents other than the initial source document. They
both rely on the ability to treat a string as a URI reference that is
mapped to a node-set; this mapping always takes places relative to a
node that can be used to resolve a relative URI into an absolute URI.
If the URI reference does not contain a fragment identifier, then it
will be mapped to a node-set containing the root node in a tree
representing the XML document whose document entity is the resource
identified by the URI. If the URI reference contains a fragment
identifier, then it will first map the URI to a tree representing the
XML document whose document entity is the resource identified by the
URI and then use the fragment identifier to select a set of nodes in
that tree; the semantics of the fragment identifier is dependant on
media type of the result of retrieving the URI.
doc()
takes a string argument which it treats as a URI reference which is
mapped to a node-set relative to the element in the stylesheet
containing the expression. Note that a zero-length URI reference is a
reference to the document relative to which the URI reference is being
resolved; thus
doc("") refers to the root node of the
stylesheet; the tree representation of the stylesheet is exactly the
same as if the XML document containing the stylesheet was the initial
source document.
docref() takes a node-set argument; for
each node in the node-set,
docref() treats the value of
the node as a URI reference that is mapped to a node-set relative to
that same node;
docref() returns the union of the
resulting node-sets.
Ed. Note: What if the fragment identifier identifies something that isn't a set of nodes (eg a span or a substring within a text node)? What are the allowed media types for the returned data? What is document order for node sets including nodes from multiple documents?
The
local-part() function returns a string containing
the local part of the name of the first node in the argument
node-set. If the node-set is empty or the first node has no name, an
empty string is returned. If the argument is omitted it defaults to
the context node.
The
namespace() function returns a string containing
namespace of the name of the first node in the argument node-set. If
the node-set is empty or the first node has no name or the name has no
namespace, an empty string is returned. If the argument is omitted it
defaults to the context node.
The
qname() function returns a string containing a
QName representing the name of
the first node in the argument. The QName must represent the name with
respect to the namespace declarations in effect on the node whose name
is being represented. Typically this will be the form in which the
name occurred in the XML source. This need not be the case if there
are namespace declarations in effect on the node that associate
multiple prefixes with the same namespace. However, an implementation
may include information about the original prefix in its
representation of nodes; in this case an implementation can ensure
that the returned string is always the same as the QName used in the XML source. If the
argument it omitted it defaults to the context node.
The
generate-id() function returns a string that can
be used as a unique identifier for the first node in the argument
node-set. The unique identifier must consist of ASCII alphanumeric
characters and must start with an alphabetic character. An
implementation is free to generate an identifier in any convenient way
provided that it always generates the same identifier for the same
node and that different identifiers are always generated from
different nodes. An implementation is under no obligation to generate
the same identifiers each time a a document is transformed. If the
argument node-set is empty, the empty string is returned. If the
argument is omitted, it defaults to the context node.
An object of type boolean can have two values, true and false.
The
boolean() function converts its argument to a
boolean as follows:
a number is true if and only if it is neither positive or negative zero nor NaN
a node-list is true if and only if it is non-empty
a result fragment is true if and only if it is non-empty
a string is true if and only if its length is non-zero
If the argument is omitted, it defaults to the context node.
A BooleanExpr is evaluated by
converting the result of evaluating the Expr to
a boolean as if by a call to the
boolean() function.
An
= expression is evaluated as follows. If at least
one operand is a boolean, then each operand is converted to a boolean
as if by applying the
boolean() function and the operands
are compared as booleans. Otherwise, if at least one operand is a
number, then each operand is converted to a number as if by applying
the
number() function and the operands are compared as
numbers; positive and negative zero compare equal. Otherwise both
operands are converted to strings as if by applying the
string() function and the operands are compared as
strings; two strings are equal if they contain the same sequence of
UCS characters.
A
<,
>,
<= or
>= expression is evaluated by first converting each
operand to a number as if by a call to the
number()
function and then comparing the two numbers.
Issue (node-set-comparision): What should the semantics of comparison operators be when either or both of the operands are node-sets? Should there be an "any" or "all" semantic?
An
or expression is evaluated by evaluating each
operand and converting its value to a boolean. The result is true if
either value is true and false otherwise.
An
and expression is evaluated by evaluating each
operand and converting its value to a boolean. The result is true if
both values are true and false otherwise.
The
not() function returns true if its argument is
false, and false otherwise.
The
true() function returns true.
The
false() function returns false.
The
lang() function returns true or false depending on
whether the language of the context node as specified by
xml:lang attributes is the same as or,. For example,
lang("en") would return true
if the context node is any of these five elements:
<para xml: <div xml:<para/></div> <para xml: <para xml:
A number represents a floating point number. A number can have any double-precision 64-bit format IEEE 754 value. These include a special "Not-a-Number" (NaN) value, positive and negative infinity, and positive and negative zero.
A NumberExpr is evaluated by
converting the result of evaluating the Expr to
a number as if by a call to the
number() function.
The
number() function converts its argument to a
number as follows:
if a string parses as Number possibly preceded or followed by whitespace, then it is converted to that number; otherwise it is converted to the number 0
Ed. Note: Would NaN be better than 0 here?
boolean true is converted to 1; boolean false is converted to 0
a node-set is first converted to a string as if by a call to the
string() function and then converted in the same way as a
string argument
Ed. Note: Should we take advantage of xml:lang here?
a result tree fragment is first converted to a string as if
by a call to the
string() function and then converted in
the same way as a string argument
If the argument is omitted, it defaults to the context node.
The
div operator performs floating point division
according to IEEE 754.
The
quo operator performs a floating point division
and then truncates the result to an integer. For example,
5 quo 2 returns
2
5 quo -2 returns
-2
-5 quo 2 returns
-2
-5 quo -2 returns
2
The
mod operator returns the remainder from the
quo operation. For example,
5 mod 2 returns
1
5 mod -2 returns
1
-5 mod 2 returns
-1
-5 mod -2 returns
-1
NOTE: This is the same as the
%operator in Java and ECMAScript.
NOTE: This is not the same as the IEEE remainder operation which returns the remainder from a rounding division.
The
sum() function returns the sum of the values of
the nodes in the argument node-set. even is returned.
A string consists of a sequence of UCS characters.
A StringExpr is evaluated by
converting the result of evaluating the Expr to
a string as if by a call to the
string() function.
The
string() function converts an object to a string
as follows:
A node-set is converted to a string by returning the value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
A result tree fragment is converted to a string by treating it as a single document fragment node that contains the nodes of the fragment, and then converting that document fragment node to a string in the same was as if the document fragment node were a source tree node.
A number is converted to a string by returning a string in
the form of a Number, preceded by a
- character if the number is negative.
Ed. Note: What about positive zero, negative zero, NaN and infinities?
The boolean false value is converted to the string
false. The boolean true value is converted to the
string
true.
If the argument is omitted, it defaults to the context node..
Ed. Note: Should the first argument of the above functions default to the value of the current node?
The
normalize() function returns the argument string
with white space normalized by stripping leading and trailing
whitespace and replacing sequences of whitespace characters by a
single space. Whitespace characters are the same allowed by the S production in XML. If the argument is
omitted, it defaults to the context node converted to a string, in
other words the value of the context node.
The
translate() function returns the first argument
string with occurrences of characters in the second argument string
replaced by the corresponding characters from the third argument
string. For example,
translate("bar","abc","ABC") returns
the string
BAr.. See [6.4.3 Declaring Locales]
for how to declare a locale.
Issue (regex): Should XSLT support regular expressions for matching against any or all of pcdata content, attribute values, attribute names, element type names?
Issue (equality-case): Do we need to be able to do comparisons in a case insensitive way?
Issue (equality-normalize): Do we need to normalize strings before comparison? Does the stylesheet need to specify what kinds of normalization are required (eg compatibility character normalization)?
Issue (resolve-expr): Do we need a
resolve(NodeSetExpr)string expression that treats the characters as a relative URI and turns it into an absolute URI using the base URI of the addressed node?
Ed. Note: Add explanation of what a result tree fragment is.
The only operations that can be performed on a result tree fragment
are to convert it to a string or a boolean. In particular, it is not
permitted to use the
/,
//, and
[] on result tree fragments.
Expressions can only return values of type result tree fragment by referencing variables of type result tree fragment or calling extension functions that return a result tree fragment.
The CName is expanded to a name using the
namespace declarations from the evaluation context. The XSLT
processor attempts to locate an implementation of the extension
function with the specified name that it can use. The implementation
may be provided by an
xsl:functions element (see [6.4.2 Declaring Extension Functions]) or the XSLT processor may be able to locate an
implementation by other means not specified by XSLT. If the XSLT
processor cannot locate such a function, then evaluating the
expression is an error. Otherwise the implementation is called
passing it the values of the expressions and the value returned by the
function is the value of the expression. The
function-available() function can be used to test whether
an implementation of a particular function is available (see [6.2.8 System Functions]). A XSLT processor is allowed always to give an error
when evaluating an ExtensionFunctionCall (with such
an XSLT processor the
function-available() function would
always return false). Therefore if an XSLT stylesheet includes an ExtensionFunctionCall and does not
use the
function-available() function to test for and
handle the possibility that an implementation of the function is not
available, then it may not be portable across all XSLT
implementations.
For both these functions, the StringExpr
The
function-available() function returns true if an
implementation of the named extension function is available. For
example:
<xsl:if <xsl:value-of </xsl:if>
When tokenizing, the longest possible token is always returned.
For readability, whitespace may be used in patterns even though not explicitly allowed by the grammar: ExprWhitespace may be freely added within patterns before or after any ExprToken.
A NodeType, FunctionName, CName
or AxisIdentifier token is recognized
only when the following token is
(. An OperatorName token or MultiplyOperator token is recognized as
such only when there is a preceding token and the preceding token is
not one of
@,
(,
[,
, or an Operator.
This section explains what expressions are allowed as patterns and what the semantics of matching a pattern are.
pi() matches any processing instruction
id("W11") matches the element with unique ID
W11
para[1] matches any
para element
that is the first
para child element of its
parent
*[position()=1 and use either
AxisIdentifiers or
. or
... Location path patterns can also start with an
id() or
key() function call with a literal
argument (see [6.2.2 Node-sets]). element
being matched as the context node and the siblings of the elements.
Ed. Note: Need to revise above paragraph if we decide not to call the element to which an attribute is attached the parent of the attribute.
The
xsl:key element is used to declare keys. The
name specifies the name of the key. The
match attribute is a Pattern; a
xsl:key element gives information about the keys of any
node that match the pattern specified in the match attribute. The
use attribute is a NodeSetExpr, which specifies the set of
values for which the node has a key of the specified name. A node
x has a key with name y and value
z if and only if there is NodeSetExpr specified in the
use attribute of the
xsl:key element with
x as the current node and with a node list containing
just x as the current node list.
Note that the NodeSetExpr may return
a node-set with more than one node; all of the returned nodes serve as
a key value. Note also that there may be more than one
xsl:key element that matches a given node; all of the
matching
xsl:key elements are used.
Ed. Note: Add some examples.
Implementations of the extension functions in a namespace can be
provided using the
xsl:functions element. The required
ns attribute specifies the namespace for which an
implementation is being provided. The value of the
ns
attribute is a namespace prefix which is expanded to a namespace URI
using the namespace declarations in effect on the
xsl:functions element.
The implementation may be provided in two ways. If the
code attribute is present, then its value is a URI that
identifies a resource containing an implementation of the functions in
the namespace; in this case a
type attribute giving the
MIME media type of the data providing the implementation may also be
provided, so as to allow the XSLT processor to avoid fetching
resources of types that it is unable to make use of. If the
code attribute is not present, then the content of the
xsl:functions element contains the implementation of the
functions; in this case the
type attribute
must be present.
Multiple alternative implementations may be provided for the same namespace. For example,
<xsl:stylesheet xmlns: <xsl:template <xsl:value-of </xsl:template> <xsl:functions function currentDate() { return Date().toString() } <p>When multiple alternative implementations are provided, it is up to the XSLT processor to determine which to use.</p> </xsl:functions> <xsl:functions </xsl:stylesheet>
The
xsl:functions element may also have an
archive attribute that specifies a whitespace-separated
list of URIs of resources relevant to the provided implementation.
An XSLT processor is not required to be able to make use of
implementations provided by
xsl:functions elements. The
MIME media types that an XSLT processor is able to make use of and the
way the XSLT processor interfaces with implementations is dependent on
the particular XSLT processor. Therefore if an XSLT stylesheet
includes an ExtensionFunctionCall of an
extension function in a namespace for which an implementation is
provided by an
xsl:functions element, then it may not be
portable across all XSLT implementations.
The
xsl:locale element declares a locale which
controls the interpretation of a format pattern used by the
format-number() function. If there is a
name attribute then the element declares a named locale,
otherwise it declares the default locale. specify characters that may appear in the result of formatting the number and also control the interpretation of characters in the format pattern:
decimal-separator specifies the character used
for the decimal sign
grouping-separator specifies the character used
as a grouping (eg thousands) separator
percent specifies the character used as a
percent sign
per-millpatterns in a pattern
The following attributes specify strings that may appear in the result of formatting the number:
infinity specifies the string used to represent
infinity
NaN specifies the string used to represent the
NaN value
minus-sign specifies the string used as the
default minus sign.
A template rule is specified with the
xsl:template
element. The
match attribute is a Pattern that identifies the source node or nodes
to which the rule applies. The
match attribute is
required unless the
xsl:template element has a
name attribute (see [8 Named Templates]).
The content of the
xsl:template element is the
template.
Issue (template-match-default): Should the
matchattribute have a default? Any node? Any child node? The root node? [4.8 Whitespace Stripping]
will not be processed.
Ed. Note: There is no WG consensus on the use of xsl:apply-templates without a select attribute to process all children of a node.
A
select attribute can be used to process nodes
selected by an expression instead of all children. The value of the
select attribute is a NodeSetExpr. The selected set of nodes are
processed in document
order, unless a sorting specification is present (see
[12="from-ancestors.
Use of expressions in
xsl:apply-templates can lead to
infinite loops. It is an error if, during the invocation of a rule
for a node, that same rule is invoked again for that node. An
XSLT processor may signal the error; if it does not signal the error,
it must recover by creating an empty result tree structure for the
nested invocation.
Ed. Note: This isn't right with parameters.
Ed. Note: Also doesn't apply to built-in rules because they can be invoked in multiple modes.
It is possible for a source node to match more than one template rule. The template rule to be used is determined as follows:
First, all matching template rules that are less important than the most important matching template rule or rules are eliminated from consideration.
Next, all matching template rules that have a lower priority
than the matching template rule or rules with the highest priority are
eliminated from consideration. The priority of a template rule is
specified by the
priority attribute on the template rule.
The value of this must be a real number (positive or negative). -1.
Otherwise the priority is 1.
The idea is that the most common kind of pattern (a pattern that just tests for an element with a specific name) has priority 0; a pattern more specific than this has priority 1; a pattern less specific than this has priority -1.
Ed. Note: Say exactly what syntax is allowed for real numbers..
There is a built-in template rule to allow recursive processing to continue in the absence of a successful pattern match by an explicit rule in the stylesheet. This rule applies to both element nodes and the root node. The following shows the equivalent of the built-in template rule:
<xsl:template <xsl:apply-templates/> </xsl:template>
There is also a built-in template rule for text nodes that copies text through:
<xsl:template <xsl:value-of </xsl:template>
The built-in rule does not apply to processing instructions and comments. When a comment or processing instruction is processed, and no rule is matched, nothing is created.
The built-in template rules are treated as if they were imported
implicitly before the stylesheet and so are considered less important than all other template rules.
Thus the author can override a built-in rule by including an
explicit rule with
match="*|/" or
match="text()".
Modes allow an element to be processed multiple times, each time producing a different result.
Both
xsl:template and
xsl:apply-templates
have an optional
mode attribute whose value is a name..
If there is no matching template, then the built-in template rules
are applied, even if a
mode attribute was specified in
xsl:apply-templates.
Ed. Note: Add some examples.
Templates can be invoked by name. An
xsl:template
element with a
name attribute specifies a named template.
If.
Ed. Note: Expand this.
It is an error if a stylesheet contains more than one template with the same name and same importance. An XSLT processor may signal the error; if it does not signal the error, it must recover by choosing from amongst the templates with highest importance the one that occurs last in the stylesheet.
This section describes instructions that directly create nodes in the result tree.
Issue (multiple-results): Should it be possible to create multiple result trees?
In a template an element in the stylesheet that does not belong to
the XSLT namespace is instantiated to create an element node of the
same type. The created element node will have the attribute nodes
that were present on the element node in the stylesheet tree. The
created element node will also have the namespace nodes that were
present on the element node in the stylesheet tree with the exception
of any namespace node whose value is the XSLT namespace URI
().
The value of an attribute of a literal result element is
interpreted as an attribute
value template: it can contain string;
the string value from instantiating it must be a QName. If the
namespace
attribute is not present, then the QName is expanded into a name using
the namespace declarations in effect for the
xsl:element
element, element to be created. The local part of the QName specified by the
name attribute is used as the local part of the name of
the element;
the string value from instantiating it must be a QName. If the
namespace
attribute is not present, then the QName is expanded into a name using
the namespace declarations in effect for the
xsl:attribute element, not attribute to be created. The local part of the QName specified by the
name attribute is used as the local part of the name of
the attribute attribute as XML. They are not however
required to do so.
The following are all errors:
Adding an attribute to an element after children have been added to it; implementations may either signal the error or ignore the attribute.
Adding an attribute that has the same name as an attribute already added; implementations may either signal the error or ignore the duplicate.
The
xsl:attribute-set element defines a named set of
attributes. The
name attribute specifies the name of the
attribute set. The
xsl:use element adds a named set of
attributes to an element. It has a required
attribute-set attribute that specifies the name of the
attribute set.
xsl:use is allowed in the same places as
xsl:attribute. The content of the
xsl:attribute-set consists of
xsl:attribute
elements that specify attributes; it may also contain
xsl:use elements. The value of attributes in an attribute
set is determined when the attribute set is used rather than when the
attribute set is defined.
The following example creates a named attribute set
title-style and uses it in a template rule.
<xsl:attribute-set <xsl:attribute12pt</xsl:attribute> <xsl:attributebold</xsl:attribute> </xsl:attribute-set> <xsl:template <fo:block <xsl:use <xsl:apply-templates/> </fo:block> </xsl:template>
Any attribute in a named attribute set specified by
xsl:use is not added to an element if the element already
has an attribute of that name.
Multiple definitions of an attribute set with the same name are merged. An attribute from a definition that is more important takes precedence over an attribute from a definition that is less important. It is an error if there are two attribute sets with the same name that are equally important and that both contain the same attribute unless there is a more important definition of the attribute set that also contains the attribute. An XSLT processor may signal the error; if it does not signal the error, it must recover by choosing from amongst the most important definitions that specify the attribute the one that was specified last in the stylesheet.
A template can also contain text nodes. Each text node in a template remaining after whitespace has been stripped as specified in [4.8 [4.8 Whitespace Stripping]) but
does not affect how the characters are handled by the XSLT processor
thereafter.
The
xsl:pi element is instantiated to create a
processing instruction node. The content of the
xsl:pi
element is a template for the value of the processing instruction
node. The
xsl:pi element has a required
name attribute that specifies the name of the processing
instruction node. The value of the name attribute is interpreted as
an attribute value
template.
For example, this
<xsl:pihref="book.css" type="text/css"</xsl:pi>
would create the processing instruction
<?xml-stylesheet href="book.css" type="text/css"?>
It is an error if instantiating the content of
xsl:pi
creates anything other than characters. An XSLT processor may signal
the error; if it does not signal the error, it must recover by
ignoring the offending nodes together with their content.
It is an error if the result of instantiating the content of the
xsl:pi contains the string
?>. An XSLT
processor may signal the error; if it does not signal the error, it
must recover by inserting a space after any occurrence of
? that is followed by an
>.
Ed. Note: What should happen if the name is not a valid NCName?="*|@*|comment()|pi()|text()"> <xsl:copy> <xsl:apply-templates </xsl:copy> </xsl:template>
The
xsl:copy-of element copies a list of nodes
specified by an expression. The required
select attribute
contains an expression. The result of evaluating the expression must
be a node-set or a result tree fragment. When it is node-set, all the
nodes in the set together with their content are copied in document
order over into the result tree; when it is a result tree fragment;
the complete fragment is copied over into the result tree.
When the current node is an attribute, then if it would be an error
to use
xsl:attribute to create an attribute with the same
name as the current node, then it is also an error to use
xsl:copy (see . String
expressions can also be used inside attribute values of literal result
elements by enclosing the string expression in curly brace
(
{}).
xsl:value-of
The
xsl:value-of element is replaced by the result of
evaluating the expression specified by the
attribute. The
select attribute is required. The
expression is a StringExpr, which means
the result of evaluating the expression is converted to a string. The
element is called
xsl:value-of because a node-set is
converted to a string by returning the value of the first
node.
Issue (value-of-select-default): Should the
selectattribute have a default </fo:block> <xsl:apply-templates/> </xsl:template>
In an attribute value that is interpreted as an
attribute value template, such as an attribute of a
literal result element, a StringExpr can
be used by surrounding the StringExpr
with curly braces (
{}). The attribute value
template is instantiated by replacing the string expression together
with surrounding curly braces by the result of evaluating the string
expression. Curly braces are not recognized in an attribute value in
an XSLT stylesheet unless the attribute is specifically stated to be
one which is interpreted as an attribute value template.
NOTE: Not all attributes are interpreted as attribute value templates. Attributes whose value is an expression or pattern, attributes of top-level elements (children of a
xsl:stylesheetelement) and attributes that refer to named XSLT objects are not interpreted as attribute value templates. Also a string expression will be replaced by a single curly brace. It is an error if a right curly brace occurs in an attribute value template outside a string expression without being followed by a second right curly brace; an XSLT processor may signal the error or recover by treating the right curly brace as if it had been doubled. A right curly brace inside a Literal in a string expression is not recognized as terminating the string expression.
Curly braces are not recognized recursively inside string expressions. For example:
<a href="#{id({@ref})/title}">
is not allowed. Instead use simply:
<a href="#{idref(@ref)/title}">
The
xsl:number element is used to insert a formatted
number into the result tree. The number to be inserted may be
specified by an expression. The
expr attribute contains a
NumberExpr. The value of the NumberExpr is rounded to an integer and then
converted to a string using the attributes specified in <xsl:value-of </p> </xsl:for-each> </xsl:template>
If no
expr,
multi or
any. The
default is
single.
The
count attribute is a pattern that specifies
what elements should be counted at those levels. The
count attribute defaults to the element type name of the
current node.
The
from attribute is a pattern that specifies
where counting starts from.
In addition the
xsl:number element has the attributes
specified in .
When
level="multi", it constructs a list of all
ancestors of the current node in document order followed by the
element itself; it then selects from the list those elements that
match the
count pattern; it then maps each element of the
list to one plus the number of preceding siblings of that element that
match the
count pattern. If the
from
attribute is specified, then the only ancestors that are searched are
those that are descendants of the nearest ancestor that matches the
from pattern.
When
level="any", it constructs a list of length
one containing one plus the number of elements at any level of the
document that start before this node and that match the
count pattern. If the
from attribute is
specified, then only elements after the first element before this
element that match the
from pattern are
considered.
Ed. Note: Would it be better to return the number of nodes that match the pattern from the set consisting of the node itself and the nodes starting before the node? This would mean that when the node does not match the pattern, the number of the previous matching node would be returned rather than the number of the next matching node.
The list of numbers is then converted into a string using the
attributes specified in [9.7.1 Number to String Conversion Attributes]; when used with
xsl:number the value of each of these attributes is
interpreted as an attribute
value template. After conversion, the resulting string is
inserted in the result tree.
Ed. Note: Allowing them to be attribute value templates isn't consistent with the current DTD: the declared values would all have to be CDATA, and we couldn't use xml:lang because the XML spec doesn't allow the value to be expressed as a template.="multi" count="chapter|section|subsection" format="1.1. "/> <xsl:apply-templates/> </fo:block> </xsl:template> <xsl:template <fo:block> <xsl:number level="multi"ii ix x ....
A format token
I generates the sequence
I
II III IV V VI VII VII IX X ....
Any other format token indicates a numbering sequence that
starts with that token. If an implementation does not support a
numbering system that starts with that token, it must use a format
token of
1.
When numbering with an alphabetic sequence, the
xml:lang attribute specifies which language's alphabet is
to be used.
NOTE: This can be considered as specifying the language of the value of the
formatattribute and hence is consistent with the semantics of
xml:lang.
The
letter-value attribute disambiguates between
numbering schemes that use letters. In many languages there are two
commonly used numbering schemes that use letters. One numbering
scheme.
The
digit-group-sep attribute gives the separator
between groups of digits, and the optional
n-digits-per-group specifies the number of digits per
group. For example,
digit-group-sep="," and
n-digits-per-group="3" would produce numbers of the form
1,000,000.
The
sequence-src attribute gives the URI of a text
resource that contains a whitespace separated list of the members of
the numbering sequence.
Ed. Note: Specify what should happen when the sequence runs out. NodeSetExpr specified by the
select attribute, which is required. The template is
instantiated with the selected node as the current node, and with a
list of all of the selected nodes as the current node list. The nodes
are processed in document
order, unless a sorting specification is present (see
[12 a BooleanExpr. The content is a template. If
the expression evaluates to true, then the content a
BooleanExpr. The content of the
xsl:when and
xsl:otherwise elements is a
template. When an
xsl:choose element is processed, each
of the
xsl:when elements is tested in turn." expr="size(from-ancestors.
Ed. Note: Say that the current node list is in sorted order.
xsl:sort has a
select attribute whose
value is a StringExpr. For each node to
be processed, the StringExpr is evaluated
with that node as the current node. The string that results from
evaluating the expression is used as the sort key for that node. The
default value of the
select attribute is
.,
which, as a StringExpr, returns the value
of the current node.
The default value is
text.
Ed. Note: We plan to leverage the work on XML schemas to define further values in the future..
Ed. Note: We plan also to add an attribute whose value is a label identifying the sorting scheme, to be specified by the I18N WG.
The values of all of the above attributes are interpreted as attribute value templates.
NOTE: It is recommended that implementors consult [UNICODE TR10] for information on internationalized sorting.
The sort must be stable: in the sorted list of nodes, any sublist-variable. The
difference is that the value specified on the
xsl:param-variable variable is only a default value for
the binding; when the template or stylesheet within which the
xsl:param-variable element occurs is invoked, parameters
may be passed that are used in place of the default values..
A variable binding element can specify the value of the variable in
two ways. It can have a
expr attribute whose value is
an expression, which is evaluated to give the value of the
variable. If there is no
expr attribute, then the
contents of the variable binding element specifies the value. The
contents is a template which is instantiated to give the value. In
this case the value is a result tree fragment.
Both
xsl:variable and
xsl:param-variable
are allowed at the top-level. A top-level variable binding element
declares a global variable that is visible everywhere. A top-level
xsl:param-variable element declares a parameter to the
stylesheet; XSLT does not define the mechanism by which parameters
are passed to the stylesheet. It is an error if a stylesheet contains
more than one binding of a top-level variable the same name and same
importance. An XSLT processor
may signal the error; if it does not signal the error, it must recover
by choosing from amongst the bindings with highest importance-variable-variable is allowed as a child
at the beginning of an
xsl:template element. In this
context, the binding is visible for all following siblings and their
descendants. Note that the binding is not visible for the
xsl:param-variable element itself.
Parameters are passed to templates using the
xsl:param
element. The required
name attribute specifies the name
of the parameter (the variable the value of whose binding is to be
replaced).
xsl:param is allowed within both
xsl:call-template and
xsl:apply-templates.
The value of the parameter is specified in the same way as for
xsl:variable and
xsl:param-variable. The
current node and current node list used for computing the value
specified by
xsl:param element is the same as that used
for the
xsl:apply-templates or
xsl:call-template element within which it occurs. It is
not an error to pass a parameter x to a template that
does not have a
xsl:param-variable element for
x; the parameter is simply ignored.
This example defines a named template for a
numbered-block with an argument to control the format of
the number.
<xsl:template <xsl:param-variable1. </xsl:param-variable> <xsl:number <fo:block><xsl:apply-templates/></fo:block> </xsl:template> <xsl:template <xsl:call-template <xsl:paramA. </xsl.
XSLT provides two mechanisms to combine stylesheets:
An XSLT stylesheet may contain
xsl:import elements. All
the
xsl:import elements must occur at the beginning of
the stylesheet. The
xsl:import element has an
href attribute whose value is the URI of a stylesheet to
be imported. A relative URI is resolved relative to the base URI of
the
xsl:import element (see [4.2.2 Base URI]).
Ed. Note: Say what importing a stylesheet means.
<xsl:stylesheet xmlns: <xsl:import <xsl:import <xsl:attribute-set <xsl:attributeitalic</xsl:attribute> </xsl:attribute-set> </xsl:stylesheet>
Definitions and template rules in the importing stylesheet are defined to be more important than definitions and template rules in any imported stylesheets. Also definitions and template rules in one imported stylesheet are defined to be more important than definitions and template rules in previous imported stylesheets.
In general a more important definition or template rule takes precedence over a less important definition or template rule. This is defined in detail for each kind of definition and for template rules.
Ed. Note: Say something about the case where the same stylesheet gets imported twice. This should be treated the same as importing a stylesheet with the same content but different URIs. What about import loops?
xsl:apply-imports processes the current node using
only template rules that were imported into the stylesheet containing
the current rule; the node is processed in the current rule's
mode.
Ed. Note: Expand this.
An XSLT stylesheet may include another XSLT stylesheet using an
xsl:include element. The
xsl:include element
has an
href attribute whose value is the URI of a
stylesheet to be included. A relative URI is resolved relative to the
base URI of the
xsl:include element (see [4.2.2 Base URI]). The
xsl:include element can occur as
the child of the
xsl:stylesheet element at any point
after all
xsl:import elements.
The inclusion works at the XML tree level. The resource located by
the
href attribute value is parsed as an XML document,
and the children of the
xsl:stylesheet element in this
document replace the
xsl:include element in the including
document. Also any
xsl:import elements in the included
document are moved up in the including document to after any existing
xsl:import elements in the including document. Unlike
with
xsl:import, the fact that rules or definitions are
included does not affect the way they are processed.
Ed. Note: What happens when a stylesheet directly or indirectly includes itself?.
In the second case, the possibility arises of documents with inline style, that is documents that specify their own style. XSLT does not define a specific mechanism for this. This is because this can be done by means of a general purpose mechanism for associating stylesheets with documents provided that:
It is not in the scope of XSLT to define such a mechanism.
NOTE: This is because the mechanism should be independent of any one stylesheet mechanism.
The
xsl:stylesheet element may have an ID attribute
that specifies a unique identifier.
NOTE: In order for such an attribute to be used with the
idXPointer location term, it must actually be declared in the DTD as being an ID.
The following example shows how inline style can be accomplished
using the
xml-stylesheet processing instruction mechanism
for associating a stylesheet with an XML document. The URI uses an
XPointer in a fragment identifier to locate the
xsl:stylesheet element.
<?xml version="1.0"?> <?xml-stylesheet <!ENTITY % char-template " (#PCDATA %char-instructions;)* "> <!ENTITY % template " (#PCDATA %instructions; %result-elements;)* "> <!-- Used for attribute values that are URIs.--> <!ENTITY % URI "CDATA"> <!-- Used for attribute values that are patterns.--> <!ENTITY % pattern "CDATA"> <!-- Used for attribute values that are expressions.--> <!ENTITY % expr "CDATA"> <!-- Used for an attribute value that consists of a single character.--> <!ENTITY % char "CDATA"> <!-- Used for attribute values that are a priority. --> <!ENTITY % priority "NMTOKEN"> <!ENTITY % space-att "xml:space (default|preserve) #IMPLIED"> <!ENTITY % top-level " (xsl:import*, (xsl:include | xsl:strip-space | xsl:preserve-space | xsl:key | xsl:functions | xsl:locale | xsl:attribute-set | xsl:variable | xsl:param-variable | xsl:template)*) "> <!ELEMENT xsl:stylesheet %top-level;> <!ELEMENT xsl:transform %top-level;> <!ATTLIST xsl:stylesheet result-ns NMTOKEN #IMPLIED default-space (preserve|strip) "preserve" indent-result (yes|no) "no" id ID #IMPLIED xmlns:xsl CDATA #FIXED "" %space-att; > <!ELEMENT xsl:import EMPTY> <!ATTLIST xsl:import href %URI; #REQUIRED> <!ELEMENT xsl:include EMPTY> <!ATTLIST xsl:include href %URI; #REQUIRED> <!ELEMENT xsl:strip-space EMPTY> <!ATTLIST xsl:strip-space elements NMTOKENS #REQUIRED> <!ELEMENT xsl:preserve-space EMPTY> <!ATTLIST xsl:preserve-space elements NMTOKENS #REQUIRED> <!ELEMENT xsl:key EMPTY> <!ATTLIST xsl:key name NMTOKEN #REQUIRED match %pattern; #REQUIRED use %expr; #REQUIRED > <!ELEMENT xsl:functions (#PCDATA)> <!ATTLIST xsl:functions ns NMTOKEN #REQUIRED code CDATA #IMPLIED archive CDATA #IMPLIED > <!ELEMENT xsl:locale EMPTY> <!ATTLIST xsl:locale name NMTOKEN #IMPLIED decimal-separator %char; "." grouping-separator %char; "," infinity CDATA "∞" minus-sign %char; "-" NaN CDATA "�" percent %char; "%" per-mill %char; "‰" zero-digit %char; "0" digit %char; "#" pattern-separator %char; ";" > <!ELEMENT xsl:template (#PCDATA %instructions; %result-elements; | xsl:param-variable)* > <!ATTLIST xsl:template match %pattern; #IMPLIED name NMTOKEN #IMPLIED priority %priority; #IMPLIED mode NMTOKEN #IMPLIED %space-att; > <!ELEMENT xsl:value-of EMPTY> <!ATTLIST xsl:value-of select %expr; #REQUIRED > <!ELEMENT xsl:copy-of EMPTY> <!ATTLIST xsl:copy-of select %expr; #REQUIRED> <!ELEMENT xsl:number EMPTY> <!ATTLIST xsl:number level (single|multi|any) "single" count CDATA #IMPLIED from CDATA #IMPLIED expr %expr; #IMPLIED format CDATA '1' xml:lang NMTOKEN #IMPLIED letter-value (alphabetic|other) #IMPLIED digit-group-sep CDATA #IMPLIED n-digits-per-group NMTOKEN #IMPLIED sequence-src %URI; #IMPLIED > <!ELEMENT xsl:apply-templates (xsl:sort|xsl:param)*> <!ATTLIST xsl:apply-templates select %expr; "node()" mode NMTOKEN CDATA #IMPLIED data-type (text|number) "text" order (ascending|descending) "ascending" case-order (upper-first|lower-first) |xsl:use)*> <!ATTLIST xsl:attribute-set name NMTOKEN #REQUIRED > <!ELEMENT xsl:call-template (xsl:param)*> <!ATTLIST xsl:call-template name NMTOKEN #REQUIRED > <!ELEMENT xsl:param %template;> <!ATTLIST xsl:param name NMTOKEN #REQUIRED expr %expr; #IMPLIED > <!ELEMENT xsl:variable %template;> <!ATTLIST xsl:variable name NMTOKEN #REQUIRED expr %expr; #IMPLIED > <!ELEMENT xsl:param-variable %template;> <!ATTLIST xsl:param-variable name NMTOKEN #REQUIRED expr %expr; #IMPLIED > <!ELEMENT xsl:text (#PCDATA)> <!ELEMENT xsl:pi %char-template;> <!ATTLIST xsl:pi name CDATA #REQUIRED %space-att; > <!ELEMENT xsl:element %template;> <!ATTLIST xsl:element name CDATA #REQUIRED namespace CDATA #IMPLIED %space-att; > <!ELEMENT xsl:attribute %char-template;> <!ATTLIST xsl:attribute name CDATA #REQUIRED namespace CDATA #IMPLIED %space-att; > <!ELEMENT xsl:use EMPTY> <!ATTLIST xsl:use attribute-set NMTOKEN #REQUIRED> <!ELEMENT xsl:comment %char-template;> <!ATTLIST xsl:comment %space-att;> <!ELEMENT xsl:copy %template;> <!ATTLIST xsl:copy %space-att;> <!ELEMENT xsl:message %template;> <!ATTLIST xsl:message %space-att;>
The following is a simple but complete stylesheet.
<?xml version='1.0'?> <xsl:stylesheet xmlns: <xsl:template <fo:basic-page-sequence <fo:simple-page-master <fo:queue <xsl:apply-templates/> </fo:queue> </fo:basic-page-sequence> </xsl:template> <xsl:template <fo:block <xsl:apply-templates/> </fo:block> </xsl:template> <xsl:template <fo:block> <xsl:apply-templates/> </fo:block> </xsl:template> <xsl:template <fo:inline-sequence <xsl:apply-templates/> </fo:inline-sequence> </xsl:template> </xsl:stylesheet>
With the following source document
<doc> <title>An example</title> <p>This is a test.</p> <p>This is <emph>another</emph> test.</p> </doc>
it would produce the following result
<fo:basic-page-sequence xmlns: <fo:simple-page-master <fo:queue <fo:blockAn example</fo:block> <fo:block>This is a test.</fo:block> <fo:block>This is <fo:inline-sequenceanother</fo:inline-sequence> test.</fo:block> </fo:queue> </fo:basic-page-sequence>
This is an example of using XSLT to create an XHTML document (see [XHTML]). The following stylesheet:
<?xml version="1.0"?> <xsl:stylesheet xmlns: <xsl:template <html> <head> <title>Sales Results By Division</title> </head> <body> <table border="1"> <tr> <th>Division</th> <th>Revenue</th> <th>Growth</th> <th>Bonus</th> </tr> <xsl:apply-templates/> </table> </body> </html> </xsl:template> <xsl:template <xsl:apply-templates <!-- order the result by revenue --> <xsl:sort </xsl:apply-templates> </xsl:template> <xsl:template <tr> <td><em><xsl:value-of</em></td> <xsl:apply-templates <xsl:apply-templates <xsl:apply-templates </tr> </xsl:template> <xsl:template <td><xsl:apply-templates/></td> </xsl:template> </xsl:stylesheet>
with the following input document
<?xml version="1.0"?> <sales> <division id="North"> <revenue>10</revenue> <growth>9</growth> <bonus>7</bonus> </division> <division id="South"> <revenue>4</revenue> <growth>3</growth> <bonus>4</bonus> </division> <division id="West"> <revenue>6</revenue> <growth>-1.5</growth> <bonus>2</bonus> </division> </sales>
would produce the following result
<?xml version="1.0"?> >-1.5</td> <td>2</td> </tr> <tr> <td><em>South</em></td> <td>4</td> <td>3</td> <td>4</td> </tr> </table> </body> </html>; Scott Boag, Lotus; Jeff Caruso, Bitstream; James Clark (XSLT Editor); Peter Danielsen, Bell Labs; Don Day, IBM; Stephen Deach, Adobe; Angel Diaz, IBM; Dwayne Dicks, SoftQuad; Andrew Greene, Bitstream; Paul Grosso, ArborText; Eduardo Gutentag, Sun; Mickey Kimchi, Enigma; Chris Lilley, W3C; Daniel Lipkin, Oracle; Chris Maden, O'Reilly; Jonathan Marsh, Microsoft; Alex Milowski, CommerceOne; Boris Moore, RivCom; Steve Muench, Oracle; Carolyn Pampino, Interleaf; Scott Parnell, Xerox; Vincent Quint, W3C; Gregg Reynolds, Datalogics; Jonathan Robie, Software AG; Henry Thompson, University of Edinburgh; Philip Wadler, Bell Labs; Randy Waki, Novell; Norm Walsh, ArborText; Sanjiva Weerawarana, IBM; Umit Yalcinalp, Sun; Steve Zilles, Adobe (Co-Chair)
The following is a summary of changes since the previous public working draft.
Select patterns, string expressions and boolean expressions have been combined and generalized into an expression language with multiple data types (see [6 Expressions and Patterns]).
xsl:strip-space and
xsl:preserve-space
have an
elements attribute which specifies a list of
element types, rather than a
element attribute specifying
a single element type.
The
id() function has been split into
id() and
idref().
xsl:id has been replaced by the
xsl:key
element (see [6.4.1 Declaring Keys]), and associated
key()
and
keyref() functions.
The
doc() and
docref() have been added to
support multiple source documents.
Namespace wildcards (
ns:*) have been added.
ancestor() and
ancestor-or-self() have
been replaced by a more general facility for addressing different
axes.
Positional qualifiers (
first-of-type(),
first-of-any(),
last-of-type(),
last-of-any()) have been replaced by the
position() and
last() functions and numeric
expressions inside
[].
Counters have been removed. An
expr attribute has been
added to
xsl:number which in conjunction with the
position() allows numbering of sorted node lists.
Multiple adjacent uses of
[] are allowed.
Macros and templates have been unified by allowing templates to be named and have parameters.
xsl:constant have been replaced by
xsl:variable which allows variables to be typed and
local.
The default for
priority on
xsl:template
has changed (see [7.4 Conflict Resolution for Template Rules]).
An extension mechanism has been added (see [6.4.2 Declaring Extension Functions]).
The namespace URIs have been changed.
xsl:copy-of has been added (see [9.5 Copying]).
A error recovery mechanism to allow forwards-compatibility has been added (see [3 Forwards-compatible Processing]).
A
namespace attribute has been added to
xsl:element and
xsl:attribute. | http://www.w3.org/TR/1999/WD-xslt-19990421.html | CC-MAIN-2015-06 | en | refinedweb |
17 September 2010 15:20 [Source: ICIS news]
TORONTO (ICIS)--Eastman Chemical plans to expand 2-ethyl hexanol (2-EH) and butyraldehyde capacities at its site in ?xml:namespace>
The 2-EH expansion would include a 4,500 tonne/year debottleneck in October of this year, the company said.
The full 2-EH expansion of almost 37,000 tonne/year was expected to be completed by mid-2012, Eastman said.
In support of the 2-EH expansion, Eastman would also increase the site’s butyraldehyde capacity by 40,000 tonne/year, it said.
“This increase in capacity reinforces our commitment to reliably supply our 2-EH customers while also supporting growth in our plasticizer business for products like Eastman 168 non-phthalate plasticiser,” said Ron Lindsay, executive vice president, performance polymers and chemical intermediates
An oxo derivative, 2-EH is used in end products such as plasticisers and additives for fuels and lube oils, the company said.
End markets for 2-EH include building and construction, transportation, medical, consumables, and durable goods manufacture, it added.
For more on Eastman | http://www.icis.com/Articles/2010/09/17/9394364/Eastman-to-expand-Texas-2-EH-capacity-by-37000-tonnesyear.html | CC-MAIN-2015-06 | en | refinedweb |
java codes
java codes hi .. i need a login code in java with restriction that with 3 error attempts then the program will terminate .. thanks
java codes
java codes why is every application allowed to use classes System and String without first importing the item image converting to byte codes - Java Beginners
java image converting to byte codes i want to convert an image to human unreadable format which is uploaded by client to server.How can i
Java Example Codes and Tutorials
Java Tutorials - Java Example Codes and Tutorials
Java is great programming... the name to Java and modified the language to take advantage of the
burgeoning World Wide Web.
Java is an object-oriented language, and this is very
similar to C
Java Tutorials - Java Example Codes and Tutorials
Lambda Expression in Java 8
Lambda Expression in Java 8: Learn the power of Lambda Expression
In this section we will learn about the Lambda Expression which is introduced
in the Java...
in the Java 8. This is the biggest upgrade introduced in the Java so far
show codes of this
show codes of this search for the number of occurrence of "and" and "the" in the following sentence by writing a codes. the student like the best teacher at the end of the lessons and others
Spring AOP tutorials and example codes.
in pure java
and there is no need of special compilation process. It does... in a Java EE web
container or application server.
It is another way of thinking about
Iterator in java, Iterator Java Examples
The Iterator is an java interface, it can be used to iterate the java collection objects. In this Java iterator tutorial you will learn how to define of Java Iterator interface
HTML codes
HTML codes Hi,
I am trying to find HTML codes to learn HTML. Can any one html me?
Thanks
Hi,
Please check HTML examples and HTML5 Tutorials page.
Thanks
java application - Applet
java application codes in repetition and decision codes in repition and decision
java
java hello,i am learning java from past 1 month,i learnt till the inheritance & i want to write a program to test weather a given string is palindrome or not...,can you please help me or give codes
import
codes for displaying in calendar
codes for displaying in calendar can i get jsp codes for displaying comments, when the pointer is placed over the particular date in calendar
files uploding and downloading codes
files uploding and downloading codes any one know JSP codes for upload files,download files and delete files from a created virtual memory
Needed jsp codes
Needed jsp codes jsp code for employee payroll.producing a payslip of every employees monthly calculating the gross pay of a particular employee considering the income tax and producing a report which can be printed out
java
java sir I want to create an html page which is going to be interact with the servlet program.
i want to do it by using eclipse ide can you give me the step by step as well as codes?
thanks
Here is a code
Open Source Charting and Reporting Tools in Java
Open Source Charting and Reporting Tools in Java... for which source codes are available under a General User?s License agreement. Some of them are given
below :
JfreeChart: This is a free java library for creating
Java basics
Java Basics are necessary to learn by programmers who are willing to learn Java language. These basics must be followed every-time a program is made in Java.
Java language is completely specified that helps the programmer
JAVA Basics
JAVA Basics What is byte code? Java programs are compiled and compiler generate a class files which contain byte codes. These byte codes can be run in any platform which makes java platform independent language
Online Java Class
Online Java Classes
Today, softwares have made their foray into every field... to simplify tasks everywhere. Any
Software needs a platform to be developed on and Java... to be designed in the best
possible way.
For developing software on Java technology, one
No complete codes for Simple Form Controlle Example
No complete codes for Simple Form Controlle Example No complete codes
java programming - Java Beginners
java programming heloo expert,
thanks for your coding
i recently asked about the question on abt how to program a atm system
may i noe in which platform can i run those codes ??
netbeans ?? any suggestions Tutorial with examples
Java Tutorial with examples What is the good urls of java tutorial with examples on your website?
Thanks
Hi,
We have many java tutorial with examples codes. You can view all these at Java Example Codes
Java BigDecimal hashCode example
Java BigDecimal hashCode example
.... For every number method generates different hash codes.
Method generated hash codes does...).hashCode();
Java_BigDecimal_hashCode.java
java coding
java coding i am using netbean to my project and it is Desktop Application.i want my textfield to accept only numbers or only alphabets .........plez plez plez do help me..........i am just beginner to java codes
HTML color codes
HTML Color Codes
In this tutorial we will show you how to get the different color codes for
designing your HTML pages. You will be able to find the hexadecimal color
code by color name.
We have also provided the tool to create
Welcome to Java Developers paradise!
SCJP Module-1 Question-5
Encapsulation in Java
are the four concepts of Object Oriented Programming (OOPs). Encapsulation in Java is the technique of binding or wrapping the data and the codes in a class private... the class and thus provides security.
Example of Encapsulation in Java:
package
HTML Color Codes
:5px 0px 5px 5px;
}
HTML Web color codes
In this page we have created a list of most used HTML Web color codes. We have
shown the color... color codes:
Name/String
Code
Name
Code
java program - Java Beginners
java program 1.Write a program in java to input a sentence and find out how many palindromes are there in the sentence.
2. Write a program in java...; Hi Friend,
Try the following codes:
1) Palindrome Example
import
java applets - Java Beginners
calculator using java codes?...
4.write a java application to open the file...java applets 1.write main method for display clock applet including... a java applet programme to implement moving a ball from top to bottom... without
java applet notpad
java applet notpad i need Codes Or programe in java applet ; i want add this programe to my site html > please help me our
Learn Java Applets, if you want to learn java applets then please visit the following link
Java - Java Beginners
codes (sorting and partitioning) to Java. It should be able
to execute any set... and contrast it to the quicksort
algorithm
(f) Write a java program
java code and logic - Java Beginners
java code and logic Q1:
how to write java program for the following:
*
* * *
* * * * *
* * *
*
Q2...
T
S Hi Friend,
Try the following codes:
1
simple calculator - Java Beginners
simple calculator how can i create a simple calculator using java codes? Hi Friend,
Please visit the following link:
Thanks
designing on my own but some codes are not compiling help. Don't ignore me please
Convert To Java Program - Java Beginners
Convert To Java Program Can anyone convert this C program codes to Java codes,please...thanks!
#include
int array[20];
int dcn;
int cntr=0;
void add();
void del();
void insert();
void display();
void exit();
void
java - Java Interview Questions
and that contains data and codes with behavior.
In Java everything happens within... classes in languages like C++ and Pascal.
But in Java one can define his/her own... helloObject.helloWorld()
For read in details :
Tutorial For Java beginners
Tutorial For Java beginners I am beginners in Java. Is there any good tutorial and example for beginners in Java? I want to learn Java before Jan 2014.
Thanks
Yes,
If you spend time you can learn Java in the month
web crawler - Java Beginners
web crawler Sir, i want to develop a web crawler using java & java applet.Can u suggest me any ebook that can help me developing that? Can u provide me with some codes regarding the development of web crawler
java
java diff bt core java and java compilation error - Java Beginners
java compilation error Hello,
I sent a previous message regarding... because I figured out I had the codes typed in wrong. After I corrected the codes I still received this message. My program compiles with no errors but I just
java
java what is java
java script - JSP-Servlet
java script How to open a form while clicking a image button? Hi Friend,
You can use the following codes:
1) 'ImageButton.html'
Click the Image Button
2) 'form.html'
Form
Learn Hibernate programming with Examples
. Here is the pre-requisite of learning the Hibernate with
these example codes... knowledge and experience in Java programming
specially the database driven... the Hibernate based codes.
Hibernate Configuration files -
Understand the various
java
java different between java & core java
Java
Java Whether Java is pure object oriented Language Exception - Handle Exceptions in Java
different types of exception in Java
with the example codes... Java Exception - Handle Exceptions in
Java
What is Exception in Java? How
java - Java Beginners
java hello sir . i have some problem in my java program .i have inserted records into sql server database.
the table name is "proj". now i want... help me . Thank you sir. My three codes are as under:--
1 | http://www.roseindia.net/tutorialhelp/comment/89288 | CC-MAIN-2015-06 | en | refinedweb |
ok yes i am a n00b at C++, i am wondering how i would have a full screen movie to play in a exe file. Could anyone tell me please?
Printable View
ok yes i am a n00b at C++, i am wondering how i would have a full screen movie to play in a exe file. Could anyone tell me please?
What? By fullscreen movie I am assuming you mean just run an exe in a fullscreen mode.
like i wanna creat a .exe file that is in fullscreen and plays a movie. IM creating a game and im using this for a cinimatic. The files are a .wmv
Good luck with that. No offense that is a pretty difficult task
Since wmv files are Windows Media Videos, you will most likely have to use MFC or Win32, I personally hate MFC and really like Win32. Anyways, I found this tutorial here. Unfortunately the tutorial uses MFC, but oh well. If you are a noob to C++ then I think you are not nearly ready to do this. You should get comfortable with C++ and maybe move into Win32 or, heaven forbid, MFC. Then try to take this on.
Take these guys advice, its a ........... Fortunately, DirectX comes with a nice wrapper class to handle playing videos for you, but a strong knowledge of Win32 is required. Check out DirectShow when you're ready.
I believe the recommended API for playing a movie is DirectShow. However, we can cheat by using the simpler MCI API. Here is a simple example that plays a video in a maximized window.
Code:
#include <windows.h>
#include <stdio.h>
#if defined(_MSC_VER)
# pragma comment(lib, "Winmm.lib")
#endif
/*
* Plays an WMV, AVI or MPEG video file.
*/
BOOL xPlayVideo(LPCTSTR szFile)
{
TCHAR szCommandString[500];
wsprintf(szCommandString, TEXT("open \"%.260s\"("window MediaFile text \"Game Intro\""), NULL, 0, NULL) &&
ERROR_SUCCESS == mciSendString(TEXT("window MediaFile state show maximized"), NULL, 0, NULL) &&
ERROR_SUCCESS == mciSendString(TEXT("play MediaFile"), NULL, 0, NULL))
{
return TRUE;
}
return FALSE;
}
int main(void)
{
MSG msg;
if (!xPlayVideo(TEXT("C:\\PathTo\\YourVideo.wmv")))
printf("Failed to play video!");
/* We must run a message loop while the video window is open. */
while (GetMessage(&msg, 0, 0, 0) > 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
what are you using as a complier? im using Dev-C++ and im getting errors on this code so
May I ask how deep your knowledge of C++ goes? Something a little more detailed than "I'm a n00b", because if you're creating a console game and have no knowledge of windows or game programming, then I'd say you're years off from creating a "cinematic".
im creating the program in another programming language. I am completly new at C++. All i need C++ for is to play the video file straight away thenonce its finished to continue back into the first language i was dealing with. The cinimatics are an avi or wmv format therefore if i can get something to run the video then im good. can't have play button ormenu or fast forwards or anything just needs to play
what language is the game in? Have you thought about playing the video in that language? DirectX has support for almost all windows programming languages so you might want to look into some DirectShow tutorials.
>> what are you using as a complier? im using Dev-C++ and im getting errors on this code so <<
For Dev-C++, you need to link with the winmm library. You do this by adding "-lwinmm" to the linker box under Project->Project Options->Parameters (you need to create a new project and add the code as a C file, if you haven't already).
ok now i am getting
" cannot find -lobjc
ld returned 1 exit status
C:\Dev-Cpp\Makefile.win [Build Error] [Project1.exe] Error 1 "
It's not -lobjc it's -lwinmm.
i know, i placed the -lwinmm into the linker box, but the error i am reciving now is:
cannot find -lobjc
ld returned 1 exit status
C:\Dev-Cpp\Makefile.win [Build Error] [Project1.exe] Error 1 | http://cboard.cprogramming.com/cplusplus-programming/71827-movie-program-printable-thread.html | CC-MAIN-2015-06 | en | refinedweb |
iDebugPrintQuestSeqOpFactory Struct Reference
This interface is implemented by the seqop that prints debug messages on standard output. More...
#include <tools/questmanager.h>
Inheritance diagram for iDebugPrintQuest 20 | http://crystalspace3d.org/cel/docs/online/api-1.4.1/structiDebugPrintQuestSeqOpFactory.html | CC-MAIN-2015-06 | en | refinedweb |
#include <Wire.h>int slaveIn;void setup() { Wire.begin();}void loop() { Wire.requestFrom(1, 1); while(Wire.available()==0); slaveIn = Wire.read(); Serial.println(slaveIn); delay(1000);}
#include <Wire.h>int counter = 0;void setup() { Wire.begin(1);}void loop() { Wire.onRequest(request);}void request(){ Wire.write(counter); counter++;}
I'm having trouble getting the master to request a byte of data, the slave to send that data, and then the master to print that data.
QuoteI'm having trouble getting the master to request a byte of data, the slave to send that data, and then the master to print that data.But, you want to keep the problem a secret. Well, then, we'll need to keep the solution a secret, too.Wire.onRequest() registers an event handler to be called when an event occurs. You only need to do that once, in setup().
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=148028.0;prev_next=prev | CC-MAIN-2015-06 | en | refinedweb |
09 November 2012 11:50 [Source: ICIS news]
LONDON (ICIS)--?xml:namespace>
Fourth-quarter oil demand could increase marginally, however, as cold weather at the end of the year puts pressure on heating oil in the US and Europe, the cartel said in its latest monthly oil report.
The transportation sector contributed to the slowdown in oil use in its peak summer season as a result of slower economic activities, OPEC said.
World oil demand for 2012 and 2013 is estimated at 800,000bbl/day, unchanged from the previous month’s report.
“Expected weakness in the world economy is placing a considerable amount of uncertainty on the world oil demand forecast,” OPEC said.
The cartel’s global economic growth expectations were also unchanged, at 3.1% for 2012 and 3.2% for 2013.
Non-OPEC supply in 2012 is forecast to increase by 500,000 bbl/day, a downward revision of around 50,000 bbl/day from the previous report. Non-OPEC supply growth for 2013 was unchanged at 900,000 bbl/day, the report said.
Demand for OPEC crude in 2012 was unchanged at 30.1m bbl/day but the 2013 forecast was revised down by 100,000 bbl/day to 29.7m bbl/day.
On Thursday, OPEC released its World Oil Outlook for 2012 in which it revised down global oil demand forecasts on economic growth | http://www.icis.com/Articles/2012/11/09/9612497/hurricane-sandy-to-impact-us-oil-demand-opec.html | CC-MAIN-2015-06 | en | refinedweb |
NAME
VFS_MOUNT - mount a file system
SYNOPSIS
#include <sys/param.h> #include <sys/mount.h> #include <sys/vnode.h> int VFS_MOUNT(struct mount *mp, struct thread *td);
DESCRIPTION
The VFS_MOUNT() macro mounts a file system into the system’s namespace or updates the attributes of an already mounted file system. The arguments it expects are: mp Structure representing the file system. td Thread which is mounting the file system. The VFS_MOUNT() macro is called both to mount new file systems and to change the attributes of an existing file system. If the MNT_UPDATE flag is set in mp->mnt_flag then the file system should update its internal state from the value of mp->mnt_flag. This can be used, for instance, to convert a read-only file system to read-write. It is also used by mountd(8) to update the NFS export information for the file system. If the MNT_UPDATE flag is not specified, then this is a newly mounted file system. The file system code should allocate and initialize any private data needed to represent the file system (it can use the mp->mnt_data field to store this information).
SEE ALSO
VFS(9), vnode(9)
AUTHORS
This manual page was written by Doug Rabson. | http://manpages.ubuntu.com/manpages/intrepid/man9/VFS_MOUNT.9freebsd.html | CC-MAIN-2015-06 | en | refinedweb |
C#: Reading lines from a file
The “Quest” app is evolving, slowly but steady. And in this post I am going to share the things I have been learning regarding the manipulation of lines from files in C#.
Getting a list of lines
To be able to manipulated the lines of a file, I am using the “ReadAllLines” method from the File class, which is in the System.IO namespace. Here is an example of how I am using it:
As the C# documentation describes, the “ReadAllLines” method:
Opens a text file, reads all lines of the file into a string array, and then closes the file.
In my example above I call the “ToList” method to convert the string array into a List of strings. The List<string> has some convenient methods such as “Remove”, which I use to delete a line.
It is also important to understand what defines a line. The C# documentation also explains what is considered a line by the ReadAllLines method:
A line is defined as a sequence of characters followed by a carriage return (‘\r’), a line feed (‘\n’), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
What I like about this method is that, since it returns an enumerable object, I can use the “foreach” loop to iterate over the list. Quest uses the “Find” method on the List<string> to search for a line that contains the string provided by the user to delete a “todo” or mark it as complete. | https://robwillup.medium.com/c-reading-lines-from-a-file-1493c388f0de?source=post_internal_links---------3------------------------------- | CC-MAIN-2022-05 | en | refinedweb |
What I Learned at Work this Week: Updating a Jest Snapshot
A big part of my job is writing “custom tag configurations” for my company’s clients. My company’s product is a “tag,” or a script that runs custom logic when it’s added to a client’s website. Since every website is different, our tag doesn’t always work perfectly out of the box, or by default, for every client. That’s why we’ll customize it to optimize for the location of various objects on their site.
But every once in a while, we’ll find a consistent pattern over several sites that would allow us to deploy the same tag configuration with equal effectiveness. Something like that is a huge win because it means we can service two or more clients while only having to spend time writing one configuration. In this case, we would write a “preset” that could be applied to any company through our UI. Presets carry more weight than custom configurations because if they break, our product will stop working for a series of clients instead of just one. As you might expect, testing for presets is more robust than testing for custom configurations.
This week, I had to make a change to a preset I had written, but when I tried to push my code, I saw that it was now failing a test. It turned out my new configuration wasn’t returning the correct snapshot, so if I wanted to make my change, I’d have to learn what that meant and how to fix it.
Jest
The first thing you’ll read on jestjs.io is that
Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
And indeed, Jest is a framework we can use to test our JavaScript. Much like React, Jest was built and is maintained by Facebook. And so, as you might expect, there’s plenty of emphasis on how well it works with React. Since React is a framework that primarily builds dynamic user interfaces, it provides a unique challenge of how to test interactive displays.
A traditional method that still has its advantages is to actually render a page, interact with it, and see what happens as part of your automated test. While this can be thorough, it is also time-consuming, even when automated. What’s worse, variability can make tests flaky, failing inconsistently when nothing in the code has changed. Dealing with this experience, the folks at Jest created a test based on snapshots.
A Jest Snapshot
The concept of a snapshot isn’t unique to Jest. For example, we could augment the previously mentioned test which renders a page by taking a digital “snapshot” of a rendered page and compared that to the page that renders whenever we try to push out a new change. But that still suffers from the issues of having to run most or all of your app whenever you have to test.
In their documentation, the authors of Jest say that instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree.
In other words, we can save a component’s JSX as a string and then regenerate that component whenever we want to test. Here’s the example React that the documentation provides:
import React from 'react';
import renderer from 'react-test-renderer';
import Link from '../Link.react';it('renders correctly', () => {
const tree = renderer
.create(<Link page="">Facebook</Link>)
.toJSON();
expect(tree).toMatchSnapshot();
});
This assumes some knowledge of Jest syntax, but since it’s got a focus on simplicity, it’s not too difficult for us to follow. Everything is wrapped in an it function, which essentially defines our test. The function accepts two arguments, a string which is the name of the test and an anonymous function. That second argument sets a variable called tree that uses an imported object called renderer to run a create function.
I haven’t seen the code behind renderer, but I think it’s safe to assume that it can be used to run JSX. We’re passing a Link component to the create function and them immediately converting the result to JSON, which will stringify it. What does that string look like? We can see it in the Jest document right after this snippet:
exports[`renders correctly 1`] = `
<a
className="normal"
href=""
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
</a>
`;
It’s easy to miss the tick marks, but they indicate that everything we’re seeing here, from <a to </a> is a string. And if we go back to the last line of our sample test:
expect(tree).toMatchSnapshot();
Our expectation is that the JSON conversion of our component “matches” the snapshot that’s generated when we first run Jest. Of course, the very first time we do this, they’ll always match, even if there’s a problem with the initial code. But if we feel good about our initial component, we’ll have a saved version of that which we can compare to all future iterations.
Advantages and Disadvantages
The advantages to this methodology are clear: it’s faster and more reliable than having to actually run our app, and our snapshot is pretty lightweight too. In a blog post linked in the Jest documentation, Ben McCormick shares a few shortcomings of the process that are also important to recognize:
- Compared to assertion-based tests, snapshot testing is better for testing behavior that will change often, like where elements fit on our page as we develop it. If the behavior is expected to remain static over time, a classic assertion might be better, since we can describe it ourselves and it’s not so easy to update the test (more on updating snapshots later).
- Snapshot tests won’t provide guidance when they fail. Instead, they just tell us that the string generated from our code doesn’t match the snapshot. Sometimes this is intentional and sometimes our subject is so complicated that a simple “this is different” doesn’t get us any closer to identifying why.
- Ease of updating means we can more easily add a mistake to our code. There’s a single-line command to automatically update our Jest snapshots. Even better, when our tests fail, we’re given the option to make a selection that will update the snapshots in that moment. McCormick argues that this necessitates extra-thorough code review so that we don’t absent-mindedly update our snapshot when we instead should have refactored our code.
Generating my Snapshot
Jest provides pretty clear messaging on its tests, so I knew that my change was failing because my snapshot was out of date. As I mentioned, Jest provides a very easy way to address that issue:
jest --updateSnapshot~ OR ~jest -u
But in practice, my code is in a big monorepo with a bunch of different test files and snapshots, most of which have nothing to do with my code at all. I’ll be in a very bad situation if I mistakenly update one of those, so I have to be more specific with my command.
If I want to see what commands I can run within my micro front end (MFE), I can check the package.json file. The file mapped a command test with jest, so I learned that I could run test -u to update my snapshot. I can specify a workspace in yarn and then add the test command, like so:
yarn workspace @my-chosen-workspace test -u
That last line was actually the main thing I learned at work this week, but I wanted to be able to better understand what a snapshot is and why it’s important. I feel like I’ve been hearing about testing forever, but it’s not an easy muscle to flex, especially when you’re iterating on existing code rather than starting from scratch. I’m not sure how much closer I am to writing a suite of Jest tests, but at least I understand the concept just a little bit better than I did before.
Sources
- Jest
- Snapshot Testing, Jest
- Jest 14.0: React Tree Snapshot Testing, Jest
- Testing with Jest Snapshots: First Impressions, Ben McCormick
- Use Jest’s Snapshot Testing Feature: Kent C. Dodds | https://mike-diaz006.medium.com/what-i-learned-at-work-this-week-updating-a-jest-snapshot-77376ddbf029 | CC-MAIN-2022-05 | en | refinedweb |
In this second post about Java 9, we will focus on changes in the Collections and Streams API in the Java language. Examples can be downloaded via the following git repository: . The examples in the post below can be executed with JShell, the examples on GitHub contain the examples with unit tests.
Convenience factory methods for Collections
Factory methods are added to the Collections interfaces in order to create compact, immutable collection instances. The focus for these factory methods lies on small collections. Before Java 9, it was quite tedious to create such small collections. You had to write something like this (examples can be found in the NewCollections class):
Set<String> set = new HashSet<>(); set.add("apple"); set.add("lemon"); set.add("pineapple"); set = Collections.unmodifiableSet(set);
List/Set factory methods
In Java 9, factory methods for List and Set are available which take 0 up to 10 elements or varargs. The example above can now be rewritten as follows:
Set.of("apple", "lemon", "pineapple");
Pretty simple right? Now, you may wonder why 11 methods are made available why you also have a varargs method. The answer is because of performance. Also remember, that the focus for the usage lies on small collections.
Map factory methods
For Map, similar methods are available. Only difference is that they contain key/value pairs:
Map.of(1, "apple", 2, "lemon", 3, "pineapple");
The varargs variant for Map differs from the one for List/Set. It is called ofEntries and a list of Map entries must be provided:
Map.Entry<Integer, String> entry1 = Map.entry(1, "apple"); Map.Entry<Integer, String> entry2 = Map.entry((2, "lemon"); Map.Entry<Integer, String> entry3 = Map.entry((3, "pineapple"); Map.ofEntries(entry1, entry2, entry3);
Streams
The Streams interface API is extended with some useful methods. Examples can be found in the NewStreams class and the corresponding unit tests (the examples below can be executed with JShell).
dropWhile
The method dropWhile gives you the opportunity to read the stream from the moment the condition (predicate) matches. In the example below, the items from the stream are dropped until an item is found which matches the text ‘pineapple’. From that moment on, the items are processed.
Stream.of("apple", "lemon", "pineapple", "orange").dropWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
The output is:
pineapple orange
takeWhile
The method takeWhile is similar to dropWhile. The items of the stream are read up to the moment the condition (predicate) matches. In the example below, the items from the stream are processed until an item is found which matches the text ‘pineapple’.
Stream.of("apple", "lemon", "pineapple", "orange").takeWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
The output is:
apple lemon
As you can see, dropWhile starts from the item which matches the predicate (‘pineapple’ is included), takeWhile stops when an item matches the predicate (‘pineapple’ is not included).
Improved iteration
The new iterate method takes three arguments:
- seed: the initial element for the stream
- hasNext: the condition (predicate) which stops the iteration
- next: the next element
In the example we start to iterate from 0, after each iteration we increase the element by two until the value of 10 has been reached.
IntStream.iterate(0, x -> x < 10, x -> x + 2).forEach(System.out::println);
The output is:
0 2 4 6 8
ofNullable
With Java 9, the ofNullable method is introduced in the Streams API. How does this work?
First, we create a Customer class which returns a stream of fruits.
public class Customer { public Stream<String> fruits() { return Stream.of("apple", "lemon", "pineapple", "orange"); } }
Let’s use the same example of the dropWhile method from above.
Customer customer = new Customer(); Stream.of(customer).flatMap(Customer::fruits).dropWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
The output is as expected the same as in the above example, namely:
pineapple orange
What if customer is retrieved from a database or a third party library and that it could return null? We simulate this behavior by explicitly setting customer to null.
Customer customer = null; Stream.of(customer).flatMap(Customer::fruits).dropWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
As expected, the output is a NullPointerException 😦
When we rewrite the customer examples with ofNullable, the first example returns the same output as with the ‘of’-method.
Customer customer = new Customer(); Stream.ofNullable(customer).flatMap(Customer::fruits).dropWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
Output:
pineapple orange
The outcome of the example when customer is null, gives us a different result.
Customer customer = null; Stream.ofNullable(customer).flatMap(Customer::fruits).dropWhile(s -> !s.equals("pineapple")).forEach(System.out::println);
No NullPointerException is thrown now, because the ofNullable method checked whether the customer object is null or not and returned an empty stream 🙂 | https://mydeveloperplanet.com/2017/11/16/java-9-collections-streams/ | CC-MAIN-2022-05 | en | refinedweb |
8. Canvas Widgets in Tkinter
By Bernd Klein. Last modified: 16 Dec 2021.
Introduction
The Canvas widget supplies graphics facilities for Tkinter. Among these graphical objects are lines, circles, images, and even other widgets. With this widget it's possible to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.
We demonstrate in our first example, how to draw a line.
The method create_line(coords, options) is used to draw a straight line. The coordinates "coords" are given as four integer numbers: x1, y1, x2, y2 This means that the line goes from the point (x1, y1) to the point (x2, y2). After these coordinates follows a comma separated list of additional parameters, which may be empty. We set, for example, the colour of the line to the special green of our website: fill="#476042"
We kept the first example intentionally very simple. We create a canvas and draw a straight horizontal line into this canvas. This line vertically cuts the canvas into two areas.
The casting to an integer value in the assignment "y = int(canvas_height / 2)" is superfluous, because create_line can work with float values as well. They are automatically turned into integer values. In the following you can see the code of our first simple script:
from tkinter import * master = Tk() canvas_width = 80 canvas_height = 40 w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() y = int(canvas_height / 2) w.create_line(0, y, canvas_width, y, fill="#476042") mainloop()
If we start this program, using Python 3, we get the following window:
For creating rectangles we have the method create_rectangle(coords, options). Coords is again defined by two points, but this time the first one is the top left point and the bottom right point of the rectangle.
The window, you see above, is created by the following Python tkinter code:
from tkinter import * master = Tk() w = Canvas(master, width=200, height=100) w.pack() w.create_rectangle(50, 20, 150, 80, fill="#476042") w.create_rectangle(65, 35, 135, 65, fill="yellow") w.create_line(0, 0, 50, 20, fill="#476042", width=3) w.create_line(0, 100, 50, 80, fill="#476042", width=3) w.create_line(150,20, 200, 0, fill="#476042", width=3) w.create_line(150, 80, 200, 100, fill="#476042", width=3) mainloop()
The following image with the coordinates will simplify the understanding of application of create_lines and create_rectangle in our previous example.
Text on Canvas
We demonstrate now how to print text on a canvas. We will extend and modify the previous example for this purpose. The method create_text() can be applied to a canvas object to write text on it. The first two parameters are the x and the y positions of the text object. By default, the text is centred on this position. You can override this with the anchor option. For example, if the coordinate should be the upper left corner, set the anchor to NW. With the keyword parameter text, we can define the actual text to be displayed on the canvas.
from tkinter import * canvas_width = 200 canvas_height = 100 colours = ("#476042", "yellow") box=[] for ratio in ( 0.2, 0.35 ): box.append( (canvas_width * ratio, canvas_height * ratio, canvas_width * (1 - ratio), canvas_height * (1 - ratio) ) ) master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() for i in range(2): w.create_rectangle(box[i][0], box[i][1],box[i][2],box[i][3], fill=colours[i]) w.create_line(0, 0, # origin of canvas box[0][0], box[0][1], # coordinates of left upper corner of the box[0] fill=colours[0], width=3) w.create_line(0, canvas_height, # lower left corner of canvas box[0][0], box[0][3], # lower left corner of box[0] fill=colours[0], width=3) w.create_line(box[0][2],box[0][1], # right upper corner of box[0] canvas_width, 0, # right upper corner of canvas fill=colours[0], width=3) w.create_line(box[0][2], box[0][3], # lower right corner pf box[0] canvas_width, canvas_height, # lower right corner of canvas fill=colours[0], width=3) w.create_text(canvas_width / 2, canvas_height / 2, text="Python") mainloop()
Though the code of our example program is changed drastically, the graphical result looks still the same except for the text "Python":
You can understand the benefit of our code changes, if you change for example the height of the canvas to 190 and the width to 90 and modify the ratio for the first box to 0.3. Image doing this in the code of our first example. It would be a lot tougher. The result looks like this:
Oval Objects
An oval (or an ovoid) is any curve resembling an egg (ovum means egg in Latin). It resembles an ellipse, but it is not an ellipse. The term "oval" is not well-defined. Many different curves are called ovals, but they all have in common:
- They are differentiable, simple (not self-intersecting), convex, closed, plane curves
- They are very similar in shape to ellipses
- There is at least one axis of symmetry
The word oval stems from Latin ovum meaning "egg" and that's what it is: A figure which resembles the form of an egg. An oval is constructed from two pairs of arcs, with two different radii A circle is a special case of an oval.
We can create an oval on a canvas c with the following method:
id = C.create_oval ( x0, y0, x1, y1, option, ... )
This method returns the object ID of the new oval object on the canvas C.
The following script draws a circle around the point (75,75) with the radius 25:
from tkinter import * canvas_width = 190 canvas_height =150 master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() w.create_oval(50,50,100,100) mainloop()
We can define a small function drawing circles by using the create_oval() method.
def circle(canvas,x,y, r): id = canvas.create_oval(x-r,y-r,x+r,y+r) return id
Painting Interactively into a Canvas
We want to write an application for painting or writing into a canvas. Unfortunately, there is no way to paint just one dot into a canvas. But we can overcome this problem by using a small oval:
from tkinter import * canvas_width = 500 canvas_height = 150 def paint( event ): python_green = "#476042" x1, y1 = ( event.x - 1 ), ( event.y - 1 ) x2, y2 = ( event.x + 1 ), ( event.y + 1 ) w.create_oval( x1, y1, x2, y2, fill = python_green ) master = Tk() master.title( "Painting using Ovals" ) w = Canvas(master, width=canvas_width, height=canvas_height) w.pack(expand = YES, fill = BOTH) w.bind( "<B1-Motion>", paint ) message = Label( master, text = "Press and Drag the mouse to draw" ) message.pack( side = BOTTOM ) mainloop()
Drawing Polygons
If you want to draw a polygon, you have to provide at least three coordinate points:
create_polygon(x0,y0, x1,y1, x2,y2, ...)
In the following example we draw a triangle using this method:
from tkinter import * canvas_width = 200 canvas_height =200 python_green = "#476042" master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() points = [0,0,canvas_width,canvas_height/2, 0, canvas_height] w.create_polygon(points, outline=python_green, fill='yellow', width=3) mainloop()
It looks like this:
When you read this, there may or not be Christmas soon, but we present a way to improve your next Christmas with some stars, created by Python and Tkinter. The first star is straight forward with hardly any programming skills involved:
from tkinter import * canvas_width = 200 canvas_height =200 python_green = "#476042" master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() points = [100, 140, 110, 110, 140, 100, 110, 90, 100, 60, 90, 90, 60, 100, 90, 110] w.create_polygon(points, outline=python_green, fill='yellow', width=3) mainloop()
As we have mentioned, this approach is very unskilful. What if we have to change the size or the thickness of the star? We have to change all the points manually, which is of course an error-prone and tedious task to do. So, we present a new version of the previous script which involves more "programming" and programming skills. First, we put the creation of the star in a function, and we use an origin point and two lengths p and t to create the star:
Our new improved program looks like this now:
from tkinter import * canvas_width = 400 canvas_height =400 python_green = "#476042" def polygon_star(canvas, x,y,p,t, outline=python_green, fill='yellow', width = 1): points = [] for i in (1,-1): points.extend((x, y + i*p)) points.extend((x + i*t, y + i*t)) points.extend((x + i*p, y)) points.extend((x + i*t, y - i * t)) print(points) canvas.create_polygon(points, outline=outline, fill=fill, width=width) master = Tk() w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() p = 50 t = 15 nsteps = 10 step_x = int(canvas_width / nsteps) step_y = int(canvas_height / nsteps) for i in range(1, nsteps): polygon_star(w,i*step_x,i*step_y,p,t,outline='red',fill='gold', width=3) polygon_star(w,i*step_x,canvas_height - i*step_y,p,t,outline='red',fill='gold', width=3) mainloop()
The result looks even more like Xmas and we are sure that nobody doubts that it would be hell to define the polygon points directly, as we did in our first star example:
Bitmaps
The method create_bitmap() can be be used to include a bitmap on a canvas. The following bitmaps are available on all platforms:
"error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", "warning"
The following script puts all of these bitmaps on a canvas:
from tkinter import * canvas_width = 300 canvas_height =80 master = Tk() canvas = Canvas(master, width=canvas_width, height=canvas_height) canvas.pack() bitmaps = ["error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", "warning"] nsteps = len(bitmaps) step_x = int(canvas_width / nsteps) for i in range(0, nsteps): canvas.create_bitmap((i+1)*step_x - step_x/2,50, bitmap=bitmaps[i]) mainloop()
The result looks like this:
The Canvas Image Item
The Canvas method create_image(x0,y0, options ...) is used to draw an image on a canvas. create_image doesn't accept an image directly. It uses an object which is created by the PhotoImage() method. The PhotoImage class can only read GIF and PGM/PPM images from files
from tkinter import * canvas_width = 300 canvas_height =300 master = Tk() canvas = Canvas(master, width=canvas_width, height=canvas_height) canvas.pack() img = PhotoImage(file="rocks.ppm") canvas.create_image(20,20, anchor=NW, image=img) mainloop()
The window created by the previous Python script looks like this:
Exercise
Write a function, which draws a checkered pattern into a canvas. The function gets called with checkered(canvas, line_distance). "canvas" is the Canvas object, which will be drawn into. line_distance is the distance between the vertical and horizontal lines.
Solution
from tkinter import * def checkered(canvas, line_distance): # vertical lines at an interval of "line_distance" pixel for x in range(line_distance,canvas_width,line_distance): canvas.create_line(x, 0, x, canvas_height, fill="#476042") # horizontal lines at an interval of "line_distance" pixel for y in range(line_distance,canvas_height,line_distance): canvas.create_line(0, y, canvas_width, y, fill="#476042") master = Tk() canvas_width = 200 canvas_height = 100 w = Canvas(master, width=canvas_width, height=canvas_height) w.pack() checkered(w,10) mainloop()
The result of the previous script looks like this:
| https://python-course.eu/tkinter/canvas-widgets-in-tkinter.php | CC-MAIN-2022-05 | en | refinedweb |
17. Diagnostics
<assert.h>
The header
<assert.h> defines the
assert macro and refers to another
macro,
NDEBUG which is not defined by
<assert.h>. If
NDEBUG is
defined as a macro name at the point in the source file where
<assert.h> is
included, the
assert macro is defined simply as:
#define assert(ignore) ((void)0)
17.1.1. The
assert macro
Synopsis
#include <assert.h> void assert(scalar expression);
Description
The
assert macro puts diagnostic tests into programs; it expands to a void
expression. When it is executed, if expression (which shall have a scalar type)
is false (that is, compares equal to 0), the assert macro writes information
about the particular call that failed (including the text of the argument, the
name of the source file, the source line number, and the name of the enclosing
function - the latter are respectively the values of the preprocessing macros
__FILE__ and
__LINE__ and of the identifier
__func__) on the
standard error stream in an implementation-defined format.. | https://www.ashtavakra.org/c-programming/assert/ | CC-MAIN-2022-05 | en | refinedweb |
GREPPER
SEARCH
SNIPPETS
USAGE DOCS
INSTALL GREPPER
All Languages
>>
Whatever
>>
yarn dev error eacces windows
“yarn dev error eacces windows” Code Answer
yarn dev error eacces windows
whatever by
Cheerful Chicken
on Jun 01 2021
Comment
0
Windows users - if you have Vmware workstation installed, disable all the vmware network adapters. This solved the issue for me.
Add a Grepper Answer
Whatever answers related to “yarn dev error eacces windows”
bash: yarn: command not found
yarn : File C:\Users\Developer Daiyan\AppData\Roaming\npm\yarn.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
yarn problem
yarn start not working on windows because scripts disabled
create react app with npm not yarn
File C:\Users\skill\AppData\Roaming\npm\yarn.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
yarn unable to verify local issuer certificate
yarn: command not found
yarn install No such file or directory: 'install'
yarn 2 outdated packages
npm ERR! code EACCES
WSL2 request to failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
yarn install production only
GPG error: stable InRelease:
Usage: yarn [options] yarn: error: no such option: --template
unable to find expo in this project - have you run yarn / npm install yet?
command failed with exit code 1: yarn build
yarn audit fix
ubuntu error: EACCES: permission denied, symlink '../lib/node_modules/yarn/bin/yarn.js' -> '/usr/local/bin/yarn'
install Hardhat locally using npm or Yarn
I used yarn before and now it is going with yarn how to make nom use
command not available after yarn add global linux
yarn incompatible module node
Whatever queries related to “yarn dev error eacces windows”
yarn dev error eacces windows
More “Kinda” Related Whatever Answers
View All Whatever Answers »
[webpack-cli] Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin' Require stack:
Error: spawnSync ./gradlew EACCES
Error: spawn ./gradlew EACCES at Process.ChildProcess._handle
Error: spawn ./gradlew EACCES
./gradlew permission denied
permission denied: ./gradlew
Error: Cannot find module 'webpack/lib/rules/DescriptionDataMatcherRulePlugin'
Could not find the implementation for builder @angular-devkit/build-angular:dev-server
Your lock file does not contain a compatible set of packages. Please run composer update
'mix' is not recognized as an internal or external command, operable program or batch file.
Could not resolve project :react-native-camera.Required by:
CocoaPods could not find compatible versions for pod "Firebase/Messaging":
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
pip Fatal error in launcher: Unable to create process using e:\python\python39\python.exe
Fatal error in launcher: Unable to create process using pip.exe
Manifest merger failed : Apps targeting Android 12 and higher are required to specify an explicit value for `android:exported`
'heroku' is not recognized as an internal or external command, operable program or batch file.
react-native command not found
OSError: libespeak.so.1: cannot open shared object file: No such file or directory
Class 'App\Providers\schema' not found
CocoaPods specs repository is too out-of-date to satisfy dependencies.
dpkg: error: dpkg frontend lock was locked by another process with pid 4368
, you have held broken packages.
homebrew cocoapods
your bundle is locked to mimemagic (0.3.5)
JavaFX runtime components are missing, and are required to run this application
pecl: command not found
License for package Android SDK Platform 30 not accepted.
dpkg: error: dpkg frontend lock is locked by another process
No LSB modules are available
Error: pg_config executable not found.
cannot find symbol BuildConfig.DEBUG symbol: variable BuildConfig
npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree
zsh: command not found: wget
set staticroot settings to a filesystem path
: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.
The Schematic workflow failed.
ModuleNotFoundError: No module named 'rest_framework'
rest_framework import-error
Import "rest_framework.views" could not be resolved
yarn ERROR: There are no scenarios; must have at least one.
Failed to resolve: com.crashlytics.sdk.android:crashlytics:17.2.2
Error: Cannot run with sound null safety, because the following dependencies don't support null safety:
null safety error
Cannot run with sound null safety, because the following dependencies don't support null safety
Heroku: Rails 5 ActiveCable configuration issue. Error during WebSocket handshake: 'Upgrade' header is missing
'Upgrade' header is missing
The following signatures were invalid: EXPKEYSIG B188E2B695BD4743 DEB.SURY.ORG
Error: Cannot find module 'karma-mocha-reporter'
mamp error log
unknown command cask
SPDX license identifier not provided in source file.
npm run dev mix not found
sh: mix: command not found
impossible d'accéder à '/usr/local/lib/node_modules': Aucun fichier ou dossier de ce type
checkPermissions Missing write access to /usr/lib/node_modules
sudo apt update error E: The repository ' focal Release' does not have a Release file.
E: The repository ' focal Release' does not have a Release file.
Module not found: Can't resolve '@emotion/styled' in '/Users/arjungautam/Documents/VsCodeProjects/materialui-demo/node_modules/@mui/styled-engine'
Execution failed for task ':app:lintVitalRelease'. > Lint found fatal errors while assembling a release target.
[error] Error: Cannot find module '@schematics/angular/utility/config'
command failed with exit code 1: yarn build
Error: Module not found: Error: Can't resolve 'fs'
protoc-gen-go: program not found or is not executable
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation
E: Unable to locate package nvidia-docker2
Failed to load config "airbnb" to extend from. Referenced from:
Installation failed: Could not create directory. wordpress
retrofit problem Invoke-customs are only supported starting with Android O (--min-api 26)
Invoke-customs are only supported starting with Android O (--min-api 26)
wordpress-plugin-install-could-not-create-directory
Error: Cannot find module 'autoprefixer'
sudo: aptitude: command not found
laravel: command not found
unable to create process using
perl: warning: Please check that your locale settings:
perl: warning: Setting locale failed.
perl: warning: Falling back to the standard locale ("C").
E: Could not get lock /var/cache/apt/archives/lock - open (11: Resource temporarily unavailable) E: Unable to lock the download directory
NDK at /Users/Library/Android/sdk/ndk/21.1.6352462 did not have a source.properties file
Execution failed for task ':app:lintVitalRelease'.
command not found: neovim>
GPG error: stable InRelease:
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag.
database files are incompatible with server
Cannot find module '@angular-devkit/build-angular/src/angular-cli-files/models/webpack-configs/utils'
zsh: command not found: brew
Invalid package name "__ngcc_entry_points__.json": name cannot start with an underscore
@headlessui/react
Module not found: Can't resolve '@headlessui/react'
module not found: Can't resolve 'firebase'
/usr/bin/env: ‘bash\r’: No such file or directory.
No Xcode or CLT version detected!
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
Please provide a valid cache path
InvalidArgumentException Please provide a valid cache path.
gdebi: command not found
Fatal error: Unable to find local grunt.
Unable to resolve dependency tree error when installing npm packages
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR!
Module not found: Can't resolve 'web-vitals'
> Could not find method kapt() for arguments
react-native: command not found
The package needs to be reinstalled, but I can't find an archive for it
Cypress failed to start. This is usually caused by a missing library or dependency. The error below should indicate which dependency is missing.
does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
gcc add debug symbols
codecrepper npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree
Preview features enabled at an invalid source release level 15, preview can be enabled only at source level 16Java(2098258)
Module not found: Can't resolve 'react-redux'
ERROR: Version in "./docker-compose.yml" is unsupported. You might be seeing this error because you're using the wrong Compose file version.
SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir
Cannot find name 'process'
Error - [spfx-serve] Error: Invalid glob argument:
Could not find file \bin\roslyn\csc.exe
what is error make sure you have android development environment set up
go: not found The command
yarn ERROR: [Errno 2] No such file or directory: 'install'
Error: no repositories found. You must add one before updating
adb is not recognized
Module not found: Can't resolve '@emotion/react' in '/Users/arjungautam/Documents/VsCodeProjects/materialui-demo/node_modules/@mui/styled-engine'
gcc: Command not found
bash: bundle: command not found
brew not found
bash: /usr/local/bin/npm: No such file or directory
[!] No podspec found for `FBReactNativeSpec` in `../node_modules/react-native/Libraries/FBReactNativeSpec`
'NAME': BASE_DIR / 'db.sqlite3', TypeError: unsupported operand type(s) for /: 'str' and 'str'
active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
no xcode or clt version detected
This dependency was not found: * firebase in ./src/main.js To install it, you can run: npm install --save firebase
Error: Nest can't resolve dependencies of the RedisCoreModule (Symbol(REDIS_MODULE_OPTIONS), ?). Please make sure that the argument ModuleRef at index [1] is available in the RedisCoreModule context.
configure: error: no acceptable C compiler found in $PATH
Error installing cocoapods: ERROR: Failed to build gem native extension.
expo installation problem cannot be loaded because running scripts is disabled on this system. For more information, see abou t_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
can't find gem cocoapods (>= 0.a) with executable pod (gem::gemnotfoundexception)
Could not find mimemagic-0.3.10 in any of the sources
event-config.h file not found
Execution failed for task ':app:processDebugGoogleServices'.
ionic cannot be loaded because running scripts is disabled on this system. vscode
pycocotools command 'x86_64-linux-gnu-gcc' failed with exit status 1
ERROR: While executing gem ... (Gem::FilePermissionError)
License Android SDK not accepted
ModuleNotFoundError: No module named 'qrcode'
Failed to start DevTools: Dart DevTools exited with code 255.
Execution failed for task ':app:mergeDexDebug'
m1 cocoapods
clarifai 2.6.2 requires configparser
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
cannot update snap namespace: cannot create symlink in "/etc/docker": existing file in the way snap-update-ns failed with code 1
Cannot find module 'child_process'
groovy check if file exists
AAPT: error: resource android:attr/lStar not found.
import { createStackNavigator, createAppContainer } from 'react-navigation' error removed
tessbridge.cpp:5:10: fatal error: tesseract/baseapi.h: No such file or directory
react-native-push-notification Execution failed for task ':app:processDebugGoogleServices'
persist Uint8List to shared preference
the generatedepsfile task failed unexpectedly visual studio 2017
unity yaml set to unknown tool
extension unexpectedly stopped in vs code
CordovaPlugins dependency were found, but they required a higher minimum deployment target
error:02001003:system library:fopen:no such process
2 files found with path 'androidsupportmultidexversion.txt'. Adding a packagingOptions block may help, please refer to
ERROR: Failed building wheel for guidedlda
php.validate.executablepath wamp
native-run err_no_target
ERROR: Unknown command-line argument "-tgt-fs"
new world createfile failed with 32
tmpro could not be found
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', validator/src/bin/solana-test-validator.rs:294:71
Syntax error: "(" unexpected when execute a compiled c program
ios expo project not showing
Cimg Failed to recognize format of file
aapt.exe not found
could not load Ensure it is referenced by the startup project 'PDFCertificateWeb'
Running system mono/msbuild, ERROR: Invalid SDK MacOSX.sdk, not found in /Library/Developer/CommandLineTools/Platforms/MacOSX.platform/Developer/SDKs
DeprecationWarning: executable_path has been deprecated, please pass in a Service object
The IO action `main' is not defined in module `Main
expo error emfile too many open files watch
An error occurred (MalformedPolicyDocument) when calling the CreatePolicy operation: Syntax errors in policy.
ostream was not declared in this scope
codeship error if [[ -z ${SKIP_RSPEC} ]]; then bin/rake parallel:spec; fi
Windows/TEMP/ccOzwhEr:%20Invalid%20argument%20avr-gcc:%20fatal%20error:%20no%20input%20files%20compilation%20terminated.
/usr/share/metasploit-framework/modules/exploits/windows/http/rejetto_hfs_exec.rb:110: warning: URI.escape is obsolete
ios exception rctrefreshcontrol was unable to find its associated view
Sublime Text 3 Error: Package Control Locale Issues
ionic cannot find name 'Platform'
zsh: bad CPU type in executable: wine
System has not been booted with systemd as init system (PID 1). Can't operate
)
ionic cannot find name Directory
ionic cannot find name Filesystem
ionic cannot find name Encoding
error occurred while detecting hyperlinks eclipse
java.lang.noclassdeffounderror: failed resolution of: lcom/google/gson/gson;
Couldn't check the working tree for unmerged files because of an error. bad signature 0x00000000 index file corrupt
com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
If you do want to externalize this module explicitly add it to `build.rollupOptions.external`
zsh: command not found: julia
library not found for -lDoubleConversion
Plugin project :firebase_core_web not found. Please update settings.gradle
he project's Bundle ID is inconsistent with either the Bundle ID in 'GoogleService-Info.plist', or the Bundle ID in the options if you are using a customized options.
suid privilege escalation systemctl
Illuminate\Contracts\Container\BindingResolutionExceptionTarget class [ProjectController] does not exist.
cannot find module util uuid
Class 'ZipArchive' not found
Failed to load OpenH264 library: openh264-1.8.0-win64.dll
Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
problems opening an editor reason does not exist
The Mix manifest does not exist
Treating warnings as errors because process.env.CI = true. Most CI servers set it automatically.
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicuio.66.dylib
dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.67.dylib
xcode archive is disabled
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
xcrun: error: invalid active developer path (/Applications/Xcode.app/Contents/Developer),
The SUID sandbox helper binary was found, but is not configured correctly.
macos gradlew clean permission denied
npm ERR! code ELIFECYCLE npm error
Error: Cannot find module 'schema-utils'
AssertionError: View function mapping is overwriting an existing endpoint function: home
Could not find a part of the path ... bin\roslyn\csc.exe
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
Could not scan for classes inside which d oes not appear to be a file nor a folder
uses-sdk:minSdkVersion 16 cannot be smaller than version 19 declared in library
Your bundle is locked to mimemagic (0.3.5), but that version could not be found in any of the sources listed in your Gemfile
ERROR: dump failed because resource AndroidManifest.xml not found
command code not found mac
batch error code 9009
InvocationException: GraphViz's executables not found
Source "@openzeppelin/contracts/token/ERC20/ERC20.sol" not found: File import callback not supported
No SDKs were found after running dotnet --info
'nodemon' is not recognized as an internal or external command, operable program or batch file.
cordova-res' is not recognized as an internal or external command
selenium.common.exceptions.StaleElementReferenceException
npx create app not working eperm operation not permitted mkdir
`config.options.enableArithAbort`
xcode project archive option not available
utserver: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: No such file or directory
adb command not found
ouldn't adb reverse: device 'adb' not found ubuntu andrid emulator
modulenotfounderror: no module named 'openssl'
package system does not exist
the type or namespace azure does not exist
`FirebaseAnalytics` requires CocoaPods version `>= 1.10.0`, which is not satisfied by your current version, `1.5.2`.
minimum required opengl version (2.0) not found kivy
Cannot fit requested classes in a single dex file (# methods: 65710 > 65536)
Invariant Violation: Module AppRegistry is not a registered callable module
vs2019 ng serve missing Developer Command Prompt
why is intellij not opening
HelloWorld.c:1:10: fatal error: stdio.h
IllegalStateException: Cannot load driver class: oracle.jdbc.driver.OracleDriver
androidx-adapter: EXCEPTION: Failed to load dependencies: Error: Cannot find module 'recursive-readdir'
Could not resolve HEAD to a revision
flutter failed to build gem native extension
The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.2.99. (in target 'Flutter' from project 'Pods'
unity psd importer not working
kotlin.NotImplementedError: An operation is not implemented:
Expected linebreaks to be 'LF' but found 'CRLF'
com.zaxxer.hikari.util.DriverDataSource : Registered driver with driverClassName=com.mysql.jdbc.Driver was not found, trying direct instantiation.
libf77blas.so.3: cannot open shared object file: No such file or directory
raspberry pi numpy libf77blas.so.3: cannot open shared object file: No such file or directory
error: package android.support.annotation does not exist
OverwriteModelError: Cannot overwrite `UsersStore` model once compiled.
valueerror: could not get version for chrome with this command: google-chrome --version || google-chrome-stable --version
gradle threw an error while downloading artifacts from the network. retrying to download
Task 'wrapper' not found in project ':'.
heroku sh: 1: webpack: not found
code .is not recognized as an internal or external command
Execution failed for task ':app:kaptProdDebugKotlin'.
Xcode /Podfile.lock: No such file
Starting a Gradle Daemon, 1 busy Daemon could not be reused, use --status for details
Execution failed for task ':app:lintVitalRelease flutter build
Gradle include external jar
add external jar dependencies to grade build
Cannot run with sound null safety, because the following dependencies don't support null safety:
Library not loaded: /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib
class [App\Http\Middleware\EnsureEmailIsVerified] does not exist when there is a file
Error injecting: org.apache.maven.report.projectinfo.CiManagementReport
building for iOS Simulator, but linking in object file built for iOS, file
skipped loading symbols. module is optimized and the debugger option
Could not find tools.jar. Please check that
ng is not recognized
PANIC: Missing emulator engine program for 'x86' CPU.
Firebase deploy error - Cannot find module 'firebase'
./utserver: error while loading shared libraries: libssl.so.1.0.0: cannot open shared object file: no such file or directory
The minCompileSdk (31) specified in a dependency's AAR metadat
Class "Predis\Client" not found
functions predeploy error: command terminated with non-zero exit code1
Could not load dynamic library 'libcudnn.so.8'; dlerror:
remote: fatal: pack exceeds maximum allowed size
Description Resource Path Location Type Unbound classpath container: 'JRE System Library [JavaSE-11]' in project 'FirstProj' FirstProj Build path Build Path Problem
pg_dump command not found
CocoaPods could not find compatible versions for pod "EXFileSystem
numpy Original error was: DLL load failed: The specified module could not be found.
'chromedriver_win32' executable may have wrong permissions.
mvn' is not recognized as an internal or external command intelj
wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error+dd image
error: src refspec main does not match any
WARNING: cgroup v2 is not fully supported yet, proceeding with partial confinement
Task :unimodules-react-native-adapter:compileDebugJavaWithJavac FAILED
app:compileDebugJavaWithJavac FAILED
Could not initialize class com.android.sdklib.repository.AndroidSdkHandler
code command is not found in mac
go testing cannot find main module; see 'go help modules'
src refspec main does not match any
'choco' is not recognized as an internal or external command, operable program or batch file.
ImportError: libpng12.so.0: cannot open shared object file: No such file or directory
roovy.lang.MissingPropertyException: No such property: scope for class: com.android.build.gradle.internal.variant.ApplicationVariantData
ERROR: could not open extension control file "/usr/share/postgresql/10/extension/postgis.control": No such file or directory
NameError: name 'App' is not defined
MissingPluginException(No implementation found for method DocumentReference#setData on channel plugins.flutter.io/cloud_firestore
Error: 0x80370102 The virtual machine could not be started because a required feature is not installed.
Class 'Intervention\Image\ImageServiceProvider' not found
package javax.servlet does not exist
Message: 'chromedriver' executable needs to be in PATH.
libcusolver.so.9.0: cannot open shared object file: No such file or directory
Cannot find module 'autoprefixer'
ERROR: Could not find a version that satisfies the requirement ruamel
Expected linebreaks to be 'LF' but found 'CRLF'.
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3
How To Fix Error PS1 Can Not Be Loaded Because Running Scripts Is Disabled On This System In Angular
protoc-gen-go: program not found or is not executable Please specify a program using absolute path or make sure the program is available in your PATH system variable --go_out: protoc-gen-go: Plugin failed with status code 1.
error while loading shared libraries: libmod2.so: cannot open shared object file: No such file or directory
E: Sub-process dpkg --set-selections returned an error code (2) E: Couldn't clean the currently selected dpkg states
cmake keep debugging symbol
Failed to build build_runner
! [rejected] main -> main
error: src refspec develop does not match any
Could not resolve all files for configuration '
EPERM: operation not permitted, rename
An unhandled exception occurred: Job name "..getProjectMetadata" does not exist.
build runner command
ERROR Invariant Violation: requireNativeComponent: "RNCViewPager" was not found in the UIManager.
No CMAKE_CXX_COMPILER could be found.
'.' is not recognized as an internal or external command,
Permission denied @ apply2files - /usr/local/lib/node_modules/expo-cli/node_modules/timers-browserify/.DS_Store
include for sprintf
include for sprintf c++
c code to java converter
problems microsoft code c #include errors detected plaese update your includepath
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
FFMpeg\Exception\ExecutableNotFoundException Unable to load FFProbe windows
error: the sandbox is not in sync with the podfile.lock. run
Class 'Google_Client' not found in
Execution failed for task ':react-native-gesture-handler:compileDebugJavaWithJavac'
could not resolve a module for a custom reporter. module name jest-junit
NDK at Library/Android/sdk/ndk-bundle did not have a source.properties file
Cause: zip END header not found
A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade > java.lang.OutOfMemoryError (no error message)
A problem occurred evaluating project ':app'. > Plugin with id 'com.android.application' not found.
configurationmanager does not exist in the current context
cocoapods could not find compatible versions for pod cloud_firestore
[microsoft][odbc driver manager] data source name not found and no default driver specified (0) (sqldriverconnect)
The following packages have unmet dependencies: winehq-stable : Depends: wine-stable (= 5.0.2~focal) E: Unable to correct problems, you have held broken packages.
fatal: index file corrupt
Execution failed for task ':react-native-gesture-handler:compileReleaseJavaWithJavac'.
locate: can not stat () `/var/lib/mlocate/mlocate.db': No such file or directory
firebase_core_web not found. Please update settings.gradle.
fatal: could not lookup name for submodule
remote: error Command "webpack" not found.rails
bash: /usr/bin/node: No such file or directory
zsh: command not found: nvm
Error: pg_config executable not found. macos
vboxnetadpctl: error while adding new interface: failed to open /dev/vboxnetctl: no such file or directory.
Pods-Hepta/Pods-Hepta.debug.xcconfig: unable to open file
Your Android App Bundle is signed with the wrong key. Ensure that your App Bundle is signed with the correct signing key and try again. Your App Bundle is expected to be signed with the certificate with fingerprint
Module not found: Can't resolve '@reduxjs/toolkit'
default firebaseapp is not initialized in this process
ruby check if a file exists
dpkg: error processing package postfix (--configure)
Try updating your pubspec.yaml to set the minimum SDK constraint to 2.12.0 or higher, and running 'pub get
Navigator operation requested with a context that does not include a Navigator.
invalid active developer path (/applications/xcode.app/contents/developer)
'export' is not recognized as an internal or external command
DevTools failed to load SourceMap: Could not load content for
The system cannot find the path specified. npm script
AppData\Roaming\npm\ng.ps1 cannot be loaded
Failed to initialize NVML: Driver/library version mismatch
Could not find method compile()
'event2/event-config.h' file not found
could not find driver
NotImplementedError: Please use HDF reader for matlab v7.3 files
File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
Missing script: "dev"
libcublas.so.9.0: cannot open shared object file: No such file or directory
Module not found: Can't resolve 'react/jsx-runtime'
The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try
build environmet error
Module not found: Error: Can't resolve 'child_process'
error: no display environment variable specified
exec: "serve": executable file not found in $PATH
Manifest: Line: 1, column: 1, Syntax error
More than one file was found with OS independent path 'META-INF/AL2.0'. when running android test
Solve Cannot Install Dependency Error for NPM install
eresolve unable to resolve dependency tree react
1 error and 0 warnings potentially fixable with the `--fix` option.
if __name__ == '__main__': app.run(debug=True) not running
Class 'App\Models\DB' not found
Cannot find module 'ms'
No module named 'traitlets'
RLException: Invalid <param> tag: Cannot load command parameter [robot_description]: no such command [['/opt/ros/noetic/share/xacro/xacro.py', '/home/megara_1/catkin_ws/src/robot_description/urdf/robot.xacro']].
"protoc-gen-go: program not found or is not executable"
warning: LF will be replaced by CRLF
cargo add command not found
unable to resolve dependency tree
DeprecationWarning: executable_path has been deprecated, please pass in a Service in a class object self.driver = webdriver.Chrome
java.lang.runtimeexception: unable to load script. make sure you're either running metro (run 'react-native start') or that your bundle 'index.android.bundle' is packaged correctly for release.
Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib ruby
WARNING: This is a development server. Do not use it in a production deployment.
It is required that your private key files are NOT accessible by others.
Error: Unknown command: cask
npm update syntax
clone from git Could not find module "@angular-devkit/build-angular
error: unknown type name ‘uint64_t’
‘uint64_t’ was not declared in this scope
laravel Please provide a valid cache path
SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file
generatedpluginregistrant.registerwith(registry) error
error: incompatible types: PluginRegistry cannot be converted to FlutterEngine\
Could not build the application for the simulator
Execution failed for task ':app:checkDebugAarMetadata'. react native
Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
Task :app:lintVitalRelease FAILED
Error: bundle initial-es2017 exceeded maximum budget. angulra
org.apache.http.ProtocolVersion
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
Error: Cannot find module 'stripe' Require stack:
The method 'CachedNetworkImage' isn't defined for the type '_MainScreenState'.
commandFile.run is not a function
OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR)
Resource punkt not found.
Check /app/package.json: command not found. Is a start script missing?
configure: error: --with-openssl was given but OpenSSL could not be detected
Could not find package "build_runner". Did you forget to add a dependency?
symfony: command not found lunix mint
Usage: yarn [options] yarn: error: no such option: --template
'conda' is not recognized as an internal or external command,
An error occurred while trying to start ChromeDriver: cannot resolve path:
Error: package or namespace load failed for ‘ggplot2’ in loadNamespace(i, c(lib.loc, .libPaths()), versionCheck = vI[[i]]): namespace ‘rlang’ 0.4.7 is already loaded, but >= 0.4.10 is required
there is an instance of anaconda already running
the type or namespace name 'system' could not be found visual studio 2019
"export 'createStore' was not found in 'vuex'
the image file could not be opened. ionic
No module named 'progressbar'
sudo: yum: command not found
system.drawing class not found
fatal error compiling: invalid flag: --release
androidmanifest.xml could not be found.
Could not find a package configuration file provided by "ECM" (requested version 1.0.0) with any of the following names: ECMConfig.cmake ecm-config.cmake
Execution failed for task ':app:installDebug'.
libpq-dev depends libpq5
restcontroller cannot be resolved to a type eclipse
Target class [App\Http\Controllers\EmployeeController] does not exist.
dimsBackgroundDuringPresentation' was deprecated in iOS 12.0
command not found: code
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties) is greater than this module's compileSdkVersion (android-30). Dependency: androidx.work:work-runtime:2.7.0.
the mix manifest does not exist. (view: /home/daridart/domains/darydar.tn/public_html/resources/views/application.blade.php)
PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
the import org.mockito.junit.mockitojunitrunner cannot be resolved
This project references NuGet package(s) that are missing on this computer.
Module mpm_prefork is enabled - cannot proceed due to conflicts. It needs to be disabled first!
bundle.config in mvc is missing
ffmpeg: error while loading shared libraries: libopenh264.so.5: cannot open shared object file: No such file or directory
gcc: error: –o: No such file or directory
Terrain Tools unity missing
Could not resolve org.jetbrains.kotlin:kotlin stdlib jdk8:1.4.30
unhandled exception: missingpluginexception(no implementation found for method launch on channel plugins.flutter.io/url_launcher)
process tried to write to a nonexistent pipe
Another active Homebrew update process is already in progress
sequelize-auto : The term 'sequelize-auto' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
TypeError: You must specify a directory to build in path
java.lang.noclassdeffounderror: org/json/jsonexception
e unable to locate package pyrit
e unable to locate package pyrit in ubuntu
unhandled Exception: MissingPluginException(No implementation found for method Firebase#initializeCore on channel plugins.flutter.io/firebase_core)
W: Some index files failed to download. They have been ignored, or old ones used instead.
'React/RCTEventDispatcher.h' file not found
Failed to determine a suitable driver class mongodb
Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified and no embedded datasource could be auto-configured.
failed to determine a suitable driver class
Could not find com.google.android:cameraview:1.0.0.
cudatoolkit 11.1 and cudatoolkit 11.3
cudatoolkit 11.1 not found
/bin/bash^M: bad interpreter: No such file or directory
command not found mvn
Target class [AppController] does not exist.
shared preferences flutter
shared_preferences: 'latest version'
zsh: permission denied: ./gradlew
could not initialize sdl(no available video device) - exiting
Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
apt-key deprecated
ImportError: DLL load failed while importing _sqlite3: The specified module could not be found.
ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'z.routing'
xcode error: unable to find utility "simctl", not a developer tool or in PATH
'imagick' already loaded in Unknown on line 0
progrids not in package manager
Execution failed for task ':geolocator_android:compileDebugJavaWithJavac'.
Import "django.contrib" could not be resolved from sourcePylancereportMissingModuleSource
LoadError: cannot load such file -- parallel_tests/rspec/failures_logger
Must explicitly set engine if not passing in buffer or path for io
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
ERROR: Could not find a version that satisfies the requirement skin grabber (from versions: none) ERROR: No matching distribution found for skin grabber
modulenotfounderror no module named 'setuptools_rust' ansible
/vendor/phpunit/phpunit/phpunit' is not recognized
Composer detected issues
eazfuscator virtualization
command not found
The following build commands failed: PhaseScriptExecution [CP-User]\ Generate\ Specs
no bundle url present make sure you're running a packager server or have included a .jsbundle
failed to write core dump
Cannot proceed with delivery: an existing transporter instance is currently uploading this package
java.lang.NoClassDefFoundError: org/powermock/tests/utils/TestSuiteChunker
No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi
No cached version of org.jetbrains.kotlin:kotlin-android-extensions-runtime:1.5.31 available for offline mode.
Error in checking parameter list: AH00526: Syntax error on line 9 of /etc/apache2/ports.conf: Cannot define multiple Listeners on the same IP:port
ERROR: Failed building wheel for typed-ast
Apache is unable to check whether or not the module is loaded because Apache is misconfigured.
Use of unresolved identifier 'MFMailComposeViewController'
Cannot find module '@angular/platform-browser'
libgd-dev (missing):
tree is not recognized as an internal command
were invalid: EXPKEYSIG
MPI_STATUS_IGNORE
this app has no process types yet heroku but it has
Couldn't find that process type (web)
Flutter http package does not exist
Exception: Expected file android\gradle.properties
webdriver.Chrome() SessionNotCreatedExceptio
undefined reference to `PlaySoundA@12'
python webdriverexception message 'chromedriver.exe' executable needs to be in path
zsh: command not found: code
Error: Could not symlink share/systemtap/tapset/node.stp /usr/local/share/systemtap/tapset is not writable.
ERROR: Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.google.android.gms:play-services-ads-lite:[17.2.0]. Show Details Affected Modules: app
Error: Unable to find a match: ansible
Not an editor command: LspInstall
"export 'default' (imported as 'firebase') was not found in 'firebase/app'
No application found for TargetPlatform.ios.
Could not resolve androidx.test:core:1.3.0.
Docker Compose failed to build - Filesharing has been cancelled - eShopOnContainers
loadstring(game:HttpGet(""))()
The repository '... stable Release' does not have a Release file.
Multiple head revisions are present for given argument 'head'; please specify a specific target revision
ext-json' is missing in composer.json
Imagick was compiled against Image Magick version 1654 but version 1650 is loaded.
dot is not recognized as an internal or external command
DLL load failed while importing _multiarray_umath: The speci fied module could not be found.
unpacking the package... could not create directory. wordpress
composer config -g -- disable-tls true not working
held broken packages
clang-tidy iostream not found
clang cannot detect basic headers
Task :expo-updates:checkDebugManifest FAILED
Start : This command cannot be run due to the error: The system cannot find the file specified. At line:1 char:1 + Start "
\pyrcc_main.py: File does not exist 'resources.qrc'
npm run build npm ERR! Missing script: "build" for firebase
Resource and asset merger: Duplicate resources
DOTENV_CONFIG_PATH
command failed with EACCES android
Errors were encountered while processing: libglx-mesa0:amd64
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).
installutil is not recognized as an internal or external command
decompiling DEX into jar
'protoc-gen-dart' is not recognized as an internal or external command, operable program or batch file. --dart_out: protoc-gen-dart:
ENOENT, no such file or directory
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
emulator: ERROR: No AVD specified. Use '@foo' or '-avd foo' to launch a virtual device named 'foo'
Could not find method kapt() for arguments
if a path exists or not in PowerShell
error: cannot find module
Some problems were found with the configuration of task ':app:compileFlutterBuildRelease' (type 'FlutterTask'). Type 'FlutterTask' property 'assets' is missing an input or output annotation.
shell_exec() has been disabled for security reasons
ERROR: Could not find a version that satisfies the requirement OpenGL (from versions: none) ERROR: No matching distribution found for OpenGL
Updating from such a repository can't be done securely, and is therefore disabled by default. not secured Release' is not signed.
: error: package android.support.v4.content does not exist import android.support.v4.content.ContextCompat;
SDK Version Issue. This app was built with the iOS SDK. All iOS apps submitted to the App Store must be built with the iOS 14 SDK or later, included in Xcode 12 or later.
:latest not found: manifest unknown: manifest unknown
Access to the path 'C:\ProgramData\chocolatey\.chocolatey' is denied.
haskell load module
Error while merging dex archives
error: cannot find symbol if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
dpkg: command not found
Module not found: Can't resolve 'App.scss
A Livewire component was not found
manifest merger failed in android studio
react native the iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.5.99.
Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)
sinatra app.rb
unable to find valid certification path to requested targe
Execution failed for task ':app:kaptDebugKotlin'
: open failed: ENOENT (No such file or directory) android 10
Unexpected lock protocol found in lock file. Expected 3, found 0.
zsh: command not found: adb
warning: The iOS deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.2.99. (in target 'GoogleSignIn' from project 'Pods')
'scriptcs' is not recognized as an internal or external command, operable program or batch file.
no such file or directory
java.lang.NoClassDefFoundError
cannot execute binary file
opencv(4.4.0) c:\users\appveyor\appdata\local\temp\1\pip-req-build-71670poj\opencv\modules\imgproc\src\color.cpp:182: error: (-215:assertion failed) !_src.empty() in function
prolog not operator
phpstorm no reformat
"asm/bitsperlong.h: No such file or directory"
Compilation Error
unityads/unityads.h file not found
npx create-react-app v2 Error: EPERM: operation not permitted, mkdir 'C:\Users\Viktor' command not found: create-react-app
mini_ssl.c:145:7: warning: unused variable 'min' rails
yarn dev error eacces windows
file failed to open for writing (permission denied): /opt/ros/kinetic/share/maven/rospack_nosubdirs
ld: framework not found Pods_OneSignalNotificationServiceExtension
: El subproceso dpkg --set-selections devolvió un código de error
mnrm run watch compiles successfully but not working
Import "" could not be resolved
cannot find module is-doker
xamarin definition not found
error cannot find symbol pending intent
unhandled exception occurred: Schematic "component" not found in collection "@schematics/angular".
Execution failed for task ':cryptography_flutter:compileDebugKotlin'.
Execution failed for task ':android:validateSigningDebug'. > as_sys_sec_alg_ideaCBC
Please update to the latest Carthage version: 0.38.0. You currently are on 0.34.0
IOException: Failed to prepare target build directory. Is a built game instance running? UnityEditor.WindowsStandalone.WindowsDesktopStandalonePostProcessor.DeleteDestination (UnityEditor.Modules.BuildPostProcessArgs args)
rails notprecompiled
The command help is already an existing command or alias.
app:mergeDexDebug
xampp pdoexception could not find driver
windows missing dll files
E: Des valeurs entrant en conflit ont été renseignées pour l'option Signed-By à propos de la source cloud-sdk: /usr/share/keyrings/cloud.google.gpg !=
java.util.concurrent.CancellationException showing in suggestion
the .net core sdk cannot be located
ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'c:\\python39\\Scripts\\virtualenv.exe' -> 'c:\\python39\\Scripts\\virtualenv.exe.deleteme'
installation of package had non-zero exit status r windows).
ci/jenkins Expected — Waiting for status to be reported
mpg321 is not recognized
/var/tmp/rpm-tmp.issTeS: line 37: $'\r': command not found
could not find module "@angular-devkit/build-angular"
exec: "python": executable file not found in $PATH Error compiling for board ESP32 Dev Module.
Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platfo rm may not support it.
cannot run program mvn error=2 no such file or directory
webdev: command not found
/usr/bin/nvidia-modprobe: unrecognized option: "-s
how-to-fix-held-broken-packages
Could not find a declaration file for module 'crypto-js'
ansible error unzipping "Could not find a part of the path"
dyld: lazy symbol binding failed: Symbol not found: _OPENSSL_add_all_algorithms_noconf
SSLMutex', perhaps misspelled or defined by a module not included in the server configuration
glew init failed
xcode warnings fixme todo error
Invalid sourceApiVersion found in sfdx-project.json. Expected 49.0, found 51.0
The type or namespace name 'CefSharp' could not be found
(linux/arm) does not match the detected host platform (linux/amd64)
Cannot find module '../xcode' Require stack
fatal: malformed object name HEAD
error in unable to locate glob webpack
error path not found
UsersremiaOneDriveBureauProjet1: command not found
No location permissions are defined in the manifest. Make sure at least ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION are defined in the manifest.
webdriver.Firefox(firefox_binary=binary, executable_path=
fatal error: stdio.h: Ficheiro ou pasta inexistente
Uploading is not possible. App measurement disabled
Could not download aapt2-proto-4.1.0-alpha01-6193524.jar
ImportError: DLL load failed: The paging file is too small for this operation to complete.
error failed to build ios project. we ran "xcodebuild" command but it exited with error code 65
open config file without dependency injection
Errors: grub-efi-amd64-signed & shim-signed
Could not read source map for f@google-cloud/storage/build/src/channel.js: ENOENT: no such file or directory
package manager hlapi unity 2020
gcc fatal error
GeneratedPluginRegistrant.m:10:9: fatal error: module 'cloud_firestore' not found @import cloud_firestore;.
v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
Description: The job has failed because the VSS snapshot could not be created
bean not found
Pulling sail project to a computer with no local php / composer installed
the associated script cannot be loaded
ORA-39168: Object path STATISTICS was not found.
Running multiple emulators with the same AVD is an experimental feature
exception not showing line number
Exception has occurred: SystemExit usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied
permission denied, open '/Users/johannbuscail/.config/yarn'
stylelint config Error: ENOENT: no such file or directory
Can't locate API module structure `php7_module' in file C:/php/php8apache2_4.dll:
video id not found
crosscheck archvelog and delete failed
error: No file attributes configured
published net core did not have wwwroot
platforms\android\app\src\main\res\xml\network_security_config.xml:7: AAPT
"E: Unable to locate packet snort"
java.lang.IllegalStateException: Could not obtain identifier
Possible missing firmware /lib/firmware/nvidia/tu102/sec2/desc.bin for module nouveau
vscode unable to open extension xhr failed
aestan tray menu configuration file syntax error on line 0
webdriver cannot be resolved to a type
what does this means Error on line 78, column 4 of pubspec.yaml: Expected a key while parsing a block mapping.
CocoaPods could not find compatible versions for pod "Capacitor":
nmake.exe is not found in the windows
gradle failed to build capacitor.settings.gradle' as it does not exist.
if (! File::exists(public_path()."uploads/properties")) { File::makeDirectory(public_path()."uploads/properties"); }
Error: Directory not empty @ dir_s_rmdir - /usr/local/Cellar/python/3.7.3
Error: Could not execute bundle monit
MODPOST /home/umar/Desktop/hw3/2/Module.symvers ERROR: modpost: missing MODULE_LICENSE()
manifest merger
#include <OneWire.h> arduino no such file or directory
unable to open include file unistd.h
go docker $GOPATH/go.mod exists but should not The command '/bin/sh -c go mod download go build -o main' returned a non-zero code: 1
AppStore Provisioning Profile Get this profile file from the iTunes store.
Rails public folder items not available in production
Save Uint8List to shared-preference
LockExistsError: Lock already being held for file
Note: Please add this to the release build type in your app build.gradle to avoid crashes on android release builds
@Inject(PLATFORM_ID)private platformId
E: No se pudo abrir el fichero de bloqueo «/var/cache/apt/archives/lock»
"Class 'League\\Flysystem\\Cached\\Storage\\AbstractCache' not found
“jdk” can’t be opened because it was not downloaded from the App Store elastic search
Error: Unable to locate env file at default location (./.env)
package not found in package manager unity
vs scaffolding identity package restore failed
unable to resolve module @firebase/app
applicationcomponent hilt not found
Vagrant RawFile failed to create the raw output file
error itms-90086 missing 64-bit support
necessarAndroid SDK does not include your Target SDK of 28.
yarn No such file or directory: 'init' Linux Ubuntu
/bin/grep: /sbin/init: No such file or directory
MissingPluginException(No implementation found for method share on channel flutter_share)
./if: The term './if' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
ahk2exe error Error: Could not move final compiled binary file to destination. (CI)
rnimagepicker error This library does not require Manifest.permission.CAMERA, if you add this permission in manifest then you have to obtain the same.
parse error - invalid geometry postgis
pmc not recognising migration
Malformed SCM_RUN_FROM_PACKAGE when uploading built content.
debian md5sum: command not found
public static Int64 m_pSpottingTargetComponentData
On the deployable machine, what is the file type of "unknown1" in "tryhackme's" home directory?
The --org command line argument must be specified to recreate project.
Error: Cannot find module 'prettier' for vs code apex
apple configurator 2 downloaded ipa location
Could NOT find Boost (missing: filesystem)
Lumen (8.2.4 ) There are no commands defined in the "vendor" namespace.
conflicting provisioning settings error when I try to archive to submit an iOS app
java.io.FileNotFoundException: /home/user/.gradle/daemon/6.7/registry.bin.lock (Permission denied)
InvalidArgumentException] Could not find package maatwebsite/excle.
gdiplus compile errors
Module is optimized and the debugger option
inSdkVersion 16 cannot be smaller than version 21 declared in library [:appcenter
Cannot load ClearScript V8 library. Load failure information for ClearScriptV8.win-x86.dll:
failed. CAfile: none CRLfile: none
'export' is not recognized as an internal or external command, operable program or batch file.
Gem::MissingSpecError : “Could not find ‘ed25519’ mac os
cannot create directory no such file or directory
ERROR:: AAPT: error: resource style/Widget.AppCompat.TextView (aka com.detoxexample.test:style/Widget.AppCompat.TextView)
The application “Anaconda-Navigator” can’t be opened.The application “Anaconda-Navigator” can’t be opened.
yarn: error: no such option: --integrity in docker
missing
create if not exists neo4j
'statusBarFrame' was deprecated
conda command not found
ReflectionException::(Class DriversSeeder does not exist)
intellij cannot access
centos remote desktop
katelyn_runck
No publishable resources for tag [activitylog-migrations].
Error: EPERM: operation not permitted, copyfile
Invalid element name: - dependency One of the following is expected: - parent - packaging - name - description - url - inceptionYear - organization - licenses - developers -
Import " xxx module" could not be resolvedPylance (reportMissingImports)
libc-bin error #2
install homebrew without errors like : ambiguous argument 'refs/remotes/origin/master': unknown revision or path not in the working tree.
intellij cannot build artifact
stuck Starting a Gradle Daemon (subsequent builds will be faster)
.swhat does this means :app:dataBindingMergeDependencyArtifactsDebug'. > Could not resolve all files for configuration ':app:debugCompileClasspath'
maven invalid flag: --release
reason: failed to load driver class com.mysql.cj.jdbc.driver in either of hikariconfig class loader or thread context classloader
Failed to mount cgroup at /sys/fs/cgroup/systemd: Operation not permitted
The system cannot find the file
a fatel error occurred liobrary hostfxr.dll not found
The type com.google.protobuf.GeneratedMessageV3 cannot be resolved. It is indirectly referenced from required .class files
COPY failed: no source files were specified
bad configuration
--perhaps a missing \item
latin failure is not an option
Unresolved reference: GsonConvertorFactory
framework not found Protobuf
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /mnt/c/users/hp/desktop/prompt_app/src/Dockerfile: no such file or directory
c# resource file doesn't get moved to output
failed to read artifact descriptor for com.adobe.acs:acs-aem-commons-bundle:jar:3.17.2: could not find artifact com.adobe.acs:acs-aem-commons:pom:3.17.2 in central ()
$GOPATH/go.mod exists but should not
usr/bin/ld: skipping incompatible /home/guta/intelFPGA/18.1/hld/host/arm32/lib/libalteracl.so when searching for -lalteracl
Class 'BinaryCats\Sku\SkuServiceProvider' not found
chmod: cannot access 'ADB': No such file or directory
error failed to download metadata for repo 'appstream'
AAPT: error: resource style/AppTheme (aka com.aryabhattanursing:style/AppTheme) not found.
Package laravel/ui at version 2.4 has a PHP requirement incompatible with your PHP version,
could not autowire no beans of type found
Failed assertion: line 1927 pos 12: 'hasSize'
no suitable driver found for jdbc:mysql:
CentOS Extras aarch64 epel-release-8-8.el8.noarch.rpm
@react-navigation/bottom-tabs package itself specifies a `main` module field that could not be resolved
aqueduct is not recognized
expo urboModule Registry.set Enforcing(...): 'Linking Manager' could not be found.
laravel install problem solution
unresolved reference launch kotlin
kavenegar error code 411
process finished with exit code 0 intellij
System.PlatformNotSupportedException compiler
NodeJS Google Vision is unable to detect a Project Id in the current environment
Failed to resolve loader: worker-loader
Error: package or namespace load failed for ‘tidyverse’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
A problem Could not read script 'plugins/dynatrace-cordova-plugin/files/plugin.gradle' as it does not exist.
do moorhens still exist?
common_site_config in frappe
Fatal error: Cannot redeclare excute() (previously declared in
#include <gst/gst.h> compilation terminated. jetson nano
the include file package:flutter_lints/flutter.yaml cannot be found.
C1083: Cannot open include file: 'd3dx9.h': No such file or directory
error: unable to lookup item 'Path' in SDK 'iphoneos'
dotnet-ef: command not found
CONFIG_X86_X32 enabled but no binutils support
Skipping device 'emulator-5554' for 'app:debug': Unknown API Level
windows/amd64 10.0.17763 in the manifest list entries
Delta compression using up to 32 threads fatal : unable to create
Error: Failed to lookup view "roomlist" in
The following signatures were invalid: EXPKEYSIG 964B5E720AA4F31A Sonatype Community <community-group@sonatype.com>
Exception: Please correct the pubspec.yaml file at ./pubspec.yaml
Suspect!3c7a26bbbb6e
sh: /Applications/WhatsApp.app: is a directory mac
internal app sharing link not found
launch:program does not exist
kernel does not boot 5.13.0-23-generic
zoom sdk not initialized
AAPT: error: <adaptive-icon> elements require a sdk version of at least 26.
gem install puma
duplicate xaml compilation attribute
package itself specifies a `main` module field that could not be resolved
Unable to find a specification for `UMFileSystemInterface` depended upon by `EXContacts`
expo osascript -e tell app "System Events" to count processes whose name is "Simulator
Caused by: org.gradle.cache.internal.btree.CorruptedCacheException: Corrupted DataBlock 1892864 found in cache '/Users/apple/.gradle/caches/journal-1/file-access.bin'.
nativescript build debug apk
the import org.hamcrest.matchers cannot be resolved
jquery DevTools failed to load source map: Could not load content for
symfony 4 Error: Invalid PathExpression. Must be a StateFieldPathExpression.
filename not matched: /usr/local/ignition/
expo issue Cannot find module 'jsonfile/utils'
The term 'Get-TransportConfig' is not recognized as the name of a cmdlet, function, script file, or operable program.
error ‘sdl_blitscaled’ library
host name may not be empty android studio
Backreferences To Failed Groups
test the application if the requirements are not available
library not found for -lssl
fatal error LNK1181: cannot open input file 'Irprops.lib'
/snap/snap-store/518/usr/bin/snap-store: symbol lookup error: /snap/snap-store/518/gnome-platform/usr/lib/x86_64-linux-gnu/libgtk-3.so.0: undefined symbol: atk_plug_set_child
dbal driver not found
analysis_options.yaml cannot be found.
Error: ENOENT: no such file or directory, lstat \node_modules\@react-navigation\core\src\getStateFromPath.tsx
error: resource android:attr/lStar not found.
truffle/assert sol not found
Error CS0246 The type or namespace name 'Form1' could not be found (are you missing a using directive or an assembly
'flutter/flutter.h' file not found
how can i check permission strage in xamarin
liblua.a: No such file or directory
#file: "/media/imprint/software/projects/sookh/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php"
env\scripts\activate cant load
unable to access jupiter assertions
Task 'projectReport,' not found in root project 'icepdf-os'. Some candidates are: 'projectReport'.
nodemon not detect any file chages in linux
An unhandled exception occurred: Cannot find module './isArrayLike'
aspnet_regiis not recognized
114:25: AAPT: error: resource android:attr/lStar not found.
see the log file error in eclipse
General error Unable to open registry key Temporary
How to solve bad signature... index file corrupt
sh: /Applications/PyCharm: No such file or directory
macos catalina fatal error: 'stdio.h' file not found
Could not refresh actions for navigator org.jenkinsci.plugin.gitea.GiteaSCMNavigator@69ec289c org.jenkinsci.plugin.gitea.client.api.GiteaHttpStatusException: HTTP 404/Not Found
repositories.cfg could not be loaded
Publishable packages can't have path dependencies. Try adding a 'publish_to: none' entry to mark the package as not for publishing or remove the path dependency.
gem install therubyracer
the pipe async could not be found
file ignored because of a matching ignore pattern. use "--no-ignore" to override
odoo 11 while loading problem this error occured while compiling the bundle 'web.assets_common' containing odoo10
Could not get unknown property 'android' for project ':app' of type org.gradle.api.Project
install alpine plugin x-trap
turmex cloning commands no checkpoint
bash: rspec: command not found
E: Unable to locate package rbp-userland-dev-osmc
import { Device } from '@ionic-native/device'; not working
.woff not found error
The CUDA compiler identification is unknown CMake Error at CMakeLists.txt:441 (enable_language): No CMAKE_CUDA_COMPILER could be found.
expo\appentry.js: cannot find module './transformation/file/file'
Unable to load dynamic library 'clos_ssa.so'
Unused import: 'dart:io'. Try removing the import directive.
a reference to x could not be added circular dependency c#
Access to the path 'D:\$RECYCLE.BIN\S-1-5-18' is denied.
psql.exe not found
Xcode xip “The archive does not come from Apple”
win32api dll load failed kernel
Got it run as usual, however, systemd is not running, although it does exist in the file system
unity package manager progrids
dpkg: unrecoverable fatal error, aborting: files list file for package 'libhdf5-dev' contains empty filename
cron pipe error output to file
java.lang.RuntimeException: cannot find implementation
app/View/Errors/missing_controller.ctp
cannot download ios 10.3.1 simulator in xcode12
kylekatarnls/update-helper does not exist and could not be created
[RuntimeException] Could not delete /var/www/html/docroot/web/sites/default/default.services.yml:
bundler requires RubyGems version >
Jacoco with Maven - missing execution data file
Test suite failed to run ReferenceError
Error: Truffle is currently using solc +
copy-globs-webpack-plugin compilation.fileDependencies.has is not a function
Error: `createStackNavigator()` has been moved to `react-navigation-stack`.
publish-error-found-multiple-publish-output-files-with-the-same-relative-path
packages cannot have path dependencies
gcc not found as an external or internal command
WARNING: 'makeinfo' is missing on your system
my device is not showing in the list of adb devies\
it is showing bodies is not defined error visual studio
The configuration section 'log4net' cannot be read because it is missing a section declaration
reac native /bin/sh: adb: command not found
configure: error: Could not find /usr/lib/libsybdb.a|so
SOLVED: "Application" is damaged and can't be opened in macOS Sierra
Attempted to load class “WebProfilerBundle” from namespace “Symfony\Bundle\WebProfilerBundle” when deploying on Heroku using development dependencies
error: Multiple commands produce '/platforms/ios/build/Debug-iphonesimulator/myhorses.app/Frameworks/TNSWidgets.framework'
platforms/android/app/build/outputs/apk/debug/app-debug.apk [ERROR] An error occurred while running subprocess cordova.
A problem occurred configuring project ':app'. > groovy.lang.MissingPropertyException: No such property: ABI for class: org.gradle.api.tasks.OutputFile
namespace gtk not available conda
first, you need to generate a signing key using keytool and create keystore file for your project. Move to android/app/ directory in your terminal and run this command to create a new one on Mac.
jasmine karma 'pipe' could not be found!
error this build is outdated
unresolved compilation error int test[5] = {1, 2, 3, 4, 5}
E/MAINDEBUG: No ad config.
fatal error: yaml.h: No such file or directory
Failed to download package 'runtime.win10-x86.Microsoft.Net.Native.SharedLibrary.2.1.8'
Could not load file or assembly 'System.Security.Permissions
active developer path does not exist
[!] Automatically assigning platform `iOS` with version `9.0
Could not open /dev/vmmon
ffi gem error mac
unable to load the service index for source https //
ERROR: Service 'webapp' failed to build : When using COPY with more than one source file, the destination must be a directory and end with a /
vb6 adding control win7 "object library not registered" Richtx32.ocx
cannot find symbol BuildConfig.APPLICATION_ID + ".reactnativefirebaseappinitprovider"
File 'com.android.builder.files.ZipCentralDirectory@7adb3185' was deleted, but previous version not found in cache
no application app licenses found
** (Mix) Invalid option: --live
could not decode base64 cloudinary
No module named "podm"
package org.netbeans.lib.awtextra does not exist
could not create key: \SOFTWARE\Meld
folder Controller" not found
exec user process caused: no such file or directory
visual studio cannot find create dbml
Module not found: Can't resolve 'google-spreadsheet'
error: no pubspec.yaml file found. this command should be run from the root of your flutter project.
WSL2 request to failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
sample fix config file
MissingMethodException: PlayerManager.OnPlayerLeft Due to: Attempted to access a missing member.
Error: Could not find "stylelint-scss". Do you need a `configBasedir`?
.dsc: Unknown section 'unknown'
helm3 global: imagePullSecrets: - name: regcred
Error: Cannot find module 'multiparty'
Checking the license for package Android SDK Build-Tools 28.0.3 in /home/
rvm stderr: bash: /usr/local/rvm/bin/rvm: No such file or directory
Error: No Homebrew ruby 2.6.8 available for arm64 processors!
Could not initialize class com.intellij.pom.java.LanguageLevel
Webpacker::Manifest::MissingEntryError in Events#index
Error NU5012: Unable to find bin\Release dll Make sure the project has been built.
tempcoderunnerfile.cpp:1:1: error: does not name a type
warning: Building for iOS Simulator, but the linked and embedded framework 'TNSWidgets.framework' was built for iOS + iOS Simulator
NOT FOUND
You are not inside a Hardhat project.
please check gdb is codesigned - see taskgated(8)
To set up the apt repository for stable nginx packages, run the following command:
Maven executable not found in PATH. Please specify "maven.executable.path"
Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again.
yocto sdk build error
ondevice ready not calling on ios
Class 'doctrine/dbalDriverPDOMySqlDriver' not found
rmmod: ERROR: Module nvidia_drm is in use
FAILURE: Build failed with an exception. * What went wrong: Could not initialize class org.codehaus.groovy.runtime.InvokerHelper
/Users/sanguine/Tutorial/c_web/Fresh/Fresh/Fresh.csproj: Error MSB4236: The SDK 'Microsoft.NET.Sdk' specified could not be found
flutter the asset does not exist.
"when run flutter doctor in cmd show error ""some android studio licence is not accepted "
zipline ImportError: DLL load failed: The specified module could not be found.
The project: ioapplet which is referenced by the classpath, does not exist.
#include <iostream> using namespace std; int main()sdlkafsldjfñlksajdflsjfdñlkj
how to write executable for ios on windows
executable library dependency check
RNCWebViewModule.java:276: error: cannot find symbol
unknown system group 'smmsp' in statoverride file; the system group got removed
c# filenotfoundexception could not load file or assembly microsoft data sqlite
ex:beans
what to do when delphi says cannot creat output file
laradock xdebug launch.json
javax.annotation.PreDestroy cannot be found by org.eclipse.e4.
error: ‘va_start’ was not declared in this scope
(game:HttpGet(""))()
Eaccess docker vscode
E: Unable to locate package ros-noetic-depthimage-to-laserscan
erreur de segmentation (core dumped)
The system cannot find the path specified when tryiong to add service reference
Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
libboost_thread.so.1.72.0: cannot open shared object file: No such file or directory
Error: Could not find "stylelint-config-standard". Do you need a `configBasedir`?
#error <thread> is not supported when compiling with /clr or /clr:pure.
./gradlew bundleRelease apk folder missing
error running `xcrun simctl list devices --json`: you may need to run sudo xcode-select -s /applications/xcode.app and try again.
mkdir: cannot create directory ‘/shared’: Permission denied capistrano
HOW DO I FIX THE ERROR ‘UNABLE TO FIND THE WRAPPER “HTTPS
kylekatarnls/update-helper 1.1.1 requires composer-plugin-api ^1.1.0 -> found composer-plugin-api[2.0.0] but it does not match the constraint.
errorviewmodel could not be found
manpath: can't set the locale; make sure $LC_* and $LANG are correct
installshield intel64 or amd64 must be specified stackoverflow
publishing license or creators license unreal engine
at _AstToIr Visitor.visit Quote (C:\wamp64\www\MAC\MACIE\node_modules\@angular\compiler\bundles\compiler.umd.js:9123:19)
is an executable program. for safety it will not be started
docker error 2 matches found based on name network is ambiguous
Can't locate path: <C:\xampp\htdocs\B2B\B2B-1.1.0\packages\Itec\Sales\src/resources/database/migrations
intellij gradle sync dependencies
no-plusplus lint error fix
ImageManagerStatic not found
exception handling disabled use '-fexceptions' to enable CMake
#ifdef in podfile
Error: Error Updating IAM Role (lambda_exec) Assume Role Policy: MalformedPolicyDocument: Missing required field Principal
code/CMakeFiles/assimp.dir/Importer/StepFile/StepFileGen1.cpp.o' failed
Windows only: Native build dependencies
no such fie exception
FBSDKUserDataStore.h' file not found
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Cannot open file, path = '/sdcard/download/Jolt.mp4' (OS Error: Permission denied, errno = 13)
'dart' is not recognized on VS
loadstring(game:HttpGet(""))()
not create if exist neo4j
vscode private repository remote: Repository not found.
what is application error in global.asax
the selected build configuration is using the shared mono
The type or namespace name 'IConfiguration' could not be found
DLL load failed while importing _ssl: The specified module could not be found.
unable-to-locate-a-class-or-view-for-component
std::enable_shared_from_this include
Class not found in Psy Shell code on line
why classpath resources is not showing files in eclipse
error detected in pubspec.yaml
failure vs defect
Maven error 501
checksum error
Execution failed for task ':app:validateSigningDebug'. > Keystore file '/Users/apple/Documents/GitHub/tfbrandnew/android/app/debug.keystore' not found for signing config 'debug'.
1>LINK : fatal error LNK1104: cannot open file 'glfw3.lib'
How to rerun the failed tests again in TestNG?
[Running] scriptcs "c:\Users\Aaditya Joshi work\Documents\Aaditya Joshi\tempCodeRunnerFile.csharp" 'scriptcs' is not recognized as an internal or external command, operable program or batch file.
maven download dependencies to folder
Warning: 2 possible package resolutions (only showing differing packages):
error while loading shared libraries: libz.so.1
Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package
error: could not install packages due to an oserror: [winerror 2] the system cannot find the file specified:
Path.op() not supported
Could not parse the Android Application Module's Gradle config. Resolve gradle build issues and/or resync.
error statuslogger log4j2 could not find a logging implementation
error statuslogger log4j2 could not find a logging implementation. please add log4j-core
android studio not open missing essentian plugin
There seem to be a transient problem with Expo servers, using the cached dependency map (bundledNativeModules.json) from the package "expo" installed in your project
clear watchmam wathc
Failed to fetch
Illuminate\Database\QueryException could not find driver windows
what does error CS1022: Type or namespace definition, or end-of-file expected
the process cannot access the file because another process has locked a portion of the file
could not load file or assembly
vim: command not found centos
RuntimeError: Failed to process string with tex because latex could not be found
Failed to find .env file at default
invalid prettier configuration file detected. see log for details.
Can't open C:\ci\openssl_1581353098519\_h_env\Library/openssl.cnf for reading, No such file or directory
Unable to find package 'Microsoft.VisualStudio.TestTools.UnitTesting
error in haskell
There is no extension able to load the configuration for "_translation_webui"
javax.persistence.EntityNotFoundException: Unable to find spring save repository
rc.local not running
Reading package lists... DoneBuilding dependency treeReading state information... DoneE: Unable to locate package android-sdk-platform-tools-common
"Error: pg_config executable not found."
Dependency is not satisfiable: realpath
RNGestureHandlerModule pod spec
Bad state: Unexpected diagnostics:
how to add the package containing the executable pg_config
npoifsfilesystem cannot be resolved latest version
GPG error: stable Release: The following signatures were invalid: KEYEXPIRED
import { plugins } from '@capacitor/core'; cannot find
Member shr4.o is not found in archive in AIX 7.2
*** Missing development files for the GeoIP library
Please select the Solidity (*.sol) files for upload *
how to set include package parameter in error prone command line
'AppKit/AppKit.h' file not found
Plugin [id: 'com.bmuschko.tomcat'] was not found in any of the following sources:
No roam key found
Some conflicting dependencies were found. The following dependency versions were modified: com.android.support:appcompat-v7:25.3.1
The Dev Hub org cannot be deleted.
hdbcli.dbapi.Error: (-10104, 'Invalid value for KEY, directory search path:
dpkg: error processing package newrelic-infra (--configure):
runonuithread not found-extension npm
redux devtools
nodemon
nodemon node
installing nodemon in windows
logan paul net worth
jake paul
latex text size
delta symbol
delta
use npm to update packages to latest version
input file define type
update all dependencies npm package.json
update all dependencies with npm
file input file types
input type file filter extensions
.htaccess file
wordpress default htaccess
wordpress ht access file
arch
flutter create new project
myspace
find out process using port windows
pm2 start npm start
pm2 start with name
pm2 starts npm run start
flutter web
image modal in bootstrap
how to enable flutter web
bootstrap modal center
flutter enable web command
modal form bootstrap
stripe test card
bootstrap button group
December global festivities
add background image in bootstrap 5
nvm for mac
links
git remote add wrong thing how to remove
remove remote origin already exists.
dark gray hex
nodemon install ubuntu 20
nodemon global instal npm
install nodemon
install nodemon globally
node mon
install nodemon npm
apex legends
apex legneds
android glide
flutter sdk path
flex all child same width
large button in bootstrap
regex 10 numbers only
extract text from image online
how to update requirements.txt
command to make requirements.txt
necrophilia
nitric acid
get data in from a collection firestore
checking the npm version
bootstrap overflow hidden
overflow hidden in bs4
overflow bootstrap
how to set a div size to full screen
make a div full screen css
windows 10 search bar not working
windows start menu is not working
npm concurrently
how to check rabbitmq vhosts
https redirect htaccess
cut audio using ffmpeg
create a database in matlab
leo masseglia
what is system testing
teenage pregnancy affect child and mother
does csgo have cheaters
chocolatey
grepper test
rejetto http file server metasploit
move word forward linux
open new window in selenium
mac terminal curl
qwebengine download
if else c language
excel F
the abscissa of the point on the curve 3y = 6x - 5 x cubed , the normal at which passes through origin is
helloworld
how do i do hello world in scratch plz thank you
50 second timer
MEN'S LIGHTWEIGHT RECYCLED POLY-FILL PACKABLE JACKET
vs code how to add path in brave browser
solc assert.js:339 throw err
bootstrap background transparent
how to create a line in xml
cmd get serial number
nginx if location proxy_pass examples
Gitlab docker installation
extranet significado
address already in use :::3000
randomgen
how to add a limit in owl-carousel
infyom generator
ngfor
yarn ERROR: [Errno 2] No such file or directory: 'install'
container fixed width flutter
arrow functions javascript
what is your team velocity
leap year 0r not
snake
facotrs of 9
Create an environment and venv folder
how to create a rectangle class in java
How to steam buns
readme.md table
sap delete workflows report
getx arguments
time complexity bubble sort
register temporary table pyspark
Code=1011 “Display Format Mismatch” facebook
light indicator
qt windows.h lnk2019
set tick params for all subplots
tf2 lerp
increase xlabel font size matplotlib
claim faucets
texshop fast comment
what does tbh & idk mean
how to pass headers in axios
translate english to spanish
android loop array
flatpak repo
Viewmodel provider
hubris meaning
what kind of exception after explicit wait
what jenkins job
Flutter give image rounded corners
open weather api
how to add icon in input button
cst pika quality
Null check in angular template
where do you keep test data in api
forward and back mouse buttons not working in vmware ubuntu
nginx syntax check
jay z oj simpson lyrics
javascript desktop app
golang reload server
how to center items in bootstrap
layout preview not showing android studio
unreal engine operators
mongodb default log path
splunk rex field=_raw
advance logic in css
how to check 504 response using curl
how to cout 4 dimensional cv::Mat
if equal to excel
pagination bootstrap
rx5500m vs gtx 1650ti
handsprit på skärm
view error bag associate array
close app with terminal
HTTP ERROR 403 No valid crumb was included in the request\
c== clear screen
passing variables from python to html
scroll in sfchart xamarin
keras conv2d
ex-libris meaning
Save current page as HTML to server
how to locate symlink location
skip main content - keyboard accessible buttons on navbar
<style type="text/css"> body {cursor: url();} </style> <a href="" title="get free cursors for your web.">kokichi oma cursors</a>
how to share code
dissuade sentence
r markdown page break
next field
Display an image over another image at a particular co-ordinates in openCV
insert commands to create three new folders with mac
2001 a space odyssey
object has property godot
how often api deprecated
jhonny
pip Fatal error in launcher: Unable to create process using e:\python\python39\python.exe
how to format textbox thousand separator
What is the code for Arduino Board reset
north west india
funny spongebob quotes
How to make mat-icon disabled in angular?
set developer mode docker magento 2
javascript coding questions
super lig puan durumu
shake animation android
who was live and let die song made for
what is bundesliga
Cannot find name 'process'
file upload
change column type snowflake
how to restart postgres mac
how to update ui with increase of database changes
protractor sleep example
difference between .append and .appendChild
sdlc stands for
Payumoney Could not save Webhook. There was an exception posting data to the url. HTTP call status: 419
how to view the code in your raspberry pi
rdkit
Redirect request .htaccess–%202 019%20legal%20aspects%20of%20business%20_%20602%20(new).pdf
new library comand rust
import bson to mongodb
how to cat a file that has spaces
Apache2
create a new repository on the command line
how to respond to options request
css window id
view model android
clip video using ffmpeg
fetch assoc oop
ret, img_frame = cap.read()
Spring Boot API Gateway Unable to resolve name
atal: Could not parse object
header file
minecraft allocate ram
fun roblox games to play when your bored
Group based sort pandas
how to save recyclerview state in android
drag and drop primefaces
streamlit beta columns
definition watt
float vs inline
flutter call provider in initstate
axon stream read
for loop in oracle
FTPSMTPDNS
node-localstorage example
covid 19
nested table in markdown
"Implement a binary search algorithm in your function"
verticle line css
samsung s3 in odin mode, but oding doesnt see it
macd in mt5 is different
getting uid of user firebase flutter
rails scope alias
ios standalone web-app window.open
rest
New bundles must use latest available Audience Network SDK.
instance variables
position of item in array dart
how to show values in pie chart using jfreechart
Strategy " v2ds " ( demand & supply )
object of type 'Response' has no len()
i am bored..
server error
nginx https
flutter datetime add hours
> Task :app:dataBindingMergeDependencyArtifactsStagingDebug FAILED
react js docker
heroku select appp
apex list remove duplicates
How to make String.Contains case insensitive?
gaming chair
simbolo composicion latex
how to use constructors in framework
dereference
BusyIndicator
list all branhces git
No module named 'object_detection'
Domain name should not be "localhost" or "127.0.0.1 instamojo
regex bearer token
viewport
. | https://www.codegrepper.com/code-examples/whatever/yarn+dev+error+eacces+windows | CC-MAIN-2022-05 | en | refinedweb |
lookup (3) - Linux Man Pages
lookup: exchange-rate repository
NAME
QuantLib::ExchangeRateManager - exchange-rate repository
SYNOPSIS
#include <ql/currencies/exchangeratemanager.hpp>
Inherits Singleton< ExchangeRateManager >.
Public Member Functions
void add (const ExchangeRate &, const Date &startDate=Date::minDate(), const Date &endDate=Date::maxDate())
Add an exchange rate.
ExchangeRate lookup (const Currency &source, const Currency &target, Date date=Date(), ExchangeRate::Type type=ExchangeRate::Derived) const
void clear ()
remove the added exchange rates
Friends
class Singleton< ExchangeRateManager >
Detailed Description
exchange-rate repository
Tests
- lookup of direct, triangulated, and derived exchange rates is tested.
Member Function Documentation
void add (const ExchangeRate &, const Date & startDate = Date::minDate(), const Date & endDate = Date::maxDate())
Add an exchange rate.
The given rate is valid between the given dates.
Note:
- If two rates are given between the same currencies and with overlapping date ranges, the latest one added takes precedence during lookup.
ExchangeRate lookup (const Currency & source, const Currency & target, Date date = Date(), ExchangeRate::Type type = ExchangeRate::Derived) const.
Author
Generated automatically by Doxygen for QuantLib from the source code. | https://www.systutorials.com/docs/linux/man/3-lookup/ | CC-MAIN-2022-05 | en | refinedweb |
/* * ReverbInputBuffer_h #define ReverbInputBuffer_h #include "AudioArray.h" namespace WebCore { // ReverbInputBuffer is used to buffer input samples for deferred processing by the background threads. class ReverbInputBuffer { public: ReverbInputBuffer(size_t length); // The realtime audio thread keeps writing samples here. // The assumption is that the buffer's length is evenly divisible by numberOfFrames (for nearly all cases this will be fine). // FIXME: remove numberOfFrames restriction... void write(const float* sourceP, size_t numberOfFrames); // Background threads can call this to check if there's anything to read... size_t writeIndex() const { return m_writeIndex; } // The individual background threads read here (and hope that they can keep up with the buffer writing). // readIndex is updated with the next readIndex to read from... // The assumption is that the buffer's length is evenly divisible by numberOfFrames. // FIXME: remove numberOfFrames restriction... float* directReadFrom(int* readIndex, size_t numberOfFrames); void reset(); private: AudioFloatArray m_buffer; size_t m_writeIndex; }; } // namespace WebCore #endif // ReverbInputBuffer_h | https://opensource.apple.com/source/WebCore/WebCore-7537.77.4/platform/audio/ReverbInputBuffer.h.auto.html | CC-MAIN-2022-05 | en | refinedweb |
the following example we define a regular expression with named groups and use them with several methods:
package mrhaki.pattern; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NamedPatterns { public static void main(String[] args) { // Define pattern and use names for the capturing groups. // The first group has the name project, second org unit number and finally a project number. // The format is ?<name>. // To make sure the separator is - or / (and not a combination) // we use group with name sep and use the backreference \k<sep> to match. Pattern issuePattern = Pattern.compile("(?<project>[A-Z]{3})(?<sep>[-/])(?<org>\\w{3})\\k<sep>(?<num>\\d+)$"); // Create Matcher with a string value. Matcher issueMatcher = issuePattern.matcher("PRJ-CLD-42"); assert issueMatcher.matches(); // We can use capturing group names to get group. assert issueMatcher.group("project").equals("PRJ"); assert issueMatcher.group("org").equals("CLD"); assert issueMatcher.group("num").equals("42"); // Using separator / also matches. assert issuePattern.matcher("EUR/ACC/91").matches(); // But we cannot mix - and /. assert !issuePattern.matcher("EUR-ACC/91").matches(); // Backreferences to the capturing groups can be used by // their names, using the syntax ${name}. assert issueMatcher.replaceAll("${project} ${num} in ${org}.").equals("PRJ 42 in CLD."); } }
Written with Java 14. | https://blog.mrhaki.com/2020/04/java-joy-using-named-capturing-groups.html | CC-MAIN-2022-05 | en | refinedweb |
GETNAMEINFO(3) NetBSD Library Functions Manual GETNAMEINFO(3)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
getnameinfo -- socket address structure to hostname and service name
SYNOPSIS
#include <netdb.h> int getnameinfo(const struct sockaddr * restrict sa, socklen_t salen, char * restrict host, socklen_t hostlen, char * restrict serv, socklen_t servlen, int flags);
DESCRIPTION a sockaddr_in (for IPv4), sockaddr_in6 (for IPv6), sockaddr_atalk (for AppleTalk), sockaddr_link (for link layer), or sockaddr_local (for local/unix) structures); } NetBSD 7.1.2 August 18, 2013 NetBSD 7.1.2 | https://man.netbsd.org/NetBSD-7.1.2/i386/getnameinfo.3 | CC-MAIN-2022-05 | en | refinedweb |
attribute
Finally arrived css attribute , In front of the scattered use of what color,font-size And so on , This blog introduces it specially
Font properties
font-family
This property sets the font style , For example, Microsoft YaHei , Founder style , Chinese Song typeface and so on
example , to body Label set font :
body { font-family: "Microsoft Yahei", " Microsoft YaHei ", "Arial", sans-serif }
You can use multiple font names as one “ Back off ” System to save . If the browser doesn't support the first font , Will try the next . The browser will use the first value it recognizes
font-weight
Word again , That is to set the thickness of the font
The values are as follows :
font-size
This is also used before , It's about setting the font size
example :
p { font-size: 14px; }
color
Set font color , I used it in the front
example :
p{ color:red; }
Supports three color values :
- Hexadecimal value Such as : #FF0000
- One RGB value Such as : RGB(255,0,0)
- The name of the color Such as : red,blue,black,white( English words for color )
Character properties
text-align
Set the horizontal alignment of the text , Its value is :
example :
p{ text-align:center; }
line-height
That is, Xinggao , Space occupying in the vertical direction of the text , Its value is pixel size
example :
p{ line-height:20px }
text-decoration
Text decoration , Its value is :
example :
a{ text-decoration:none;/* Express a The label has no underline */ }
text-index
Set text indent , Its value is in pixels
example :
p{ text-index:2px; /* Represents the indentation of two pixel positions */ }
text-shadow
Set font reflection , Its value is pixel unit plus color value
example :
p{ text-shadow:0px 0px 2px 2px #cdcdcd; }
Background properties
There are a lot of background attributes , But don't forget :
background-color
The background color to use , Its value is the same as the previous color The value of the property is the same
example :
body{ backgroud-color:red; }
background-image
The background image to use
example :
body{ background-image: url(xx.png); }
background-size
The size of the background picture
example :
body{ background-image: url(xx.png); background-size:200px; }
background-repeat
How to repeat the background image , After setting the size of the background image , If the size doesn't fit the picture , It's going to stretch or tile
example :
body{ background-image: url(xx.png); background-size:200px; background-repeat:no-repeat; }
background-attachment
Is the background image fixed or scrolling with the rest of the page , The values are as follows :
example :
body{ background-image: url(xx.png); background-size:200px; background-repeat:no-repeat; background-attachment:scroll }
background-position
The location of the background image , The values are as follows :
inherit
Indicates that should be inherited from the parent element background Property settings , This is seldom used
The above background attributes are used in combination :
body { background-color: blue; backgraound-image: url(xx.png); background-size: 200px 250px; background-repeat: no-repeat; background-position: center }
Of course , It can also be abbreviated as this :
body { background: red url(xx.png) no-repeat fixed center/200px 250px; }
display attribute
Learn from the front html When labeling , We've learned about intraindustry labels , Block level label , Intra row block level labels , And that's what controls these tags from one to another display attribute
Let's start with the concept of intra and block level tags :
The properties of elements within a row :
- Side by side with other in line elements ;
- Can't set width 、 high . Default width , It's the width of the text , have access to line-height Set the ratio in the vertical direction
Properties of block level elements :
- Occupy a business , It can't be juxtaposed with any other element ;
- Can accept wide 、 high . If the width is not set , Then the width will default to the father's 100%
Classification of block level elements and in line elements :
In the past HTML In knowledge , We've categorized tags , It was divided into : Text level 、 Container level .
from HTML In terms of , The label is divided into :
- Text level label :p、span、a、b、i、u、em.
- Container level label :div、h series 、li、dt、dd.
PS: Why say p It's a text level tag ? because p Only words can be put in it & picture & Form Elements ,p You can't put... In it h and ul,p You can't put... In it p.
from CSS The perspective of ,CSS It's very similar to the above classification , Just p Is not the same :
Inline elements : except p outside , All the text level tags , It's all in-line elements .p It's a text level , But it's a block level element .
Block-level elements : All container level tags are block level elements , also p label
transformation :
Block level to in line , Previous features are missing :
div{
display:inline;
}
After that, it will have the feature of in-line label :
- At this point div Can't set width 、 Height ;
- At this point div You can go side by side with other people
Intra row to block level , Previous features are missing :
span{
display:block;}
After that, it will have the feature of in-line label :
- At this point span Can set width 、 Height
- At this point span We have to take over a line , No one else can be with him
- If the width is not set , Will fill the parent html Elements
The box model
The box model is based on div Tag is the model of block level tag , stay html5 and css3 There's a lot more like that in the library div The label of , Let's talk about it when we need it
stay CSS in ,"box model" The term is used in design and layout , And then in the web page will basically show some square boxes . We call this box the box model
There are two kinds of box models : Standard models and IE Model
If you still don't understand my friend , such , Let's take Baidu home page as an example :
I chose id by head Of div, And then the one on the right css There's this figure at the bottom of the style , This is what a box model looks like . I believe you've noticed that margin and padding Words like that , Let's start with them
margin
It means outer margin , Indicates the distance from the border to the nearest box ,( For example, two. div Between )
margin-top,margin-left,margin-right,margin-bottom It means the distance up, left, right and down
example :
div{ margin: 20px; /* The outer distance in four directions is 20px*/ margin-top: 30px;/* The box is far from the top 30px*/ margin-left: 50px;/* The box is to the right 50px*/ margin-bottom: 100px;/* It means the distance from the box to the bottom 100px*/ }
padding
Inside margin means inside margin , Indicates the distance between the inner contents of the box and the border of the box
Again ,padding Also have padding-top,padding-left,padding-right,padding-bottom Four little attributes , It means the distance is up, left, right and down
Write separately :
padding-top: 30px; padding-right: 30px; padding-bottom: 30px; padding-left: 30px;
Abbreviation :
The up and down or so */ padding: 20px; /* There are other abbreviations :*/ /* On Right Next Left */ padding: 20px 30px 40px 50px ; /* On about Next */ padding: 20px 30px 40px; /* Up and down about */ padding: 20px 30px; /*
According to the above , I believe you may have seen this before :
*{ padding:0; margin:0; }
So this is easy to understand , It is to control the inner and outer margins of the universal selector , Because a lot of html Tags have some default styles , So we need to reset
Other properties of the box model
width: The width of the content
height: The height of the content
left: The left margin
right: The right margin
top: From the above
bottom: Bottom margin
box-shadow: Box shadow , Its value is : Add color values to the pixel units in the upper, lower, left and right directions
example : box-shadow: 0px 0px 2px 2px #cdcdcd;
The calculation of box model
The true width of the box =width+2*padding+2*border
The true width of the box =height+2*padding+2*border
And because html The relationship between label nesting , The child element inherits from the parent element css style , So there are different pixel units for width, height, etc
If a big div The pattern is as follows :
width:1000px;
This is big div There's also a little div, Its style is :
width:80%
So this little div What's the width ?
We know , By default ,80% It's the width of the screen 80% Right , But because there's a big one in the outer layer div, And big div The width has been set to 1000px, So this little div Reality width It's actually 1000px multiply 80%=800px
border
It means border , Describe the border of the box . The border has three elements : thickness ( Pixel unit ) Linear style Color (color value )
Linear styles also have small attributes :
- solid( Solid line )
- dashed( Dotted line )
- double( Double solid line )
border There are the same margin and padding The same up, down, left and right four small attributes
example :
border-width: 3px; border-style: solid; border-color: red; /* border-width: 5px 10px; border-style: solid dotted double dashed; border-color: red green yellow; */
Clear the default style of the border :
border:none; border:0;
example : Use border Set up a small triangle
/* Trigonometry The arrow points down */ div{ width: 0; height: 0; border-bottom: 20px solid red; border-left: 20px solid transparent; border-right: 20px solid transparent; }
web front end (9)—— CSS More articles on attributes
- Python web front end 03 CSS attribute
Python web front end 03 CSS attribute One . written words . Text attribute 1. Character properties font-family # Font type browser default font is Microsoft YaHei , When there are multiple fonts in the font , If the front font doesn't, use the back font ...
- Good programmer web Front end sharing css Common attribute abbreviations
Good programmer web Front end sharing css Common attribute abbreviations , Using abbreviations can help reduce your CSS File size , Easier to read .css The main rules for abbreviations are as follows : Color 16 The color value of the base , If every two digits have the same value , You can abbreviate it in half , for example : #0000 ...
- WEB The front-end development CSS A comprehensive summary of basic styles
Web The front-end development css A comprehensive summary of basic styles The use of colors and units Color Use the name of color to denote color , such as :red use 16 Hexadecimal means Demo such as :#FF0000 use rgb The number represents the color ,rgb( red , green , blue ), Each value is in 0-2 ...
- Python web front end 02 CSS
Python web front end 02 CSS One . Selectors 1.CSS There are several styles of (CSS To embellish . Beautify the website ) # Establish a template Copy content --->SETTING---> Editor -----> ...
- Good programmer web Front end sharing CSS Element type
Good programmer web Front end sharing CSS Element type The goal is 1. Element type classification basis and element type classification 2. Conversion of element types 3.inline-block Application of element type 4. Concepts and application cases of permutation and non permutation elements One . Element types are classified according to ...
- Front end Foundation -CSS Attribute operation
Front end Foundation -CSS Attribute operation css text text color :color The color attribute is used to set the color of the text . Color is through CSS The most frequent designation : Hexadecimal value - Such as : #FF0000 One RGB value - Such as : RGB( ...
- 1+x certificate Web The front-end development css Special exercises
official QQ Group 1+x certificate Web The front-end development css Special exercises
- Web Review the old and learn the new -CSS Basics
One .CSS Define and write CSS 1.1 CSS The definition of full name :Cascading Style Sheets -> Cascading style sheets Definition :CSS Become a cascading style sheet , It's mainly used to set up HTML Text content in the page ( typeface . ...
- web@ front end --html,css,javascript brief introduction 、 The first page ( Introduction to common labels )
1. What is a label #1. stay HTML Angle brackets in English are used in the label `<` and `>` wrap up , Such as `<html>`.`<head>`.`<body>` It's all labels ,#2. ...
- web The front-end development ——css
One .css Introduce 1.css What is it? ? Cascading Style Sheets abbreviation , Cascading style sheets . Styles define how to display HTML Elements , Styles usually exist in style sheets again . 2. Why css? send HTML The page becomes ...
Random recommendation
- js in function Parameter default
-- stay dreamweaver When making a website , Function definition is in a *.js In file , It defines a func, There are four parameters ,function func(string1,url,flag,icon), And then in the other one asp in ...
- In the browser WebSocket("ws://127.0.0.1:9988");
<script type="text/javascript"> function WebSocketTest() { if ("WebSocket" ...
- python Variable of
What is a variable ? Variable is to store an unfixed value , Its value can be changed at any time . 1. Variables can be more than numbers , It can also be any data type 2. The variable name must be case English . Numbers and _ The combination of , And can't start with a number python How variables are stored First ...
- java Several common thread pools in development
Thread pool java.util.concurrent:Class Executors Common thread pool Several common methods of generating thread pool : newCachedThreadPool newFixedThreadPoo ...
- @Autowired mapper level bean With red line
Using @Autowired Annotation creation bean When There will be a red line when there is time It gives people a sense of reporting mistakes Here's how to remove the red line Turn the color red error Level down to yellow warn that will do
- UGUI Blood strip
using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI; pu ...
- Salesforce Invoking Http Callouts and Testing Http Callouts
This article refers to official documents and zero zhang The blog of : ...
- webrtc real-time video .net websocket Signaling server
This article mainly refers to Webrtc WebSocket Realize audio and video communication , Thank you very much for the code The front end is completely copied from this article , Just modified webscket Of url, And joined webrtc-adapterjs ...
- iOS Cool animation effect collection
iOS Cool animation effect collection Source code address The effect is absolutely cool , Contains a variety of animation types , Such as POP.Easing. Particle effects and so on , although ...
- WinForm Control keyboard message processing analysis ( turn )
Always wanted to sort out the calling sequence of keyboard events , Just saw this article in the garden , Well written , And reprinted : ... | https://chenhaoxiang.cn/2021/06/20210604144008686J.html | CC-MAIN-2022-05 | en | refinedweb |
How to integrate external lexer with NPP?
I’ve made an external lexer that performs as expected if I send an SCI_SETLEXER msg to the nppData._scintillaMainHandle to set SCLEX_CONTAINER.
I’ve integrated it with the standard CPP plugintemplate and exported GetLexerFactory, GetLexerStatusText, GetLexerName & GetLexerCount.
How do I now make it appear in NPP Languages menu and Settings -> Style Configurator menu?
Thanks.
Afaik only if it would be added within npp source code.
Thanks, but I wonder then how the Gedcom plugin lexer manages it!?
I’ve been looking through it’s source, but I can’t figure out how it does it yet…
Putting it into the menu isn’t the problem.
I assume it is calling InsertMenu(A/W) at some point and is hooking
the message queue to receive the click event.
The problem starts when you want to appear it in the settings dialog and want npp to interact with it.
All in all, you can make it work if you start subclassing everything npp offers.
looks like I’m wrong, there is a way, npp knows something about external lexers.
Thanks again - will be able to try some more based on highlighted NPP source.
The issue is probably my imperfect understanding of C++ - especially exports etc!
I don’t know if you are using PS, probably not but in case you do,
here a little script which would check if your plugin has the exports
and do act correctly.
import ctypes from ctypes import wintypes external_lexer = ctypes.WinDLL(r'D:\temp\GedcomLexer\GedcomLexer.dll') GetLexerCount = external_lexer.GetLexerCount GetLexerName = external_lexer.GetLexerName GetLexerName.argtypes = [wintypes.UINT, wintypes.LPCSTR, wintypes.INT] GetLexerStatusText = external_lexer.GetLexerStatusText GetLexerStatusText.argtypes = [wintypes.UINT, wintypes.LPCWSTR, wintypes.INT] GetLexerFactory = external_lexer.GetLexerFactory # ?? MAX_EXTERNAL_LEXER_NAME_LEN = 16 #+1 MAX_EXTERNAL_LEXER_DESC_LEN = 32 #+1 numLexers = GetLexerCount() print('Lexers:{}'.format(numLexers)) lexName = ctypes.create_string_buffer(MAX_EXTERNAL_LEXER_NAME_LEN) lexDesc = ctypes.create_unicode_buffer(MAX_EXTERNAL_LEXER_DESC_LEN) for x in range(numLexers): GetLexerName(x, lexName, MAX_EXTERNAL_LEXER_NAME_LEN) print(lexName.value) GetLexerStatusText(x, lexDesc, MAX_EXTERNAL_LEXER_DESC_LEN) print(lexDesc.value)
Testing with Gedcom lexer returns
Lexers:1 GEDCOM GEDCOM file
and a Npp pop saying that the GedcomLexer.xml is missing.
Not a surprise as I just loaded the dll but did not install the plugin at all.
Note, the GetLexerFactory is missing in the script.
@Ekopalypse Cool! It gave me expected count, but no name - I will investigate further tomorrow.
how are you, I hope good.
One question, did you follow up on your lexer plugin?
If so, one question, where does your lexer appear in the language menu?
What I see so far is that external lexers appear since 7.?? above the builtin lexers.
Like here the nim lexer.
What is strange is that my VLang lexer does not do this.
I just can’t figure out what I’m missing. Do you have any ideas?
- PeterJones last edited by
@Ekopalypse said in How to integrate external lexer with NPP?:
@moon6969
I think I have found it. It is a “feature”.
When the name of the lexer comes before the “normal text” lexer, from the alphabetical point of view, it appears before “normal text”, but when it comes after that, it appears below it, but inside the Builtin lexers. Hmm.
I’d recommend pointing that out as a bug. I don’t know if they’ll fix it, but it should be officially documented.
- Alan Kilborn last edited by
It probably became a bug recently when None (Normal Text) was moved out of the N 's and up to the top.
Wasn’t I the one that said that change shouldn’t negatively impact anything (to @guy038)? :-)
@Ekopalypse Yea, it seems like you should put a bug report in on it. | https://community.notepad-plus-plus.org/topic/19523/how-to-integrate-external-lexer-with-npp | CC-MAIN-2022-05 | en | refinedweb |
my package.json:
“dependencies”: {
"@capacitor-community/http": "^1.3.0", "@capacitor/android": "3.2.5", "@capacitor/app": "1.0.5", "@capacitor/core": "3.2.5", "@capacitor/filesystem": "^1.0.6", "@capacitor/haptics": "1.1.2", "@capacitor/keyboard": "1.1.2", "@capacitor/status-bar": "1.0.5", "@capacitor/storage": "^1.2.2", "@ionic-native/file-opener": "^5.36.0", "@ionic/storage": "^3.0.6", "@ionic/vue": "^5.4.0", "@ionic/vue-router": "^5.4.0", "axios": "^0.23.0", "cordova-plugin-file-opener2": "^3.0.5", "core-js": "^2.5.7", "swiper": "^6.8.4", "vue": "^3.2.1", "vue-flickity": "^1.2.1", "vue-router": "^4.0.0-0", "vuex": "^4.0.2"
},
I tried both capacitor/filesystem plugin and ionic/file-opener but I was not able to configure either of those in Vue3
There is no documentation for using File opener in Vue. I am using Vue 3 and I already tried importing FileOpener in my main.js file like this:
import { FileOpener } from ‘@ionic-native/file-opener’;
const app = createApp(App)
.use(store)
.use(IonicVue)
.use(router)
.use(FileOpener)
I also tried importing FileOpener inside the component which I will be using it but still I cant make it work
Preformatted text | https://forum.ionicframework.com/t/how-to-configure-ionic-file-opener-for-vue-3/217934 | CC-MAIN-2022-05 | en | refinedweb |
Provided by: manpages-dev_5.10-1_all
NAME
fflush - flush a stream
SYNOPSIS
#include <stdio.h> int fflush(FILE *stream);
DESCRIPTION
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.fflush().10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | https://manpages.ubuntu.com/manpages/hirsute/en/man3/fflush.3.html | CC-MAIN-2022-05 | en | refinedweb |
In this post, we take a look at how we can easily manage our database migration scripts by means of Liquibase. Liquibase will automatically execute necessary database migration scripts during application startup. We will explore some of the features of Liquibase by means of a simple Spring Boot application in combination with a PostgreSQL database.
1. Introduction
When your application makes use of a relational database like PostgreSQL, you inevitably will have to cope with database migration scripts. When your application evolves, new functionality is being added and this often impacts your database schema. You probably have multiple database instances running for development, test, acceptance and production. How will you keep track of which scripts have been applied to which instance? You can develop something yourself which will keep track of an internal database schema version and apply the necessary database scripts based on this version, but you can also make use of a tool like Liquibase which will provide this task for you.
We will create a simple Spring Boot application which makes use of a PostgreSQL database. Docker is a prerequisite for this post. Installation instructions for Docker are available at the Docker website.
The sources being used in this blog are available at GitHub. Beware that the GitHub repository contains the state of the sources as we will reach at the end of this post.
2. Create Simple Application
Our sample application will have the possibility to add an employee and to retrieve the list of added employees by means of an http request. We start at Spring Initialzr and select the following dependencies: Spring Web, PostgreSQL Driver and Liquibase Migration. This leads to the following dependencies in our
pom:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency>
The domain object
Employee contains just an id, a first name and a last name. The getters and setters are left out for brevity.
public class Employee { private long id; private String firstName, lastName; public Employee(long id, String firstName, String lastName) { this.id = id; this.firstName = firstName; this.lastName = lastName; } // Getters and setters }
We create a DAO (Data Access Object) which contains the methods for accessing our database. We use
JdbcTemplate for our database access and add two methods: one for adding an employee and one for retrieving the list of employees.
@Repository public class EmployeeDao { @Autowired JdbcTemplate jdbcTemplate; public List getAllEmployees() { return jdbcTemplate.query("SELECT * FROM EMPLOYEE", new EmployeeRowMapper()); } public void addEmployee(final String firstName, String lastName) { jdbcTemplate.update("INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME) VALUES (?, ?)", firstName, lastName); } private static final class EmployeeRowMapper implements RowMapper { @Override public Employee mapRow(final ResultSet rs, final int rowNum) throws SQLException { return employee = new Employee(rs.getLong("ID"), rs.getString("FIRST_NAME"), rs.getString("LAST_NAME")); } } }
The
EmployeeController will take care of processing the http requests in order to add and retrieve employees.
@Controller public class EmployeeController { @Autowired public EmployeeDao employeeDao; @PostMapping(path = "/addEmployee") public @ResponseBody String addEmployee(@RequestParam String firstName, @RequestParam String lastName) { employeeDao.addEmployee(firstName, lastName); return "Saved Employee"; } @GetMapping(path = "/getAllEmployees") public @ResponseBody Iterable getAllEmployees() { return employeeDao.getAllEmployees(); } }
Now it is time to create our database scripts. By default, Spring expects the Liquibase database changelog file at the following location:
src/main/resources/db/changelog/db.changelog-master.yaml. Liquibase expects your database changes in this changelog master file. Inside the file, your database changes must be indicated by different changesets, each with a unique id. The complete list of options can be found here, we will explore some of these options. The syntax is quite easy and recognizable. In our case, we just create the
Employee table, the three columns and add an auto-increment option to our
id column.
databaseChangeLog: - changeSet: id: 1 author: gunter changes: - createTable: tableName: employee columns: - column: name: id type: serial autoIncrement: true constraints: primaryKey: true nullable: false - column: name: first_name type: varchar(255) constraints: nullable: false - column: name: last_name type: varchar(255) constraints: nullable: false
The only thing for us to do, is to add the database properties to the
application.properties file and to set up the database. The
application.properties contains the
datasource properties in order to be able to connect to the PostgreSQL database which we will run locally.
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres spring.datasource.username=postgres spring.datasource.password=root
We make use of the PostgreSQL Docker image to run the database:
$ docker run -p 5432:5432 --name mypostgres -e POSTGRES_PASSWORD=root -d postgres
Start the Spring Boot application:
$ mvn spring-boot:run
Let’s add an entry to the list of employees:
$ curl --data "firstName=John" --data "lastName=Doe" Saved Employee
Retrieve the list of employees:
$ curl [{"id":1,"firstName":"John","lastName":"Doe"}]
We now know that our application is up and running and the database table has been created.
3. Inspect the Database
As you probably noticed during startup of the application, quite some Liquibase log statements passed by. It is also interesting to inspect the database a bit further in order to verify what has happened here. We can make use of the
psql command inside the PostgreSQL container in order to do so.
$ docker exec -it mypostgres psql -U postgres psql (12.2 (Debian 12.2-2.pgdg100+1)) Type "help" for help. postgres=#
Now that we have a postgres command prompt, we can execute database commands. Let’s retrieve a list of tables with the
\d command:
postgres=# \d List of relations Schema | Name | Type | Owner --------+-----------------------+----------+---------- public | databasechangelog | table | postgres public | databasechangeloglock | table | postgres public | employee | table | postgres public | employee_id_seq | sequence | postgres (4 rows)
As expected, we see our employee table and the corresponding sequence table. We also notice two tables
databasechangelog and
databasechangeloglock which are created by Liquibase itself. The
databasechangelog table contains a list of all the changes that have been run against the database. The
databasechangeloglock table is used to make sure two machines don’t attempt to modify the database at the same time. Let’s inspect the
databasechangelog table:
postgres=# select * from databasechangelog ; -[ RECORD 1 ]-+------------------------------------------------- id | 1 author | gunter filename | classpath:/db/changelog/db.changelog-master.yaml dateexecuted | 2020-03-22 16:14:33.492585 | 4890073466
The
databasechangelog table contains one entry with the details of the
changeset, just as we expected.
4. Use XML
By default, Spring Boot expects the changelog to be in YAML format. Personally, we prefer the XML format, which seems to be more readable, but it is mainly a matter of taste. First of all, we need to configure Spring Boot in order to use the XML format. We add the following line to the
application.properties file:
spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml
Besides that, we will refer from our master changelog to version update files. This is a Liquibase best practice. For more best practices, see the Liquibase website. The
db.changelog-master.xml file now looks like the following:
<databaseChangeLog xmlns="" xmlns: <include file="/db/changelog/db.changelog-1.0.xml"/> </databaseChangeLog>
In the
resources/db/changelog/ directory, we add a file
db.changelog-1.0.xml which contains the same create table entries as in the YAML file we created earlier. We also add a rollback tag. When something goes wrong during the SQL execution, the rollback statement will be executed, leaving your database in a consistent state.
<databaseChangeLog xmlns="" xmlns: <changeSet author="gunter" id="changelog-1.0"> <createTable tableName="employee"> <column name="id" type="serial" autoIncrement="true"> <constraints nullable="false" primaryKey="true"/> </column> <column name="first_name" type="varchar(255)"> <constraints nullable="false"/> </column> <column name="last_name" type="varchar(255)"> <constraints nullable="false"/> </column> </createTable> <rollback> <dropTable tableName="employee"/> </rollback> </changeSet> </databaseChangeLog>
Stop and remove the PostgreSQL container:
$ docker stop mypostgres $ docker rm mypostgres
Start the PostgreSQL container with
docker run just like we did before and start the application with
mvn spring-boot:run.
By means of the
psql command, we check the contents of the
databasechangelog table and notice that the filename has changed to the XML file.
postgres=# select * from databasechangelog; -[ RECORD 1 ]-+----------------------------------- id | changelog-1.0 author | gunter filename | /db/changelog/db.changelog-1.0.xml dateexecuted | 2020-03-28 11:13:20.163418 | 5390400140
5. Add a Migration Script
In the next section, we will add a new column
country to the
Employee table. We will need to change the
Employee,
EmployeeDao and
EmployeeController to support the new column.
The
Employee is changed as follows:
public class Employee { private long id; private String firstName, lastName, country; public Employee(long id, String firstName, String lastName, String country) { this.id = id; this.firstName = firstName; this.lastName = lastName; this.country = country; } // Getters and setters }
The
EmployeeDao is changed as follows:
public void addEmployee(final String firstName, String lastName, String country) { jdbcTemplate.update("INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME, COUNTRY) VALUES (?, ?, ?)", firstName, lastName, country); } private static final class EmployeeRowMapper implements RowMapper { @Override public Employee mapRow(final ResultSet rs, final int rowNum) throws SQLException { return new Employee(rs.getLong("ID"), rs.getString("FIRST_NAME"), rs.getString("LAST_NAME"), rs.getString("COUNTRY")); } }
The
EmployeeController is changed as follows:
@PostMapping(path = "/addEmployee") public @ResponseBody String addEmployee(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String country) { employeeDao.addEmployee(firstName, lastName, country); return "Saved Employee"; }
Add a
db.changelog-2.0.xml file to the
resources/db/changelog/ directory:
<databaseChangeLog xmlns="" xmlns: <changeSet author="gunter" id="changelog-2.0"> <addColumn tableName="employee"> <column name="country" type="varchar(255)"/> </addColumn> <rollback> <dropColumn tableName="employee"> <column name="country" type="varchar(255)"/> </dropColumn> </rollback> </changeSet> </databaseChangeLog>
And add a line to the master file:
<include file="/db/changelog/db.changelog-2.0.xml"/>
Run the application, the log shows us clearly that the migration script is executed:
2020-03-28 11:33:12.775 INFO 11117 --- [ main] liquibase.executor.jvm.JdbcExecutor : ALTER TABLE public.employee ADD country VARCHAR(255) 2020-03-28 11:33:12.776 INFO 11117 --- [ main] liquibase.changelog.ChangeSet : Columns country(varchar(255)) added to employee 2020-03-28 11:33:12.779 INFO 11117 --- [ main] liquibase.changelog.ChangeSet : ChangeSet /db/changelog/db.changelog-2.0.xml::changelog-2.0::gunter ran successfully in 4ms
Check the schema of the
Employee table where we can verify that the
country column is added:
postgres=# \d employee Table "public.employee" Column | Type | Collation | Nullable | Default ------------+------------------------+-----------+----------+---------------------------------- id | integer | | not null | generated by default as identity first_name | character varying(255) | | not null | last_name | character varying(255) | | not null | country | character varying(255) | | | Indexes: "employee_pkey" PRIMARY KEY, btree (id)
Add an employee via the web request and retrieve all employees:
$ curl --data "firstName=John" --data "lastName=Doe" --data "country=The Netherlands" Saved Employee $ curl [{"id":1,"firstName":"John","lastName":"Doe","country":"The Netherlands"}]
6. Something About Contexts
The last feature of Liquibase we will discuss is
contexts. A context can be added to a changeset. For example when a changeset should only be executed on a test environment. First, we will create two Spring Profiles, one for
prod and one for
test. We rename the
application.properties file to
application-prod.properties and add the following line to it:
spring.liquibase.contexts=prod
We create an
application-test.properties similar to the
application-prod.properties and change the above line to context
test.
We add a new changelog
db.changelog-3.0.xml which inserts a record in the
Employee table and we add the context
test to it:
<databaseChangeLog xmlns="" xmlns: <changeSet author="gunter" id="changelog-3.0" context="test"> <insert tableName="employee"> <column name="first_name" value="Foo"/> <column name="last_name" value="Bar"/> <column name="country" value="Sweden"/> </insert> </changeSet> </databaseChangeLog>
The other changelogs are given the
prod or test contexts and will be executed for context
prod as well as for context
test.
Run the application again and run it with the
prod Spring profile:
$ mvn spring-boot:run -Dspring-boot.run.profiles=prod
Verify the
Employee table or execute the
getAllEmployees web request. We notice that it returns an empty list.
Stop the application and run it with the
test Spring profile:
$ mvn spring-boot:run -Dspring-boot.run.profiles=test
The console log shows us already that the 3.0 changelog is being executed:
2020-03-29 11:22:23.806 INFO 9277 --- [ main] liquibase.executor.jvm.JdbcExecutor : INSERT INTO public.employee (first_name, last_name, country) VALUES ('Foo', 'Bar', 'Sweden') 2020-03-29 11:22:23.807 INFO 9277 --- [ main] liquibase.changelog.ChangeSet : New row inserted into employee 2020-03-29 11:22:23.815 INFO 9277 --- [ main] liquibase.changelog.ChangeSet : ChangeSet /db/changelog/db.changelog-3.0.xml::changelog-3.0::gunter ran successfully in 10ms
Execute the
getAllEmployees web request and you will notice that the record from our changelog is returned.
$ curl [{"id":1,"firstName":"Foo","lastName":"Bar","country":"Sweden"}]
7. Conclusion
In this post we looked at how Liquibase can help you with versioning and migrating your database changes. It is easy to set up and easy to use. We only scratched the surface of what is possible with Liquibase, so take the time to take a look at all the other features it has to offer.
Simply superb for learners… I’m totally new to Liquibase. In half a day, I learned most of the things from this post. Thanks a lot..
LikeLiked by 1 person
Thank you very much for your feedback. It is always nice to read that it has been useful for someone 🙂
LikeLiked by 1 person | https://mydeveloperplanet.com/2020/04/21/easy-database-migration-with-liquibase/?like_comment=17377&_wpnonce=7d55247d60 | CC-MAIN-2022-05 | en | refinedweb |
Computer Vision library that makes simple the new powerful.
Project description
Eye Vision
Eye Vision provides a simple but powerful python library for Computer Vision. It uses well know libraries like OpenCv and Matplotlib. Typical usage often looks like this::
import ziso from ziso import read from ziso import view # to read the image in the rgb color scale file = read.rgb("test.jpg") # to view the image view.im(file) # to view the easter egg in the library from ziso import zen
Speed
Your favourite libraries compressed:
OpenCV
Matplotlib
etc
Note:
Things to expect and know:
Easy implementation
Rapid Scalability
Portability
Read the Docs:-> Urls are
Eye-vision webpage:->
Personal webpage:->
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/eye-vision/0.0.2/ | CC-MAIN-2022-05 | en | refinedweb |
The:
using System; using System.Collections.Generic; using System.Linq; using Common.Lists; using Common.Logging; using FullTextIndexer.Indexes; using FullTextIndexer.Indexes.TernarySearchTree; using FullTextIndexer.IndexGenerators; using FullTextIndexer.TokenBreaking; namespace FullTextIndexerDemo { public
Dan is a big geek who likes making stuff with computers! He can be quite outspoken so clearly needs a blog :)
In the last few minutes he seems to have taken to referring to himself in the third person. He's quite enjoying it. | https://www.productiverage.com/the-full-text-indexer-adding-and-subtracting | CC-MAIN-2022-05 | en | refinedweb |
Convert local time to calendar time
#include <time.h> time_t mktime( struct tm* timeptr );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The mktime() function converts the local time information in the struct tm specified by timeptr into a calendar time (Coordinated Universal Time) with the same encoding used by the time() function.
The original values of the tm_sec, tm_min, tm_hour, tm_mday and tm_mon fields aren't restricted to the ranges described for struct tm. If these fields aren't in their proper ranges, they, or -1 if mktime() can't convert it.
#include <stdio.h> #include <stdlib.h> #include <time.h> static const char *week_day[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; int main( void ) { struct tm new_year; time_t t; new_year.tm_year = 2001 - 1900; new_year.tm_mon = 0; new_year.tm_mday = 1; new_year.tm_hour = 0; new_year.tm_min = 0; new_year.tm_sec = 0; new_year.tm_isdst = 0; t = mktime( &new_year ); if ( t == (time_t)-1) printf("No conversion possible.\n"); else printf( "The 21st century began on a %s.\n", week_day[ new_year.tm_wday ] ); return EXIT_SUCCESS; }
produces the output:
The 21st century began on a Monday. | https://www.qnx.com/developers/docs/7.1/com.qnx.doc.neutrino.lib_ref/topic/m/mktime.html | CC-MAIN-2022-05 | en | refinedweb |
Android One of the four components :service:
Service There are five life cycles :onCreat,onStartCommand, onBind,onUnbind, onDestroy
There are mainly two ways of binding and unbound
The prime minister is here Activity There are four Button, For testing both bound and unbound , Press down Button Play music , Stop the music , Unbound with StopService stop it , The binding method uses Bind Service start-up , For unbinding unbindService stop it .
Unbound :Intent intent=new Intent(MainActivity.this,MyService.class);
start Service(intent);/stopSercice(intent)
from Activity start-up service Mainly use the above code ,
binding :Intentintent=newIntent(MainActivity.this,MyService.class);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
serviceConnection by :
private ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name,
IBinder service) {
myService=((MyService.MyBinder)service).getService();
} @Override
public void onServiceDisconnected(ComponentName name) { }
};
The binding method is fixed
stay Service You can also use function callbacks to perform certain operations
Function callbacks generally have four steps :
1. Define an excuse , Define a method in an excuse
2. Activity In order to realize this excuse , And the method in the excuse
3.Service In the definition of public static void setMusicStop(Context context){
stopImg = (StopImg) context;
}
4. stay Activity You can call Service The method in .
Function callbacks are generally divided into these four steps .
Function callbacks are not only used for Activity And Service in , It can also be used for Activity And Activity in .
Function callbacks are commonly used in music players .
Broadcast: radio broadcast
The registration method is not static 、 Dynamic two ways
Static is manually registered in the manifest file
<receiver
android:name=".Broadcast.MySMS"
android:enabled="true"
android:
<intent-filter>
<action android:
</intent-filter>
</receiver>
Among them android:name="android.provider.Telephony.SMS_RECEIVED"
Name defined for yourself
Dynamic registration :
// Dynamic registration broadcast
IntentFilter intent Filter);
}
}
After the radio registration is completed , And the next inheritance BroadcastReceiver Methods , Used to receive broadcast content , Where do you want to receive the radio , Where to register for broadcasting .
Write a broadcast test program to illustrate : Use what I said before Service
First , Build a Activity1, Set the two Button,
A test static registration , One for jump test dynamic registration .
Build another one Service, Static registration ,
stay Service In manifest file , Join in
<receiver
android:name=".Broadcast.MyReceiver"
android:enabled="true"
android:
<intent-filter>
<action android:
</intent-filter>
</receiver>
This statically registers a broadcast , Broadcast name by
<action android:
Build another one Activity2, Test dynamic sending .
for Activity1 The content of
public class BroadcastActivity extends AppCompatActivity {
private Button bt1,bt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broadcast);
bt1= (Button) findViewById(R.id.bt1);
bt2= (Button) findViewById(R.id.bt2);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("arg"," Hello ");
intent.setAction("android.jredu.broadcast.ZHANG");
sendBroadcast(intent);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(getBaseContext(),BroadActivity.class);
startActivity(intent);
}
});
// Dynamic registration broadcast
IntentFilter intentFilter);
}
}
}
for Activity2 The content of : There is one of them. Button, Press send broadcast
public class BroadActivity extends AppCompatActivity {
private Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad);
bt1= (Button) findViewById(R.id.bt1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("arg2","42870");
intent.setAction("android.jredu.action.WEN");
sendBroadcast(intent);
}
});
}
}
Android Of the four components service And Broadcast More articles about
- Android Of the four components Service
Android Of the four components Service Android The concept of support services , Services are components that run in the background , No user interface ,Android Services can have a lifecycle independent of activities .Android Supports two types of services : The local service : ...
- 【Android Development diary 】 Introduction to ( 5、 ... and )——Android Of the four components Service
I'm busy with driving school test these days , I can't even touch the computer , It's finally over today ~~Service As Android The service component of , Silently serve the whole program in the background , The auxiliary application communicates with other components or system services in the system . It goes with Activity Of ...
- Android Growth Diary -Android Of the four components Service Component learning
1. What is? Service? Service yes Android Among the four major components, there are Activity The most similar component , They all represent executable programs ,Service And Activity The difference is that :Service Always running in the background , it ...
- Android One of the four components Service Introduce -android Learning journey ( Twelve )
Basic concepts : service yes android One of the four components , Running time-consuming operations in the background , It doesn't provide a user interface . Other components such as acticity Can pass startService Start the component , It can also be done through bindService ...
- Android One of the four components -- Service Detailed explanation
I believe most of my friends are right Service This term is not strange , you 're right , An experienced Android If the programmer even Service Never heard of anything , That's too bad .Service As Android One of the four components , In every application ...
- Android Four components :Service
Preface Service As Android One of the four components , Very widely used This article will introduce the concept of Service Give a full introduction ( Basic knowledge . Life cycle . Usage and application scenarios ) Catalog Catalog 1. Basic knowledge of Definition : service , Belong to Androi ...
- Android Of the four components Service My humble opinion
Service yes Android One of the four components , It can run in the background without displaying the interface . Another function is through AIDL To achieve interprocess communication . Service Mode of starting Service There are two ways to start ,startSe ...
- Android Of the four components Service
--- Resume content start --- 1,Service Life cycle of
- To talk about Android Of the four components Service piece
Service brief introduction Service yes Android One of the four components in the system , It's a long life cycle , No visual interface , A service program running in the background .Service Must be in AndroidManifest.xml In a statement ...
Random recommendation
- Don't use return false prevent event Default behavior
When we click on a a When labeling , If this label is href It points to another address , The browser will jump to this address by default . In the page , Sometimes we need to trigger click events , But I don't want to trigger the default behavior , We need to stop event The default behavior of . routine ...
- Hello, AnnsShadow!
Hello! It's been almost a year since I found this magical garden , It's been a year since I had a bumpy learning experience , Think , For so long , It's time to take notes and be a sharer . From the beginning, I only dare to see Blog, So far, I want to express my feelings and thoughts , It's a kind of growth ...
- The first gui program by Qt
#include<QApplication> #include<QPushButton> int main(int argc, char **argv) { QAppl ...
- console, And define events for yourself
console.log This command outputs the log in the browser console , Used to debug programs Follow alert similar But not like alert That would interrupt the program .
- ubuntu Under the supervisor start-up express The problem of failure
ubuntu Next apt-get install nodejs The next startup command is nodejs, And different from windows Under the node So I am supervisor start-up express There was a problem The tips are as follows : / ...
- haproxy Configuration file analysis of
function --> Provide high availability / Load balancing / be based on tcp and http Agent for application ; Support virtual host , It is especially suitable for heavy load web Site . Profile parsing --> # The configuration file --> Turn on /proc/net/ipv4 ...
- springMVC3 Study ( Four )-- Access static files such as js,jpg,css
Suppose your DispatcherServlet Intercept is *.do such URL. There is no access to static resources Suppose your DispatcherServlet Intercepted "/" All requests , At the same time ...
- django---- utilize Form Whether the two password inputs are the same ( Local hook and global hook )
from django import forms # Import form module from django.core.exceptions import ValidationError class RegisterF ...
- linux Users and groups
1. The user belongs to the user group . 2. User and user group profiles 1) User group profile /etc/group First column : The group name of the user group Second column : Set the password ( The real password is stored in gshadow in ) The third column : User groups ID, The user group is ...
- Redis note ( 6、 ... and ):Java Use in Redis
Java Program usage Redis Add dependency package Maven Dependent manner <dependency> <groupId>redis.clients</groupId> <ar ... | https://chenhaoxiang.cn/2021/06/20210604202044137u.html | CC-MAIN-2022-05 | en | refinedweb |
Створення додатків are still many things you can do with them. Note that a plugin is similar to any scene you can already make, except it is created using a script to add editor.
The script file¶
Upon creation of the plugin, the dialog will automatically open the
EditorPlugin script for you. The script has two requirements that you cannot
change: it must be a
tool script, or else it will not load properly in the
editor, and it must inherit from EditorPlugin.
Попередження.
Попередження
Nodes added via an EditorPlugin are "CustomType" nodes. While they work with any scripting language, they have fewer features than the Script Class system. If you are writing GDScript or NativeScript, we recommend using Script Classes instead.!")
using Godot; using System; [Tool] public class MyButton : Button { public override void _EnterTree() { Connect("pressed", this, "clicked"); } public void clicked() { GD.Print("You clicked me!"); } }
That's it for our basic button. You can save this as
my
With that done, the plugin should already be available in the plugin list in the Project Settings, so activate it as explained in Checking the results.
Then try it out by adding your new node:
When you add the node, you can see that it already"
[plugin] name="My Custom Dock" description="A custom dock made so I can learn how to make plugins." author="Your Name Here" version="1.0" script="CustomDock.cs" life cycle.. | https://docs.godotengine.org/uk/stable/tutorials/plugins/editor/making_plugins.html | CC-MAIN-2022-05 | en | refinedweb |
As far as I understand the documentation for BatchNorm1d layer we provide number of features as argument to constructor(
nn.BatchNorm1d(number of features)).
As an input the layer takes (N, C, L), where N is batch size (I guess…), C is the number of features (this is the dimension where normalization is computed), and L is the input size.
Let’s assume I have input in following shape:
(batch_size, number_of_timesteps, number_of_features)
which is usual data shape for time series if batch_first=True.
Question
Should I transpose the input (swap dimension 1 and 2) before running the batch normalization?
In this case I will have to transpose the output again to use it in RNN later. It looks quite weird to me.
Can someone please take a look at below example and let me know if this is the proper way.
E.g.:
import torch from torch import nn # data (batch size, number of time steps, number of features) x = torch.rand(3, 4, 5) # layers bn = nn.BatchNorm1d(5) rnn = nn.RNN(5, 10, 1, batch_first=True) # computation - transpose TWICE x_normalized = bn(x.transpose(1, 2)).transpose(1, 2) rnn(x_normalized) | https://discuss.pytorch.org/t/batchnorm1d-input-shape/91364 | CC-MAIN-2020-34 | en | refinedweb |
If you’ve been following the site, you may have noticed the VR Baseball game. While this was an interesting project, there was one part that stood out as particularly worthy of writing about. In this article, I’ll show you how to setup physics in your own baseball, cricket, or other batting style game in Virtual Reality. We’ll use a simple trick to make the batting feel real and fun.
Video Version
The Game
In VR Baseball, the goal is simple. A ball is pitched, you swing the bat, and if you hit, the ball goes flying.
The Problem
The first implementation of VR Baseball had a very simple batting system. There was a colider on the bat and the ball had some bounciness. Choosing a level would just adjust the bounciness factor of the ball by switching out the PhysicsMaterial on the balls Collider. It was simple, it worked, but it felt weird. The main issue was that no-matter where on the bat you hit, the ball flew the same speed.
You could hit it with the handle, it’d go flying. You could push forward with the bat and get a home run off the tip. The only thing that was taken into account was the velocity of the bat at the time.
Now in most situations, you don’t need to worry about the velocity of the exact part where your collisions happen, only the general velocity of the object it’s colliding with. But with baseball, we have a swinging action, and we need the velocity at the end of the bat to be different from the velocity at the handle (just like real life).
The Solution
Instead of having the baseballs collide with the bat, we spawn some new objects to collide with.
The bat has a set of child objects that determine where these new objects will spawn and be at run-time.
As you can see, the BatCapsules don’t have much to them. They’re really just a script and a transform. There’s a collider and a mesh renderer, but those are only for debugging and visualizing, which is why they’re disabled normally (I would toggle them on when the follower seemed to be in the wrong spot, so I could verify the location I was giving them was valid).
The most important part though is the “Bat Capsule” script on them.
using UnityEngine; public class BatCapsule : MonoBehaviour { [SerializeField] private BatCapsuleFollower _batCapsuleFollowerPrefab; private void SpawnBatCapsuleFollower() { var follower = Instantiate(_batCapsuleFollowerPrefab); follower.transform.position = transform.position; follower.SetFollowTarget(this); } private void Start() { SpawnBatCapsuleFollower(); } }
The method SpawnBatCapsuleFollower() does exactly what its name implies. It spawns a BatCapsuleFollower, and calls a single initialization method named SetFollowTarget. We pass “this” into SetFollowTarget() as we want the BatCapsuleFollower to follow this object which is attached to the bat.
The Start() method in this script does a single thing, it calls SpawnBatCapsuleFollower(). We do this so anyone reading the code later can tell exactly what we want to do, without needing comments.
using UnityEngine; public class BatCapsuleFollower : MonoBehaviour { private BatCapsule _batFollower; private Rigidbody _rigidbody; private Vector3 _velocity; [SerializeField] private float _sensitivity = 100f; private void Awake() { _rigidbody = GetComponent<Rigidbody>(); } private void FixedUpdate() { Vector3 destination = _batFollower.transform.position; _rigidbody.transform.rotation = transform.rotation; _velocity = (destination - _rigidbody.transform.position) * _sensitivity; _rigidbody.velocity = _velocity; transform.rotation = _batFollower.transform.rotation; } public void SetFollowTarget(BatCapsule batFollower) { _batFollower = batFollower; } }
The BatCapsuleFollower script is responsible for following the bat capsule…
The work for that is done in FixedUpdate(). To follow the BatCapsule, it gets the position it wants to be in, then subtracts it from the current position. That distance is multiplied by a sensitivity value that can be adjusted in the editor. For my game, I found a value of about 50 worked well. It sets the rigidbody velocity to that calculated value which makes it move toward the BatCapsule.
Next it adjusts the rotation to match the BatCapsule. If we don’t do that, it will end up sideways.
Important – Physics Layers
When setting up your BatCapsuleFollower, make sure the Layer it’s on does not collide with itself. If you don’t, the BatCapsuleFollowers will be bouncing off each other, not doing what you want.
To get to the physics settings, click Assets->Project Settings->Physics
In here, you need to make sure the layer you’ve chosen for your BatCapsuleFollowers (please put them on their own layer), does not collide with itself. It should also not collide with anything other than the ball (unless there’s something else you want to hit). You can see I’ve set mine up to do exactly that.
Conclusion
With it setup like this, the BatCapsuleFollowers will move at different velocities, causing the outer most one to hit much further than the innermost. While this could be further tuned to make a real sweet spot on the bat, I’ve found that this functionality works well enough.
Project Download
Get Some Bats
A good friend of mine made the awesome bats featured here and they’re available on the asset store. If you wanna do some baseball stuff and support him, go grab one now 🙂 | https://unity3d.college/2016/04/11/baseball-bat-physics-unity/ | CC-MAIN-2020-34 | en | refinedweb |
Private/unsupported build options should be marked as advanced so that they are hidden to users listing CMake options (e.g. with 'cmake -L').
Er wait, we already have code for this (WebKitFeatures.cmake):
option(${_name} "${_WEBKIT_AVAILABLE_OPTIONS_DESCRIPTION_${_name}}" ${_WEBKIT_AVAILABLE_OPTIONS_INITIAL_VALUE_${_name}})
if (NOT _WEBKIT_AVAILABLE_OPTIONS_IS_PUBLIC_${_name})
mark_as_advanced(FORCE ${_name})
endif ()
Created attachment 291645 [details]
Patch
Comment on attachment 291645 [details]
Patch
Clearing flags on attachment: 291645
Committed r207351: <>
All reviewed patches have been landed. Closing bug. | https://bugs.webkit.org/show_bug.cgi?id=163451 | CC-MAIN-2020-34 | en | refinedweb |
Deploying Sync Gateway cluster
This guide demonstrates how to deploy a Sync Gateway cluster on Kubernetes.
Prerequisites
Before you begin, you must have the following:
A Couchbase Server cluster already running on Kubernetes. If you don’t already have one, you can refer to this guide for instructions.
A Couchbase Server RBAC user with application access privileges. Sync Gateway will connect to the Couchbase Server as this RBAC user. Refer to this section for instructions.
If you have configured your Couchbase Server cluster to use exposedFeatures then you must include "client" in the
exposedFeatureslist. This is required for Sync Gateway to be able to connect to the server. Alternatively, remove the exposedFeatures section altogether in the server configuration if you don’t need it.
Deploying a Sync Gateway Cluster
The Sync Gateway nodes in a cluster have a homogeneous configuration with the exception of import node.
-).
The following sections cover the steps to deploy regular or import Sync Gateway nodes.
You will have to repeat the steps in this section once for the "regular" or non-import nodes and once for the "import" node. The difference is the Sync Gateway configuration file and the Kubernetes Deployment Controller config file.
Sync Gateway Configuration File
In this section, you will create a Kubernetes secret from a new or existing Sync Gateway configuration.
Open the Sync Gateway configuration file corresponding to your deployment. If you don’t have a configuration file you may also use our sample configuration shown below as a starting point.
Replace the
serverkey with the addressable Couchbase Server hostname. The following example shows the configuration file for a regular node.
{ "logging": { "log_file_path": "/var/tmp/sglogs", "console": { "enabled": true, "log_level": "info", "log_keys": ["*"] } }, "databases": { "db": { "server": "cb-example-0000.cb-example.default.svc:8091", (1) "bucket": "default", "username": "admin", (2) "password": "password", "users": { "GUEST": { "disabled": false, "admin_channels": ["*"] } }, "allow_conflicts": false, "revs_limit": 20, "enable_shared_bucket_access": true } } }
You will use a Kubernetes Secret to pass the configuration file to Sync Gateway on launch. Alternatively, you could use a Kubernetes configMap if you are not concerned about security. However, since the Sync Gateway contains sensitive information, it is recommended that you create a secret from the config file and pass that to the Sync Gateway. Run the following command to create a secret called "sgw-config" or "sgw-config-import" corresponding to regular and import versions of Sync Gateway configuration file respectively
kubectl create secret generic sgw-config --from-file sgw-config.json
kubectl create secret generic sgw-config-import --from-file sgw-config-import.json
If successful, you will see the following.
Deployment controller
In this section you will deploy the Sync Gateway cluster with the configuration file that you created above.
You will be using a Kubernetes deployment controller. A deployment controller allows you to define the number of Sync Gateway replicas and other parameters.
Open the controller file corresponding to your deployment.
The following example shows the controller file for a regular node.
apiVersion: extensions/v1beta1 kind: Deployment metadata: name: sync-gateway (1) spec: replicas: 2 (2) template: metadata: labels: app: sync-gateway spec: affinity: (3) podAntiAffinity: requiredDuringSchedulingIgnoredDuringExecution: - labelSelector: matchExpressions: - key: app operator: In values: - sync-gateway topologyKey: "kubernetes.io/hostname" containers: - name: sync-gateway image: couchbase/sync-gateway:2.6.0-enterprise (4) args: ["/sync-gateway-config/sgw-config.json"] (5) volumeMounts: (6) - name: sgw-config-volume mountPath: /sync-gateway-config readOnly: true env: - name: GOMAXPROCS (7) value: "1" resources: requests: cpu: 500m limits: cpu: 500m (8) volumes: (9) - name: sgw-config-volume secret: secretName: sgw-config
Deploy the Sync Gateway cluster from the specified deployment controller file.
kubectl create -f sgw-deployment.yaml
kubectl create -f sgw-deployment-import.yaml
If successful, you will see the following.
You can check the status of the deployment with the following command until all the pods corresponding to the Sync Gateway are in the "Ready" state and the status is "Running".
kubectl get pods --watch
The
--watchoption is optional but you use it to be asynchronously notified of updates to status of the pods instead of having to repeatedly run the command.
If successful, you will see a listing of the Sync Gateway pods that were deployed. In the sample output below, we have Couchbase Server and Sync Gateway pods running in the same namespace. In a production deployment, you may have Couchbase Server deployed on a separate namespace.
NAME READY STATUS RESTARTS AGE cb-example-0000 1/1 Running 0 3d cb-example-0001 1/1 Running 0 3d cb-example-0002 1/1 Running 0 3d couchbase-operator-fd8db588b-9fzsw 1/1 Running 1 3d sync-gateway-7474f5df4b-c29xw 1/1 Running 2 18m sync-gateway-7474f5df4b-p98sq 1/1 Running 0 18m
Make sure that you have sufficient CPU resources on the node on which the pods are being deployed. Failure to do so will result in an "insufficient resource" exception when attempting to deploy the pods.
Deploying a Load Balancer
In a production deployment, you will likely have one or more Sync Gateway nodes fronted by a load balancer.
You will deploy the load balancer using the Kubernetes Load Balancer service. The load balancer service provides an externally accessible IP address and routes traffic to the right ports in the cluster.
Follow these steps to deploy a load balancer in front of the Sync Gateway cluster.
Create a new file called sgw-load-balancer.yaml with the following.
kind: Service apiVersion: v1 metadata: name: sgw-load-balancer (1) spec: selector: app: sync-gateway (2) ports: - protocol: TCP port: 4984 (3) targetPort: 4984 type: LoadBalancer
Deploy the load balancer.
kubectl create -f sgw-load-balancer.yaml
If successful, you will see the following.
service "sgw-load-balancer" created
Verify the status of the service creation with the following.
kubectl get services
If successful, you will see a new service corresponding to the load balancer. In the sample output below, we have the
sgw-load-balancerservice.
NAME TYPE CLUSTER-IP EXTERNAL-IP cb-example ClusterIP None <none> cb-example-srv ClusterIP None <none> cb-example-ui NodePort 10.3.246.239 <none> kubernetes ClusterIP 10.3.240.1 <none> sgw-load-balancer LoadBalancer 10.3.253.17 35.184.19.17
The sgw-load-balancer's
EXTERNAL-IPis the load balancer’s publicly accessible hostname.
Verify the pods that the load balancer is targeting.
kubectl describe service sgw-load-balancer
You should see the equivalent of the following.
Name: sgw-load-balancer Namespace: default Labels: <none> Annotations: <none> Selector: app=sync-gateway Type: LoadBalancer IP: 10.3.253.17 LoadBalancer Ingress: 35.184.19.17 Port: <unset> 4984/TCP TargetPort: 4984/TCP NodePort: <unset> 32397/TCP Endpoints: 10.0.0.34:4984,10.0.0.35:4984 Session Affinity: None External Traffic Policy: Cluster Events:
Notice the "endpoints" field and confirm that it corresponds to the Sync Gateway nodes. In this example, we have 2 Sync Gateway nodes.
Verify the Sync Gateway cluster is accessible with the following command; where
EXTERNAL-IPis the IP that was copied in step 3.
curl
It should return the following.
{"couchdb":"Welcome","vendor":{"name":"Couchbase Sync Gateway","version":"2.1"},"version":"Couchbase Sync Gateway/2.1.1(17;fea9947)"}
You have successfully deployed a Sync Gateway cluster on Kubernetes. The Manage a Cluster page contains additional details related to the management of the cluster. | https://docs.couchbase.com/sync-gateway/2.6/kubernetes/deploy-cluster.html | CC-MAIN-2020-34 | en | refinedweb |
How to: Implement an ASP.NET Web List Editor Using a Custom Control
- 6 minutes to read
The eXpressApp Framework is shipped with a number of built-in List Editors. However, in certain scenarios, you may need to implement a custom List Editor, to display object collections in a particular way. This topic demonstrates how to implement a custom ASPxCustomListEditor List Editor that uses a custom control. This List Editor is designed to display objects, implementing a custom IPictureItem interface as a list of images, one for each object. It can be used, for instance, to display DVD covers.
The following image demonstrates the implemented List Editor in an Album List View:
NOTE
- You can see the code implemented here in the FeatureCenter Demo installed with XAF. This demo is located in the %PUBLIC%\Documents\DevExpress Demos 20.1\Components.NET Core Desktop Libraries\eXpressApp Framework\FeatureCenter folder, by default.
ASP.NET controls that use the ClientScriptManager.RegisterStartupScript method cannot be integrated using this example. If need to integrate such a control, feel free to contact our Support Team.
When implementing a custom List Editor that works with specific data, you can design it for a particular class. However, in this example, an interface will be introduced containing the properties required by the List Editor. Then, the List Editor will be designed to display objects implementing the interface. This approach allows you to simultaneously use that same List Editor for different classes. List Views displayed via the ASPxCustomListEditor will have two columns: Image and Text. The special interface has an additional ID property that represents a unique object identifier.
using System.Drawing; //... public interface IPictureItem { Image Image { get; } string Text { get; } string ID { get; } }
Start implementing the List Editor by inherit its class from the ListEditor class, and implement basic functionality by overriding the following members. Note that your editor should be public.
- CreateControlsCore method that instantiates the List Editor's control. Override it to create and configure an instance of the custom control (in this example, ASPxCustomListEditorControl).
- AssignDataSourceToControl method that assigns the List Editor's data source to its control.
- ListEditor.Refresh method that refreshes the data source of the List Editor's control.
- To specify that List Views displaying IPictureItem objects should use the ASPxCustomListEditor, decorate the List Editor class with the ListEditorAttribute.
using System; using DevExpress.ExpressApp.Editors; using DevExpress.ExpressApp.Model; using DevExpress.ExpressApp.Utils; // ... [ListEditor(typeof(IPictureItem))] public class ASPxCustomListEditor : ListEditor { public ASPxCustomListEditor(IModelListView info) : base(info) { } private ASPxCustomListEditorControl control; protected override object CreateControlsCore() { control = new ASPxCustomListEditorControl(); control.ID = "CustomListEditor_control"; return control; } protected override void AssignDataSourceToControl(Object dataSource) { if (control != null) { control.DataSource = ListHelper.GetList(dataSource); } } public override void Refresh() { if (control != null) control.Refresh(); } }
The List Editor demonstrated above can display a collection of objects implementing the IPictureItem interface. Additionally, a List Editor should be able to invoke a Detail View for the focused object when an end-user clicks the object. For this purpose, modify the following members:
- In the CreateControlsCore method, subscribe to the control's OnClick event. In the event handler, call the OnSelectionChanged and OnProcessSelectedItem methods.
- Override the ListEditor.FocusedObject method, to get and set the focused object.
Additionally, implement the custom CustomListEditorClickEventArgs class with the IPictureItem field for the OnClick event.
[ListEditor(typeof(IPictureItem))] public class ASPxCustomListEditor : ListEditor { //... protected override object CreateControlsCore() { //... control.OnClick += control_OnClick; //... } private void control_OnClick(object sender, CustomListEditorClickEventArgs e) { this.FocusedObject = e.ItemClicked; OnSelectionChanged(); OnProcessSelectedItem(); } private object focusedObject; public override object FocusedObject { get { return focusedObject; } set { focusedObject = value; } } } public class CustomListEditorClickEventArgs : EventArgs { public IPictureItem ItemClicked; }
The final step is to implement the following abstract members:
- Override the ListEditor.SelectionType property. Since the List Editor supports selection which is active only while a postback is processed, this property must return the SelectionType.TemporarySelection value.
- Override the ListEditor.GetSelectedObjects method. This method must return a list of the selected objects. In our case, this is the focused object.
- Override the ListEditor.ContextMenuTemplate property. This property is used to support the List Editor's context menu. Since Internet browsers already have a context menu, we return null in this property.
using System.Collections; using System.Collections.Generic; using DevExpress.ExpressApp; using DevExpress.ExpressApp.Templates; // ... [ListEditor(typeof(IPictureItem))] public class ASPxCustomListEditor : ListEditor { //... public override SelectionType SelectionType { get { return SelectionType.TemporarySelection; } } public override IList GetSelectedObjects() { List<object> selectedObjects = new List<object>(); if(FocusedObject != null) { selectedObjects.Add(FocusedObject); } return selectedObjects; } public override IContextMenuTemplate ContextMenuTemplate { get { return null; } } } | https://docs.devexpress.com/eXpressAppFramework/113126/task-based-help/list-editors/how-to-implement-an-asp-net-web-list-editor-using-a-custom-control?p=netcore | CC-MAIN-2020-34 | en | refinedweb |
Natural Language Toolkit (NLTK) Sample and Tutorial: Part 1
Natural Language Toolkit (NLTK) Sample and Tutorial: Part 1
Join the DZone community and get the full member experience.Join For Free
What is NLTK?
Natural Language Toolkit (NLTK) is a leading platform for building Python programs to work with human language data (Natural Language Processing). It is accompanied by a book that explains the underlying concepts behind the language processing tasks supported by the toolkit. NLTK is intended to support research and teaching in NLP or closely related areas, including empirical linguistics, cognitive science, artificial intelligence, information retrieval, and machine learning.
The library contains
- Lexical analysis: Word and text tokenizer
- n-gram and collocations
- Part-of-speech tagger
- Tree model and Text chunker for capturing
- Named-entity recognition
Download and Install
1. You can download NLTK from here in windows
2. Once NLTK is installed, start up the Python interpreter to install the data required for rest of the work.
import nltk nltk.download()
It consists of about 30 compressed files requiring about 100Mb disk space. If any disk space issue or network issue you can pick only what you need.
Once the data is downloaded to your machine, you can load some of it using the Python interpreter.
from nltk.book import *
Basic Operation in Text
from __future__ import division from nltk.book import * #Enter their names to find out about these texts print text3 #Length of a text from start to finish, in terms of the words and punctuation symbols that appear. print 'Length of Text: '+str(len(text3)) #Text is just the set of tokens #print sorted(set(text3)) print 'Length of Token: '+str(len(set(text3))) #lexical richness of the text def lexical_richness(text): return len(set(text)) / len(text) #percentage of the text is taken up by a specific word def percentage(word, text): return (100 * text.count(word) / len(text)) print 'Lexical richness of the text: '+str(lexical_richness(text3)) print 'Percentage: '+ str(percentage('God',text3));
Now we will pick ‘text3’ called '”The Book of Genesis” to try NLTK features. The above code sample shows:
- Name of the Text
- The length of a text from beginning to end
- Token count of the text. (A token is the technical name for a sequence of characters. Text is just the set of tokens that it uses, since in a set, all duplicates are collapsed together.)
- Calculate a measure of the lexical richness of the text (number of distinct words by total number of words)
- How often a word occurs in a text (compute what percentage of the text is taken up by a specific word)
Note
In Python 2, to start with from __future__ import for division.
Output of above code snippet
Searching Text
- Count(word) - support count the word in the text
- Concordance(word) - give every occurrence of a given word, together with some context.
- Similar(word) - appending the term similar to the name of the text
- Common_contexts([word]) - contexts are shared by two or more words
from nltk.book import * #names of the Text print text3 #count the word in the Text print "===Count===" print text3.count("Adam") #'concordance()' view shows us every occurrence of a given word, together with some context. #Here 'Adam' search in 'The Book of Genesis' print "===Concordance===" print text3.concordance("Adam") #Appending the term similar to the name of the text print "===Similar===" print text3.similar("Adam") #Contexts are shared by two or more words print "===Common Contexts===" text3.common_contexts(["Adam", "Noah"])
Output of the code sample:
Now I need plot words that are distributed over the text, such as "God", "Adam", "Eve", "Noah", "Abram","Sarah", "Joseph", "Shem", "Isaac".
text3.dispersion_plot(["God","Adam", "Eve", "Noah", "Abram","Sarah", "Joseph", "Shem", "Isaac"])
References
[1] Bird, Steven; Klein, Ewan; Loper, Edward (2009). Natural Language Processing with Python. O'Reilly Media Inc. ISBN 0-596-51649-5. }} | https://dzone.com/articles/natural-language-toolkit-nltk | CC-MAIN-2020-34 | en | refinedweb |
Hi, today I give a step by step guide to use mongoDB Atles with a python program. I decided to use the cloud version since it’s easy and as well as free. And most importantly I got ‘Unable to locate package mongodb-org/mongo’ error while trying to install on Kali 2020.1. If you still want to install mongodb on host please refer to this.
Step 1: Create an Account of MongoDB Atlas
Visit to create a free account.
Step 2: Next Create a New Cluster
You have to give the IP address that can access the cluster. It could be your device or can allow for anyone.
- Find IP of your device: On browser visit
- The IP for anyone to access : 0.0.0.0/0 (Have security issues)
Next, give give the name and password for a DB user. These credentials later required to connect with the cluster from the python program.
Step 3. Connect the DB
Since I’m using the MongoDB within a Python program, I select as follows.
“Connect Your Application” -> Choose “Python” driver and version (3.6 or later) used in the program
Next, copy the generated String and replace the <password> with the given password when generating the DB user.
Step 4. Generate a Database and a Collection
Select ‘Collection’ –> It will prompt to create the database. Provide a name from Database and a Collection. –> Create
Step 5: Update Python Program
You should install the pymongo driver to use with the program.
from pymongo import MongoClient client = MongoClient(<Past the generated String >)db = client.get_database('service')collection = db.get_collection('authdetails')
Cheers ! | https://techstarspace.engineer/2020/03/01/use-mongodb-cloud-with-python-on-kali-2020/ | CC-MAIN-2020-34 | en | refinedweb |
Get the highlights in your inbox every week.
How to 'Kubernetize' an OpenStack service
How to 'Kubernetize' an OpenStack service
Kuryr-Kubernetes provides networking for Kubernetes pods by using OpenStack Neutron and Octavia.
Subscribe now
Kuryr-Kubernetes is an OpenStack project, written in Python, that serves as a container network interface (CNI) plugin that provides networking for Kubernetes pods by using OpenStack Neutron and Octavia. The project stepped out of its experimental phase and became a fully supported OpenStack ecosystem citizen in OpenStack's Queens release (the 17th version of the cloud infrastructure software).
One of Kuryr-Kubernetes' main advantages is you don't need to use multiple software development networks (SDNs) for network management in OpenStack and Kubernetes. It also solves the issue of using double encapsulation of network packets when running a Kubernetes cluster on an OpenStack cloud. Imagine using Calico for Kubernetes networking and Neutron for networking the Kubernetes cluster's virtual machines (VMs). With Kuryr-Kubernetes, you use just one SDN—Neutron—to provide connectivity for the pods and the VMs where those pods are running.You can also run Kuryr-Kubernetes on a bare-metal node as a normal OpenStack service. This way, you can provide interconnectivity between Kubernetes pods and OpenStack VMs—even if those clusters are separate—by just putting Neutron-agent and Kuryr-Kubernetes on your Kubernetes nodes.
Kuryr-Kubernetes consists of three parts:
- kuryr-controller observes Kubernetes resources, decides how to translate them into OpenStack resources, and creates those resources. Information about OpenStack resources is saved into annotations of corresponding Kubernetes resources.
- kuryr-cni is an executable run by the CNI that passes the calls to kuryr-daemon.
- kuryr-daemon should be running on every Kubernetes node. It watches the pods created on the host and, when a CNI request comes in, wires the pods according to the Neutron ports included in the pod annotations.
In general, the control part of a CNI plugin (like Calico or Nuage) runs as a pod on the Kubernetes cluster where it provides networking, so, naturally, the Kuryr team decided to follow that model. But converting an OpenStack service into a Kubernetes app wasn't exactly a trivial task.
Kuryr-Kubernetes requirements
Kuryr-Kubernetes is just an application, and applications have requirements. Here is what each component needs from the environment and how it translates to Kubernetes' primitives.
kuryr-controller
- There should be exactly one instance of kuryr-controller (although that number may be higher with the A/P high-availability feature implemented in OpenStack Rocky). This is easy to achieve using Kubernetes' Deployment primitive.
- Kubernetes ServiceAccounts can provide access to the Kubernetes API with a granular set of permissions.
- Different SDNs provide access to the OpenStack API differently. API SSL certificates should also be provided, for example by mounting a Secret in the pod.
- To avoid a chicken-and-egg problem, kuryr-controller should run with hostNetworking to bypass using Kuryr to get the IP.
- Provide a kuryr.conf file, preferably by mounting it as a ConfigMap.
In the end, we get a Deployment manifest similar to this:
apiVersion: apps/v1beta1
kind: Deployment
metadata:
labels:
name: kuryr-controller
name: kuryr-controller
namespace: kube-system
spec:
replicas: 1
template:
metadata:
labels:
name: kuryr-controller
name: kuryr-controller
spec:
serviceAccountName: kuryr-controller
automountServiceAccountToken: true
hostNetwork: true
containers:
- image: kuryr/controller:latest
name: controller
volumeMounts:
- name: config-volume
mountPath: "/etc/kuryr/kuryr.conf"
subPath: kuryr.conf
- name: certificates-volume
mountPath: "/etc/ssl/certs"
readOnly: true
volumes:
- name: config-volume
configMap:
name: kuryr-config
- name: certificates-volume
secret:
secretName: kuryr-certificates
restartPolicy: Always
kuryr-daemon and kuryr-cni
Both of these components should be present on every Kubernetes node. When the kuryr-daemon container starts on the Kubernetes nodes, it injects the kuryr-cni executable and reconfigures the CNI to use it. Let's break that down into requirements.
- kuryr-daemon should run on every Kubernetes node. This means it can be represented as a DaemonSet.
- It should be able to access the Kubernetes API. This can be implemented with ServiceAccounts.
- It also needs a kuryr.conf file. Again, the best way is to use a ConfigMap.
- To perform networking operations on the node, it must run with hostNetworking and as a privileged container.
- As it needs to inject the kuryr-cni executable and the CNI configuration, the Kubernetes nodes' /opt/cni/bin and /etc/cni/net.d directories must be mounted on the pod.
- It also needs access to the Kubernetes nodes' netns, so /proc must be mounted on the pod. (Note that you cannot use /proc as a mount destination, so it must be named differently and Kuryr needs to be configured to know that.)
- If it's running with the Open vSwitch Neutron plugin, it must mount /var/run/openvswitch.
- To identify pods running on its node, nodeName should be passed into the pod. This can be done using environment variables. (This is also true with the pod name, which will be explained below.)
This produces a more complicated manifest:
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
name: kuryr-cni
namespace: kube-system
labels:
name: kuryr-cni
spec:
template:
metadata:
labels:
Name: kuryr-cni
spec:
hostNetwork: true
serviceAccountName: kuryr-controller
containers:
- name: kuryr-cni
image: kuryr/cni:latest
command: [ "cni_ds_init" ]
env:
- name: KUBERNETES_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: KURYR_CNI_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
securityContext:
privileged: true
volumeMounts:
- name: bin
mountPath: /opt/cni/bin
- name: net-conf
mountPath: /etc/cni/net.d
- name: config-volume
mountPath: /etc/kuryr/kuryr.conf
subPath: kuryr-cni.conf
- name: proc
mountPath: /host_proc
- name: openvswitch
mountPath: /var/run/openvswitch
volumes:
- name: bin
hostPath:
path: /opt/cni/bin
- name: net-conf
hostPath:
path: /etc/cni/net.d
- name: config-volume
configMap:
name: kuryr-config
- name: proc
hostPath:
path: /proc
- name: openvswitch
hostPath:
path: /var/run/openvswitch
Injecting the kuryr-cni executable
This part took us the longest time. We went through four different approaches until everything worked. Our solution was to inject a Python application from the container into the container's host and to inject the CNI configuration files (but the latter is trivial). Most of the issues were related to the fact that Python applications aren't binaries, but scripts.
We first tried making our kuryr-cni script a binary using PyInstaller. Although this worked fairly well, it had serious disadvantages. For one thing, the build process was complicated—we had to create a container with PyInstaller and Kuryr-Kubernetes that generated the binary, then build the kuryr-daemon container image with that binary. Also, due to PyInstaller quirks, we ended up with a lot of misleading tracebacks in kubelet logs, i.e., in exceptions, we could get the wrong traceback on the logs. The deciding factor was that PyInstaller changed paths to the included Python modules. This meant that some checks in the os.vif library failed and broke our continuous integration (CI).
We also tried injecting a Python virtual environment (venv) containing a CPython binary, the kuryr-kubernetes package, and all its requirements. The problem is Python venvs aren't designed to be portable. Even though there is a --relocatable option in the virtualenv command-line tool, it doesn't always work. We abandoned that approach.
Then we tried what we think is the "correct" way: injecting the host with an executable script that does docker exec -i on a kuryr-daemon container. Because the kuryr-kubernetes package is installed in that container, it can easily execute the kuryr-cni binary. All the CNI environment variables must be passed through the docker exec command, which has been possible since Docker API v1.24. Then, we only needed to identify the Docker container where it should be executed.
At first, we tried calling the Kubernetes API from the kuryr-daemon container's entry point to get its own container ID. We quickly discovered that this causes a race condition, and sometimes the entry point runs before the Kubernetes API is updated with its container ID. So, instead of calling the Kubernetes API, we made the injected CNI script call the Docker API on the host. Then it's easy to identify the kuryr-daemon container using labels added by Kubernetes.
Lessons learned
In the end, we've got a working system that is easy to deploy and manage because it's running on Kubernetes. We've proved that Kuryr-Kubernetes is just an application. While it took a lot of time and effort, the results are worth it. A "Kubernetized" application is much easier to manage and distribute.
Michał Dulko will present How to make a Kubernetes app from an OpenStack service at OpenStack Summit, November 13-15 in Berlin. | https://opensource.com/article/18/10/how-kubernetize-openstack-service | CC-MAIN-2020-34 | en | refinedweb |
Introduction to Methods in Java
A method in java can be defined as a set of logical java statements written in order to perform a specific task. They provide a way to reuse code without writing the code again. In Java, any method should be part of a class that is different from Python, C, and C++. The existence of methods is not possible without a java class. Here is the list of components involved while creating java methods:
Components for Creating Java Methods
Here is the list of components involved while creating java methods:
- Access Modifier: In java, there exist four different types of access modifiers:
- Public: Methods declared as public are accessible from all classes within an application.
- Protected: Methods declared as protected are accessible from the class within which it is defined and all subclasses of that class.
- Private: Methods declared as private are only accessible from the class within which it is defined.
- Default: Methods declared as default are accessible from the class within which it is defined and from classes declared within the same package as the class enclosing the method.
- Return Type: This contains the data type of the value the method is supposed to return or it is void if the method does not return anything.
- Method Name: This is the named assigned to the method, which may or may not be unique. It is to be noted that the method name should be verbs and words used show follow camel case notation.
- Parameters: This includes a list of input parameters separated by commas with their data types. If the method does not require any input parameters then () is used.
- Exceptions: In case a method may throw one or more exceptions, we can list exceptions separated by commas.
- Method Body: It is the programming content enclosed between braces. The method body contains one or more logical statements for executing a particular task.
Syntax:
Here is a basic syntax of methods:
//declare Enclosing class
public class Myclass{
//declare java method
public String concat(String s1, String s2){
// combine two strings with space
String s3= s1 + " " + s2 ;
//return resulting string
return s3;
}
}
Types of Methods in Java
Methods can be categorized in the following two types:
- Build-in Methods: These methods are available in the java library and does not need to be created by a developer. For example max() method present in Math class in java.
- User-defined Methods: These methods are explicitly defined by a developer in java classes.
Calling a Java Method
When a method is called by a calling program, the control goes into the method body. After control goes to method body, it returns to the calling program under the following three conditions:
- All statements written inside the method body are executed successfully.
- Any return statement is encountered.
- An Exception is thrown.
Static methods are called using class name and non-static methods are called using object instance.
Example #1
Now we will see java code examples show how methods are declared and called using java. In this example, we will see how to create a static method and how is it called.
Code:
package com.edubca.methods;
public class MethodDemo{
public static int getMaximum(int a , int b){
if(a>b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
int maxvalue1 = getMaximum(10,23);
System.out.println("Out of 10 and 23, " + maxvalue1 + " is greater" );
int maxvalue2= getMaximum(40,20);
System.out.println("Out of 40 and 20, " + maxvalue2 + " is greater" );
}
}
Output:
Example #2
In the next example, we will see how to call non–static methods.
Code:
package com.edubca.methods;
public class MethodDemo{
public int getMinimum(int a , int b){
if(a<b){
return a;
}else {
return b;
}
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
int minvalue1 = demo.getMinimum(10,23);
System.out.println("Out of 10 and 23, " + minvalue1 + " is smaller" );
int minvalue2= demo.getMinimum(40,20);
System.out.println("Out of 40 and 20, " + minvalue2 + " is smaller" );
}
}
As we can see above an instance of an enclosing class is required to call a non-static method. The above code will produce the following output:
Output:
Example #3
In the next example, we how to create methods throwing exceptions.
Code:
import java.io.*;
package com.edubca.methods;
public class MethodDemo{
public void mymethod() throws IOException{
throw new IOException("IO Exception occurred...");
}
public static void main (String args[]){
MethodDemo demo =new MethodDemo();
try{
demo.mymethod();
}catch(Exception e){
e.printStackTrace();
}
}
}
As we can see from the above code, whenever a method throws an exception caller of the method must handle exception using try-catch or any other suitable error handling mechanism. The above code shows the below output on screen:
Output:
Conclusion
From the above article, we have a clear idea about methods in java. Therefore will the help of methods we can achieve any task. Using methods make our code reusable and easy to test, understand and debug.
Recommended Articles
This is a guide to Methods in Java. Here we discuss the types of methods and list of components involved while creating java methods along with examples and its code implementation. You may also look at the following articles to learn more – | https://www.educba.com/methods-in-java/?source=leftnav | CC-MAIN-2020-34 | en | refinedweb |
For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See:
How to write an indicator equivalent to pandas.expanding().mean()?
I've read the following source code:
It seems every indicator has a
period.
I found no way to implement an indicator with the following logic:
import pandas as pd data = pd.Series([1.0, 2.0, 3.0, 4.0]) indicators = data.expanding(2).mean()
Any ideas? Thanks
I assume that equivalent will be this formula in the
value = sum(self.data.close.get(size=len(self.data)))/len(self.data)
@ab_trader It works, thanks!
I implemented the EWMAC strategy from the book "Systematic Trading" by Robert Carver, Jupyter notebook: | https://community.backtrader.com/topic/2763/how-to-write-an-indicator-equivalent-to-pandas-expanding-mean | CC-MAIN-2020-34 | en | refinedweb |
SortColumn
Since: BlackBerry 10.0.0
#include <bb/pim/contacts/ContactConsts>
The SortColumn class represents the columns that can be used to sort contacts.
You can use the SortColumn::Type enumeration to specify the columns that should be used to sort contacts. For example, you can use a SortColumn::Type enumeration value in ContactListFilters::setSortBy() to sort contacts by first name, last name, or company name.
Overview
Public Types Index
Public Types
An enumeration of possible columns that can be used to sort contacts.
BlackBerry 10.0.0
- FirstName 0
Indicates that contacts should be sorted by FirstName.
- LastName 1
Indicates that contacts should be sorted by LastName.Since:
BlackBerry 10.0.0
- CompanyName 2
Indicates that contacts should be sorted by CompanyName.Since:
BlackBerry 10.0.0
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/cascades/bb__pim__contacts__sortcolumn.html | CC-MAIN-2020-34 | en | refinedweb |
I mentioned that I worked together with Paul Hellawell of GHD on a full-blown end-user-capable little application for the automatic creation of setout points for on-site location and construction of structural elements at the Melbourne DevLab.
Paul provided a description of the task and the initial idea for an implementation approach.
We got the application to a useful working state in the two days during the DevLab, and Paul has provided it to his designers to use in real projects ever since.
Before we look at the full-fledged application, let's explore the core API functionality required:
- Filtering for structural concrete elements.
- Retrieving their corners, i.e. geometry traversal to retrieve unique vertices.
- Converting from Revit model to real-world coordinates.
Once this is all in place, we can explain how to use the core functionality to implement the real-world end-user application.
Filtering for Structural Concrete Elements
We already looked at retrieving structural elements.
Just like there, we check for certain specific classes like Wall and Floor, and also for generic family instances with categories from our list of interest, including structural columns, framing, foundation, floors and ramps.
In this case, we are only interested in concrete elements, so we apply two structural material type filters as well, for concrete and precast concrete.
This is the method we ended up with to suit our purposes:
/// <summary> /// Retrieve all structural elements that we are /// interested in using to define setout points. /// We are looking at concrete for the moment. /// This includes: columns, framing, floors, /// foundations, ramps, walls. /// </summary> FilteredElementCollector GetStructuralElements( Document doc ) { // What categories of family instances // are we interested in? BuiltInCategory[] bics = new BuiltInCategory[] { BuiltInCategory.OST_StructuralColumns, BuiltInCategory.OST_StructuralFraming, BuiltInCategory.OST_StructuralFoundation, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Ramps }; IList<ElementFilter> a = new List<ElementFilter>( bics.Length ); foreach( BuiltInCategory bic in bics ) { a.Add( new ElementCategoryFilter( bic ) ); } LogicalOrFilter categoryFilter = new LogicalOrFilter( a ); // Filter only for structural family // instances using concrete or precast // concrete structural material: List<ElementFilter> b = new List<ElementFilter>( 2 ); b.Add( new StructuralMaterialTypeFilter( StructuralMaterialType.Concrete ) ); b.Add( new StructuralMaterialTypeFilter( StructuralMaterialType.PrecastConcrete ) ); LogicalOrFilter structuralMaterialFilter = new LogicalOrFilter( b ); List<ElementFilter> c = new List<ElementFilter>( 3 ); c.Add( new ElementClassFilter( typeof( FamilyInstance ) ) ); c.Add( structuralMaterialFilter ); c.Add( categoryFilter ); LogicalAndFilter familyInstanceFilter = new LogicalAndFilter( c ); IList<ElementFilter> d = new List<ElementFilter>( 6 ); d.Add( new ElementClassFilter( typeof( Wall ) ) ); d.Add( new ElementClassFilter( typeof( Floor ) ) ); //d.Add( new ElementClassFilter( // typeof( ContFooting ) ) ); #if NEED_LOADS d.Add( new ElementClassFilter( typeof( PointLoad ) ) ); d.Add( new ElementClassFilter( typeof( LineLoad ) ) ); d.Add( new ElementClassFilter( typeof( AreaLoad ) ) ); #endif d.Add( familyInstanceFilter ); LogicalOrFilter classFilter = new LogicalOrFilter( d ); FilteredElementCollector col = new FilteredElementCollector( doc ) .WhereElementIsNotElementType() .WherePasses( classFilter ); return col; }
Geometry Traversal to Retrieve Unique Vertices
Once the required elements have been retrieved, we analyse their geometry to determine all corners, i.e. geometry vertices.
This goes back to the second day of the Melbourne Revit API training, where we looked at retrieving unique geometry vertices from a selected element.
This involves comparing XYZ points, i.e. real number equality testing.
First of all, we need an equality comparer for points:
/// PointString( p ).GetHashCode(); } }
With that in hand, we can retrieve all unique vertices of a given solid retrieved from the element geometry:
/// <summary> /// Return all the "corner" vertices of a given solid. /// Note that a circle in Revit consists of two arcs /// and will return a "corner" at each of the two arc /// end points. /// </summary> solid is retrieved by traversing the element geometry and picking the first non-empty one found.
Special handling is required for family instances, of course, since they have an additional transformation that we have to take account of. The family definition defines its own local coordinate system, and we need to transform the solid from that to the Revit model space.
This implementation processes all the cases we have run into so far correctly and elegantly:
/// ) { GeometryElement geo = e.get_Geometry( opt ); Solid solid = null; GeometryInstance inst = null; Transform; }
Transforming Revit Model Coordinates to the Real World
After the solid vertices have been retrieved in Revit model space, we convert them to real-world coordinates using the project location.
We initially tried to achieve this piecewise by fiddling with the base point offset and manually rotating to project north. This was both complicated and returned incorrect results.
The correct solution is very simple and was already discussed a couple of times in the past:
This led us to implement the following GetProjectLocationTransform method:
/// <summary> /// Return the project location transform. /// </summary> Transform GetProjectLocationTransform( Document doc ) { // Retrieve the active project location position. ProjectPosition projectPosition = doc.ActiveProjectLocation.get_ProjectPosition( XYZ.Zero ); // Create a translation vector for the offsets XYZ translationVector = new XYZ( projectPosition.EastWest, projectPosition.NorthSouth, projectPosition.Elevation ); Transform translationTransform = Transform.get_Translation( translationVector ); // Create a rotation for the angle about true north Transform rotationTransform = Transform.get_Rotation( XYZ.Zero, XYZ.BasisZ, projectPosition.Angle ); // Combine the transforms Transform finalTransform = translationTransform.Multiply( rotationTransform ); return finalTransform; }
Making use of the resulting transform later is trivial:
Transform projectLocationTransform = GetProjectLocationTransform( doc ); for each concrete corner point XYZ p: { // Transform insertion point by applying // project location transformation. XYZ r2 = projectLocationTransform.OfPoint( p ); }
Now I just need to find some more time to discuss how this can all be put together and wrapped into a useful real-world end-user application. | https://thebuildingcoder.typepad.com/blog/2012/06/real-world-concrete-corner-coordinates.html | CC-MAIN-2020-34 | en | refinedweb |
Related
Tutorial
Using Bootstrap 4 Bootstrap 4 beta is “right around the corner,” and I’m sure there are plenty who are excited to start using it with Vue. Well, they already can, using bootstrap-vue. However, be warned that bootstrap-vue (like Bootstrap 4) is not yet stable, and usage may change between releases.
Installation
As usual, bootstrap-vue can be installed from NPM or Yarn. You’ll also want to install the normal bootstrap package for styles.
# Yarn $ yarn add bootstrap-vue bootstrap # NPM $ npm install bootstrap-vue bootstrap --save
Then, in your app’s main file, enable the VueBootstrap plugin.
import Vue from 'vue'; import BootstrapVue from 'bootstrap-vue/dist/bootstrap-vue.esm'; import App from 'App.vue'; // Import the styles directly. (Or you could add them via script tags.) import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap-vue/dist/bootstrap-vue.css'; Vue.use(BootstrapVue); new Vue({ el: '#app', render: h => h(App) });
NOTE: Styles are injected globally and may affect other components. Use with care.
Components
NOTE: You don’t need to worry about including Bootstrap’s JS, interactivity is handled by the components.
Usage
Just use the various components in your app as normal! Non-interactive elements are still handled via CSS, so don’t get too worried about it deprecating all your current Bootstrap knowledge.
<template> <b-card no-block> <b-tabs> <b-tab Tab 1 Contents </b-tab> <b-tab Tab 2 Contents <b-buttonBoop</b-button> </b-tab> <b-tab title="Tab 3" disabled> Tab 3 Contents </b-tab> </b-tabs> </b-card> </template>
Documentation
Obviously there’s not a lot here to help you write a complete app, so consult the docs for Bootstrap Vue, and Bootstrap 4. | https://www.digitalocean.com/community/tutorials/vuejs-using-bootstrap4 | CC-MAIN-2020-34 | en | refinedweb |
Functions in C++ programming
Definition of C++ function
A function is a collection of statements that performs a specific task. So far you have used functions in two ways:
- you have created a function called main in every program you’ve written.
- you have called library functions such as pow and sqrt.
Functions are commonly used to break a problem down into small manageable pieces, or modules.
Instead of writing one long function that contains all the statements necessary to solve a problem, several smaller functions can be written, with each one solving a specific part of the problem.
Defining and calling functions
A function call is a statement that causes a function to execute. A function definition contains the statements that make up the function. When creating a function, you must write its definition. All function definitions have the following parts:
- Name. Every function must have a name. In general, the same rules that apply to variable names also apply to function names.
- Parameter list. The parameter list is the list of variables that hold the values being passed to the function. If no values are being passed to the function, its parameter list is empty.
- Body. The body of a function is the set of statements that carry out the task the function is performing. These statements are enclosed in a set of braces.
- Return type. A function can send a value back to the program module that called it. The return type is the data type of the value being sent back.
A function is executed when it is called. Function main is called automatically when a program starts, but all other functions must be executed by function call statements.
#include <iostream> using namespace std; void displayMessage() // create displayMessage function { cout << "Hello from the function displayMessage.\n"; } int main() { cout << "Hello from main.\n"; displayMessage(); // Call displayMessage function return 0; }
Output: Hello from main. Hello from the function displayMessage.
Each call statement causes the program to branch to a function and then back to main when the function is finished.
Any argument listed inside the parentheses of a function call is copied into the function’s parameter variable.
In essence, parameter variables are initialized to the value of the corresponding arguments passed to them when the function is called.
The program demonstrates a function with a parameter.
#include <iostream> using namespace std; // Function prototype void displayValue(int num); int main() { cout << "I am passing several values to displayValue.\n"; displayValue(5); // Call displayValue with argument 5 displayValue(10); // Call displayValue with argument 10 displayValue(2); // Call displayValue with argument 2 displayValue(16); // Call displayValue with argument 16 cout << "Now I am back in main.\n"; return 0; } void displayValue(int num) { cout << "The value is " << num << endl; }
Output: I am passing several values to displayValue. The value is 5 The value is 10 The value is 2 The value is 16 Now I am back in main.
The displayValue function is called four times, and each time num takes on a different value. Any expression whose value could normally be assigned to num may be used as an argument.
When a function is called, it is best if each argument passed to it has the same data type as the parameter receiving it.
Ads Right | https://www.infocodify.com/cpp/functions | CC-MAIN-2020-34 | en | refinedweb |
hornetq jmsjjgrego Jul 13, 2012 10:41 AM
We have a jboss as (6.0.0). Since hornetq is already embedded, I configured it to use jaas, since our jboss
server has it's own custom authenticator. Using the examples in the ssl-enabled and jaas folders, it appears
I've successfully completed the configuration. I had to work through a couple errors, but finally, jboss started
without error.
Next, I wrote a MDB and deployed it to the server. Presently, all this does is spit out the text in the
onMessage. Now, I have some logging in the constructor & init functions, but I don't see this in any
log files. There are no errors printing, so I'm not sure if it deployed properly. I have other beans where
I do this same similar set up, but the logging prints out. The difference is it was on a weblogic server...
Now, I want to post a message to the queue and see whether the mdb picks it up.
I wrote my client mirroring the examples in the hornetq example folder. One major difference is that
my client class doesn't extend HornetQExample. When I create my initial context to do a jndi lookup
on the queue name, I get an exception that there is "no such object in the table". When I bring up the
jboss jmx-console, I can see that this object does in fact exist.
Our jboss server is sitting on one of our lab machines labvm014. My client is on labvm025. I'm guessing there
is some "other" configuration required, but not certain what that would be. I need to be able to require it to
use 2-way ssl, which in my client is the first step.
In the configuration of the server, I changed all instances of "localhost" to labvm014, as that is the name of the
machine.
Can anyone shed some light on what I may need to do in order to get this to work??
Thanks,
John
1. Re: hornetq jmsjbertram Jul 23, 2012 10:25 AM (in response to jjgrego)
Let's tackle one issue at a time. Which is the most important issue for you at this point? These are the ones I noted:
- MDB init/ctor logging.
- JNDI look-up from the client.
- 2-way SSL.
2. Re: hornetq jmsjjgrego Jul 23, 2012 11:03 AM (in response to jbertram)
Justin,
Thanks for checking in. I'm at a loss as to what to try here.
I guess the most important thing is doing a jndi lookup from my standalone client. I've followed the hornetq configuration for the jaas and ssl-enabled
examples, so I think I'm good to go there. At least for now.
Now, I'm just trying to bind to my queue so I can put a message on it.
You list 2-way ssl as item 3, but this is requirement. I've done 2-way ssl before w/weblogic, but not jboss. I can create a regular queue
and put messages on it using the regular jboss properties stuff...just never done this with hornetq though.
Thanks,
John
3. Re: hornetq jmsjbertram Jul 23, 2012 1:33 PM (in response to jjgrego)
I guess the most important thing is doing a jndi lookup from my standalone client.
My understanding is that you have a remote client trying to perform a JNDI lookup on JBoss AS 6 for HornetQ JMS resources. Is that correct? If so you should be able to use code like this:
import java.util.Properties; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Session; import javax.naming.InitialContext; ... Properties props = new Properties(); props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); props.put("java.naming.provider.url", "jnp://127.0.0.1:1099"); props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); InitialContext initialcontext = new InitialContext(props); ConnectionFactory connectionFactory = (ConnectionFactory) initialcontext.lookup("ConnectionFactory"); connection = connectionFactory.createConnection(); Destination destination = (Destination) initialcontext.lookup("/queue/A"); initialcontext.close(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(destination); Message msg = session.createTextMessage("example text"); producer.send(msg); connection.close();
4. Re: hornetq jmsjjgrego Jul 23, 2012 2:53 PM (in response to jbertram)
Justin,
Yes, I have a remote client attempting to do a jndi lookup on a on a jboss AS 6 server to send a message to a hornetq configured queue.
Prior to configuring hornetq for jaas and ssl-enabling it, the snippet worked, provided my client jboss are on the same machine. However,
since my client resides on a different machine, I changed the provider.url to:
jnp://mytestmachine:1099.
The resulting naming exception states that it failed to retrieve Naming interface for provider
Not quite sure where it pulled that http.
John
5. Re: hornetq jmsjbertram Jul 23, 2012 2:58 PM (in response to jjgrego)
Couple of questions..
- Can you paste the full exception here?
- Are there any errors in the server's log?
- To what interface are you binding the server (e.g. using the "-b" command line option)?
- Does it work with JAAS and SSL when the client and server are on the same machine?
6. Re: hornetq jmsjjgrego Jul 23, 2012 3:10 PM (in response to jbertram)
Justin,
Nevermind when I said I don't know where it's pulling the http when I passed jnp. During some digging I changed the name
of the initial factory.
I've since changed it and now get a different error stating the connection was refused to host 127.0.0.1...
John
7. Re: hornetq jmsjjgrego Jul 23, 2012 3:50 PM (in response to jbertram)
Justin,
My client can send a message, provided it is on the same machine...I got it to send one. I did this by changing the settings
to what you had in your snippet above. My mdb threw all kinds of errors, but I'll look @ those tomorrow. BTW, when the mdb
picked up the message, I saw some of the logging i inserted in the thing...progress.
After I finished sending the jms message from the local machine, I went back to my remote client to connect and got a connection
exception. It has to be a remote client because the process that puts the message on the server is a cron job that runs daily to
perform updates.
As for the stack trace, this machine and my client machines are on different networks and can't be connected. I'll look at pasting the
exception on the remote client tomorrow.
This snippet:
<!-- Trying to get JAAS authentication -->
<security-domain>myapp</security-domain>
</hornetq-server>
Since I'm using jboss 6, what file do I edit? I've looked for elements hornetq-server but nothing comes up...it's getting late!
Again, appreciate your help.
John
8. Re: hornetq jmsjbertram Jul 23, 2012 5:31 PM (in response to jjgrego)
After I finished sending the jms message from the local machine, I went back to my remote client to connect and got a connection exception.
That indicates to me that one of three things is wrong:
- The client is sending the message to the wrong host.
- The network between the client and host is bad.
- The server is not configured to bind to the proper network interface and therefore is not visible to the remote client.
Since I'm using jboss 6, what file do I edit? I've looked for elements hornetq-server but nothing comes up...it's getting late!
In JBoss AS 6 you need to edit the HornetQSecurityManager bean in hornetq-jboss-beans.xml. Add this:
<property name="securityDomainName">java:/jaas/myapp</property>
9. Re: hornetq jmsjjgrego Jul 24, 2012 8:01 AM (in response to jbertram)
Justin,
Here is the full stack trace. I had to type it as I had no way of transferring it from one system to the other.
Hopefully, you'll see something that sticks out. I know it won't connect, but what I don't know is why. The reference
to 127.0.0.1 - to me - seems like it's trying to connect to a local jboss vice the remote one
Debug - TimesSocketFactory - 87 createSocket, hostAddr: mytestmachine/7.... port: 1099 localAddr: null localPort: 0
timeOut: 0
Debug - Main - 33 - Exception caught javax.naming.CommunicationException [ Root exception is java.rmi.ConnectionException:
Connection refused to host 127.0.0.1; nested exception is
java.net.ConnectionException: Connection refused ]
javax.naming.CommunicationException [ Root exception is java.rmi.ConnectionException: Connection refused to host 127.0.0.1;
nested exception is
java.net.ConnectionException: Connection refused ]
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:841)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:688)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at myjbosstest.Main.runExample(Main.java:82)
at myjbosstest.Main.main(Main.java:31)
Caused by: java.rmi.ConnectionException Connection refused to host 127.0.0.1; nested exception is;
java.net.ConnectException: Connection refused java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
at java.rmi.server.RemoteObjectInvocationHandler(RemoteObjectInvocationHandler.java:132)
at $Proxy0.lookup(Unknown Source)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:728)
... 4 more.PlainSocketImpl.(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at java.net.Socket.<init>(Socket.java:366)
at java.net.Socket.<init>(Socket.java:180)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:128)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595).
... 11 more
John
10. Re: hornetq jmsjbertram Jul 24, 2012 10:43 AM (in response to jjgrego)
Can you attach myjbosstest.Main? It looks like it is just trying to connect to the wrong host.
11. Re: hornetq jmsjjgrego Jul 24, 2012 10:51 AM (in response to jbertram)
It'll take a bit, but yes, I can. It's on the same isolated network as the one with jboss 6 installed.
However, it's just a plagarazation of the hornetq ssl-enabled example... modified with my info. The
only difference is I setSSLEnv, which does system.setProperty for keystore and truststore, and maybe
modifying the text of the message sent.
John
12. Re: hornetq jmsjbertram Jul 24, 2012 10:55 AM (in response to jjgrego)
All I really need to see is what properties you are passing to the InitialContext.
13. Re: hornetq jmsjjgrego Jul 24, 2012 12:11 PM (in response to jbertram)
Justin,
The properties are listed in a Hashtable<String, String> variable called props.
props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
props.put("java.naming.provider.url", "jnp://mytestmachine:1099");
props.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
I've played around with the provider url, changing it to some of the following:
jnps://mytestmachine:1099
jnp://mytestmachine: 5445 // i got this port # from one of the hornetq configuration files. // this was from an example I now can't find. this also changed the type of Naming Context to some HTTP one.
John
14. Re: hornetq jmsjbertram Jul 24, 2012 1:04 PM (in response to jjgrego)
Despite what you have specified for "java.naming.provider.url" the code is somehow being told to connect to "localhost" instead. Do you have a jndi.properties file in your classpath anywhere?
Couple of other points:
- 1099 is the default JNDI port. 5445 is the default HornetQ port. You can't use the HornetQ port for a JNDI lookup.
- You can't simply swap protocols (i.e. jnps, https, etc.). | https://developer.jboss.org/message/749716 | CC-MAIN-2020-16 | en | refinedweb |
Expose JSONField data as a virtual django model fields.
Project description
Expose Django JSONField data as virtual model fields
Use ModelForm and ModelAdmin as usual. Perform simple queries. Migrate to real table columns when needed without code change.
Suitable to store dumb business data, quick prototypes without DB migrations, and replace multi-table inheritance joins.
Use with caution! Replacing relational structures with JSON data should be mindfull architecture decision.
Works with any JSONField django.contrib.postgres, django-annoying, django-mysql, upcoming django Cross-db JSONField
Work in progress part of definitions are only supported.
Quick start
from django import forms from django.contrib import admin from django.db import models from jsonfield_schema import JSONSchema class EmployeeSchema(JSONSchema): full_name = { "type": "string" } hire_date = { "type": "string", "format": "date" } salary = { "type": "number", "multiplyOf": 0.01, } class Employee(models.Model): _schema = EmployeeSchema() data = JSONField(default={}) class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['full_name', 'hire_date', 'salary'] @admin.register(Employee) class EmployeeAdmin(admin.ModelAdmin): list_display = ['full_name', 'hire_date'] fields = ['full_name', ('hire_date', 'salary')]
Demo
The demo shows how to handle multiple User types within single table with JSONField and Django-Polymodels proxies.
$ export DATABASE_URL=postgresql://viewflow:viewflow@localhost/viewflow $ export DJANGO_SETTINGS_MODULE=demo.settings $ tox python manage.py migrate $ tox python manage.py runserver
License
Django JSONField-Schema is an Open Source project licensed under the terms of the AGPL license - The GNU Affero General Public License v3.0 with the Additional Permissions described in LICENSE_EXCEPTION
You can more read about AGPL at AGPL FAQ This package license scheme follows to GCC Runtime library licensing. If you use Linux already, probably this package license, should not bring anything new to your stack.
Latest changelog
0.3.0 2019-11-01
- Support for date/time/datetime values
- Support for help_text (description) and verbose_name (verboseName) field specs
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/django-jsonfield-schema/ | CC-MAIN-2020-16 | en | refinedweb |
When working in the field, typing information is often tedious and a source of collection errors. While there are many ways to improve the efficiency of collecting attribute information, one of the most useful is through using barcodes. We find barcodes on many items, from cereal boxes to books. Capturing barcodes is fast, accurate, and doesn’t require any additional equipment. In this blog post we’ll show you how to quickly capture barcodes in Collector. In addition, we’ll use arcade expressions to decipher information stored in the barcode to make it available immediately to those in the field as well as the office.
The natural gas industry in the US is required to be able to identify information for any gas distribution component. This includes production date, manufacturer, component size or sizes for a given gas distribution components encoded using the ASTM F2897 standard. The specification defines requirements for the data and the format of the resultant barcode to characterize various components used in fuel gas piping systems. Each gas component has a printed barcode that stores this information in a compact manner. Unfortunately, the compact nature means it is difficult to understand the information it contains.
Capturing the barcode
Let’s start off by capturing a barcode for a new gas service line. From within Collector it’s easy to access the barcode scanner and populate any text or numeric field. In our case we’re using a field specifically intended to store the scanned barcode value. This is a really efficient way to accurately capture information about an asset in the field. Once we’ve scanned the barcode, we submit the edit.
Let’s take a look at the resulting popup, paying specific attention to the Component Details section as well as the title. This displays all the information we’ve derived from the barcode, such as the production date and lot number.
Extracting information from the barcode with Arcade
Each piece of information is extracted from the barcode using an Arcade expression. These expressions can be used within the popup, as well as labels to display the result. The following Arcade expression extracts the lot number from the barcode.
var base62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; var BARCODE = $feature.BARCODE; // extract the encoded lot number from the barcode var lotnumberEncoded = Mid(BARCODE,2,4); // unencode the lot number var manufacturerLotCode = 0; for (var z=0;z < Count(lotnumberEncoded);z++) { manufacturerLotCode = manufacturerLotCode * Count(base62) + Find(Mid(lotnumberEncoded,z,1), base62); }; return (manufacturerLotCode);
The Arcade expressions are processed immediately in Collector, even when working offline. All of the Arcade expressions used to decode the barcode are available on Github.
Testing the solution
Want to give it a try yourself? Head over to our Try It account and open the Gas network map.
Open the Gas Network map. Scan this example barcode in Collector, and view the information in the popup once you submit your feature.
Summary
This is just one example of how you can use barcodes in your field data collection workflows. Give them a try, increase the productivity of your asset inspections, and unlock the information for the organization to easily access.
More Information
Learn more about how to take advantage of Collector as part of a broader tracking and traceability solution for gas utilities in this GeoNet post.
Arcade developer reference
Capturing barcodes in Collector
Commenting is not enabled for this article. | https://www.esri.com/arcgis-blog/products/collector/field-mobility/capture-barcodes-arcade-collector/ | CC-MAIN-2020-16 | en | refinedweb |
.
You may need to read my previous tutorial How to install Git on Windows
Creating a Project
This section is to learn how to create a git repository from scratch.
Creating a hello directory
Go to the physical drive
D and create a directory called
GitProjects and under this
GitProjects directory create another directory called
hello.
Creating a repository
So in the previous step I have created a
hello directory under another directory
GitProjects but the
hello directory has not yet been repository.
Now open a cmd prompt and navigate to the directory
D:\GitProjects\hello and type the command
git init to create a repository hello. You will see the message after successful creation of the git repository on directory
hello
Initialized empty Git repository in D:/GitProjects/hello/.git/
Adding a page to the repository
Create the below java class under the directory
hello
public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" to the terminal window. System.out.println("Hello, World"); } }
But the above java file has not been yet added to the repository. To add the above file to the repository, type the command
git add HelloWorld.java. Now the java file has been added to the repository but has not been committed to the repository, something similar to the SVN concept. Now to commit the file execute the command
git commit -m "First java commit", where
-m "First java commit" represents your commit comment. You will see the below message after successful commit to the repository
[master (root-commit) f7f4e7c] First java commit 1 file changed, 8 insertions(+) create mode 100644 HelloWorld.java
Checking status of the repository
This section is to learn how to check the status of repository.
To check the status of the repository execute the command
git status. You will see the below message
On branch master nothing to commit, working tree clean
The above message means that there is nothing left in the repository to commit in the current state of the working directory.
Modification on the working directory files
This section is to learn how to monitor on the state of current working directory.
Modification to the HelloWorld.java file
Let’s remove the comment
// Prints "Hello, World" to the terminal window. from the HelloWorld class
Checking the status
Run the command
git status, you will see the following message
On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: HelloWorld.java no changes added to commit (use "git add" and/or "git commit -a")
The first important point here is that git knows
HelloWorld.java file has been changed, but the changes are not yet committed to the repository.
Another point is that the status message hints about what to do next. If you want to add these changes to the repository, use
git add <file>. To undo the changes use
git checkout -- <file>.
Staging the Modifications or Changes
This section is to learn how to stage changes or modifications for the upcoming commits.
Staging is a step before the commit process in Git. That is, a commit in Git is performed in two steps: staging and actual commit. As long as a change or modification is in the staging area, Git allows you to edit it as you like (replace staged files with other versions of staged files, remove changes from staging, etc.).
Let Git know about the changes
Run the command
git add HelloWorld.java. Then again run the command
git status. You will see the following message
On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: HelloWorld.java
Changes to the
HelloWorld.java have been staged. This means that Git knows about the changes, but it is not permanent in the repository.
If you want not to commit the change, the status command above reminds you that you can use the
git reset HEAD <file> command to unstage these changes.
If you want to add multiple files to the Git repository then execute the command, for example, if you want to add three files – file1, file2, file3 to the repository,
git add file1 file2 file3
If you want your all modified files to be added to the repository then execute the command
git add -A
Commit the changes
This section is to learn how to commit the changes or modifications.
If you simply execute the command
git commit then it will ask for comment message for the commit. If you execute the command
git commit -m "<some comment>" then it will not prompt for the commit comment.
When you simply execute
git commit then you will see something similar to below window for inputting your comment for the commit and a cursor will continuously blink.
So now press
i from keyboard and write the comment as
"remove comment" and press
Esc from keyboard and type
:wq and press
Enter key.
You will see the following message in the cmd prompt
[master 76a6e8d] "remove comment" 1 file changed, 1 deletion(-)
Now if you execute command
git status then you will see the below message and it clearly says there is nothing to commit. So all commits have been made permanent to the repository.
On branch master nothing to commit, working tree clean
Project’s History
This section is to learn about the history of changes in the project or working directory.
To list the changes in a project, execute the command
git log. You will see the history of changes made to the repository
hello
commit 76a6e8d79acf28003d0ba351079bdcadab32af9c Author: moni <[email protected]> Date: Thu Jan 5 10:23:53 2017 +0530 "remove comment" commit f7f4e7c6b0a28ecd6cd59ec259fcda48d0174678 Author: moni <[email protected]> Date: Wed Jan 4 08:20:42 2017 +0530 First java commit
The above history shows in multiple lines and if you want to see it in one line, execute the command
git log --pretty=oneline. You will see the below output
76a6e8d79acf28003d0ba351079bdcadab32af9c "remove comment" f7f4e7c6b0a28ecd6cd59ec259fcda48d0174678 First java commit
You can have other options with the git log command, for example
To see the history of only last two changes:
git log --pretty=oneline --max-count=2
To see the history of changes that have happened since 04/01/2017:
git log --pretty=oneline --since='04/01/2017'
To see the history of changes that have happened until 04/01/2017:
git log --pretty=oneline --until='04/01/2017'
To see the history of changes done by an author:
git log --pretty=oneline --author=<your name>
To see the history of all changes:
git log --pretty=oneline --all
More about git log command can be found at
Thanks for reading.Tags: Version Control
2 thoughts on “Git Tutorial”
HI, Soumitra Roy Sarkar
Do you have source code in github?
No. | https://www.roytuts.com/git-tutorial/ | CC-MAIN-2020-16 | en | refinedweb |
span8
span4
span8
span4
Hello everyone!
Long time user of FME and a big lurker here!
I am currently designing a FME Server Workbench where I expect a user to upload spreadsheets that does not have any sort of schema requirements aside from Lat/Long and a prefix of 'h_' for any hyperlinks in their spreadsheet.
I currently have two branches in my workbench
BRANCH 1
With Dynamic Reader and Writers the process is relatively simple, but my issue is with the hyperlinks. My hyperlink URLs need to be wrapped with <a href> </a> tags in order to work on web app builder mapping services. This branch creates the points out of the provided Lat/Long and accepts schemas for an increase in character width for larger hyperlinks
BRANCH 2
In order to test attribute names that contain 'h_', I used an attributeexploder and was able to determine which fields have a h_ thus needing the <a href> tags. Once I have the <a href> tag in place I want to transpose it again to return it to the original state with the attribute names being the fields with 'h_' and to reconnect it to branch 1
My issue:
In branch 2 my transposition does the job of identifying my 'h_' fields, but afterwards my attempts to transpose it again is failing me! Does anyone know a solution to rebuilding attributeexploded/aggregated lists?
Hopefully I have conveyed my issue clearly otherwise I will be checking over this post for more questions.
Thanks,
Patrick
Hi @pcheng, if I understand the requirement correctly, the workflow in the attached workspace might help you: format-urls-example.fmw (FME 2016.1.3.1)
Python Edition:
def formatURLs(feature): for attr in feature.getAllAttributeNames(): if attr.startswith('h_'): v = feature.getAttribute(attr) feature.setAttribute(attr, '<a href="%s">%s</a>' % (v, v))
Tcl Edition:
proc formatURLs {} { foreach attr [FME_AttributeNames] { if {[regexp ^h_ $attr]} { set v [FME_GetAttribute $attr] FME_SetAttribute $attr "<a href=\"$v\">$v</a>" } } }
The easiest way to do this would be to use a PythonCaller to loop through all the attributes and replace the 'h_' with the tags:
import fme import fmeobjects import re def formatURLs(feature): # get names of feature attributes attNames = feature.getAllAttributeNames() # loop through attributes for att in attNames: # don't process generic attributes if not att.startswith('fme'): # get attribute value value = feature.getAttribute(att) # does attribute start with h_? if value.startswith('h_'): # replace h_ with tags newval = re.sub('^h_','<a href>',value) + '</a>' # write updated attribute back to feature feature.setAttribute(att,newval)
Answers Answers and Comments
8 People are following this question.
Attribute names to values in a single new attribute 2 Answers
how to extract attributes definition and export it to excel or word 2 Answers
Dynamic ESRI.shp reader 1 Answer
Translate xml TransXchange data to another format 3 Answers
S-57 (ENC) Hydrographic Data Reader missing ENC edition 3.1 attributes 1 Answer | https://knowledge.safe.com/questions/37599/double-transposing-attributes-to-test-for-attribut.html | CC-MAIN-2020-16 | en | refinedweb |
In this article you will learn how to consume the WCF created earlier and access data in the Silverlight 2 application.
Introduction:In this article, we will make use of the WCF service created in the previous part of this article and access data in the Silverlight application, DBDemo. We begin with adding a service reference to MovieService. To do this, right click on the project, DBDemo and select Add Service Reference. Click Discover and then select MovieService.svc after it is shown in the Add Service Reference dialog box. Rename the service reference to MovieServiceReference. To generate a client class that can consume the service, use the SvcUtil tool as shown in Figure 5. This tool is typically found in the C:\Program Files\Microsoft SDKs\Windows version xx folder where xx may change based on your machine configuration. To use it in your current application directory, give the following:path=%path%;C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin;Then type the command similar to the one in Figure 1 in your application directory, that is, SvcUtil *.wsdl *.xsd /language:C#Figure 1: Using SvcUtilThis will generate client code from the local metadata service document.You will see MovieService.cs now in the MovieServiceReference directory as a result of the above command. Now, the final step. Edit Page.xaml.cs as follows:using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes;using DBDemo.MovieServiceReference;
namespace DBDemo{ public partial class Page : UserControl { public Page() { InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e) { var client = new MovieServiceClient(); client.GetMoviesCompleted += new EventHandler<GetMoviesCompletedEventArgs>(client_GetMoviesCompleted); client.GetMoviesAsync(this.txtLang.Text); }
void client_GetMoviesCompleted(object sender, GetMoviesCompletedEventArgs e) { this.dgMovieData.ItemsSource = e.Result; this.dgMovieData.Visibility = Visibility.Visible; } }}The last two methods are the most important. One is an event handler for Button Click and one is the custom event handler method to assign the retrieved data to the data grid.When you save, build and execute and specify language as English, you will get results similar to Figure 2.Figure 2: OutputNow, that you know how to retrieve data using a WCF Service, you can tweak the code to make many changes and perform different kinds of data operations.Conclusion: Thus, in the second part of this article series, you explored how to create a LINQtoSQL class, a WCF service and consume the service in Silverlight 2 to access data.
View All | https://www.c-sharpcorner.com/uploadfile/mamta_m/using-data-in-silverlight-2-applications-ii/ | CC-MAIN-2020-16 | en | refinedweb |
DLINQ: Bridging the Object Relational Divide
Are you a DataSet person or more of a business object person? What an awful choice to make! On the DataSet side, you lose the intelligence that you can stuff into your business objects. On the business object side, you lose searching, sorting, and other basic abilities to work with your data that the .NET Framework provides in the System.Data namespace.
Fortunately, Microsoft will soon offer an alternative: LINQ (Language Integrated Query), and specifically for database-related operations, DLINQ. DLINQ is the component of the LINQ project that provides a run-time infrastructure for managing relational data as objects—without giving up the ability to query.
Ostensibly, DLINQ provides this solution by giving you the representation of a strongly typed database. In other words, if you had a customers table, you could create a class very similar to the following:
[Table(Name="Customers")] public class Customer { [Column(Id=true)] public string CustomerID; [Column] public string City; }
This class, with some other work, then would allow you to write queries in your .NET code as follows:
var q = from c in db.Customers where c.City == "London" select c;
So, you could use a relational, tabular representation of data in the database as objects that are strongly typed and checked at compile time in your .NET code. This allows you to both query your objects and stuff intelligence in them via mechanisms such as inheritance or partial classes. But isn't that what LINQ provides? Then, what does DLINQ add to the puzzle, besides simple query and persistence?
On the surface, DLINQ's functions sound quite straightforward: "represent relational data as objects," and "provide a mechanism to do the translation." But, a closer look quickly reveals various other hairy monsters in the sewer that need to be tamed.
For instance, the data that DLINQ queries upon does not have to worry about concurrency issues or transactional support. It doesn't have to worry about versioning or being disconnected from a huge data cache—your database. It also doesn't have to worry about preserving object identities. An object, when queried, always returns a copy of the data, but what if your object (say, "Customers") had been modified since the last time you read it? Objects that rely on database objects aren't instantaneously updated by the underlying database, unlike regular business objects, of which there is only one in-memory instance.
Also, how should your DLINQ queries be written so they execute efficient queries on the database and participate as good connection-pooling citizens in your architecture? Can you override the default behaviors?
This article attempts to answer a few of these questions. But first, how does DLINQ work?
The DataContext Class
At the heart of DLINQ is the DataContext class. Suppose you have a database that is created by the following T-SQL script:
Create Database Test Go Use Test Go Create Table Entity ( EntityID INT IDENTITY PRIMARY KEY, EntityName Varchar(100) NOT NULL ) Go Create Table EntityDetail ( EntityDetailID INT IDENTITY PRIMARY KEY, EntityID INT REFERENCES Entity(EntityID), EntityDetailName Varchar(100) NOT NULL ) Go
The following figure represents the two resulting tables.
If you insert some sample data using the following script:
BEGIN DECLARE @LASTID INT Insert Into Entity (EntityName) Values ('TestEntity') Select @LastID = SCOPE_IDENTITY() Insert Into EntityDetail(EntityID, EntityDetailName) Values (@LastID, 'Detail 1') ; Insert Into EntityDetail(EntityID, EntityDetailName) Values (@LastID, 'Detail 2') ; END Go
You could easily create a not-strongly-typed DataContext and use it to query the Entity Table as follows:
DataContext db = new DataContext(connectionString); Table<Entity> Entities = db.GetTable<Entity>(); var q = from e in Entities where e.EntityName == "TestEntity" select e; foreach (var entity in q) Console.WriteLine("EntityID = " + entity.EntityID);
For this code to work, it assumes a class called Entity already has been set up with the following structure:
[Table] public class Entity { [Column(Id=true)] public int EntityID; [Column] public string EntityName; }
But wouldn't it be a lot better to have a strongly typed DataContext instead? This would allow compile-time checking, and enable you to write more intuitive code like this:
TestDataContext db = new TestDataContext(connectionString); var q = from e in db.Entities where e.EntityName == "TestEntity" select e;
You could use a tool such as SqlMetal to do this, but it is important to understand the structure and layout of a strongly typed DataContext. Much like a strongly typed DataSet, at the heart of a strongly typed DataContext is a class that inherits from DataContext:
public partial class TestDataContext : DataContext { public Table<Entity> Entity; public Table<EntityDetail> EntityDetail ; public TestDataContext(string connStr) : base(connStr) {} }
As you can see, you now need to create two classes that represent the "Entity" and "EntityDetail" tables. Let's start with Entity:
[Table(Name="Entity")] public class Entity { ... }
The "Name" property is really not necessary, because in this case it matches the database. However, by specifying it anyway, you can explicitly map to a table. You then could put the name in a resource/satellite assembly, so that if the structure changes, you can update all names in one place. | https://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c12063/DLINQ-Bridging-the-Object-Relational-Divide.htm | CC-MAIN-2020-16 | en | refinedweb |
- Grammar
- Contracts
- Function Return Values
- Functions Without Bodies
- Pure Functions
- Nothrow Functions
- Ref Functions
- Auto Functions
- Auto Ref Functions
- Inout Functions
- Optional Parentheses
- Property Functions
- Virtual Functions
- Inline Functions
- Function Overloading
- Function Parameters
- Local Variables
- Nested Functions
- Delegates, Function Pointers, and Closures
- main() Function
- Function Templates
- Compile Time Function Execution (CTFE)
- No-GC Functions
- Function Safety
- Function Attribute Inference
- Uniform Function Call Syntax (UFCS)
Functions
Grammar
Function declaration attributes
FunctionAttributes: FunctionAttribute FunctionAttribute FunctionAttributes FunctionAttribute: nothrow pure Property MemberFunctionAttributes: MemberFunctionAttribute MemberFunctionAttribute MemberFunctionAttributes MemberFunctionAttribute: const immutable inout return shared FunctionAttribute
Function body contracts
Contracts
The in and out blocks or expressions of a function declaration specify the pre- and post-conditions of the function. They are used in Contract Programming. The code inside these blocks should not have any side-effects, including modifying function parameters and/or return values.
Function Return Values
Function return values are considered to be rvalues. This means they cannot be passed by reference to other functions.
Functions Without Bodies:
- does not read or write any global or static mutable state
- cannot call functions that are not pure
- can override an impure function, but cannot be overridden by an impure function
- is covariant with an impure function
- cannot perform I/O:
- read and write the floating point exception flags
- read and write the floating point mode flags, as long as those flags are restored to their initial state upon function entry
- perform impure operations in statements that are in a ConditionalStatement controlled by a DebugCondition.
Nothrow functions can only throw exceptions derived from class Error.
Nothrow functions are covariant with throwing ones.
Ref Functions
Ref functions allow functions to return by reference. This is analogous to ref function parameters.
ref int foo() { auto p = new int; return *p; } ... foo() = 3; // reference returns can be lvalues
Auto Functions
Inout Functions:
- No argument types are composed of inout types.
- A mutable, const or immutable argument type can be matched against each corresponding parameter inout type.(); }
Optional Parentheses); }
Property Functions
WARNING: The definition and usefulness of property functions is being reviewed, and the implementation is currently incomplete. Using property functions is not recommended until the definition is more certain and implementation more mature..
Simple getter and setter properties can be written using UFCS. These can be enhanced with the additon of the @property attribute to the function, which adds the following behaviors:
- @property functions cannot be overloaded with non-@property functions with the same name.
- @property functions can only have zero, one or two parameters.
- @property functions cannot have variadic parameters.
- For the expression typeof(exp) where exp is an @property function, the type is the return type of the function, rather than the type of the function.
- For the expression __traits(compiles, exp) where exp is an @property function, a further check is made to see if the function can be called.
- @property are mangled differently, meaning that @property must be consistently used across different compilation units.
- The ObjectiveC interface recognizes @property setter functions as special and modifies them accordingly.
A simple property would be:
struct Foo { @property int data() { return m_data; } // read property @property int data(int value) { return m_data = value; } // write property private: int m_data; }.. Static or final functions with Objective-C linkage are virtual as well. This results in fewer bugs caused by not declaring a function virtual and then overriding it anyway.
Member functions which are private or package are never virtual, and hence cannot be { override int def() { ... } // ok, overrides A.def override { // overrides and is covariant with Foo.test() override B test() { return null; } }
Virtual functions all have a hidden parameter called the this reference, which refers to the class object for which the function is called.
Functions with Objective-C linkage has an additional hidden, unnamed, parameter which is the selector it was called with.(); }
Function Inheritance and Overriding
A function foo = A,. }
Static functions with Objective-C linkage are overridable.
Inline Functions
The compiler makes the decision whether to inline a function or not. This decision may be controlled by pragma(inline), assuming that the compiler implements it, which is not mandatory.
Note that any FunctionLiteral should be inlined when used in its declaration scope.
Function Overloading
Functions are overloaded based on how well the arguments to a function can match up with the parameters. The function with the best match is selected. The levels of matching are:
- no match
- match with implicit conversions
- match with qualifier conversion (if the argument type is qualifier-convertible to the parameter type)
- exact match
Each argument (including any this pointer) is compared against the function's corresponding parameter, to determine the match level for that argument. The match level for a function is the worst match level of each of its arguments.
Literals do not match ref or out parameters.. This is because the name mangling might) }
Function Parameters
Parameter Storage Classes
Parameter storage classes are in, out, ref, lazy, const, immutable, shared, inout or scope. For example:
int foo(in int x, out int y, ref int z, int q);
x is in, y is out, z is ref, and q is none.
- The function declaration makes it clear what the inputs and outputs to the function are.
- It eliminates the need for IDL (interface description language) as a separate language.
- It provides more information to the compiler, enabling more error checking and possibly better code generation.
void foo(out int x) { // x is set to int.init, // which Parameters
An argument to a lazy parameter is not evaluated before the function is called. The argument is only evaluated if/when the parameter is evaluated within the function. Hence, a lazy argument can be executed 0 or more times.
import std.stdio : writeln; void main() { int x; 3.times(writeln(x++)); writeln("-"); writeln(x); } void times(int n, lazy void exp) { while (n--) exp(); }
prints to the console:
0 1 2 − 3
A lazy parameter cannot be an lvalue.
The underlying delegate of the lazy parameter may be extracted by using the & operator:
void test(lazy int dg) { int delegate() dg_ = &dg; assert(dg_() == 7); assert(dg == dg_()); } void main() { int a = 7; test(a); }
A lazy parameter of type void can accept an argument of any type.
See Also: Lazy Variadic Functions
Function Default Arguments
Function parameter declarations can have default values:
void foo(int x, int y = 3) { ... } ... foo(4); // same as foo(4, 3);
Default parameters are resolved and semantically checked in the context of the function declaration.
module m; private immutable int b; pure void g(int a=b){}
import m; int b; pure void f() { g(); // ok, uses m.b }
The attributes of the AssignExpression are applied where the default expression is used.
module m; int b; pure void g(int a=b){}
import m; enum int b = 3; pure void f() { g(); // error, cannot access mutable global `m.b` in pure function }
If the default value for a parameter is given, all following parameters must also have default values.
Return Ref Parameters }
Struct non-static methods marked with the return attribute ensure the returned reference will not outlive the struct instance.
struct S { private int x; ref int get() return { return x; } } ref int escape() { S s; return s.get(); // Error: escaping reference to local variable s }
Returning the address of a ref variable is also checked.
int* pluto(ref int i) { return &i; // error: returning &i escapes a reference to parameter i } int* mars(return ref int i) { return &i; // ok }
If the function returns void, and the first parameter is ref or out, then all subsequent return ref parameters are considered as being assigned to the first parameter for lifetime checking. The this reference parameter to a struct non-static member function is considered the first parameter.
If there are multiple return ref parameters, the lifetime of the return value is the smallest lifetime of the corresponding arguments.
Neither the type of the return ref parameter(s) nor the type of the return value is considered when determining the lifetime of the return value.
It is not an error if the return type does not contain any indirections.
int mercury(return ref int i) { return i; // ok }
Template functions, auto functions, nested functions and lambdas can deduce the return attribute.
ref int templateFunction()(ref int i) { return i; // ok } ref auto autoFunction(ref int i) { return i; // ok } void uranus() { ref int nestedFunction(ref int i) { return i; // ok } } void venus() { auto lambdaFunction = (ref int i) { return &i; // ok }; }
inout ref parameters imply the return attribute.
inout(int)* neptune(inout ref int i) { return &i; // ok }
Return Scope Parameters
Parameters marked as return scope that contain indirections can only escape those indirections via the function's return value.
@safe: int* gp; void thorin(scope int*); void gloin(int*); int* balin(return scope int* p, scope int* q, }
Class references are considered pointers that are subject to scope.
@safe: class C { } C gp; void thorin(scope C); void gloin(C); C balin(return scope C p, scope C q, }
return scope can be applied to the this of class and interface member functions.
class C { C bofur() return scope { return this; } }
Template functions, auto functions, nested functions and lambdas can deduce the return scope attribute.
Note: Checks for scope parameters are currently enabled only for @safe functions when compiled with the -dip1000 flag.
Ref Return Scope Parameters
Parameters marked as ref return scope come in two forms:
U xerxes(ref return scope V v); // (1) ref and return scope ref U xerxes(ref return scope V v); // (2) return ref and scope
The first form attaches the return to the scope, and has return scope parameter semantics for the value of the ref parameter.
The second form attaches the return to the ref, and has return ref parameter semantics with additional scope parameter semantics.
Although a struct constructor returns a reference to the instance being constructed, it is treated as form (1).
The lexical order of the attributes ref, return, and scope is not significant.
It is not possible to have both return ref and return scope semantics for the same parameter.
@safe: struct S { this(return scope ref int* p) { ptr = p; } int val; int* ptr; } int* foo1(return scope ref S s); int foo2(return scope ref S s); ref int* foo3(return ref scope S s); ref int foo4(return ref scope S s); int* test1(scope S s) { return foo1(s); // Error: scope variable `s` may not be returned return foo3(s); // Error: scope variable `s` may not be returned } int test2(S s) { return foo2(s); return foo4(s); } ref int* test3(S s) { return foo3(s); // Error: returning `foo3(s)` escapes a reference to parameter `s` } ref int test4(S s) { return foo4(s); // Error: returning `foo4(s)` escapes a reference to parameter `s` } S test5(ref scope int* p) { return S(p); // Error: scope variable `p` may not be returned } S test6(ref return scope int* p) { return S(p); }
User-Defined Attributes for ParametersSee also: User-Defined Attributes
Variadic Functions
Functions taking a variable number of arguments are called variadic functions. A variadic function can take one of three forms:
- C-style variadic functions
- Variadic functions with type info
- Typesafe variadic functions
C-style Variadic Functions }
D-style Variadic Functions); }
0x00870FE0 5 arguments int 2 long 3 double 4.5 Foo 0x00870FE0 Bar 0x00870FD0
D-style variadic functions cannot be marked as @safe.
Typesafe Variadic Functions
Typesafe variadic functions are used when the variable argument portion of the arguments are used to construct an array or class object.
For arrays:
int;); }.
Local Static Variables:
- Declare the functions to be static members of a nested struct:.
Delegates, Function Pointers, and Closures); }
Function pointers can be passed to functions taking a delegate argument by passing them through the std.functional.toDelegate template, which converts any callable to a delegate without context.
Future directions: Function pointers and delegates may merge into a common syntax and be interchangeable with each other.
Anonymous Functions and Anonymous Delegates
See FunctionLiter(string[] args) { ... } int main() { ... } int main(string[] args) { ... }
Function Templates.
Compile Time Function Execution (CTFE)
Functions which are both portable and free of global side-effects can be executed at compile time. In certain contexts, such compile time execution is guaranteed. It is called Compile Time Function Execution (CTFE) then. The contexts that trigger CTFE are:
- initialization of a static variable or a manifest constant
- static initializers of struct/class members
- dimension of a static array
- argument for a template value parameter
- static if
- static foreach
- static assert
- mixin statement
- pragma argument
enum eval(Args...) = Args[0]; int square(int i) { return i * i; } void foo() { static j = square(3); // CTFE writeln(j); assert(square(4)); // run time writeln(eval!(square(5))); // CTFE }
CTFE is subject to the following restrictions:
- The function source code must be available to the compiler. Functions which exist in the source code only as extern declarations cannot be executed in CTFE.
- Executed expressions may not reference any global or local static variables.
- asm statements are not permitted
- Non-portable casts (eg, from int[] to float[]), including casts which depend on endianness, are not permitted. Casts between signed and unsigned types are permitted
- Reinterpretation of overlapped fields in a Union is not permitted.
Pointers are permitted in CTFE, provided they are used safely:
- C-style semantics on pointer arithmetic are strictly enforced. Pointer arithmetic is permitted only on pointers which point to static or dynamic array elements. Such pointers must point to an element of the array, or to the first element past the array. Pointer arithmetic is completely forbidden on pointers which are null, or which point to a non-array.
- The memory location of different memory blocks is not defined. Ordered comparison (<, <=, >, >=) between two pointers is permitted when both pointers point to the same array, or when at least one pointer is null.
- Pointer comparisons between independent memory blocks will generate a compile-time error, unless two such comparisons are combined using &&.
- Equality comparisons (==, !=, is, !is) are permitted between all pointers, without restriction.
- Any pointer may be cast to in CTFE must also be executable at run time. The compile time evaluation of a function does the equivalent of running the function at run time. This means that the semantics of a function cannot depend on compile time values of the function. For example:
int foo(string s) { return mixin(s); } const int x = foo("1");is illegal, because the runtime code for foo cannot be generated. A function template would be the appropriate method to implement this sort of thing.
No-GC Functions
No-GC functions are functions marked with the @nogc attribute. Those functions do not allocate memory on the GC heap, through the following language features:
- constructing an array on the heap
- resizing an array by writing to its .length property
- array concatenation and appending
- constructing an associative array on the heap
- indexing an associative array (because it may throw RangeError if the specified key is not present)
- allocating an object on the heap
. A @nogc function is covariant with a non-@nogc function.
void function() fp; void function() @nogc gp; // pointer to @nogc function void foo(); @nogc void bar(); void test() { fp = &foo; // ok fp = &bar; // ok, it's covariant gp = &foo; // error, not contravariant gp = &bar; // ok }
To ease debugging, in a ConditionalStatement controlled by a DebugCondition @nogc functions can call functions that are not @nogc.
Function Safety
Safe functions are functions that are statically checked to exhibit no possibility of undefined behavior. Undefined behavior is often used as a vector for malicious attacks.
Safe Functions
Safe functions are marked with the @safe attribute.
The following operations are not allowed in safe functions:
- No casting from a pointer type to any type with pointers other than void*.
- No casting from any non-pointer type to a pointer type.
- No pointer arithmetic (including pointer indexing).
- Cannot access unions that have pointers or references overlapping with other types.
- Calling any system functions.
- No catching of exceptions that are not derived from class Exception.
- Disallow @system asm statements.
-.
- Cannot use void initializers for pointers.
- Cannot use void initializers for class or interface references.
Trusted functions are marked with the @trusted attribute.
Trusted functions are guaranteed to not exhibit any undefined behavior if called by a safe function. Furthermore, calls to trusted functions cannot lead to undefined behavior in @safe code that is executed afterwards. It is the responsibility of the programmer to ensure that these guarantees are upheld.
Example:
immutable(int)* f(int* p) @trusted { version (none) p[2] = 13; // Invalid. p[2] is out of bounds. This line would exhibit undefined // behavior. version (none) p[1] = 13; // Invalid. In this program, p[1] happens to be in-bounds, so the // line would not exhibit undefined behavior, but a trusted function // is not allowed to rely on this. version (none) return cast(immutable) p; // Invalid. @safe code still has mutable access and could trigger // undefined behavior by overwriting the value later on. int* p2 = new int; *p2 = 42; return cast(immutable) p2; // Valid. After f returns, no mutable aliases of p2 can exist. } void main() @safe { int[2] a = [10, 20]; int* mp = &a[0]; immutable(int)* ip = f(mp); assert(a[1] == 20); // Guaranteed. f cannot access a[1]. assert(ip !is mp); // Guaranteed. f cannot introduce unsafe aliasing. }
Trusted functions may call safe, trusted, or system functions.
Trusted functions are covariant with safe or system functions. Attribute Inference.
Uniform Function Call Syntax (UFCS)[]) } } | https://dlang.org/spec/function.html | CC-MAIN-2020-16 | en | refinedweb |
55942/error-package-or-namespace-load-failed-for-ggplot2-r
Hi, im getting below error while installing ...READ MORE
Try reinstalling the package quantreg. Hope this works. Its ...READ MORE
Hi, I want to use dplyr package ...READ MORE
You can try the below code as ...READ MORE
The best packages for creating interactive visualizations ...READ MORE
Hi, John,
There is a package called ggplotly ...READ MORE
By Using gridExtra library we can easily ...READ MORE
You can use the theme layer to ...READ MORE
To see all installed packages in system ...READ MORE
The error could be because of using reactive ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/55942/error-package-or-namespace-load-failed-for-ggplot2-r | CC-MAIN-2020-16 | en | refinedweb |
#include <GA_IteratorState.h>
State information for a GA_Iterator. This stores unique information for each iterator which the GA_Range bound to the iterator can reference.
Definition at line 24 of file GA_IteratorState.h.
Definition at line 27 of file GA_IteratorState.h.
Clear the nested pointer.
Copy the POD state (not including nested state)
Definition at line 38 of file GA_IteratorState.h.
Some ranges contain nested ranges. These RTIs can create nested states. These nested states should be used to store the iteration state for the nested range. Call
createNestedState() in GA_RangeTypeInterface::iterateCreate(). And it should only be called once. For example, a nested range might have code like:
Access to the nested state.
Definition at line 51 of file GA_IteratorState.h.
Definition at line 50 of file GA_IteratorState.h.
These variables provide easy storage to GA_RangeTypeInterface without the style necessarily having to allocate state information (i.e. the named storage)
Definition at line 49 of file GA_IteratorState.h.
Definition at line 52 of file GA_IteratorState.h. | https://www.sidefx.com/docs/hdk/class_g_a___iterator_state.html | CC-MAIN-2020-16 | en | refinedweb |
Return-cmd
Immediately exit from a script or a macro without generating any error.
return [value]
This command is particularly useful in an object script or in a script file script. The optional return value can only be used when returning from run.section( ), run.file( ), or run.dialog( ) calls.
Note: Macros do not return values. Also, only integer return values from 0 to 255 are supported.
Example 1
The following script defines a macro that takes an argument and types OK if the argument is greater than 2. Otherwise, it types Not OK.
def test {
if (%1 > 2) {
type "OK";
return;
}
type "Not OK";
}
In this case, test 1.876; would respond with Not OK.
Example 2
If an object named Test contains the following script:
if (var1 + 3 * var3 > 1) return 0;
else return 1;
A script that accesses the object can use the return value as follows:
if (test.run()==0)
type "Result OK";
else type "Result too small"; | http://cloud.originlab.com/doc/LabTalk/ref/Return-cmd | CC-MAIN-2020-16 | en | refinedweb |
I need help writing this program i have everthing set up except i cannot get the program to save the output from it. Here is a copy of my work (It will most likely suck Im new at this sorry.) Any help will be very appreciated. I need the file to loop over again should they need to buy tickets for another movie.
#include <iostream> #include <cstdlib> #include <fstream> using namespace std; int main() //the program starts here { cout << "Tonights Showing\n\n\n\n"; cout << "1.Attack of the C++ Programmers\n\n"; cout << "2.Bits and Bytes\n\n"; cout << "3.Killer Coding Ninja Monkeys\n\n"; cout << " Please Enter the number of the Movie\n\n"; int a; cin >> a; cout << "Please Enter the number of adult tickets please.\n\n"; int b; cin >> b; int z; z = b * 2; cout << "Please Enter the number of children Tickets.\n\n"; int c; cin >> c; int t; t = z + c; cout << " Does this Complete your order. Y or N.\n\n"; char Y; cin>> Y; cout<< " Thank you for your support! Your order will be displayed below.\n\n"; cout<< "Your movie you choose was"; cout<<" "; cout<< a; cout<<"\n\n"; cout<<"Age Group"; cout<<" | "; cout<<"Number of Tickets"; cout<<" | "; cout<<"Current Price Scheme"; cout<<" | "; cout<<"Subtotal"; cout<<"\n"; cout<< "--------------------------------------------------------------\n"; cout<< "Child Viewing"; cout<<" "; cout<< c; cout<< " "; cout<<" $1.00"; cout<<" "; cout<< "$"; cout<< c; cout<< "\n"; cout<<"Adult Viewing"; cout<<" "; cout<< b; cout<<" "; cout<<"$2.00"; cout<<" "; cout<< "$"; cout<< z; cout<<"\n"; cout<< "--------------------------------------------------------------\n\n"; cout<< "Your Total is"; cout<<" "; cout<<"$"; cout<< t; cout<<"\n\n"; if (char; Y = Y ); { ofstream myFile("c:/reciet.txt"); // Creates an ofstream object named myFile if (! myFile) // Always test to see if the file open { cout << "Error opening output file" << endl; return -1; } myFile << cout << endl; //prints hello world to the out.txt file myFile.close(); //closes the file while( char Y < N) | https://www.daniweb.com/programming/software-development/threads/23260/program-issues | CC-MAIN-2018-05 | en | refinedweb |
In the previous chapter, all of our Struts examples were built around very simple screens, which were populated with data retrieved from the JavaEdge application. However, most web applications require a high degree of interaction, with end users often submitting the data via HTML forms.
This chapter is going to look at how to simplify the construction of HTML forms and form handling code, using the Struts development framework. We are going to discuss, from both a conceptual and implementation point of view, how the Struts framework can provide a configurable and consistent mechanism for building web forms. This chapter is going to cover the following topics:
Most web development teams do not have a consistent strategy for collecting the data from the end user, validating it, and returning any error messages that need to be displayed. They use a hodge-podge of different means of collecting and processing the user's data. Two commonly used mechanisms include embedding JavaScript in the HTML or JSP page rendering the form, and mixing the validation logic for the screen with the business logic in the business tier of the application. This inconsistency in the form processing often results in:
All the problems identified above are the symptoms of the Validation Confusion antipattern. Recollecting the discussion in Chapter 1, the Validation Confusion antipattern occurs due to one of the following reasons:
Fortunately, the Struts framework provides a rich set of software services for building and managing the form data. These services allow a developer to handle the form validation in a consistent fashion. Much of the logic normally associated with capturing and presenting the errors becomes the responsibility of the Struts framework and not the application developer.
To build an HTML form in Struts we need to have the following pieces in place:
Tying all of these pieces together is the struts-config.xml file. This file will have entries in it for defining the Struts ActionForm classes used in the application, which ActionForm classes are going to be used with which action, and whether an ActionForm class is going enforce the validation against the submitted data. Each Struts action processing the form data must have its corresponding tag modified, to indicate which ActionForm class will be used by the action.
Let's discuss what happens when the user submits the data in an HTML form. The diagram below shows what happens when the user submits the form data to a Struts-based application.
Whether or not the ActionServlet places the ActionForm class in the user's request or session is determined by the scope attribute in the tag. We will be exploring the tag in greater detail in the section called The struts-config.xml File.
Once the user's data has successfully passed all the form validation, the perform() method will be invoked in the Action class associated with the action. Remember that the Java class that carries out the end user's request, is defined via the type attribute in the element. We suggest you to refer to Chapter 2, to understand how to configure a Struts action, before continuing.
Let's begin the discussion of form handling by Struts, by looking at how an HTML form is processed by Struts when a user submits it. We are going to use the Post a Story page from the JavaEdge application (discussed in Chapter 3) as our example.
This page can be accessed by either clicking the Post a Story link in the menu bar at the top of every JavaEdge page or pointing our browser to. The Post a Story page is used by a JavaEdge user to submit a story that the other users visiting this page can read.
If you have successfully reached this page, you will see the following screen:
Let's begin by looking at how to setup our struts-config.xml class to use ActionForm objects.
To use an ActionForm class to validate the data collected from a user form, the struts-config.xml file for the application must be modified. These modifications include:
The > tag holds one or more tags within it. This tag appears at the top of the struts-config.xml file. Each tag corresponds to only one ActionForm class in the application. For the JavaEdge application, the tag looks as shown below:
... //more form-bean definitions.
The element has two attributes. They are:
A unique name for the form bean being defined. Later on, this name will be used to associate this form bean with an element. This attribute is a required field.
The fully-qualified class name of the ActionForm class that the form bean represents. This attribute is also a required field.
The actually has a third optional attribute called className. This attribute allows you to plug in a new base ActionForm class. For most purposes, the default ActionFormBean defined in the tag of the ActionServlet will suffice.
Once a has been defined, we can use it in an element to perform validation of the form data. To add the validation to a , we must supply four additional attributes in an element. These attributes are:
The /postStory action, processing the data entered by the user in the postAStory.jsp page, is shown below:
The Struts ActionForm class is used to hold the entire form data submitted by the end user. It is a helper class that is used by the ActionServlet to hold the form data, which it has pulled from the end user's request object. The application developer can then use the ActionForm to access the form through get() and set() method calls.
The ActionForm class not only provides a convenient wrapper for the request data but also validates the data submitted by the user. However, an Action class is not required to have an ActionForm class. An Action class can still access the form data, submitted by the end user, by calling the getParameter() method in the request object passed into its perform() method.
To build an ActionForm class, the developer needs to extend the base Struts ActionForm class and override two methods in it, reset() and validate(). Just to review, the reset() method is overridden by the developer when an ActionForm class for an action is to be stored in the user's request context. The reset() method clears the individual attributes, in the ActionForm class, to ensure that the ActionForm class is properly initialized before it is populated with the user's form data. The validate() method is overridden by the developer. This method will contain all of the validation logic used in validating the data entered by the end user.
In addition, the application developer needs to define all the form elements that are going to be collected by the ActionForm class as private attributes in the class. For each defined attribute, there must be corresponding get() and set() methods that follow the standard JavaBean naming conventions.
For the Post a Story page, we are going to write a Struts ActionForm class called PostStoryForm.java. This class will hold the story title, the story introduction, and the body of the story. In addition, it will contain the validation code for the data being submitted by the user. The class diagram shown below illustrates the class relationships, methods, and attributes for the Struts ActionForm class and the PostStoryForm class:
It is very easy to fall into the mindset that there must be one ActionForm class for each HTML form from which the data is collected. In small-to-medium size applications, there is nothing wrong in using a single ActionForm placed in the user's session. All the forms in the application will use this ActionForm to hold the data collected from the user.
This simplifies the collection of the data because your application has only one ActionForm instance that you have to work with. By using a single ActionForm class and placing it in the user's session, you can very easily implement a wizard-based application that will remember each piece of user information entered. As the user steps back and forth through the wizard, the data can easily be retrieved from the single ActionForm class.
The problem with using a single ActionForm class in the user's session is that the application will not scale as well. Remember, the objects placed in the user's session have a reference held until the session times out and the objects are garbage-collected. Do not place ActionForm objects in the session merely as a convenience. The other problem with this method occurs if the users are carrying out a long-lived transaction. If the users lose their connection or close their browser, any of the data entered till then will be lost. To ensure that as much of the user's data is captured and persisted as possible, break the application into smaller transactions. Use an ActionForm class for each application screen and persist the data in the ActionForm class as soon as the users submit their data. Place the ActionForm class into the request so that server resources are not unnecessarily used.
The code for the PostStoryForm class is shown below. However, the reset() and validate() methods for this class are not displayed. They will be discussed in the sections called Using the reset() Method and Validating the Form Data, respectively.
package com.wrox.javaedge.struts.poststory; import org.apache.struts.action.Action; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionServlet; import org.apache.struts.util.MessageResources; import com.wrox.javaedge.common.VulgarityFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class PostStoryForm extends ActionForm { String storyTitle = ""; //defined as empty string String storyIntro = ""; String storyBody = ""; /** * Validates all data posted from the Post Story page. */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ... } /** * Used to clear out the values stored in a PostStoryForm class's * attributes. */ public void reset(ActionMapping mapping, HttpServletRequest request) { ... } /** Getter for property storyTitle. * @return Value of property storyTitle. */ public java.lang.String getStoryTitle() { return storyTitle; } /** Setter for property storyTitle. * @param storyTitle New value of property storyTitle. */ public void setStoryTitle(java.lang.String storyTitle) { this.storyTitle = storyTitle; } /** Getter for property storyIntro. * @return Value of property storyIntro. */ public java.lang.String getStoryIntro() { return storyIntro; } /** Setter for property storyIntro. * @param storyIntro New value of property storyIntro. */ public void setStoryIntro(java.lang.String storyIntro) { this.storyIntro = storyIntro; } /** Getter for property storyBody. * @return Value of property storyBody. */ public java.lang.String getStoryBody() { return storyBody; } /** Setter for property storyBody. * @param storyBody New value of property storyBody. */ public void setStoryBody(java.lang.String storyBody) { this.storyBody = storyBody; } }
The reset() method is used to ensure that an ActionForm class is always put in a "clean" state, before the ActionServlet populates it with the form data submitted in the user's request. In the struts-config.xml, the developer can choose to place an ActionForm for a specific Struts action either in the user's session or request.
If the developer declares that the ActionForm is to be placed in the session, the reset() method will not be invoked. The ActionServlet will bypass the reset() method, populate the properties in the ActionForm with the data from the user's request, and then call the validate() method of the ActionForm.
The reset() method is invoked only if the developer has declared that the ActionForm class should be stored in the request. This method is necessary because Struts maintains a cache for each of the declared ActionForm classes. A single instance of an ActionForm class can be shared by multiple users for different requests at different times. Hence, the developer must implement the reset() method to ensure that the end user never gets some other user's data.
Implementing the reset() method for the PostStoryForm, will set all its properties to an empty string. The reset() method for the PostStoryForm class is shown below:
public void reset(ActionMapping mapping, HttpServletRequest request) { storyTitle = ""; storyIntro = ""; storyBody = ""; }
So far, we have talked about using the reset() method to ensure that the contents of an ActionForm class are cleared, before the ActionServlet places data in it from the user request. However, an ActionForm class can also be used to pre-populate an HTML form with data. The data populating the form might be text information retrieved from a properties file or a database.
To pre-populate an HTML form with data, we need to have the following Struts elements in place:
For example, we can pre-populate the HTML form for the Post a Story page with some simple instructions on what data is supposed to go in each field. For this example, we are going to use the following files:
We are only going to look at the PostStoryForm and the PostStorySetupAction Java classes. The postStoryContent.jsp file will use the Struts HTML tag library to read the values out of the PostStoryForm object stored in the request and display them in each field. The postStoryContent.jsp and Struts HTML tag library is discussed in the section called The Struts HTML Tag Library.
PostStoryForm.java
Writing the reset() method for a PostStoryForm to pre-populate the ActionForm with the instructions for each field in the form is a straightforward task:
public void reset(ActionMapping mapping, HttpServletRequest request) { ActionServlet servlet = this.getServlet(); MessageResources messageResources = servlet.getResources(); storyTitle = messageResources.getMessage("javaedge.poststory.title.instructions"); storyIntro = messageResources.getMessage("javaedge.poststory.intro.instructions"); storyBody = messageResources.getMessage("javaedge.poststory.body.instructions"); }
The reset() method above reads values from the ApplicationResources.properties file and uses them to populate the properties of the PostStoryForm object.
The Struts development framework provides an easy-to-use wrapper class, called MessageResources, for directly accessing the data in the ApplicationResources.properties file. To retrieve an instance of the MessageResources class, you first need to get a reference to the ActionServlet that is currently processing the ActionForm object. Fortunately, the ActionForm class provides a getServlet() method that will retrieve an instance of the ActionServlet:
ActionServlet servlet = this.getServlet();
Once an instance of the ActionServlet is retrieved, a call to its getResources()method will retrieve a MessageResources object that wraps all the values stored in the ApplicationResources.properties file:
MessageResources messageResources = servlet.getResources();
After getting an instance of a MessageResources object, you can pass the message key of the item that you want to retrieve to the getMessage(). The getMessage()method will retrieve the desired value:
messageResources.getMessage("javaedge.poststory.title.instructions");
If the key passed to the getMessage() method cannot be found, a value of null will be returned. The following are the name-value pairs from the ApplicationResources.properties file used to pre-populate the PostStoryForm:
javaedge.poststory.title.instructions=Enter a title here. javaedge.poststory.intro.instructions=Enter the story introduction here. Please be concise. javaedge.poststory.body.instructions=Enter the full story here. Please be nice.
The PostStoryForm.reset() method is a very simple example of how to pre-populate a form with the data contained in an ActionForm class. In reality, many applications retrieve their data from an underlying relational database rather than from a properties file. How the reset() method on the PostStoryForm is invoked, is yet to be explored. Let's take a look at the PostStorySetupAction.java and see how we can trigger the reset()method.
PostStorySetupAction.java
Triggering the PostStoryForm.reset() method does not require any coding in the PostStorySetupAction.java file. All that the PostStorySetupAction class is going to do is to forward the user's request to the postStoryContent.jsp. So what role does the PostStorySetupAction.java play, if its perform() method just forwards the user on to a JSP page? How is the reset() method in the PostStoryForm class called?
If we set a Struts tag in the struts-config.xml file to use an ActionForm and tell the ActionServlet to put the PostStoryForm in the user's request, the reset() method in the PostStoryForm class will be invoked.
When a user clicks on the Post a Story link in the JavaEdge header, they are asking the ActionServlet to invoke the /postStorySetup action. This action is configured to use the ActionForm class of PostStoryForm. The PostStoryForm is going to be put in the user's request context by the ActionServlet.
Since the ActionForm class for the /postStorySetup action is the PostStoryForm class and the PostStoryForm class is going to be placed into the user's request context, the reset() method in the PostStoryForm class will be invoked. The reset() method is going to initialize each of the attributes in the PostStoryForm class to hold a set of simple instructions pulled from the ApplicationResources.properties file.
After the reset() method has been invoked the ActionServlet will place any submitted form data in the PostStoryForm instance. Since the user has not actually submitted any data, the PostStoryForm class will still hold all of the values read from the ApplicationResources.properties file. The ActionServlet will then invoke the perform() method in the PostStorySetupAction class, which will forward the user to the postStoryContent.jsp page. This page will display a form, pre-populated with instructions.
In summary, to pre-populate the form, we need to perform the following two steps:
The code for PostStorySetupAction.java is shown below:
package com.wrox.javaedge.struts.poststory;; public class PostStorySetupAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ return (mapping.findForward("poststory.success")); } }
The perform() method just forwards the user to the postStoryContent.jsp page, by returning an ActionForward mapped to this page:
return (mapping.findForward("poststory.success"));
The poststory.success mapping corresponds to the element, defined for the following tag of /postStorySetup:
The name attribute shown above tells the ActionServlet to use an instance of PostStoryForm, whenever the user invokes the /postStorySetup action:
name="postStoryForm"
Remember, the value of the name attribute must refer to a tag defined at the beginning of the struts-config.xml file.
The scope attribute tells the ActionServlet to place the PostStoryForm as an attribute in the HttpServletRequest object:
scope="request"
Setting the validate attribute to false, in the above tag, will cause the ActionServlet not to invoke the validate() method of the PostStoryForm. This means the reset() method in the PostStoryForm object is going to be invoked and placed in the user's request, but no data validation will take place.
Since no data validation takes place, the perform() method of PostStorySetupAction will be invoked. Remember, the Action class that carries out the end user's request is defined via the type attribute:
type="com.wrox.javaedge.struts.poststory.PostStorySetupAction"
There is another technique for pre-populating an ActionForm with data. It is discussed here because implementing your Struts application using this technique can cause long-term maintenance headaches.
In the PostStorySetupAction.java, you could implement the perform() method so that it creates an instance of PostStoryForm and invokes its reset() method directly. After the reset() method is invoked, the PostStoryForm can then be set as an attribute in the request object passed in the perform() method. The following code demonstrates this technique:
public class PostStorySetupAction extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ PostStoryForm postStoryForm = new PostStoryForm(); postStoryForm.setServlet(this.getServlet()); postStoryForm.reset(mapping, request); request.setAttribute("postStoryForm", postStoryForm); return (mapping.findForward("poststory.success")); } }
This technique does not require you to provide any additional configuration information in the tag. The above code carries out all the actions that the ActionServlet would carry out.
However, using this approach has two long-term architectural consequences. First, the above approach has tightly coupled the PostStoryForm class to the PostStorySetupAction class. In the future, if the development team wants the /postStorySetup to use something other than the PostStoryForm class for the pre-population or form validation, it must rewrite the perform() method. This becomes a tedious task, if the PostStoryForm class is present throughout multiple applications and a developer needs to switch it with another ActionForm class. If the developer had used the first technique and associated the PostStoryForm and PostStorySetup by declaring their usage in the struts-config.xml, a few small changes to the file could have easily switched the ActionForm class populating the postStoryContent.jsp page.
The second problem is that it takes control of the ActionForm away from the ActionServlet. The responsibility for managing the ActionForm shifts from the ActionServlet to the application developer. If the Struts development team changes how the ActionForm class is processed by the ActionServlet, the developers run the risk of having their application code break when they try to upgrade to the next release of Struts.
As discussed earlier, a common mistake in web application development is for there to be no clear distinction between business logic and validation logic. The ActionForm class helps the developers to solve this problem, by allowing them to enforce lightweight validation rules against the data entered by a user. By encapsulating these validation rules in the ActionForm class, the developer can clearly separate the validation rules from the business logic that actually carries out the request. The business logic is placed in the corresponding Action class for the end user's request.
A web developer can override the validate() method and provide their own validation rules for the submitted data, while writing their own ActionForm class. If the developer does not override the validate() method, none of the data submitted will have any validation logic run against it.
The validate() method for the PostStoryForm class is going to enforce three validation rules:
It is important to note that, in all cases, the users will not be allowed to continue until they correct the validation violation(s).
The validate() method for the PostStoryForm class is as shown below:
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); checkForEmpty("Story Title", "error.storytitle.empty", getStoryTitle(), errors); checkForEmpty("Story Intro", "error.storyintro.empty", getStoryIntro(), errors); checkForEmpty("Story Body", "error.storybody.empty", getStoryBody(), errors); checkForVulgarities("Story Title", "error.storytitle.vulgarity", getStoryTitle(), errors); checkForVulgarities("Story Intro", "error.storyintro.vulgarity", getStoryIntro(), errors); checkForVulgarities("Story Body", "error.storybody.vulgarity", getStoryBody(), errors); checkForLength("Story Title", "error.storytitle.length", getStoryTitle(), 100, errors); checkForLength("Story Intro", "error.storyintro.length", getStoryIntro(), 2048, errors); checkForLength("Story Body", "error.storybody.length", getStoryBody(), 2048, errors); return errors; }
The first step in the validate() method is to instantiate an instance, called errors, of the ActionErrors class:
ActionErrors errors = new ActionErrors();
The ActionErrors class is a Struts class that holds one or more instances of an ActionError class. An ActionError class represents a single violation of one of the validation rules being enforced in the ActionForm class. If a form element submitted by an end user violates a validation rule, an ActionError will be added to the to the errors object.
When the validate() method completes, the errors object will be returned to the ActionServlet:
return errors;
If the errors object is null or contains no ActionErrors, the ActionServlet will allow the business logic to be carried out, based on the end user's request. This is done by invoking the perform() method in the Action class associated with the request.
Let's look at the checkForVulgarities() method, to see how an ActionError class is actually created when a validation rule is violated. The checkForEmpty() and checkForLength() methods will not be discussed in detail, but the code for these methods is shown below:
/** * Ensures that the field being checked is not null */ private void checkForEmpty(String fieldName, String fieldKey, String value, ActionErrors errors) { if (value.trim().length() == 0) { ActionError error = new ActionError("error.poststory.field.null", fieldName); errors.add(fieldKey, error); } } /** * Ensures that the field in question does not exceed a maximum length */ private void checkForLength(String fieldName, String fieldKey, String value, int maxLength, ActionErrors errors){ if (value.length() > maxLength){ ActionError error = new ActionError("error.poststory.field.length", fieldName); errors.add(fieldKey, error); } }
Creating an ActionError
The checkForVulgarities() method is as shown below:
/** * Ensures that the field being checked does not violate our vulgarity list */ private void checkForVulgarities(String fieldName, String fieldKey, String value, ActionErrors errors) { VulgarityFilter filter = VulgarityFilter.getInstance(); if (filter.isOffensive(value)){ ActionError error = new ActionError("error.poststory.field.vulgar", fieldName); errors.add(fieldKey, error); } }
The first line in this method retrieves an instance of the VulgarityFilter into a variable called filter:
VulgarityFilter filter = VulgarityFilter.getInstance();
The VulgarityFilter class is implemented using a singleton design pattern and wraps a collection of words that are considered to be offensive. The code for the class is shown below:
package com.wrox.javaedge.common; public class VulgarityFilter { private static VulgarityFilter filter = null; private static String[] badWords = {"Stupid", "Idiot", "Moron", "Dummy", "Flippin", "Ninny"}; static { filter = new VulgarityFilter(); } public static VulgarityFilter getInstance(){ return filter; } public boolean isOffensive(String valueToCheck){ String currentWord = ""; for (int x = 0; x <= badWords.length - 1; x++){ if (valueToCheck.toLowerCase().indexOf(badWords[x].toLowerCase()) != -1) { return true; } } return false; } }
The VulgarityFilter class has a single method called isOffensive(), which checks if the text passed in is offensive. A value of true returned by this method indicates the user has entered data that contains offensive text:
if (filter.isOffensive(value))
When a vulgarity is found, a new ActionError is created and added to the errors object passed to the checkForVulgarity() method:
ActionError error = new ActionError("error.poststory.field.vulgar", fieldname); errors.add(fieldKey, error);
There are five constructors that can be used to instantiate an ActionError class. The first parameter of each of these constructors is a lookup key, which Struts uses to find the text of the error message displayed to the end user. Struts will look for all error messages in the ApplicationResources.properties file associated with the application. The error messages for the Post a Story page are shown below:
error.poststory.field.null=The following field: {0} is a required field. Please provide a value for {0}. error.poststory.field.vulgar=You have put a vulgarity in your {0} field. Please refer to our <a href="/javaedge/policy.html">terms of use policy.</a> error.poststory.field.length=Your {0} field is too long.
When the user violates the vulgarity validation rule and the checkForVulgarity() method creates an ActionError, the lookup key error.poststory.field.vulgar will be used to return the following error message:
The following field: {0} is a required field. Please provide a value for {0}.
The error message can contain at most four distinct parameter values. The parameter values are referenced by using the notation: {number}, where the number is between zero and three. In the above example, only one parameter is inserted into the error message. A summary of the five constructors in the ActionError class is given below:
After the error object has been created, it is later added to the errors object by calling the add() method in errors:
errors.add(fieldKey, error);
The add() method takes two parameters:
The Struts ActionServlet checks if there are any errors in the returned ActionErrors object and determines if a validation error was returned by the validate() method. If there are any ActionError objects in the returned ActionErrors instance, it means that the validation errors were found. If the value returned from the validate() method is null or contains no ActionError objects, no validation errors were found.
If the Struts ActionServlet finds that there are errors present in the ActionError object, it will redirect the user to the path set in the input attribute for the action. Most of the time, the value in this input tag is the JSP page where the data was entered. The ActionForm object holding the user's data will still be in the request. Thus, any data entered by the user in the form will appear pre-populated in the form. How does Struts present the user with all the errors raised in the validate() method? It does this using the tag. This tag is found in the Struts HTML custom JSP tag library. (There are several other form-related custom tags in the HTML tag library. We will be discussing the full HTML tag library in the section called The Struts HTML Tag Library). There are two ways of using this tag:
Writing All Error Messages to the JSP Page
To perform the first action, you must import the Struts HTML tag library and place the tag where you want the errors to appear. For instance, in the postStoryContent.jsp, we use this tag in the following manner:
<%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
This code will write all the errors messages in the ActionErrors class returned by validate() method of the PostStoryForm immediately below the header of the page. The following example shows the type of error messages that can be presented to the end-user:
You have put a vulgarity in your Story Title field. Please refer to our <a href="/javaedge/policy.html">terms of use policy.</a> The following field: Story Intro is a required field. Please provide a value for Story Intro. The following field: Story Body is a required field. Please provide a value for Story Body.
It is extremely important to note that the tag will write the error text exactly as it has been defined in the ApplicationResources.properties file. This means that the developer must provide HTML tags to format the appearance of the error message. This also includes putting any
tags for the appropriate line breaks between the error messages. The tag allows the application developer to define a header and footer for a collection of error messages. Headers and footers are defined by including an errors.header property and errors.footer property in the ApplicationResources.properties file. These two properties can contain text (and HTML code) that will appear immediately before and after the errors written by the tag. The following snippet shows these properties for the JavaEdge application:
errors.header=
Even if you do not want to use the errors.header and errors.footer properties to generate an error header and footer, you must still define them in the ApplicationResources.properties with no values. For example:
errors.header= errors.footer=
If you do not include these properties, you will get a null value appearing before and after your list of errors.
The tag provides a very simple and consistent error handling mechanism. Front-end screen developers only need to know that they have to put an tag in their JSP form pages to display any validation errors. The job of the server-side developers is simplified because they can easily validate the form data submitted by the end user and communicate any errors back to the user by populating an ActionErrors object.
Keeping in mind all the discussion that we had so far, when the end users violate a validation rule on the Post a Story page they will see the following output:
Retrieving a Single Error Message
The tag by itself is somewhat inflexible, because you have to present all the validation errors caused by the end user at a single spot on the screen. Many application developers like to break the validation errors apart and put them next to the field that contains the invalid data.
Fortunately, the tag allows you to pull a single error message from an ActionErrors object. It has an attribute called property. This attribute will let you retrieve an error message, using the key value that was used while adding the error message to the ActionErrors object. For example, when a user enters a word that violates the vulgarity filter, we add that validation error to the errors object by calling:
errors.add(fieldKey, error);
The fieldKey variable passed to the errors.add() method is the name we have chosen to represent that particular error. For example, if the user typed the word dummy into the story title field, this would violate the vulgarity validation rule and a new ActionError class would be instantiated. The new ActionError would be added to the errors class and would have a fieldKey value of error.storytitle.vulgarity.
If you wanted to put that specific error message directly above the Story Title field label, you could rewrite the postStoryContent.jsp with the following code:
By using the tag in the manner shown above, you can cause the postStoryContent.jsp to generate an error message that may look like the one shown below:
Error Handling and Pre-population
After discussing how HTML errors are handled in Struts, you might be a little bit confused. Why does the form show up with all of the fields pre-populated with the data that the user just entered? Why doesn't the reset() method in the ActionForm class reset all the values?
The reason is simple. When the validate() method is invoked and if there are validation errors, the ActionServlet is going to look at the value of the input attribute in the tag. The input attribute almost invariably points back to the JSP where the user entered the data. Remember, the reset() method gets called only when an action is invoked. Redirecting the user back to a JSP page will not invoke the reset() method. If the JSP page to which the user is redirected uses the Struts HTML tag library and an ActionForm in the user's request or session, it will pull the data out of the ActionForm and pre-populate the form elements with that data. Thus, when a validation error occurs the user sees the validation errors and a pre-populated form.
If you want to force the reset of all the elements in a form, after the validation occurs, you need to point the input attribute in the element to an action (usually a SetupAction of some kind).
As we have seen earlier in this chapter, Struts provides the ActionForm and the Action classes as the means of validating and processing the data submitted by the end user. The Struts development framework also provides a JSP tag library, called the HTML tag library, which significantly simplifies the development of HTML-based forms. The HTML tag library allows the developer to write JSP pages that tightly integrate with an ActionForm class.
The Struts HTML tag library can be used to generate HTML form controls and read data out of an ActionForm class in the user's session or request. It also helps developers avoid writing significant amounts of scriptlet code to pull the user data out of JavaBeans (that is, the ActionForm objects) in the user's request and/or session. When combined with the other Struts tag libraries, as discussed in Chapter 2, a developer can write very dynamic and data-driven web pages without ever having to write a single line of JSP scriptlet code.
The Struts HTML tag library contains a wide variety of tags for generating HTML form controls. We are not going to cover every tag in the Struts HTML tag library. Instead, we are going to go through the most commonly used tags and explore their usage. For a full list of the different tags available in the Struts HTML tag library, you can visit. The tags discussed in this chapter include:
Let's begin the discussion of the Struts HTML tag library by looking at the postStoryContent.jsp page:
<%@" %>
Before using the individual Struts HTML tag within a JSP page, three steps must be undertaken:
The Struts HTML TLD is imported as shown below:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
Next, we use the Struts HTML tags. Just as in a static HTML page, we need to define a tag that will encapsulate all the HTML form controls on the page. This is done by using the tag.
...
The tag has a number of different attributes associated with it. However, we will not be discussing every attribute in detail. Some of the attributes are given below:
The most important of these attributes is the action attribute. It maps to an element defined in the struts-config.xml file. If no name, scope, or type attribute is specified in the tag, the ActionForm that will be used to populate the form its fully qualified Java name, and the scope in which it resides will be pulled from the tag in struts-config.xml file.
In the tag used in the postStoryContent.jsp, all the ActionForm information would be retrieved by the ActionServlet, by looking at the name attribute in the tag of postStory action in the struts-config.xml file:
Since the value of name (postStoryForm) is defined as a element in the struts-config.xml, the ActionServlet can figure out its fully qualified Java class name and instantiate an instance of that class.
Let's look at the HTML generated by the tag shown earlier:
The name attribute generated tells the ActionServlet of Struts that the postStoryForm bean, defined in the tag of the struts-config.xml, is going to be used to hold all the data posted by the user. The default method of the form (since we did not define one in the tag) is going to be a POST method. The action attribute contains the URL to which the form data is going to be submitted. Since the action of the tag was postStory, the generated the action attribute (for the corresponding tag) is /javaedge/execute/postStory.
The last step in setting up an HTML form is using the Struts tag to generate an HTML submit button:
In addition to the tag, the Struts tag library has HTML tags for creating cancel buttons. When an tag is used an HTML button will be rendered that, when clicked, will cause the ActionServlet to bypass the validate() method in the ActionForm that is associated with the form.
Even though the validate() method is bypassed, the perform() method for the Action class (in this case PostStory.java) linked with the form will be invoked. This means that, if you want to use an button in your page, the perform() method must to detect when the cancel button is invoked and act accordingly. For instance, let's say the following tag was added to the postStoryContent.jsp file:
The validate() method in the PostStoryForm class would not be called. However, the perform() method on the PostStory class would be invoked. The perform() method taken from the PostStory class could be written in the following manner:
public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ if (this.isCancelled(request)){ System.out.println("*****The user pressed cancel!!!"); return (mapping.findForward("poststory.success")); } //Add the story data to the database. ... return (mapping.findForward("poststory.success")); }
If you did not want the code in the perform() method to be executed, you will have to use a method called isCancelled() to detect if the user pressed a cancel button. The isCancelled() method is inherited from the base Struts Action class. This method looks for a parameter in the user's request, called org.apache.struts.taglib.html.CANCEL. If it finds this parameter, it will return true indicating to the developer (writing the perform() method code) that the user clicked the cancel button.
The parameter name, org.apache.struts.taglib.html.CANCEL, maps to the name attribute in the tag generated by the button. The HTML button generated by the tag shown earlier looks like:
Unlike the tag, the property attribute on the tag is rarely set.
The postStoryContent.jsp files use text and textarea tags to collect the data from the end user. The and tags are used to generate the text and textarea tags, respectively. For instance, the postContent.jsp page uses the tag to generate an HTML text tag by using:
The tag has a number of attributes, but the most important are name and property. The name attribute defines the name of the ActionForm bean that the input field is going to map to. The property attribute defines the property in the ActionForm bean that is going to map to this input field. There are two things that you should keep in mind while working with the property attribute:
The input tag behaves in a similar fashion to the tag. The tag uses the column and row attributes to define the width and length of the textarea the user can type in:
The above tag will generate an tag called storyInto that will be 80 columns wide and five rows long.
Most HTML forms are more than just a collection of the simple text field controls. They use drop-down lists, checkboxes, and radio buttons to collect a wide variety of information. While the postStoryContent.jsp file did not contain any of these controls, it is important to understand how the Struts framework renders these controls using the HTML tag library. Let's begin the discussion by the looking at the drop-down list.
Drop-down List
A drop-down list HTML control provides a list of options that a user can select from. However, the user sees only the item that has been selected. All of the other items are hidden until the user clicks on the drop-down box. On clicking the box, the rest of the options will be displayed and the user will be able to make a new choice.
Since the Post a Story page does not have a drop-down box, we will have to step away from it briefly. Using the Struts HTML tag library, there are two ways of rending a drop-down box:
The tag renders a tag in HTML. The tag renders a single option for placement in the drop-down list. If you want to display a drop-down list containing a list of name prefixes, you would write the following code in your JSP file: Please select a prefix Mr. Ms. Mrs. Dr. The above code snippet would generate the following HTML:
Please select a prefixMr.Ms.Mrs.Dr.
The tag has one important attribute, the property attribute. It is the name of the ActionForm method that will store the item selected from the drop-down list. The tag must always be contained within an tag. The value attribute in the tag specifies the value that will be sent in the user's request for the selected item from the drop-down list, when they hit the "submit" button.
The and tag work well while generating a drop-down list that does not change. However, if you want to create a drop-down list based on the data that is dynamic, such as the data pulled from a database, you need to the use the tag. The allows you to generate an
list from a Java Collection object.
Let's assume that in a SetupAction class we created a Vector object and populated it with the prefix codes. We then put that code in the request object as shown below:
Vector prefixes = new Vector(); prefixes.add("NS"); prefixes.add("Mr."); prefixes.add("Ms."); prefixes.add("Mrs."); prefixes.add("Dr."); request.setAttribute("prefixes", prefixes);
We could then render this collection into a drop-down list using the following code:
CheckBoxes
Setting up a checkbox to appear on an HTML form is easy to do. It just requires the use of a checkbox flag. To create a checkbox on a form, the following syntax can be used:
The property attribute for the checkbox matches the name of the property in the ActionForm for which the checkbox is going to get and set data. The value attribute is the value that will be sent in the HTTP request if the user checks the checkbox. If no value is specified, then the default value will always be on.
One important thing to remember is that when a checkbox is not checked, no value will be passed in the HTTP request. This also means that the value that was already set in the property in the ActionForm associated with the checkbox will not change. You have to check the request to see if the checkbox is present in the request. If it is not, you have to set the ActionForm property to a false or off value:
if (request.getAttribute("someBeanProperty") == null) { this.setSomeBeanProperty(false); }
This is important because otherwise if the submitted data has a validation error and the ActionServlet returns the user to the screen, where they entered data, any checkboxes that had been moved from a checked to an unchecked state would still show up on the screen as checked.
So in your validate() method in the ActionForm you must check the request object to see if the checkbox parameter was passed as a request attribute. If it was not, you must set the corresponding property in the ActionForm to be false. This has to be done before you start doing any validation of the form data, or else you will end up with your form data inconsistently handling the checkbox information passed to it. This also means that if you want to pre-populate a form with checkboxes set in an off status, the reset() method of the ActionForm, being used to populate the page must set the properties in the ActionForm that map to the checkboxes to a false value.
Radio Buttons
To render a radio button in a form, we use the tag. This tag has two core attributes: property and value. These two attributes are similar in behavior to the tag. The property attribute defines the name of the property in the ActionForm that the radio button maps to. The value attribute is the value that will be sent, if the radio button is selected when the user submits the form.
To group a set of radio button controls together, so that only one of a group of radio buttons can be set, can be accomplished by setting each radio button's property attribute to point the same ActionForm property.
If we wanted to use a radio button, instead of the drop-down list to show a selection of prefixes to the user, we could write the following code:
The HTML generated by the above code would look as shown below:
The current stable release of Struts, v1.0.2, provides powerful development metaphors for capturing, processing, and validating the form data submitted by an end user. In medium-to-large projects, implementing an individual ActionForm class for each screen in the application can turn into a significant amount of work. The developers will find that they are writing a large number of ActionForm classes to capture the data, but are basically providing the same types of validation rules against the data.
The next release of the Strut framework, v1.1b (b standing for beta), offers two new features that promise significant reduction in the amount of work associated with building the form classes. These two new features are:
Let's take a look at these new features and see how they can be used to build our previous example, the Post a Story page. Note that since this is a beta version of Struts, the features and their implementations described here might differ slightly when version 1.1 of the framework is released.
As we discussed earlier in the chapter, to use Struts form processing capabilities, developers need to explicitly extend the Struts ActionForm class. They need to implement getter or setter methods for each of the form fields they wanted to capture in the class and override the reset() and validate() method inherited from the ActionForm class.
Struts v1.1b now gives the development team the ability to declaratively define an ActionForm class without writing a single line of code. To do this, we need to first define a class in the struts-config.xml. The following code shows the entry that is used to define the ActionForm (postStoryForm) class in the Post a Story page:
Just like the standard non-dynamic Struts ActionForm class, we need to define the dynamic ActionForm class as a entry in the struts-config.xml. However, while defining a dynamic ActionForm, we do not provide our own ActionForm class in the type attribute of the tag. Instead, we use the org.apache.struts.Action.DynaActionForm in the type attribute:
Using the DynaActionForm class tells Struts that we will be using a dynamic ActionForm. Once we have defined the , we need to define the individual properties in it. This is equivalent to writing a get()/set() method in a non-dynamic ActionForm class:
Just like the non-dynamic example shown earlier in the chapter, our dynamic ActionForm (postStoryForm) definition has three properties: storyIntro, storyBody, and storyTitle. Each of these properties has a corresponding tag.
A <form-property> tag has three attributes:
Defining the and its corresponding tags is sufficient to tell Struts to use a dynamic ActionForm class. The postStoryContent.jsp page, which pulls the data from the postStoryForm form bean, does not have to be modified. It does not care whether we are using a non-dynamic or dynamic ActionForm.
Pulling the data from a dynamic form bean in the Struts Action class is done a little differently than in a non-dynamic form bean. The following code shows the rewritten PostStoryForm class (that is, the Action class), pulling the data from the dynamic postStoryForm form bean defined above:
package com.wrox.javaedge.struts.poststory; import java.util.Vector; org.apache.struts.action.DynaActionForm; import com.wrox.javaedge.common.ApplicationException; import com.wrox.javaedge.member.MemberVO; import com.wrox.javaedge.story.StoryManagerBD; import com.wrox.javaedge.story.StoryVO; import com.wrox.javaedge.story.dao.StoryDAO; public class PostStory extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ if (this.isCancelled(request)) { return (mapping.findForward("poststory.success")); } DynaActionForm postStoryForm = (DynaActionForm) form; HttpSession session = request.getSession(); MemberVO memberVO = (MemberVO) session.getAttribute("memberVO"); try{ StoryVO storyVO = new StoryVO(); storyVO.setStoryIntro((String)postStoryForm.get("storyIntro")); storyVO.setStoryTitle((String)postStoryForm.get("storyTitle")); storyVO.setStoryBody((String)postStoryForm.get("story")); } }
The difference between the above PostStory class and the PostStoryForm class shown earlier is subtle. First, the above PostStory class no longer casts the ActionForm being passed into the perform() method in the PostStoryForm class shown earlier in the chapter. Instead, it casts the incoming ActionForm parameter to be of type DynaActionForm:
DynaActionForm postStoryForm = (DynaActionForm) form;
Then, while retrieving the data from the form, it does not call an individual getXXX() method for each property in the ActionForm. Instead, it invokes the get() method in the class by passing in the name of the property it wants to retrieve:
storyVO.setStoryIntro((String)postStoryForm.get("storyIntro")); storyVO.setStoryTitle((String)postStoryForm.get("storyTitle")); storyVO.setStoryBody((String)postStoryForm.get("storyBody"));
The code then casts the individual properties retrieved to the Java data types that were defined in the tag in the struts-config.xml file.
The dynamic form bean is a powerful feature of Struts v1.1b. It allows you to easily implement and change the form beans without having to write a single line of code. This new feature keeps very much in line with the philosophy of Struts which is to let the framework do as much of the work as possible, while allowing the developer to focus on building the business code rather than the infrastructure code.
However, the real power of dynamic form beans comes into play when they are combined with another new Struts v1.1.b feature, the Validator framework.
After building several Struts-based applications, you will often find that you are performing the same types of validation over and over again. Some common validations include the following checks:
Struts release v1.1b now provides a framework that allows you to reuse a set of common validation routines without having to write the code. This framework, called the Validator framework, allows you to write your own validation routines that can be plugged in and used across all of your own form bean classes. We are not going to discuss this framework in depth. For the purposes of this chapter, we will look at how to use it to mimic the validate() method of the PostStoryForm class shown earlier. Specifically, we are going to use a dynamic form bean to collect the form data and apply the following validation rules:
The third validation, checking for vulgarity, will not be implemented here. Writing your own validation rules requires much more explanation. For the details on extending the validation framework with your own validation rules, please refer to the Struts documentation ().
Let's begin our discussion by looking at how the Validator framework is set up and configured.
Validator Framework Setup
The Validator framework requires a modification in the struts-config.xml file and the addition of two new configuration files: validator-rules.xml and validation.xml. Struts v1.1b allows new functionality to be added to the framework via a plug-in. The Validator framework is one such plug-in. We are not going to discuss the Struts v1.1b framework in any detail. For further information on the plug-in architecture, please refer to the Struts v1.1b documentation ().
To make Struts aware of the Validator framework, we need to add the following entry (that is, ) at the end of the JavaEdge struts-config.xml file:
This defines the fully-qualified Java class that represents the plug-in point between Struts and the third-party software. The tag is used to set a plug-in specific property. In the above example, the pathnames property contains a comma-separated list telling the Validator framework where to find the validator-rules.xml file and the validation.xml file.
The validator-rules.xml file contains individual rule entries for the pre-defined validation rules that come as part of the Validator framework. A partial listing of the validation rules defined in the validator-rules.xml is shown below:
The validation.xml file contains the mappings to each form bean in that application that is going to use the Validator framework. It maps each field of the form bean to the validation rule that is going to be invoked against it. We will be going through some of the validation.xml details in the following section.
Implementing the Required Field Validation
In the Post a Story page, the story title, story introduction, and story body are all required fields. To use the Validator framework to enforce these rules, we must create a file called validation.xml. The following code shows the validation.xml file that is used to enforce the validation of the required fields:
The tag is the root element for the validation.xml file. It represents a collection of forms for the application. A tag can contain one or more
tags. A tag represents a particular form bean in the application:
The name attribute in the tag is the name of the form bean defined in the struts-config.xml file. Each tag has one or more tags associated with it.
The tag represents a single element of the that is going to be validated by the Validator framework. It has two attributes in it. These attributes are:
The name of the field that is going to be validated. This must match the name of a field defined in the in the struts-config.xml. This is a mandatory attribute.
This lists, from left to right, all of the validation rules that are going to be invoked on the field. These rules will be fired in the order in which they are listed. In our example above, we are only applying the required rule against the field. This is a mandatory attribute.
A tag can contain one or more tags. The tag is used by the Validator framework to determine which message should be displayed to the end user, when a rule is violated:
A tag has three attributes:
The name of the rule with which the message is associated. In our above example, the value of name points to the required rule.
The key for the message in the Struts resource bundle (that is, ApplicationResources.properties) file. In our above example, the value of error.poststory.field.null would be pulled from the ApplicationResources.properties file as:
The following field: {0} is a required field. Please provide a value for {0}.
The key attribute is a required attribute in the tag.
Tells the Validator framework that it should use the resource bundle to look up an error message, based on the value of the key attribute. If the value of resource is set to true, the resource bundle is used. If it is set to false, the default Struts resource bundle will not be used and the value in the key attribute will be taken as a literal string. The default value of the resource attribute is true.
A tag can also contain argument tags called , , , , and . These tags are used to pass arguments into the tags. The allows a developer to pass in the values to a message defined in the Struts resource bundle. The postStoryForm validation has one argument being passed into each of the messages in the field.
For example, the storyTitle uses the following tag. It indicate that whenever a validation error occurs in the storyValidation field of the postStoryForm, the following key will be used to look up a value from the ApplicationResources.properties file and perform a string substitution on the message:
So, if the users did not enter a value into the storyTitle field, they would get the following error message:
The following field: Story Title is a required field. Please provide a value for Story Title.
The tags have three attributes:
Defines the name of the validation rule with which this argument is associated. For example, if we wanted only the first argument of the message to be available when the required rule is invoked for the storyTitle field, we would write the tag as follows:
If the name is not provided, this argument will be available to every validation rule that fires off a validation exception for that particular field.
The key for the message in the Struts resource bundle (that is, ApplicationResources.properties) file.
Tells the Validator framework that it should use the resource bundle to look up an argument based on the value in the key attribute. If the value of resource is set to true, the resource bundle is used. If it is set to false, the default Struts resource bundle will not be used and the value of the key attribute will be taken as a literal string value. The default value of the resource attribute is true.
Once we have defined all the form and field mappings in the validation.xml file, we need to make one last change to validate our dynamic form bean against the rules we have defined. Any dynamic form bean using the Validator framework must have its entry modified in the struts-config.xml file. In this entry, the type attribute for the form bean must be set to use the org.apache.struts.validator.DynaValidatorForm class:
Now, let's look at setting up a slightly more complicated rule, the maxlength validation rule.
The maxlength Validation Rule
The next rule that we are going to implement, for our rewritten Post a Story page, puts some maximum size limit on the data entered by the user in each field. It is the maxlength validation rule.
The following code shows the revised validation.xml file, containing the new definitions of the rules:
maxlength 100 maxlength 2048 maxlength 100000
To set up each field with the maxlength validation rule, we need to add the rule to the value of the depends attribute in each tag. For the storyTitle field, this would look like:
The rules are always invoked from left to right. In the above validation.xml file, the required validation rule will be invoked before the maxlength rule.
For the two rules associated with each field, we need to add tags that will reflect the different messages for each rule. In the storyTitle, we have two tags with the name attribute of each being the same as one of the names defined in the depends attribute:
In addition, each message has two arguments passed to it. Thus, there are and tags defined in each tag. For the storyTitle field, it is as shown below:
The first argument, , is going to be shared across all the messages being thrown by the validation field. To do this, we do not define the name attribute in the tag. However, the second argument, is going to be available only to the maxlength validation rule. We indicate this by setting the name attribute in the tag to maxlength.
We need to define the constraints for the validation rule to take effect. For instance, for the maxlength validation rule, we need to specify the acceptable maximum length of the field being validated. This value can be set by using the tag. The maxlength validation rule takes a single parameter, maxlength, as an input value:
maxlength 100000
The tag contains two elements, and . The element holds the name of the input parameter being passed into the validation rule. The element holds the value that is to be set for that variable.
The table below lists all of the validation rules that accept the input parameters:
In the tag you would have noticed the unusual syntax of the key attribute. The key attribute is set to the value ${var:maxlength}. This value will pull the value defined for the tag whose is equal to maxlength. However, the value of this variable will be pulled only if the resource attribute in the tag is set to false.
Some Final Thoughts
Discussing how to use the Struts development framework is out of the scope of this book. The next release of Struts promises to offer many new features and enhancements, which will make the form processing and validation extremely automated. The section Dynamic Forms and Validation of this chapter has discussed these new features very briefly, particularly the Validator framework.
There are some other important topics on the Validator framework such as:
The discussion on these topics is out of the scope of this book. For more information on these topics, you can visit the Struts web site ().
This chapter focused on how to use Struts to collect and process the data submitted in an HTML form. The following four pieces must be present to use the Struts-based form processing:
The ActionForm class acts as a wrapper class for the form data submitted by the user. The ActionServlet will use the ActionForm class defined for an action to pull the submitted form data out of the user's HTTP request. Each piece of data sent from a form will correspond to a get()or set() method that will be used to retrieve and populate the ActionForm. The ActionForm class has two methods that can be overridden by the developer, reset() and validate(). The reset() method is used to clear the properties in ActionForm to ensure that they are always in a predetermined state. To pre-populate a form with data, you can use the reset() method.
The validate() method in the ActionForm class will contain any validation rules that need to be applied against the submitted data. This method should contain only the lightweight validation rules that check the constraints on the data. If any validation errors are found, an ActionError class will be added to the ActionErrors class, which is passed back by the validate() method. If the ActionServlet finds that the ActionErrors contains errors, it will redirect the users back to the JSP page where they submitted the data. The validation errors will then be displayed using the tag.
The Action class is used to process the user's request. Its perform() method holds all the business logic used to process the user's request. We did not discuss the Action class in detail in this chapter. We are going to explore the handling business logic in the next chapter.
To map the data submitted in the HTML form to the ActionForm class, you need to use a JSP page that uses the Struts HTML tag library. The Struts HTML tag library contains a number of tags used for the rendering HTML input tags. Some of the tags that were covered in this chapter include:
These three pieces (ActionForm class, Action class, and JSP page) together are all associated with an tag in the struts-config.xml file. Each ActionForm used in the application must be declared as a tag. Once it is declared, the ActionForm can be associated with an tag. The name attribute of the tag tells the ActionServlet class processing a user request that there is an ActionForm class that will be used to collect the data. If the tag contains a validate attribute set to true, the ActionServlet will invoke the validate() method in the ActionForm class.
Finally, the chapter discussed some of the new form processing features in Struts v1.1b, in short. This chapter gave an overview of the following:
In the next chapter, we are going to look at how to build the business logic in Struts. The Struts development framework, with the help of the Action class, provides a clean mechanism for encapsulating the business logic. However, if you are not careful, you can limit the long-term reusability of your application code. The next chapter demonstrates the use of the several core design patterns, which when coupled with the Struts provide optimal code reusability. | http://flylib.com/books/en/2.46.1/form_presentation_and_validation_with_struts.html | CC-MAIN-2018-05 | en | refinedweb |
#include "ntw.h"
Go to the source code of this file.
The grid widget is a widget that can contain multiple children. It has a specified number of rows and columns, and children are laid out automatically according to grid coordinates. Children may occupy more than one cell on the grid. The grid will take care of most resizing and placement of widgets automatically. | http://ntw.sourceforge.net/Docs/CServer/grid_8h.html | CC-MAIN-2018-05 | en | refinedweb |
hi all
i have a problem and i hope someone will help me.
i have this program and i want to find the absolute maximum difference between y1 and y2 ??!!
i have found the difference between y1 and y2 but i could not find the maximum difference between them!!!
I mean the maximum difference for all the numbers .
for example, if we have
y2-y1=23
y2-y1=20
y2-y1=12
y2-y1=40
then the maximum difference = 40
#include<iostream> #include<iomanip> #include<cmath> using namespace std; int main() { //Declaration and Initialization const double e=2.718282; int random,i(1); double y1,y2; double r; cout<<"Enter the number of random values to be entered: "; cin>>random; cout<<"\n\nx\t"<<"exact root(y1)\t"<<"estimated root(y2)\t" <<" The differnce between roots"<<"\n"; while(i<=random) } r=rand()%((20000/1000)-(5000/1000))+5000/1000; y1=sqrt(r); y2=e*(.5*log(r)); cout<<setprecision(3)<<r<<"\t"<<setprecision(6)<<y1<<" \t"<<setprecision(6) <<y2<<"\t"<<setprecision(6)<<" "<<fabs(y2-y1)<<endl; i++; } return 0; } | https://www.daniweb.com/programming/software-development/threads/397187/how-to-find-the-maximum-difference-between-a-set-of-numbers | CC-MAIN-2018-05 | en | refinedweb |
Raspberry Pi + TMP36 Temperature Sensor
Getting started
Hooking up analog sensors to the Raspberry Pi is easy with the MCP3008. Follow along to learn how to hook your Raspi up to a temperature sensor, and start streaming right away! We'll be using the Plotly Python API on the Raspberry Pi to do all the heavy lifting. This tutorial does however, assume that you have an internet connection on your Pi, as well as either SSH access or a keyboard and monitor hooked up.
Materials
- Raspberry Pi (Model B)
- Raspberry Pi wifi dongle
- TMP36 temperature sensor
- MCP3008 D/A chip
- Hookup wires
- Half-size breadboard
- Pi Cobbler or Adafruit Pi shield
Hooking it up
Software
First, install the required modules and dependencies (you can copy and paste this in your terminal):
sudo apt-get install python-dev wget -O - | sudo python sudo easy_install -U distribute sudo apt-get install python-pip sudo pip install rpi.gpio sudo pip install plotly
Create a new folder for your project. Create a config.json file in said folder and input your plotly API key, and your plotly streaming tokens.
Example config.json:
{ "plotly_streaming_tokens": ["your_stream_token", "another_stream_token"], "plotly_api_key": "api_key", "plotly_username": "username" }
The script
Grab the Python scripts here!
tmp36.py is where all the fun happens.
readadc.py is just a helper script that
tmp36.py will use to poll for analog data from the MCP3008. Copy both of these files into the folder you have created above.
Open up
tmp36.py, and let's go through it.
First we're just importing all of the necessary libraries.
readadc makes it easy to pull analog data from your Rasberry Pi's GPIO pins.
import plotly.plotly as py # plotly library import json # used to parse config.json import time # timer functions import readadc # helper functions to read ADC from the Raspberry Pi import datetime # log and plot current time
Now, we're going to pull in our config file, and use them to initialize our Plotly object.
with open('./config.json') as config_file: plotly_user_config = json.load(config_file) py.sign_in(plotly_user_config["plotly_username"], plotly_user_config["plotly_api_key"])
Now, we create a shell for our graph, and prepare it for streaming. This is where you first include your
streaming_token, to tell Plotly's servers to expect a stream from that particular stream_token!
url = py.plot([ { 'x': [], 'y': [], 'type': 'scatter', 'stream': { 'token': plotly_user_config['plotly_streaming_tokens'][0], 'maxpoints': 200 } }], filename='Raspberry Pi Streaming Example Values') print "View your streaming graph here: ", url
The TMP36 is hooked up to PIN0 on the MCP3008. We then initialize our readadc module (preparing to read analog values). We then initialize a plotly stream, indicating which token we will be using for that trace.
sensor_pin = 0 readadc.initialize() stream = py.Stream(plotly_user_config['plotly_streaming_tokens'][0]) stream.open()
Here we're just creating the main loop that polls for data on
sensor_pin, converting that to a temperature reading, and writing that data to our plotly stream with
stream.write(data)
#the main sensor reading and plotting loop while True: sensor_data = readadc.readadc(sensor_pin, readadc.PINS.SPICLK, readadc.PINS.SPIMOSI, readadc.PINS.SPIMISO, readadc.PINS.SPICS) millivolts = sensor_data * (3300.0 / 1024.0) # 10 mv per degree temp_C = ((millivolts - 100.0) / 10.0) - 40.0 # convert celsius to fahrenheit temp_F = (temp_C * 9.0 / 5.0) + 32 # remove decimal point from millivolts millivolts = "%d" % millivolts # show only one decimal place for temprature and voltage readings temp_C = "%.1f" % temp_C temp_F = "%.1f" % temp_F # write the data to plotly stream.write({'x': datetime.datetime.now(), 'y': temp_C}) # delay between stream posts time.sleep(0.25)
Wrapping it up
You're all ready to go! You've got your Pi hooked up as per the above diagram, you've created a
config.json file with your credentials, and in the same folder have you have copied over
tmp36.py and
readadc.py. From that directory, run:
sudo python tmp36.py
You can watch the console to see the URL returned from Plotly's server. Now go check out your live stream! | https://plot.ly/raspberry-pi/tmp36-temperature-tutorial/ | CC-MAIN-2018-05 | en | refinedweb |
CellGridSampler samples XCombs bins using CellGrids. More...
#include <CellGridSampler.h>
CellGridSampler samples XCombs bins using CellGrids.
Definition at line 33 of file CellGridSampler.h.
Make a simple clone of this object.
Reimplemented from Herwig::BinSampler.
Make a clone of this object, possibly modifying the cloned object to make it sane.
Reimplemented from Herwig::BinSampler.
The standard Init function used to initialize the interfaces.
Called exactly once for each class by the class description system before the main function starts or when this class is dynamically loaded.
Initialize this bin sampler.
This default version calls runIteration.
Reimplemented from Herwig::BinSampler.
The assignment operator is private and must never be called.
In fact, it should not even be implemented.
Function used to read in object persistently.
Function used to write out object persistently. | http://herwig.hepforge.org/doxygen/classHerwig_1_1CellGridSampler.html | CC-MAIN-2018-05 | en | refinedweb |
Opened 4 years ago
Closed 4 years ago
#6907 enhancement closed fixed (fixed)
Deprecate Lore
Description
As Twisted has switched to using Sphinx for generating documentation, Lore is no longer needed, and should be deprecated.
Once Lore has been deprecated, and is no longer needed, another ticket should be created to remove it.
See:
Change History (5)
comment:1 Changed 4 years ago by
comment:2 Changed 4 years ago by
I've taken a stab at deprecating it.
comment:3 Changed 4 years ago by
Looks good to me. Thanks! Buildbot test are not available.
comment:4 Changed 4 years ago by
Thanks.
- I'm not sure I see the benefit of deleting the TODO comment in
twisted/lore/__init__.pyas part of this change.
- I've tried to figure out why this module uses
unittest.TestCasebut I can't. I don't think the module should use *both*
unittest.TestCase*and*
twisted.trial.unittest.TestCase. One thing I do see is that the existing twisted imports in this test module are a subset of the imports in
twisted/__init__.py. I don't see how that could actually matter in this case though. I suspect since all the tests pass even with the new
twisted.trial.unittestimport it's safe to switch this code entirely over to trial. Also, please use the
from twisted.trial.unittest import TestCasestyle of import.
- You might like
namedAny("twisted.lore")or maybe just
__import__("twisted.lore")to avoid needing to hack around pyflakes warnings.
- American English spelling, sorry! favor instead of favour.
- There's no standard (maybe there should be) for this but consider:
exarkun@top:~/Projects/Twisted/trunk$ grep "was deprecated" twisted/ -r --include '*.py' | wc -l 76 exarkun@top:~/Projects/Twisted/trunk$ grep "is deprecated" twisted/ -r --include '*.py' | wc -l 120
Thanks again. Please merge after addressing those points.
comment:5 Changed 4 years ago by
Note: See TracTickets for help on using tickets.
(In [41772]) Branching to deprecate-lore-6907. | https://twistedmatrix.com/trac/ticket/6907 | CC-MAIN-2018-05 | en | refinedweb |
According to Yann LeCun, “adversarial training is the coolest thing since sliced bread”. I’m inclined to believe so because I don’t think sliced bread ever created this much buzz and excitement within the deep learning community. Generative Adversarial Networks are a set of models that basically learn to create synthetic data that is similar to input data it's given. In more formal terms, a GAN is a generative model that learns the probability distribution (or data distribution) of the training examples it is given. From this distribution, we can then create sample outputs. GANs have seen their largest progress with image training examples, but this idea of modeling data distributions is one that can be applied with other forms of input.In the case described in today’s post, we’ll be creating a GAN that learns to generate synthetic, yet readable, images of MNIST digits.
In this notebook, we'll be explaining generative adversarial networks, and how you can use them to create a generator network that can create realistic MNIST digits through Tensorflow
Let’s dig a little bit deeper into the structure of this model.. This is basically a binary classifier that will take the form of a normal convolutional neural network (CNN).”. There are specific game theory concepts that prove there is indeed an equilibrium to this game where the generator gets so good that the discriminator outputs a probability of ½ for every input.
Today, we’re going to create a GAN that will generate MNIST digits that can fool even the best classifiers (and humans too of course). Here’s what we’re going to need:
Let’s get started.
First, let's start with our imports. We'll mainly just need Tensorflow. I've also imported Numpy to help with some matrices, the random library for generating numbers, and Matplotlib for visualizing our image data.
import tensorflow as tf import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline
Now, we have to import our MNIST images. To do this, we’ll call a TF function called read_data_sets. This loads in the 55,000 training examples in the MNIST database.
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/")
The mnist variable we created above actually contains both the images and their labels. Let's just isolate the images for now. There will be 55,000 images and each of them will be of sixe 28 x 28.
x_train = mnist.train.images[:55000,:] x_train.shape
(55000, 784)
Let's look at what a random image might look like.
randomNum = random.randint(0,55000) image = x_train[randomNum].reshape([28,28]) plt.imshow(image, cmap=plt.get_cmap('gray_r')) plt.show()
Now, using our classical CS concept of modularity, let’s define a CNN classifier function that takes in an image (of size 28 x 28 x 1) as input. The output will be a single scalar number activation that describes whether or not the input image is real or not.
In order to do that, let's first define some functions that will help us with creating CNNs in Tensorflow
def conv2d(x, W): return tf.nn.conv2d(input=x, filter=W, strides=[1, 1, 1, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
Now, let’s see how we’re going to compose this network. We’ll start off by passing the image through a convolutional layer. First, we create our weight and bias variables through tf.get_variable. Our first weight matrix (or filter) will be of size 5x5 and will have a output depth of 8. It will be randomly initialized from a normal distribution.
Then, we’ll call the function tf.nn.conv2d() through our a helper function called conv2d. tf.nn.conv2d() is the Tensorflow’s function for a common convolution. It takes in 4 arguments. The first is the input volume (our 28 x 28 x 1 image in this case). The next argument is the filter/weight matrix. Finally, you can also change the stride and padding of the convolution. Those two values affect the dimensions of the output volume.
As with any convolutional neural network, this module is repeated, and then followed by a series of fully connected layers. At the end of the network, we do a final matrix multiply and return the activation value. For those of you comfortable with CNNs, this is just a simple binary classifier. Nothing fancy.
This architecture for this network is based on Tensorflow's sample CNN classifier model that they have explained in detail here:
def discriminator(x_image, reuse=False): with tf.variable_scope('discriminator') as scope: if (reuse): tf.get_variable_scope().reuse_variables() #First Conv and Pool Layers W_conv1 = tf.get_variable('d_wconv1', [5, 5, 1, 8], initializer=tf.truncated_normal_initializer(stddev=0.02)) b_conv1 = tf.get_variable('d_bconv1', [8], initializer=tf.constant_initializer(0)) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = avg_pool_2x2(h_conv1) #Second Conv and Pool Layers W_conv2 = tf.get_variable('d_wconv2', [5, 5, 8, 16], initializer=tf.truncated_normal_initializer(stddev=0.02)) b_conv2 = tf.get_variable('d_bconv2', [16], initializer=tf.constant_initializer(0)) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = avg_pool_2x2(h_conv2) #First Fully Connected Layer W_fc1 = tf.get_variable('d_wfc1', [7 * 7 * 16, 32], initializer=tf.truncated_normal_initializer(stddev=0.02)) b_fc1 = tf.get_variable('d_bfc1', [32], initializer=tf.constant_initializer(0)) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*16]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) #Second Fully Connected Layer W_fc2 = tf.get_variable('d_wfc2', [32, 1], initializer=tf.truncated_normal_initializer(stddev=0.02)) b_fc2 = tf.get_variable('d_bfc2', [1], initializer=tf.constant_initializer(0)) #Final Layer y_conv=(tf.matmul(h_fc1, W_fc2) + b_fc2) return y_conv
Now that we have our discriminator defined, let’s take a look at the generator module. For this, we’ll be basing our model off the generator introduced in the DCGAN paper (link:). You can think of the generator as being a kind of reverse ConvNet. With CNNs, the goal is to transform a 2 or 3 dimensional matrix of pixel values into a single probability. A generator, however, seeks to take a d-dimensional noise vector and upsample it to become a 28 x 28 image. This upsampling is done through a convolutional transpose (or deconvolution) layer. ReLUs and Batch Norm are then used to stabilize the outputs of each layer.
The structure of the generator is very similar to that of the discriminator, except we're calling the convolution transpose method, instead of the conv2d one.
The conv transpose + relu + batch norm pipeline is repeated 4 times so that the output volume grows larger and larger until a 28 x 28 x 1 image is formed.
def generator(z, batch_size, z_dim, reuse=False): with tf.variable_scope('generator') as scope: if (reuse): tf.get_variable_scope().reuse_variables() g_dim = 64 #Number of filters of first layer of generator c_dim = 1 #Color dimension of output (MNIST is grayscale, so c_dim = 1 for us) s = 28 #Output size of the image s2, s4, s8, s16 = int(s/2), int(s/4), int(s/8), int(s/16) #We want to slowly upscale the image, so these values will help #make that change gradual. h0 = tf.reshape(z, [batch_size, s16+1, s16+1, 25]) h0 = tf.nn.relu(h0) #Dimensions of h0 = batch_size x 2 x 2 x 25 #First DeConv Layer output1_shape = [batch_size, s8, s8, g_dim*4] W_conv1 = tf.get_variable('g_wconv1', [5, 5, output1_shape[-1], int(h0.get_shape()[-1])], initializer=tf.truncated_normal_initializer(stddev=0.1)) b_conv1 = tf.get_variable('g_bconv1', [output1_shape[-1]], initializer=tf.constant_initializer(.1)) H_conv1 = tf.nn.conv2d_transpose(h0, W_conv1, output_shape=output1_shape, strides=[1, 2, 2, 1], padding='SAME') H_conv1 = tf.contrib.layers.batch_norm(inputs = H_conv1, center=True, scale=True, is_training=True, scope="g_bn1") H_conv1 = tf.nn.relu(H_conv1) #Dimensions of H_conv1 = batch_size x 3 x 3 x 256 #Second DeConv Layer output2_shape = [batch_size, s4 - 1, s4 - 1, g_dim*2] W_conv2 = tf.get_variable('g_wconv2', [5, 5, output2_shape[-1], int(H_conv1.get_shape()[-1])], initializer=tf.truncated_normal_initializer(stddev=0.1)) b_conv2 = tf.get_variable('g_bconv2', [output2_shape[-1]], initializer=tf.constant_initializer(.1)) H_conv2 = tf.nn.conv2d_transpose(H_conv1, W_conv2, output_shape=output2_shape, strides=[1, 2, 2, 1], padding='SAME') H_conv2 = tf.contrib.layers.batch_norm(inputs = H_conv2, center=True, scale=True, is_training=True, scope="g_bn2") H_conv2 = tf.nn.relu(H_conv2) #Dimensions of H_conv2 = batch_size x 6 x 6 x 128 #Third DeConv Layer output3_shape = [batch_size, s2 - 2, s2 - 2, g_dim*1] W_conv3 = tf.get_variable('g_wconv3', [5, 5, output3_shape[-1], int(H_conv2.get_shape()[-1])], initializer=tf.truncated_normal_initializer(stddev=0.1)) b_conv3 = tf.get_variable('g_bconv3', [output3_shape[-1]], initializer=tf.constant_initializer(.1)) H_conv3 = tf.nn.conv2d_transpose(H_conv2, W_conv3, output_shape=output3_shape, strides=[1, 2, 2, 1], padding='SAME') H_conv3 = tf.contrib.layers.batch_norm(inputs = H_conv3, center=True, scale=True, is_training=True, scope="g_bn3") H_conv3 = tf.nn.relu(H_conv3) #Dimensions of H_conv3 = batch_size x 12 x 12 x 64 #Fourth DeConv Layer output4_shape = [batch_size, s, s, c_dim] W_conv4 = tf.get_variable('g_wconv4', [5, 5, output4_shape[-1], int(H_conv3.get_shape()[-1])], initializer=tf.truncated_normal_initializer(stddev=0.1)) b_conv4 = tf.get_variable('g_bconv4', [output4_shape[-1]], initializer=tf.constant_initializer(.1)) H_conv4 = tf.nn.conv2d_transpose(H_conv3, W_conv4, output_shape=output4_shape, strides=[1, 2, 2, 1], padding='VALID') H_conv4 = tf.nn.tanh(H_conv4) #Dimensions of H_conv4 = batch_size x 28 x 28 x 1 return H_conv4
Okay, so now we’ve defined both the generator and discriminator functions. Let’s see what a sample output from an untrained generator looks like. With Tensorflow, we need to first define a session and then create a placeholder for the input to our generator. The purpose of a placeholder is basically to tell Tensorflow "We're going to input in our random z vector later, but for now, we're going to define this placeholder variable instead". It lets Tensorflow know about the size of the inputs beforehand. The shape of the placeholder will be None x z_dimensions. The None keyword means that the value can be determined at session runtime. We normally have None as our first dimension so that we can have variable batch sizes (With a batch size of 16, the input to the generator would be 16 x 100). With the None keywoard, we don't have to specify batch_size until later.
sess = tf.Session() z_dimensions = 100 z_test_placeholder = tf.placeholder(tf.float32, [None, z_dimensions])
Now, we create a variable (sample_image) that holds the output of the generator, and also initialize the random noise vector that we’ll use as input. The np.random.normal function has three arguments. The first and second define the range of the output distribution we want (between -1 and 1 in our case), and the third defines the the shape of the vector (1 x 100).
sample_image = generator(z_test_placeholder, 1, z_dimensions) test_z = np.random.normal(-1, 1, [1,z_dimensions])
Next, we initialize all the variables, feed our test_z into the placeholder, and run the session. The sess.run function has two arguments. The first is called the "fetches" argument. It defines the value for you're interested in computing. For example, in our case, we want to see what the output of the generator is. If you look back at the last code snippet, the output of the generator function is stored in sample_image. Therefore, we'll use sample_image for our first argument. The second argument is where we input our feed_dict. This data structure is where we provide inputs to all of our placeholders. In our example, we need to feed our test_z variable into the z placeholder we defined earlier.
sess.run(tf.global_variables_initializer()) temp = (sess.run(sample_image, feed_dict={z_test_placeholder: test_z}))
Finally, we can view the output through matplotlib.
my_i = temp.squeeze() plt.imshow(my_i, cmap='gray_r') plt.show()
Not a very convincing MNIST digit right? Let’s look at how we can make our generator better. Enter loss functions and optimization!
batch_size = 16 tf.reset_default_graph() #Since we changed our batch size (from 1 to 16), we need to reset our Tensorflow graph sess = tf.Session() x_placeholder = tf.placeholder("float", shape = [None,28,28,1]) #Placeholder for input images to the discriminator z_placeholder = tf.placeholder(tf.float32, [None, z_dimensions]) #Placeholder for input noise vectors to the generator
One of the trickiest parts about understanding GANs is that the loss function is a little bit more complex than that of a traditional CNN classifiers (For those, a simple MSE or Hinge Loss would do the trick). If you think back to the introduction, a GAN can be thought of as a zero sum minimax game. The generator is constantly improving to produce more and more realistic images, while the discriminator is trying to get better and better at distinguishing between real and generated images. This means that we need to formulate loss functions that affect both networks. Let’s take a look at the inputs and outputs of our networks.
Dx = discriminator(x_placeholder) #Dx will hold discriminator outputs (unnormalized) for the real MNIST images Gz = generator(z_placeholder, batch_size, z_dimensions) #Gz holds the generated images Dg = discriminator(Gz, reuse=True) #Dg will hold discriminator outputs (unnormalized) for generated images
So, let’s first think about what we want out of our networks. We want the generator network to create images that will fool the discriminator. The generator wants the discriminator to output a 1 (positive example). Therefore, we want to compute the loss between the Dg and label of 1. This can be done through the tf.nn.sigmoid_cross_entropy_with_logits function. This means that the cross entropy loss will be taken between the two arguments. The "with_logits" component means that the function will operate on unscaled values. Basically, this means that instead of using a softmax function to squish the output activations to probability values from 0 to 1, we simply return the unscaled value of the matrix multiplication. Take a look at the last line of our discriminator. There's no softmax or sigmoid layer at the end.
The reduce mean function just takes the mean value of all of the components in the matrixx returned by the cross entropy function. This is just a way of reducing the loss to a single scalar value, instead of a vector or matrix.
g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Dg, labels=tf.ones_like(Dg)))
Now, let’s think about the discriminator’s point of view. Its goal is to just get the correct labels (output 1 for each MNIST digit and 0 for the generated ones). We’d like to compute the loss between Dx and the correct label of 1 as well as the loss between Dg and the correct label of 0.
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Dx, labels=tf.ones_like(Dx))) d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=Dg, labels=tf.zeros_like(Dg))) d_loss = d_loss_real + d_loss_fake
Once we have our 2 loss functions (d_loss and g_loss), we need to define our optimizers. Keep in mind that the optimizer for the generator network needs to only update the generator’s weights, not those of the discriminator. In order to make this distinction, we need to create 2 lists, one with the discriminator’s weights and one with the generator’s weights. This is where naming all of your Tensorflow variables can come in handy.
tvars = tf.trainable_variables() d_vars = [var for var in tvars if 'd_' in var.name] g_vars = [var for var in tvars if 'g_' in var.name]
Next, we specify our two optimizers. In today’s era of deep learning, Adam seems to be the best SGD optimizer as it utilizes adaptive learning rates and momentum. We call Adam's minimize function and also specify the variables that we want it to update.
with tf.variable_scope(tf.get_variable_scope(), reuse=False): trainerD = tf.train.AdamOptimizer().minimize(d_loss, var_list=d_vars) trainerG = tf.train.AdamOptimizer().minimize(g_loss, var_list=g_vars)
You can also specify a learning rate by passing it as an argument (I’ve found .0002 to be effective).
Ah, now the best part of neural networks, the famous training loop. During every iteration, there will be two updates being made, one to the discriminator and one to the generator. For the generator update, we’ll feed in a random z vector to the generator and pass that output to the discriminator to obtain a probability score (this is the Dg variable we specified earlier). As we remember from our loss function, the cross entropy loss gets minimized, and only the generator’s weights and biases get updated.
We'll do the same for the discriminator update. We’ll be taking a batch of images from the mnist variable we created way at the beginning of our program. These will serve as the positive examples, while the images in the previous section are the negative ones.
sess.run(tf.global_variables_initializer()) iterations = 3000 for i in range(iterations): z_batch = np.random.normal(-1, 1, size=[batch_size, z_dimensions]) real_image_batch = mnist.train.next_batch(batch_size) real_image_batch = np.reshape(real_image_batch[0],[batch_size,28,28,1]) _,dLoss = sess.run([trainerD, d_loss],feed_dict={z_placeholder:z_batch,x_placeholder:real_image_batch}) #Update the discriminator _,gLoss = sess.run([trainerG,g_loss],feed_dict={z_placeholder:z_batch}) #Update the generator
Let's now see what a sample image looks like after training.
sample_image = generator(z_placeholder, 1, z_dimensions, reuse=True) z_batch = np.random.normal(-1, 1, size=[1, z_dimensions]) temp = (sess.run(sample_image, feed_dict={z_placeholder: z_batch})) my_i = temp.squeeze() plt.imshow(my_i, cmap='gray_r')
<matplotlib.image.AxesImage at 0x7f37153e78d0>
One note that I’d like to make is that GANs are notoriously difficult to train. Without the right hyperparameters, network architecture, and training procedure, there is a high chance that either the generator or discriminator will overpower the other. A common case of this is the situation where the generator is able to find a flaw in the discriminator by repeatedly outputting an image that fits the data distribution the discriminator is looking for, but is nowhere close to being a readable MNIST digit. The generator has collapsed onto a single point, and therefore we won’t output a variety of digits. There are also cases where the discriminator becomes too powerful and is able to easily make the distinction between real and fake images.
The mathematical intuition behind this phenomenon lies in that GANs are typically trained using gradient descent techniques that are designed to find the minimum value of a cost function, rather than to find the Nash equilibrium of a game. When used to seek for a Nash equilibrium, these algorithms may fail to converge. Further research into game theory and stable optimization techniques may result in GANs that are as easy to train as ConvNets!
In this post, we showed how two networks were able to play a minimax game in order to capture the data distribution of the MNIST digits and generate similar looking samples. With applications in video frame prediction, text-image mappings, and more, GANs are definitely the hottest topic in deep learning. Hopefully, with this tutorial, you’ve gained a better understanding of how these networks work in practice and how you can build your own with Tensorflow!
Some more great GAN implementations
DCGAN Tensorflow Implentation:
Arthur Juliani's GAN Implementation:
Brandon Amos's Image Completion Project: | http://nbviewer.jupyter.org/github/adeshpande3/Generative-Adversarial-Networks/blob/master/Generative%20Adversarial%20Networks%20Tutorial.ipynb?utm_content=buffer4d411&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer | CC-MAIN-2018-05 | en | refinedweb |
(For more resources on this subject, see here.)
Introduction
When a scene is rendered, it isn't normally rendered directly to the buffer, which is displayed on the monitor. Normally, the scene is rendered to a second buffer and when the rendering is finished, the buffers are swapped. This is done to prevent some artifacts, which can be created if we render to the same buffer, which is displayed on the monitor. The FrameListener function, frameRenderingQueued, is called after the scene has been rendered to the back buffer, the buffer which isn't displayed at the moment. Before the buffers are swapped, the rendering result is already created but not yet displayed. Directly after the frameRenderingQueued function is called, the buffers get swapped and then the application gets the return value and closes itself. That's the reason why we see an image this time.
Now, we will see what happens when frameRenderingQueued also returns true.
Time for action – returning true in the frameRenderingQueued function
Once again we modify the code to test the behavior of the Frame Listener
- Change frameRenderingQueued to return true:
bool frameRenderingQueued (const Ogre::FrameEvent& evt)
{
std::cout << «Frame queued» << std::endl;
return true;
}
- Compile and run the application. You should see Sinbad for a short period of time before the application closes, and the following three lines should be in the console output:
Frame started
Frame queued
Frame ended
What just happened?
Now that the frameRenderingQueued handler returns true, it will let Ogre 3D continue to render until the frameEnded handler returns false.
Like in the last example, the render buffers were swapped, so we saw the scene for a short period of time. After the frame was rendered, the frameEnded function returned false, which closes the application and, in this case, doesn't change anything from our perspective.
Time for action – returning true in the frameEnded function
Now let's test the last of three possibilities.
- Change frameRenderingQueued to return true:
bool frameEnded (const Ogre::FrameEvent& evt)
{
std::cout << «Frame ended» << std::endl;
return true;
}
- Compile and run the application. You should see the scene with Sinbad and an endless repetition of the following three lines:
Frame started
Frame queued
Frame ended
What just happened?
Now, all event handlers returned true and, therefore, the application will never be closed; it would run forever as long as we aren't going to close the application ourselves.
Adding input
We have an application running forever and have to force it to close; that's not neat. Let's add input and the possibility to close the application by pressing Escape.
Time for action – adding input
Now that we know how the FrameListener works, let's add some input.
- We need to include the OIS header file to use OIS:
#include "OIS\OIS.h"
- Remove all functions from the FrameListener and add two private members to store the InputManager and the Keyboard:
OIS::InputManager* _InputManager;
OIS::Keyboard* _Keyboard;
- The FrameListener needs a pointer to the RenderWindow to initialize OIS, so we need a constructor, which takes the window as a parameter:
MyFrameListener(Ogre::RenderWindow* win)
{
- OIS will be initialized using a list of parameters, we also need a window handle in string form for the parameter list; create the three needed variables to store the data:
OIS::ParamList parameters;
unsigned int windowHandle = 0;
std::ostringstream windowHandleString;
- Get the handle of the RenderWindow and convert it into a string:
win->getCustomAttribute("WINDOW", &windowHandle);
windowHandleString << windowHandle;
- Add the string containing the window handle to the parameter list using the key "WINDOW":
parameters.insert(std::make_pair("WINDOW", windowHandleString.
str()));
- Use the parameter list to create the InputManager:
_InputManager = OIS::InputManager::createInputSystem(parameters);
- With the manager create the keyboard:
_Keyboard = static_cast<OIS::Keyboard*>(_InputManager-
>createInputObject( OIS::OISKeyboard, false ));
- What we created in the constructor, we need to destroy in the destructor:
~MyFrameListener()
{
_InputManager->destroyInputObject(_Keyboard);
OIS::InputManager::destroyInputSystem(_InputManager);
}
- Create a new frameStarted function, which captures the current state of the keyboard, and if Escape is pressed, it returns false; otherwise, it returns true:
bool frameStarted(const Ogre::FrameEvent& evt)
{
_Keyboard->capture();
if(_Keyboard->isKeyDown(OIS::KC_ESCAPE))
{
return false;
}
return true;
}
- The last thing to do is to change the instantiation of the FrameListener to use a pointer to the render window in the startup function:
_listener = new MyFrameListener(window);
_root->addFrameListener(_listener);
- Compile and run the application. You should see the scene and now be able to close it by pressing the Escape key.
What just happened?
We added input processing capabilities to our FrameListener but we didn't use any example classes, except our own versions.
(For more resources on this subject, see here.)
Pop quiz – the three event handlers
Which three functions offer the FrameListener interface and at which point is each of these functions called?
Our own main loop
We have used the startRendering function to fire up our application. After this, the only way we knew when a frame was rendered was by relying on the FrameListener. But sometimes it is not possible or desirable to give up the control over the main loop; for such cases, Ogre 3D provides another method, which doesn't require us to give up the control over the main loop.
Time for action – using our own rendering loop
Using the code from before we now are going to use our own rendering loop.
- Our application needs to know if it should keep running or not; add a Boolean as a private member of the application to remember the state:
bool _keepRunning;
- Remove the startRendering function call in the startup function.
- Add a new function called renderOneFrame, which calls the renderOneFrame function of the root instance and saves the return value in the _keepRunning member variable. Before this call, add a function to process all window events:
void renderOneFrame()
{
Ogre::WindowEventUtilities::messagePump();
_keepRunning = _root->renderOneFrame();
}
- Add a getter for the _keepRunning member variable:
bool keepRunning()
{
return _keepRunning;
}
- Add a while loop to the main function, which keeps running as long as the keepRunning function returns true. In the body of the loop, call the renderOneFrame function of the application.
while(app.keepRunning())
{
app.renderOneFrame();
}
- Compile and run the application. There shouldn't be any noticeable difference to the last example.
What just happened?
We moved the control of the main loop from Ogre 3D to our application. Before this change, Ogre 3D used an internal main loop over which we hadn't any control and had to rely on the FrameListener to get notified if a frame was rendered.
Now we have our own main loop. To get there, we needed a Boolean member variable, which signals if the application wishes to keep running or not; this variable was added in step 1. Step 2 removed the startRendering function call so we wouldn't hand over the control to Ogre 3D. In step 3, we created a function, which first calls a helper function of Ogre 3D, which processes all window events we might have gotten from the operating system. It then sends all messages we might have created since the last frame, and therefore makes the application "well-behaved" in the context of the host windowing system.
After this we call the Ogre 3D function renderOneFrame, which does exactly what the name suggests: it renders the frame and also calls the frameStarted, frameRenderingQueued, and frameEnded event handler of each registered FrameListener and returns false if any of these functions returned false. Since we assign the return value of the function to the _keepRunning member variable, we can use this variable to check if the application should keep running. When renderOneFrame returns a false, we know some FrameListener wants to close the application and we set the _keepRunning variable to false. The fourth step just added a getter for the _keepRunning member variable.
In step 5, we used the _keepRunning variable as the condition for the while loop. This means the while loop will run as long as _keepRunning is true, which will be the case until one FrameListener returns false, which then will result in the while loop to exit and with this the whole application will be closed. Inside the while loop we call the renderOneFrame function of the application to update the render window with the newest render result. This is all we needed to create our own main loop.
Adding a camera
We want a controllable camera in our own implementation of the frame listener, so here we go.
Time for action – adding a frame listener
Using our FrameListener we are going to add a user controlled camera.
- To control the camera we need a mouse interface, a pointer to the camera, and a variable defining the speed at which our camera should move as a member variable of our FrameListener:
OIS::Mouse* _Mouse;
Ogre::Camera* _Cam;
float _movementspeed;
- Adjust the constructor and add the camera pointer as the new parameter and set the movement speed to 50:
MyFrameListener(Ogre::RenderWindow* win,Ogre::Camera* cam)
{
_Cam = cam;
_movementspeed = 50.0f;
- Init the mouse using the InputManager:
_Mouse = static_cast<OIS::Mouse*>(_InputManager-
>createInputObject( OIS::OISMouse, false ));
- And remember to destroy it in the destructor:
_InputManager->destroyInputObject(_Mouse);
- Add the code to move the camera using the W, A, S, D keys and the movement speed to the frameStarted event handler:
Ogre::Vector3 translate(0,0,0);
if(_Keyboard->isKeyDown(OIS::KC_W))
{
translate += Ogre::Vector3(0,0,-1);
}
if(_Keyboard->isKeyDown(OIS::KC_S))
{
translate += Ogre::Vector3(0,0,1);
}
if(_Keyboard->isKeyDown(OIS::KC_A))
{
translate += Ogre::Vector3(-1,0,0);
}
if(_Keyboard->isKeyDown(OIS::KC_D))
{
translate += Ogre::Vector3(1,0,0);
}
_Cam->moveRelative(translate*evt.timeSinceLastFrame * _
movementspeed);
- Now do the same for the mouse control:
_Mouse->capture();
float rotX = _Mouse->getMouseState().X.rel * evt.
timeSinceLastFrame* -1;
float rotY = _Mouse->getMouseState().Y.rel * evt.
timeSinceLastFrame * -1;
_Cam->yaw(Ogre::Radian(rotX));
_Cam->pitch(Ogre::Radian(rotY));
- The last thing to do is to change the instantiation of the FrameListener:
_listener = new MyFrameListener(window,camera);
- Compile and run the application. The scene should be unchanged but now we can control the camera:
What just happened?
We used our knowledge from to add a user-controlled camera. The next step will be to add compositors and other features to make our application more interesting and to leverage some of the techniques we learned along the way.
Adding compositors
Previously, we have created three compositors, which we are now going to add to our application with the capability to turn each one off and on using keyboard input.
Time for action – adding compositors
Having almost finished our application, we are going to add compositors to make the application more interesting.
- We are going to use compositors in our FrameListener, so we need a member variable containing the viewport:
Ogre::Viewport* _viewport;
- We also are going to need to save which compositor is turned on; add three Booleans for this task:
bool _comp1, _comp2, _comp3;
- We are going to use keyboard input to switch the compositors on and off. To be able to differentiate between key presses, we need to know the previous state of the key:
bool _down1, _down2, _down3;
- Change the constructor of the FrameListener to take the viewport as a parameter:
MyFrameListener(Ogre::RenderWindow* win,Ogre::Camera*
cam,Ogre::Viewport* viewport)
- Assign the viewport pointer to the member and assign the Boolean value their starting value:
_viewport = viewport;
_comp1 = false;
_comp2 = false;
_comp3 = false;
_down1 = false;
_down2 = false;
_down3 = false;
- If the key number 1 is pressed and it wasn't pressed before, change the state of the key to pressed, flip the state of the compositor, and use the flipped value to enable or disable the compositor. This code goes into the frameStarted function:
if(_Keyboard->isKeyDown(OIS::KC_1) && ! _down1)
{
_down1 = true;
_comp1 = !comp1;
Ogre::CompositorManager::getSingleton().setCompositorEnabled(_
viewport, "Compositor2", _comp1);
}
- Do the same for the other two compositors we are going to have:
if(_Keyboard->isKeyDown(OIS::KC_2) && ! _down2)
{
_down2 = true;
_comp2 = !comp2;
Ogre::CompositorManager::getSingleton().setCompositorEnabled(_
viewport, "Compositor3", _comp2);
}
if(_Keyboard->isKeyDown(OIS::KC_3) && ! _down3)
{
_down3 = true;
_comp3 = !comp3;
Ogre::CompositorManager::getSingleton().setCompositorEnabled(_
viewport, "Compositor7", _comp3);
}
- If a key is no longer pressed, we need to change the state of the key:
if(!_Keyboard->isKeyDown(OIS::KC_1))
{
_down1 = false;
}
if(!_Keyboard->isKeyDown(OIS::KC_2))
{
_down2 = false;
}
if(!_Keyboard->isKeyDown(OIS::KC_3))
{
_down3 = false;
}
- In the startup() function, add the three compositors to the viewport to the end of the function:
Ogre::CompositorManager::getSingleton().addCompositor(viewport,
"Compositor2");
Ogre::CompositorManager::getSingleton().addCompositor(viewport,
"Compositor3");
Ogre::CompositorManager::getSingleton().addCompositor(viewport,
"Compositor7");
- Remember to change the instantiation of the FrameListener to add the viewport pointer as parameter:
_listener = new MyFrameListener(window,camera,viewport);
- Compile and run the application. Using the 1, 2, 3 keys, you should be able to turn different compositors on and off. The 1 key is for making the image black and white, the 2 key inverts the image, and the 3 key makes the image look like it has a smaller resolution; you can combine all of the effect the way you like:
What just happened?
We added the compositors we wrote in the article about and made it possible to turn them on and off using the 1, 2, and 3 keys. To combine the compositors, we used the fact that Ogre 3D automatically chains compositors if more than one is enabled.
(For more resources on this subject, see here.)
Adding a plane
Without a reference to where the ground is, navigation in 3D space is difficult, so once again let's add a floor plane.
Time for action – adding a plane and a light
Everything we are going to add this time is going in the createScene() function:
- As we already know we need a plane definition, so add one:
Ogre::Plane plane(Ogre::Vector3::UNIT_Y, -5);
Ogre::MeshManager::getSingleton().createPlane("plane",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
1500,1500,200,200,true,1,5,5,Ogre::Vector3::UNIT_Z);
- Then create an instance of this plane, add it to the scene, and change the material:
Ogre::Entity* ground= _sceneManager->createEntity("LightPlaneEnti
ty", "plane");
_sceneManager->getRootSceneNode()->createChildSceneNode()-
>attachObject(ground);
ground->setMaterialName("Examples/BeachStones");
- Also we would like to have some light in the scene; add one directional light:
Ogre::Light* light = _sceneManager->createLight("Light1");
light->setType(Ogre::Light::LT_DIRECTIONAL);
light->setDirection(Ogre::Vector3(1,-1,0));
- And some shadows would be nice:
_sceneManager->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_
ADDITIVE);
- Compile and run the application. You should see a plane with a stone texture and on top the Sinbad instance throwing a shadow on the plane.
What just happened?
Again, we used our previously gained knowledge to create a plane, light, and add shadows to the scene.
Adding user control
We have our model instance on a plane, but we can't move it yet; let's change this now.
Time for action – controlling the model with the arrow keys
Now we are going to add interactivity to the scene by adding the user control to the movements of the model.
- The FrameListener needs two new members: one pointer to the node we want to move, and one float indicating the movement speed:
float _WalkingSpeed;
Ogre::SceneNode* _node;
- The pointer to the node is passed to us in the constructor:
MyFrameListener(Ogre::RenderWindow* win,Ogre::Camera*
cam,Ogre::Viewport* viewport,Ogre::SceneNode* node)
- Assign the node pointer to the member variable and set the walking speed to 50:
_WalkingSpeed = 50.0f;
_node = node;
- In the frameStarted function we need two new variables, which will hold the rotation and the translation the user wants to apply to the node:
Ogre::Vector3 SinbadTranslate(0,0,0);
float _rotation = 0.0f;
- Then we need code to calculate the translation and rotation depending on which arrow key the user has pressed:
if(_Keyboard->isKeyDown(OIS::KC_UP))
{
SinbadTranslate += Ogre::Vector3(0,0,-1);
_rotation = 3.14f;
}
if(_Keyboard->isKeyDown(OIS::KC_DOWN))
{
SinbadTranslate += Ogre::Vector3(0,0,1);
_rotation = 0.0f;
}
if(_Keyboard->isKeyDown(OIS::KC_LEFT))
{
SinbadTranslate += Ogre::Vector3(-1,0,0);
_rotation = -1.57f;
}
if(_Keyboard->isKeyDown(OIS::KC_RIGHT))
{
SinbadTranslate += Ogre::Vector3(1,0,0);
_rotation = 1.57f;
}
- Then we need to apply the translation and rotation to the node:
_node->translate(SinbadTranslate * evt.timeSinceLastFrame * _
WalkingSpeed);
_node->resetOrientation();
_node->yaw(Ogre::Radian(_rotation));
- The application itself also needs to store the node pointer of the entity we want to control:
Ogre::SceneNode* _SinbadNode;
- The FrameListener instantiation needs this pointer:
_listener = new MyFrameListener(window,camera,viewport,_
SinbadNode);
- And the createScene function needs to use this pointer to create and store the node of the entity we want to move; modify the code in the function accordingly:
_SinbadNode = _sceneManager->getRootSceneNode()-
>createChildSceneNode();
_SinbadNode->attachObject(sinbadEnt);
- Compile and run the application. You should be able to move the entity with the arrow keys:
What just happened?
We added entity movement using the arrow keys in the FrameListener. Now our entity floats over the plane like a wizard.
Adding animation
Floating isn't exactly what we wanted; let's add some animation.
Time for action – adding animation
Our model can move but it isn't animated yet, let's change this.
- The FrameListener needs two animation states:
Ogre::AnimationState* _aniState;
Ogre::AnimationState* _aniStateTop;
- To get the animation states in the constructor, we need a pointer to the entity:
MyFrameListener(Ogre::RenderWindow* win,Ogre::Camera*
cam,Ogre::Viewport* viewport,Ogre::SceneNode* node,Ogre::Entity*
ent)
- With this pointer we can retrieve the AnimationState and save them for later use:
_aniState = ent->getAnimationState("RunBase");
_aniState->setLoop(false);
_aniStateTop = ent->getAnimationState(«RunTop»);
_aniStateTop->setLoop(false);
- Now that we have the AnimationState, we need to have a flag in the frameStarted function, which tells us whether or not the entity walked this frame. We add this flag into the if conditions that query the keyboard state:
bool walked = false;
if(_Keyboard->isKeyDown(OIS::KC_UP))
{
SinbadTranslate += Ogre::Vector3(0,0,-1);
_rotation = 3.14f;
walked = true;
}
if(_Keyboard->isKeyDown(OIS::KC_DOWN))
{
SinbadTranslate += Ogre::Vector3(0,0,1);
_rotation = 0.0f;
walked = true;
}
if(_Keyboard->isKeyDown(OIS::KC_LEFT))
{
SinbadTranslate += Ogre::Vector3(-1,0,0);
_rotation = -1.57f;
walked = true;
}
if(_Keyboard->isKeyDown(OIS::KC_RIGHT))
{
SinbadTranslate += Ogre::Vector3(1,0,0);
_rotation = 1.57f;
walked = true;
}
- If the model moves, we enable the animation; if the animation has ended, we loop it:
if(walked)
{
_aniState->setEnabled(true);
_aniStateTop->setEnabled(true);
if(_aniState->hasEnded())
{
_aniState->setTimePosition(0.0f);
}
if(_aniStateTop->hasEnded())
{
_aniStateTop->setTimePosition(0.0f);
}
}
- If the model didn't move, we disable the animation and set it to the start position:
else
{
_aniState->setTimePosition(0.0f);
_aniState->setEnabled(false);
_aniStateTop->setTimePosition(0.0f);
_aniStateTop->setEnabled(false);
}
- In each frame, we need to add the passed time to the animation; otherwise, it wouldn't move:
_aniState->addTime(evt.timeSinceLastFrame);
_aniStateTop->addTime(evt.timeSinceLastFrame);
- The application now also needs a pointer to the entity:
Ogre::Entity* _SinbadEnt;
- We use this pointer while instantiating the FrameListener:
_listener = new MyFrameListener(window,camera,viewport,_
SinbadNode,_SinbadEnt);
- And, of course, while creating the entity:
_SinbadEnt = _sceneManager->createEntity("Sinbad.mesh");
- Compile and run the application. Now the model should be animated when it moves:
What just happened?
We added animation to our model, which is only enabled when the model is moved.
Summary
In this article we learned:
- Adding input
- Our own main loop
- Adding a camera
- Adding compositors
- Adding a plane
- Adding user control
- Adding animation
Further resources on this subject:
- | https://www.packtpub.com/books/content/ogre-3d-double-buffering | CC-MAIN-2015-48 | en | refinedweb |
[
]
Alexey A. Ivanov commented on HARMONY-2666:
-------------------------------------------
Sergey, Alexey,
Of course, this is the problem! But not throwing NPE courses much less harm than throwing
NPE when an application want to use L&F decorations. Does it make sense?
To avoid NPE with L&F decoration the code should be re-designed -- it's not a easy thing.
Harmony implementation shares implementation of BasicInternalFrame (which is child frames)
on the main frame. Obviously it's good to share the code. But BasicInternalFrame can't configure
itself correctly if null is passed to its constructor -- this is the case where main frame
(i.e. of JFrame) decorations are initialized.
> [classlib][swing] javax.swing.plaf.metal.BasicInternalFrameTitlePane(null) doesn't throw
unspecified NPE while RI does
> ----------------------------------------------------------------------------------------------------------------------
>
> Key: HARMONY-2666
> URL:
> Project: Harmony
> Issue Type: Bug
> Components: Classlib
> Reporter: Alexander Simbirtsev
> Assigned To: Mark Hindess
> Priority: Minor
> Attachments: Harmony-2666-BasicInternalFrameTitlePane.patch, Harmony-2666-BasicInternalFrameTitlePaneTest.patch
>
>
> There is no mention of any exception in the specification.
> Harmony does not throw unspecified NPE for MetalInternalFrameTitlePane(null)
> while RI does.
> Use the following code to reproduce:
> import javax.swing.JInternalFrame;
> import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
> import junit.framework.TestCase;
> public class Test extends TestCase {
> public static void main(String[] args) {
> try {
> new BasicInternalFrameTitlePane((JInternalFrame) null);
> } catch (Exception e) {
> e.printStackTrace();
> }
> }
> }
> Inconsistency is that in Harmony's implementation of this constructor
> installTitlePane() is not called when null parameter is passed in
--
This message is automatically generated by JIRA.
-
You can reply to this email to add a comment to the issue online. | http://mail-archives.apache.org/mod_mbox/harmony-commits/200702.mbox/%3C17497372.1171875965887.JavaMail.jira@brutus%3E | CC-MAIN-2015-48 | en | refinedweb |
Corporate valuation is the process of evaluating business economic value. However the business valuation is utilized in the determination of fair value of the business for a diversity of reasons inclusive of sale value, partner’s ownership and divorce proceedings. However the value of business indicates the present value that which can be generated by the firm closure. Though the business runs on the going concern concept, periodically the business would be valued to know the liquidity of the business.
(a) The two major types of assets that which the companies tend to own are: assets-in-place and financial assets, which otherwise are also called as non-operating assets.
(b) Assets-in-place are the tangible assets like buildings, inventory, and machines. Generally they are anticipated to grow by generating the free cash flows. Their value is nothing but the operational worth; this can be ascertained by discounting their PV of future free cash flows at the weighted average capital cost (WACC).
(c) Non-operating assets includes the assets which could not generate the value through operations such as marketable securities; however ownership of non-controlling interest in another firm is also recognized to be as non-operating assets. Hence the worth of the non-operating assets in general would be near to the numerical that which are reported in balance sheets.
(d) Total value of corporation is the summarized value from operations, non-operating assets and growth options. Thus the value of a corporation can first be claimed by debt holders, then by the preferred stock holders, and finally anything left over by the common stock holders.
(e)
(1) The value from operations can be found with the help of following equation.
With the substitution of given values in the above equation we get the value of operations as,
(2) The total corporate value is the sum of value of operations and can be found with the help of following equation.
With the substitution of given values in the above formula we get the total corporate value as,
(3) The intrinsic value of equity is total value of firm exclusive of preference and debt values. This can be found with the help of following equation.
With the substitution of given and evaluated values in the above formula we get the intrinsic value of equity as,
(4) The intrinsic stock price per share can be ascertained by dividing the value of equity by the number of marketable shares outstanding. Thus the intrinsic stock price per share is,
(5) Market value of assets (MVA) is the redeemable or purchase value for the assets at times. However MVA is found with the application of following equation.
Hence by combining both the above equations we get the MVA as,
(f)
(1) The value of horizon is the value of operations at the end of 3 year before to the 6% growth. Thus the horizon value and operation value in this instance would be,
Therefore, the Company’s horizon value is
.
Now we will be evaluating the value of operation at initial stage, which is the PV of free cash flows, would be as follows.
(2) The intrinsic value of the equity as well as the price per share is found with the help of following equations.
With the substitution of given values in the above formulas we get the intrinsic value of equity and price per share as,
Therefore, the intrinsic value of equity on a price-per-share
basis is
.
(g) Value Based Management is the application that which ensures the systematic application of corporate valuation models pertaining to all the corporate decisions as well as strategic initiatives. The key objective of the value based management system is to increase the market value that is an added MVA.
(h) Usually the MVA is determined by the four drivers which are sales growth, operating profitability which is measured by dividing NOPAT with SALES, weighted average cost of capital, and Capital requirements this can be ascertained by dividing the operating capital with sales.
In the instances when MVA is improved WACC reduces, operating profitability increases and capital requirement decreases.
(i) EROIC is the anticipated return on the capital that which is in the place at the start of the period. In general the EROIC would be measured with the following equation.
With a spread in between the anticipated return (EROIC) and WACC, the required return would be positive; resulting to positive MVA and automatically the growth makes this MVA larger. In the instance if the spread is negative, then the opposite fact would become true.
(j) The general formula to evaluate the MVA at any time is,
With the substitution of given values in the above formula we get the MVA at different instances as shown in the following table.
(k) The following table shows the evaluation of EROIC and impact on MVA with different growth rates.
Here from the above table it was clear that EROIC of the ‘A’ is lesser than the WACC, thus the division must postpone its growth effects to the time till it improves its EROIC through an reduced requirements in capital and increased profitability. Similarly as the EROIC of ‘B’ is greater than the WACC, hence it can continue with its growth plans.
(l) The following are the six potential managerial behaviors that which could impact the firm’s value.
• Managers may afford a little time as well as effort.
• Managers may consume huge non-pecuniary benefits.
• Managers may avoid taking difficult decisions such as closure of plants out of the loyalty towards friends in the firm.
• Managers may tend to reject the projects with higher risk, though they could result in high NPVs on assumption to avoid the bad impact in the instance of project failure. At the same take up the risky negative NPV projects for a trial and hit a home run.
• Managers may avoid in returning of capital to the investors either by making the more and more investments in marketable securities or by paying more and more for the acquisitions.
• Managers also may make up the information releases or control earnings to avoid revealing of bad news.
(m) Corporate governance can be defined as the set of legal rules and procedures that which could impact the firm’s operations as well as the decisions that which are taken up by its managers.
However the following are the five provisions that which a firm could control internally.
• Monitoring as well as control by the board of directors.
• Deed provisions as well as the by-laws that which could impact the probability of the hostile takeovers.
• Choice of capital structures
• Compensate plans
• Control systems of accounting.
(n) The following are the features for the board of directors that in general result in effective corporate governance.
• The chief executive officer is the one who is the chairman of the board, also does not have the undue influence over the nominating committee.
• The board members has in major of outsiders, who also could bring a kind of business expertise’s into the board.
• The board size is not of too large.
• The members of the board are compensated aptly.
(o) The following are the three provisions that which could impact the corporate charter takeovers.
• Targeted repurchase of shares which otherwise would be called as green mail.
• Rights and provisions pertaining to shareholders which otherwise called as poison pills.
• Restriction in voting the right plans.
(p) It provides the right to the owner of the option in the purchase of stock share at a specified price which otherwise called as strike price, even though the stock price actually is higher. In general could not exercise the options for many of years which is called as vesting period. Also could not exercise the options even after a certain number of years, this otherwise is also called as expiration date or maturity date.
(q) Block ownership concept arises only when the outside investors is having a large value portion of investments in the firm shares, this is otherwise is also known as block of ownership. Block owners frequently monitors managers as well as takes up an active role in resulting to good corporate governance. Great institutional investors usually own a large blocks of ownership in the firms.
(r) Companies that which are established in countries that which provides strong protection for the investors, be likely to have a enhanced access towards the financial markets, less equity cost, increase of liquidity in markets, less fluctuations in stock prices. | http://www.chegg.com/homework-help/financial-management-13th-edition-chapter-13-solutions-9781111788780 | CC-MAIN-2015-48 | en | refinedweb |
Source
cpython_sandbox / Doc / library / collections.rst
:mod:`collections` --- High-performance container datatypes
Source code: :source:`Lib/collections.py` and :source:`Lib/_abcoll.py`
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, :class:`dict`, :class:`list`, :class:`set`, and :class:`tuple`.
In addition to the concrete container classes, the collections module provides :ref:`abstract base classes <collections-abstract-base-classes>` that can be used to test whether a class provides a particular interface, for example, whether it is hashable or a mapping.
:class:`Counter` objects :class:`Counter` is a :class:`dict` subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The :class: :exc:
Counter objects support three methods beyond those available for all dictionaries:
The usual dictionary methods are available for :class:`Counter` objects except for two which work differently for counters.
Common patterns for working with :class: :class:.
- The :class:`Counter` class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.
- The :meth:`most_common` method requires only that the values be orderable.
- For in-place operations such as c[key] += 1, the value type need only support addition and subtraction. So fractions, floats, and decimals would work and negative values are supported. The same is also true for :meth:`update` and :meth:`subtract` which allow negative and zero values for both inputs and outputs.
- The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.
- The :meth:`elements` method requires integer counts. It ignores zero and negative counts.
:class:`deque` objects
Returns a new deque object initialized left-to-right (using :meth: :class::
Deque objects also provide one read-only attribute:
In addition to the above, deques support iteration, pickling, len(d), reversed(d), copy.copy(d), copy.deepcopy(d), membership testing with the :keyword:`in` operator, and subscript references such as d[-1]. Indexed access is O(1) at both ends but slows to O(n) in the middle. For fast random access, use lists instead.
Example:
:class:`deque` Recipes :meth:`rotate` method provides a way to implement :class:`deque` slicing and deletion. For example, a pure Python implementation of del d[n] relies on the :meth:`rotate` method to position elements to be popped:
def delete_nth(d, n): d.rotate(-n) d.popleft() d.rotate(n)
To implement :class:`deque` slicing, use a similar approach applying :meth:`rotate` to bring a target element to the left side of the deque. Remove old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then reverse the rotation. With minor variations on that approach, it is easy to implement Forth style stack manipulations such as dup, drop, swap, over, pick, rot, and roll.
:class:`defaultdict` objects
:class:`defaultdict` Examples
Using :class:`list` as the :attr: :attr:`default_factory` function which returns an empty :class:`list`. The :meth:`list.append` operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the :meth:`list.append` operation adds another value to the list. This technique is simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
>>> d = {} >>> for k, v in s: ... d.setdefault(k, []).append(v) ... >>> d.items() [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
Setting the :attr:`default_factory` to :class:`int` makes the :class: :attr:`default_factory` function calls :func:`int` to supply a default count of zero. The increment operation then builds up the count for each letter.
The function :func:`int` which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use :func: :attr:`default_factory` to :class:`set` makes the :class:`defaultdict` useful for building a dictionary of sets:
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)] >>> d = defaultdict(set) >>> for k, v in s: ... d[k].add(v) ... >>> d.items() [('blue', set([2, 4])), ('red', set([1, 3]))]
:func:`namedtuple` Factory Function for Tuples with Named Fields
Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.
Example:
Named tuples are especially useful for assigning field names to result tuples returned by the :mod:`csv` or :mod:.
To retrieve a field whose name is stored in a string, use the :func:`getattr` function:
>>> getattr(p, 'x') 11
To convert a dictionary to a named tuple, use the double-star-operator (as described in :ref:`tut-unpacking-arguments`):
>>> :attr:`_fields` attribute:
>>> Point3D = namedtuple('Point3D', Point._fields + ('z',))
Default values can be implemented by using :meth:`)
:class:`OrderedDict` objects
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
Return an instance of a dict subclass, supporting the usual :class:`dict` methods. An OrderedDict is a dict that remembers the order that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
In addition to the usual mapping methods, ordered dictionaries also support reverse iteration using :func:`reversed`.
Equality tests between :class:`OrderedDict` objects are order-sensitive and are implemented as list(od1.items())==list(od2.items()). Equality tests between :class:`OrderedDict` objects and other :class:`Mapping` objects are order-insensitive like regular dictionaries. This allows :class:`OrderedDict` objects to be substituted anywhere a regular dictionary is used.
The :class:`OrderedDict` constructor and :meth:`update` method both accept keyword arguments, but their order is lost because Python's function call semantics pass-in keyword arguments using a regular unordered dictionary.
:class:`OrderedDict` Examples and Recipes :class:`Counter` class so that the counter remembers the order elements are first encountered:
class OrderedCounter(Counter, OrderedDict): 'Counter that remembers the order elements are first encountered' def __repr__(self): return '%s(%r)' % (self.__class__.__name__, OrderedDict(self)) def __reduce__(self): return self.__class__, (OrderedDict(self),)
Collections Abstract Base Classes
The collections module offers the following :term:`ABCs <abstract base class>`:
ABCs for classes that provide respectively the methods :meth:`__contains__`, :meth:`__hash__`, :meth:`__len__`, and :meth:`__call__`.
ABC for classes that provide the :meth:`__iter__` method. See also the definition of :term:`iterable`.
ABC for classes that provide the :meth:`__iter__` and :meth:`next` methods. See also the definition of :term:`iterator`.
ABCs for read-only and mutable :term:`sequences <sequence>`.
ABCs for read-only and mutable sets.
ABCs for read-only and mutable :term:`mappings <mapping>`.
ABCs for mapping, items, keys, and values :term:`views <view>`. :class:`Set` API, it only necessary to supply the three underlying abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`. The ABC supplies the remaining methods such as :meth:`__and__` and :meth: :class:`Set` and :class:`MutableSet` as a mixin:
- Since some set operations create new sets, the default mixin methods need a way to create new instances from an iterable. The class constructor is assumed to have a signature in the form ClassName(iterable). That assumption is factored-out to an internal classmethod called :meth:`_from_iterable` which calls cls(iterable) to produce a new set. If the :class:`Set` mixin is being used in a class with a different constructor signature, you will need to override :meth:`_from_iterable` with a classmethod that can construct new instances from an iterable argument.
- To override the comparisons (presumably for speed, as the semantics are fixed), redefine :meth:`__le__` and then the other operations will automatically follow suit.
- The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value for the set; however, :meth:`__hash__` is not defined because not all sets are hashable or immutable. To add set hashabilty using mixins, inherit from both :meth:`Set` and :meth:`Hashable`, then define __hash__ = Set._hash. | https://bitbucket.org/ncoghlan/cpython_sandbox/src/687295c6c8f2/Doc/library/collections.rst | CC-MAIN-2015-48 | en | refinedweb |
(WinXP, Borland C++ Free Command Line Compiler)
Ok, I made a short console game, you can move a dot around the screen. But, my barriers only work for up & down, left and right dont work for some odd reason. I have looked all around my code, and I tried swapping their values, but I dont understand why the barriers dont work, its just a simple if() function...
Well heres my code, its actualy pritty short:
Code:#include <windows.h> #include <iostream> #include <conio.h> using namespace std; enum { ESC_KEY = 27, UP_ARROW = 256+72, DOWN_ARROW = 256+80, LEFT_ARROW = 256+75, RIGHT_ARROW = 256+77 }; int get_arrow(); HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE ); WORD Color; CONSOLE_SCREEN_BUFFER_INFO inf; CONSOLE_CURSOR_INFO Cur; int main() { COORD Pos; COORD Pos2; int Counter; int c2; int buffer; int grid_x; int grid_y; clrscr(); GetConsoleScreenBufferInfo(h, &inf); Color = inf.wAttributes; Cur.bVisible = FALSE; Cur.dwSize = 1; SetConsoleTextAttribute(h, BACKGROUND_RED | BACKGROUND_INTENSITY); SetConsoleCursorInfo(h, &Cur); SetConsoleTitle("Hi"); for(Counter=0; Counter < 80; Counter++) for(c2=0; c2 < 25; c2++) { Pos.X = Counter; Pos.Y = c2; SetConsoleCursorPosition(h, Pos); if(Counter == 10 && c2 == 13) cout << "*" << endl; else cout << " " << endl; } Pos2.X = 0; Pos2.Y = 0; SetConsoleCursorPosition(h, Pos2); grid_x = 10; grid_y = 13; for(;;) { buffer = get_arrow(); if(buffer == ESC_KEY) { clrscr(); SetConsoleTextAttribute(h, Color); exit(0); } if(buffer == DOWN_ARROW) if(grid_y == 23) cout << ""; else grid_y++; if(buffer == UP_ARROW) if(grid_y == 1) cout << ""; else grid_y--; if(buffer == LEFT_ARROW) if(grid_y == 80) cout << ""; else grid_x--; if(buffer == RIGHT_ARROW) if(grid_y == 1) cout << ""; else grid_x++; for(Counter=0; Counter < 80; Counter++) for(c2=0; c2 < 25; c2++) { Pos.X = Counter; Pos.Y = c2; SetConsoleCursorPosition(h, Pos); if(Counter == grid_x && c2 == grid_y) cout << "*" << endl; else cout << " " << endl; SetConsoleCursorPosition(h, Pos2); } } } int get_arrow() { int ch = getch(); if(ch == 0 || ch == 224) ch = 256 + getch(); return ch; }
I'm guessing I messed up somewhere simple, but I just cant find my problem.... I have looked at this four three hours, but I'm not getting anywhere, no matter what value I give it, it just lets me bring it off the screen... Any ideas?
Thank you very much in advanced! | http://cboard.cprogramming.com/cplusplus-programming/74247-weird-console-game-logic-error.html | CC-MAIN-2015-48 | en | refinedweb |
I made some additional changes to the Spring BlazeDS Integration (RC1) Test Drive:
- The Test Drive now includes an annotation-based configuration sample (the Company Manager sample). Spring annotations such as @Service, @RemotingDestination, @Autowired, @RemotingInclude, and @RemotingExclude make it really easy to configure your beans and make them available through Remoting. As an example, here is the source code for the CompanyDAO class:
package flex.spring.samples.company; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sql.DataSource; import org.springframework.flex.remoting.RemotingDestination; import org.springframework.flex.remoting.RemotingExclude; import org.springframework.flex.remoting.RemotingInclude; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import flex.spring.samples.industry.IIndustryDAO; @Service("companyService") @RemotingDestination(channels={"my-amf"}) public class CompanyDAO implements ICompanyDAO { private final SimpleJdbcTemplate template; private final SimpleJdbcInsert insertCompany; private IIndustryDAO industryDAO; private final ParameterizedRowMapper<Company> rowMapper = new ParameterizedRowMapper<Company>(){ public Company mapRow(ResultSet rs, int rowNum) throws SQLException { Company company = new Company(); company.setId(rs.getInt("id")); company.setName(rs.getString("name")); company.setAddress(rs.getString("address")); company.setCity(rs.getString("city")); company.setState(rs.getString("state")); company.setZip(rs.getString("zip")); company.setPhone(rs.getString("phone")); company.setIndustry(industryDAO.findById(rs.getInt("industry_id"))); return company; } }; @Autowired public CompanyDAO(DataSource dataSource, IIndustryDAO industryDAO) { template = new SimpleJdbcTemplate(dataSource); insertCompany = new SimpleJdbcInsert(dataSource).withTableName("COMPANY").usingGeneratedKeyColumns("ID"); this.industryDAO = industryDAO; } @RemotingInclude public Company findById(int id) { return template.queryForObject("SELECT * FROM company WHERE id=?", rowMapper, id); } @RemotingInclude public List<Company> findAll() { return template.query("SELECT * FROM company ORDER BY name", rowMapper); } @RemotingInclude public List<Company> findByName(String name) { return template.query("SELECT * FROM company WHERE UPPER(name) LIKE ? ORDER BY name", rowMapper, "%" + name.toUpperCase() + "%"); } @RemotingInclude public Company create(Company company) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("name", company.getName()); parameters.put("address", company.getAddress()); parameters.put("city", company.getCity()); parameters.put("state", company.getState()); parameters.put("zip", company.getZip()); parameters.put("phone", company.getPhone()); parameters.put("industry_id", company.getIndustry().getId()); Number id = insertCompany.executeAndReturnKey(parameters); company.setId(id.intValue()); return company; } @RemotingInclude public boolean update(Company company) { int count = template.update("UPDATE company SET name=?, address=?, city=?, state=?, zip=?, phone=?, industry_id=? WHERE id=?", company.getName(), company.getAddress(), company.getCity(), company.getState(), company.getZip(), company.getPhone(), company.getIndustry().getId(), company.getId()); return (count == 1); } @RemotingExclude public boolean remove(Company company) { int count = template.update("DELETE FROM company WHERE id=?", company.getId()); return (count == 1); } }
- The Test Drive is now using the M3 build of Spring 3 (as opposed to M2 in the previous builds of the Test Drive).
- I modified the configuration of the long polling channel to support more persistent connections per domain based on the browser capabilities.
- And of course compared to the M2 build, this version of the Test Drive includes a number of Messaging samples.
Using the Messaging integration, setting up a destination can be as easy as:
<flex:message-destination
And here is how you configure a destination mapped to a JMS topic:
<flex:jms-message-destination
Installation Instructions:
- Download the Spring / Flex TestDrive here:
- Unzip it in your root directory
- Navigate to /spring-flex-testdrive/tomcat/bin and start Tomcat (for instance: catalina run)
- Open a browser and access
- Follow the instructions
Amazing. Thank you, Christophe for making my life easier. You’re doing some amazing work! Keep it up!
Hi, the examples work fine but it would be wonderful if you include in the archive the project’s build scripts (ant or maven) beside the source files. I am unable to find on the web an official post about how Java and Flex 3 projects should be build using maven/ant. I’m trying for about a week now to create a deployment script and still didn’t find the best way to do it, especially what maven plugins to use… It would be great to have such an example. Thanks in advance !
Hi,
It is a fantastic work. I would like to know some information related to search box, Currently I think the pop-up list position is like list.move(point.x – 30, point.y + 24);
but if I wanted to reuse this search box in many screens , where the box can be at various position, the pop up appears in different location, instead I always wanted to have it like a drop down. Can you please help on how to fix this.(since I am a java programmer and new to flex, please help, as we are planning to start a new project with spring blazeDS)
Hi Christophe, thank you, great work!
Hi, very nice,
The problem for me, and creating an environment to test. I purchased Flex Builder 3 but I do not understand how to set up for Spring-Hibernate-Mysql
help me.
Tanks.
Claudio Italy
Hi,
I am trying to upgrade my existing HelloWorld Blazeds Integration web application to 1.0.0.RC1 Release. I just annoted my Service class with @Service(“helloWorldService”) ,@RemotingDestination(channels={“my-amf”})
and method with @RemotingInclude.
I removed the bean declaration and flex:remote-service tag from web-application-config.xml. Although flex:message-broker tag still there.
With these changes in place, I am expecting the application to work, but it just deploys successfully. When tried to invoke method from flex client, nothing happens.
Am I missing something? Please help.
Cheers,
Rahul
Thanks for sharing this Christophe !
I’m glad that SpringSource finally released that annotation mechanism, that we had for long in our flex-spring-contrib lib.
cf.
Would you Christophe if they plan on adding springsecurity/blazeds_channel_security integration annotations as well ?
Hi Christophe,
I would appreciate if you can provide some details regarding “using my-secure-amf”.
Thanks in advance!
Excellent Job!
Particularly on Spring Security and JMS Integrations. Great Updates…
Thanks for sharing Christophe and Jeremy.
Is there official support for Glassfish instead of Tomcat?
Hi Christophe,
Could you also supply a working testdrive that runs on the new Springsource dm server.
Thank you in advance
Christophe,
Excellent work !
Couple of things:
1) it would be very beneficial to everybody if there is a good documentation on these samples, e.g. describing steps to configure it in Tomcat and Flex/FlashBuilder;
2) Spring-to-Flex integration API documentation ?
3) Can you provide Flex4 version of samples? Any limitations/problems to make it work with Flex4 ?
4) Can it work with Spring2.x and earlier versions of BlazeDS & LCDS ?
Thank you,
Oleg.
Christophe,
When are you planning to release 1.0 GA testdrive.
I got latest one from SpringSource and started playing with it.
I have imported 1.0 GA testdrive source code into FlexBuilder3 and trying to run on Tomcat6 which came up with testdrive M2
(on Christophe Coenraets’ site).
I did create another app context (feedstarter1 and traderdesktop1), so it should not interfere with existing M2 ones.
Have not changed anything in the code or testdrive config.
It compiles and shows on the page fine, but as soon as I start a Market Feed, getting exception:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at traderdesktop/messageHandler()[C:\Documents and Settings\Oleg\workspace\TraderDesktop\src\traderdesktop.mxml:95]:251]]
line 95 of
94: var changedStock:Stock = event.message.body as Stock;
95: var stock:Stock = stockMap[changedStock.symbol];
What am I missing ?
Please help !
TIA,
Oleg.
Christophe,
It would be great if you can implement a Flex client from the real JMS like ActiveMQ using JMSadapter, e.g. the same TraderDesktop.
Similar JMS chat with ActiveMQ & BlazeDS:
Thank you,
Oleg.
I gort some error for using this update
the Spring BlazeDS Integration Test Drive
Let me download and try again
Thanks
Hi Christophe,
On the Flex side, I see you have commented the streaming-amf channel from any ChannelSet. Is there any reason for this? cause I can’t make a message destination based on this channel to work :/
Longpolling, polling, etc seem to work fine but streaming-amf channel is not working. Im using latest spring-for-blazeds jar, etc.
Any ideas?
Thank you in advance.
A.
Hi, I´m very new to java but I know flex.
Do you know a tutorial to create a new project from scratch in eclipse. like a best practices for new projects ?
Thank you very much !! … test drive is very useful.
thank you man
model ve mankenlik ajansı
fotoğraf çekimleri
program yükle Good admin than you
Christophe,
Thanks for all your hard work. It has not only taught me a LOT, but has helped me tremendously!
Thanks!
– Derrick
version tomcat 6.18???? o not
I couldn’t get it to run.
I’m trying for about a week now to create a deployment script and still didn’t find the best way to do it, especially what maven plugins to use… It would be great to have such an example. Thanks in advance !
Great coding! It’s great that you have included the codes and examples for us readers to follow.
Not Found
The requested URL /downloads/spring-flex-testdrive-RC1v2.zip was not found on this server.
Apache/2.2.21 (Amazon) Server at coenraets.org Port 80
Can someone please upload the file again?
Seems this is the new version: | http://coenraets.org/blog/2009/05/new-update-to-the-spring-blazeds-integration-test-drive/ | CC-MAIN-2015-48 | en | refinedweb |
Hi everyone ,
By all the information that i could find in msdn, it seems that objects in the package Microsoft.Office.Tools.Word, e.g. the Content Control types, must either be added at design (compile) time within Visual Studio in a Document project type , or added
at run time.
Is there any way that i could simply add the content controls using the "Develop" tab in Office Word , and then find the object as a ContentControl, or even something like a PiectureContentControl?
And my final goal is to find the Picture Content Controls in the Word document and update the image of the control.
Thanks a lot!
Answer 1
Hi ramboisyuanbo
Yes, the Word "interop", used in an Add-in, can work with content controls that already exist in a document. The object model provides the Document.SelectContentControlsByTitle and Document.SelectContentControlsByTag methods. Both return a collection
of content controls having the same title resp. tag.
Word also assigns each content control an ID value (read-only). You can pick up a specific content control using that as the Index value.
You can also get a content control from a range if, for example, you've applied a bookmark to it.
Answer 2
Hi Cindy,
Thanks a lot for your answer!
I've also find that i can "add" an temporary ContentControl "based" on an interop content control, which seems to work like an wrapper around the interop content control. Is my understanding right?
But still there's an weird issue here. This is my code snippet:
Microsoft.Office.Interop.Word.Document doc =
Globals.ThisAddIn.Application.ActiveDocument;
Microsoft.Office.Tools.Word.Document vstoDoc = Globals.Factory.GetVstoObject(Globals.ThisAddIn.Application.ActiveDocument);
int index = 1;
foreach (Microsoft.Office.Interop.Word.ContentControl nativeControl in doc.ContentControls)
{
if (nativeControl.Type ==
Microsoft.Office.Interop.Word.WdContentControlType.wdContentControlPicture)
{
Microsoft.Office.Tools.Word.PictureContentControl tempControl =
vstoDoc.Controls.AddPictureContentControl(nativeControl,
"VSTORichTextControl" + (index++).ToString());
//Image image = Clipboard.GetImage();
Image image = new System.Drawing.Bitmap("d:/a.bmp", true);
tempControl.Image = image;
System.Windows.Forms.MessageBox.Show(tempControl.Image.Size.ToString());
}
}
This code works well, i can see the picture content control's image is successfully set.:
Many thanks Cindy!
Answer 3
<<I've also find that i can "add" an temporary ContentControl "based" on an interop content control, which seems to work like an wrapper around the interop content control. Is my understanding right?>>
Yes.
<:
System.Windows.Forms.MessageBox.Show(tempControl.Image.Size.ToString());>>
Two things to test
1. Does it work if you do the paste as an end-user into the control?
2. If the image is pasted into a "plain" part of the document (not a content control) from your code, is it then visible?
Answer 4
Answer 5
Dear Amy and Cindy,
It works if i paste as an end user.
After i went through the code step by step, it seems i always get null from Clipboard.GetImage();
My current solution is like this, where contentControl is the picture control.
contentControl.Range.Select();
contentControl.Range.Paste();
I was creating a .net 3.5 project in VS 2010 for word 2010. When I tried to use Globals.ThisAddIn.Application.ActiveDocument.GetVstoObject(), I need to "using Microsoft.Office.Tools.Word.Extensions;". But I got the following error. I added
the reference "Microsoft.Office.Tools.Word.v9.0".
VS2008 SP1 will not throw such error. But VS 2010 does, Anyone know how to solve it? Thanks!
Error 1 The type or namespace name 'Extensions' does not exist in the namespace 'Microsoft.Office.Tools.Word' (are you missing an assembly reference?)
Hello,
I have a office 2007 add in developed in Visual Studio 2010 targeting .Net Framework 3.5. The add in is deployed successfully on every machine I've tested that had office 2007 installed through the Publish feature of VS. Now, installing on machines
that have office 2010 is not that straightforward; on all the system I've used the add in loads ok but on a XP SP3 machine the images are not loaded. Images are loaded by providing a handler to the "getImage" callback and from what I could debug
the method is never called..
Any suggestions why is this happening?
Hi,
i have need to be able to identify the Microsoft.Office.Interop.Word.Rane of objects found in my document using OpenXML. Can this be donr?
For instance, i have an addin that makes a copy of the currently open document, reads that temp copy to retrieve all the inlineshape sin the document and displays them in a listview to the user with attributes such as size and type. Now
depending on which image the user selects, i want to be able to identify it in the document they have open. Given that i generated the list from a temp copy of the document that was processed using the openxml sdk, how can i at the time i am processing
that temp document, also read at the very least the range start and end of each inline shape i read?
Thanks much
hi i have done an add reference, and added "Microsoft Word 11.0 Object Library" to my project reference.
It now appear 2 reference - Microsoft.Office.Core and Microsoft.Office.Interop.WOrd in my project reference.
But why i still failed to have this below written in my .cs file. Please advice.
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;.
Hi
I'm curious if there is a way of programmatically accessing office custom dicitonaries from an excel add-in VSTO project without having to additionally use Microsoft.Office.Interop.Word.Application type (to access CustomDictionaries property).
The issue is that there are customers which do not have Word installed but they'd like to be able to use their custom dictionaries with an excel add-in application.
Good).
Thanks to the folks at Office Watch for the heads-up on this product in their latest newsletter.
I need to extract word document into number of pages and convert those pages into images by using Microsoft.Office.Interop.Word, can anybody tell me how i can do this?
I get this error in the following line of my code:
_word = new Microsoft.Office.Interop.Word.Application();
Even though the exception is not caught i can see inside _word that an exception was thrown ...this exception makes my AddIn to not load anymore after Word is closed since i can see the registry key LoadBehavior = 2 ...any ideas? Tried to clean
the references and add them again but nothing, I am working on Word 2007 in a 64 bits Vista pc. Any help would be helpful
private void CreateNewDoc()
{
try
_word = new Microsoft.Office.Interop.Word.Application();
_word.Visible = false;
_doc = _word.Documents.Add(ref _missing, ref _missing,
ref _missing, ref _missing);
catch (COMException ex)
Log.WriteEntry("XPM", ex.StackTrace + " " + ex.Message, 3);
}.
Scenario 1) Using “Microsoft.Office.Server.Search.Query”
Code
using System;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using Microsoft.Office.Server.Search.Query;
string HelloWorld() {
return "Hello World";
}
Web.
<add assembly="Microsoft.Office.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/>
<add assembly="office, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/></assemblies>
Error
error CS0234: The type or namespace name 'Query' does not exist in the namespace 'Microsoft.Office.Server.Search' (are you missing an assembly reference?)
Scenario 2) “Microsoft.SharePoint.Search.Query”
using Microsoft.SharePoint.Search.Query;
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="Microsoft.SharePoint.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71E9BCE111E9429C"/>
error CS0234: The type or namespace name 'Query' does not exist in the namespace 'Microsoft.SharePoint.Search' (are you missing an assembly reference?).
I'm creating a VSTO on .NET 4.0 for Excel 2007. I choosed MSI as a setup preparation model. Setup was created successfully, but when I try to install it on a fresh machine I get this error :
<p>
Could not load file or assembly 'Microsoft.VisualStudio.Tools.Office.Runtime.v9.0, Version=9.0.0.0
</p>
How can eliminate the necessity in Microsoft.VisualStudio.Tools.Office.Runtime.v9.0 in my VSTO? It doesn't refer to it explicitly and no refs to VSTO30 are in "References" section.
Hi All,
I'm setting up CI builds for my projects, I found that few of the projects are using Microsoft Office Interactivity Tools and Third party software like ComponetArt.
I have added the assemblies of the above in a common folder and set the reference in the build and it is succeeded.
As I'm new to build engineering, I just wanted to know that whether we need to install the Software like componentArt and Interop Dlls in the build machine or just assemblies are enough to build ?
Also, Please let me know if there any best practices to be followed in the space of Build and Deployment.
Thanks in Advance.
Regards,
Jags
Hi,I tried to install VS 2010 RC Professional. It install everuthing, except the Microsoft Office Developer tools. Which is a bummer since this is precisely what I want to try (Developping for Office) I tried various thing (uninstalling, re-installing, etc..). I download the ISO file and use Virtual Clone Drive to open it.the last line of VSSWMSIFailInfo.txt isError 1316.A network error occurred while attempting to read from the file: C:\Windows\Installer\trin_odt12.msi (obvioulsy C:\Windows\Installer\ is not on a network)OS: Windows 7 Home PremiumOffice: 2003, 2007 and 2010 BetaThere is also the following lines:======================MSI CA LOG ENTRY INFO:======================
03/09/10 18:57:36 DDSet_Entry: ImmediateDispatch: DDSE_CA_Uninstall_InstallFinalizePre entry03/09/10 18:57:36 DDSet_Status: patch uninstall Directory = 'C:\Program Files\Common Files\Microsoft Shared\SE\trin_odt12_0_x86_net_10_0'03/09/10 18:57:36 DDSet_Status: LoadLibrary('C:\Program Files\Common Files\Microsoft Shared\SE\trin_odt12_0_x86_net_10_0\worker.dll')03/09/10 18:57:36 DDSet_Warning: Setup failed to load the DLL at 'C:\Program Files\Common Files\Microsoft Shared\SE\trin_odt12_0_x86_net_10_0\worker.dll'. System error: The specified module could not be found.03/09/10 18:57:36 DDSet_CARetVal: 003/09/10 18:57:36 DDSet_Exit: ImmediateDispatch: DDSE_CA_Uninstall_InstallFinalizePre exitAny idea ?Thanks Gérard Garreau
I have bee developing MS-Office-2007 AddIns by using "using Microsoft.Office.Tools.Excel.Extensions". This worked fine until recently. However, I got an error message when I re-built the Excel AddIn, "Microsoft.Office.Tools.Excel.Extensions is NOT exist."
My last compilation was in 2010/10. Am I doing anything wrong ?
Thanks
I installed Visual Studio 2010 Professional without the feature "Microsoft Office Development Tools". Now i need them for a project. I restart the Visual Studio Setup but i cant find an Option to install the feature "Microsoft Office Development Tools".
Is there a switch for the setup or a separate msi file that i can start?
Regards Paolo | http://go4answers.webhost4life.com/Example/microsoftofficetoolswordcontentcontr-111296.aspx | CC-MAIN-2015-48 | en | refinedweb |
Java I/O Buffered Streams
Java I/O Buffered Streams
In this section we will discuss the I/O Buffered Streams.
In Java programming when we are doing an input and output operation... a memory area called buffer. In the read operation input streams
read data
Classes and Interfaces of the I/O Streams
Classes and Interfaces of the I/O Streams
... then this
exception to be occured.
InterruptedIOException
When the I/O...
When the I/O operations to be failed then it occurs.
NotActiveException... to read the data's byte.int read() throws IOException
read(byte[]
of I/O Data Streams
Data streams are filtered streams that perform... will discuss the I/O Buffered Streams.
Java I/O Data Streams
In this tutorial we will discuss the Java I/O Data Streams.
Java I/O Object... use
a binary stream.
The working process of the I/O streams can...
What is Java I/O?
Java I/O
JAVA I/O
Introduction The Java Input/Output (I/O) is a part of java.io package. The
java.io package contains a relatively large number of classes... in the package which are used
for reading from and writing to byte streams, respectively... in two ways :
Using Standard Streams
And using Console
Standard Streams
Various of the Operating Systems have the feature of Standard Streams
i/o streamas
i/o streamas java program using bufferedreader and bufferedwriter
Hi Friend,
Try the following code:
import java.io.*;
class BufferedReaderAndBufferedWriter{
public static void main(String[] args) throws
Post your Comment | http://roseindia.net/discussion/22891-Overview-of-I/O-Data-Streams.html | CC-MAIN-2015-48 | en | refinedweb |
Mock v0.7.2 documentation
Here are some more examples for some slightly more advanced scenarios than in the getting started guide.
Mocking chained calls is actually straightforward with mock once you understand the Mock.Mock object at 0x...> >>>.
Here’s how we might do it in a slightly nicer way. We start by creating our initial mocks:
>>> something = Something() >>> mock_response = Mock(spec=file) >>> mock_backend = Mock() >>> get_endpoint = mock_backend.get_endpoint >>> create_call = get_endpoint.return_value.create_call >>> start_call = create_call.return_value.start_call >>> start_call.return_value = mock_response
With these we monkey patch the “mock backend” in place and can make the real call:
>>> something.backend = mock_backend >>> something.method()
Keeping references to the intermediate methods makes our assertions easier, and also makes the code less ugly.
>>> get_endpoint.assert_called_with('foobar') >>> create_call.assert_called_with('spam', 'eggs') >>> start_call.assert_called_with() >>> # make assertions on mock_response about how it is used).
So first the topic of creating a mock object that can be called, with the return value able to act as a context manager. The easiest way of doing this is to use the new MagicMock, which is preconfigured to be able to act as a context manger. As an added bonus we’ll use the spec argument to ensure that the mocked object can only be used in the same ways a real file could be used (attempting to access a method or attribute not on the file will raise an AttributeError):
>>> mock_open = Mock() >>> mock_open.return_value = MagicMock(spec=file)
In terms of configuring our mock this is all that needs to be done. In fact it could be constructed with a one liner: mock_open = Mock(return_value=MagicMock(spec=file)).
So what is the best way of patching the builtin open function? One way would be to globally patch __builtin__.open. So long as you are sure that none of the other code being called also accesses open this is perfectly reasonable. It does make some people nervous however. By default we can’t patch the open name in the module where it is used, because open doesn’t exist as an attribute in that namespace. patch refuses to patch attributes that don’t exist because that is a great way of having tests that pass but code that is horribly broken (your code can access attributes that only exist during your tests!). patch will however create (and then remove again) non-existent attributes if you tell it that you are really sure you know what you’re doing.
By passing create=True into patch we can just patch the open function in the module under test instead of patching it globally:
>>> open_name = '%s.open' % __name__ >>> with patch(open_name, create=True) as mock_open: ... mock_open.return_value = MagicMock(spec=file) ... ... with open('/some/path', 'w') as f: ... f.write('something') ... <mock.Mock object at 0x...> >>> file_handle = mock_open.return_value.__enter__.return_value >>> file_handle.write.assert_called_with('something')() >>> generator = mock_foo.iter.return_value >>> iterator = iter([1, 2, 3]) >>> generator.__iter__.return_value = iterator >>> list(mock_foo.iter()) [1, 2, 3]
The above example is done step-by-step. The shorter version is:
>>> mock_foo = MagicMock() >>> mock_foo.iter.return_value._ mocksignature', mocksignature=True) as mock_foo: ... mock_foo.>> mock_foo.assert_called_once_with(foo)
If we don’t use mocksignature=True then the unbound method is patched out with a Mock instance instead, and isn’t called with self.
A few people have asked about mocking properties, specifically tracking when properties are fetched from objects or even having side effects when properties are fetched.
You can already do this by subclassing Mock and providing your own property. Delegating to another mock is one way to record the property being accessed whilst still able to control things like return values:
>>> mock_foo = Mock(>> mock_foo.assert_called_once_with()
This approach works fine if you can replace the whole object you’re mocking. If you just want to mock the property on another object here’s an alternative approach using the support for magic methods introduced in 0.7:
>>> class Foo(object): ... @property ... def fish(self): ... return 'fish' ... >>> with patch.object(Foo, 'fish') as mock_fish: ... mock_fish.__get__ = Mock(return_value='mocked fish') ... foo = Foo() ... print foo.fish ... mocked fish >>> mock_fish.__get__.assert_called_with(mock_fish, foo, Foo)
If you’re using an earlier version of mock, a third approach is to subclass Mock and provide a __get__ method that delegates back to the mock:
>>> class PropertyMock(Mock): ... def __get__(self, instance, owner): ... return self() ... >>> prop_mock = PropertyMock() >>> with patch.object(Foo, 'fish', prop_mock): ... foo = Foo() ... prop_mock.return_value = 'mocked fish' ... print foo.fish ... mocked fish >>> prop_mock.assert_called_with()
As you’re patching on the class these techniques affect all instances of Foo., the API is not quite so nice.
All of the calls, in order, are stored in call_args_list as tuples of (positional args, keyword args).
>>> mock = Mock(return_value=None) >>> mock(1, 2, 3) >>> mock(4, 5, 6) >>> mock() >>> mock.call_args_list [((1, 2, 3), {}), ((4, 5, 6), {}), ((), {})]
Because it stores positional args and keyword args, even if they are empty, the list is overly verbose which makes for ugly tests. It turns out that I do this rarely enough that I’ve never got around to improving it. One of the new features in 0.7.0 helps with this. The tuples of (positional, keyword) arguments are now custom objects that allow for ‘soft comparisons’ (implemented by Konrad Delong). This allows you to omit empty positional or keyword arguments from tuples you compare against.
>>> mock.call_args_list [((1, 2, 3), {}), ((4, 5, 6), {}), ((), {})] >>> expected = [((1, 2, 3),), ((4, 5, 6),), ()] >>> mock.call_args_list == expected True
This is an improvement, but still not as nice as assert_called_with. Here’s a helper function that pops the last argument of the call args list and decrements the call count. This allows you to make asserts as a series of calls to assert_called_with followed by a pop_last_call.
>>> def pop_last_call(mock): ... if not mock.call_count: ... raise AssertionError("Cannot pop last call: call_count is 0") ... mock.call_args_list.pop() ... try: ... mock.call_args = mock.call_args_list[-1] ... except IndexError: ... mock.call_args = None ... mock.called = False ... mock.call_count -=1 ... >>> mock = Mock(return_value=None) >>> mock(1, foo='bar') >>> mock(2, foo='baz') >>> mock(3, foo='spam') >>> mock.assert_called_with(3, foo='spam') >>> pop_last_call(mock) >>> mock.assert_called_with(2, foo='baz') >>> pop_last_call(mock) >>> mock.assert_called_once_with(1, foo='bar')
The calls to assert_called_with are made in reverse order to the actual calls. Your final call can be a call to assert_called_once_with, that ensures there were no extra calls you weren’t expecting. You could, if you wanted, extend the function to take args and kwargs and do the assert for you. Mock Mock [(('a',), {}), (('c',), {}), (('d',), {}), (('b',), {}), (('d',), {})] >>> mock.__setitem__.call_args_list [(('b', 'fish'), {}), (('d', 'eggs'), {})] >>> my_dict {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'}
If you have a mock object, particularly one created for you by patch, setting up attributes and return values for methods takes one line for every aspect of configuration..Mock object at 0x...> >>> mock.foo 3 >>> print mock.bar None
return_value and side_effect can be used to set them directly on the main mock anyway as they are just attributes.
>>> mock = Mock() >>> configure_mock(mock, side_effect=KeyError) <mock.Mock object at 0x...> >>> mock() Traceback (most recent call last): ... KeyError
This is fine for directly setting attributes, but what if you want to configure the return values or side effects of child mocks? How about using standard dotted notation to specify these. Instead of normal keyword arguments you’ll need to build a dictionary of arguments and pass them in with **. The function could also create a mock for us if we pass in None:
>>>
If you have any opinions on this then please comment on the issue.
A minimal implementation of configure_mock that you can start using now is:.Mock object at 0x...> >>> patch methods: start and stop, work around this by taking a reference to sys.modules inside the test rather than at import time. (Using patch.dict as a decorator takes a reference to sys.modules at import time, it doesn’t do the patching until the test is executed though.)
The Mock class allows you to track the order of method calls on your mock objects through the Mock:
>>> manager = Mock() >>> mock_foo = manager.foo >>> mock_bar = manager.bar >>> mock_foo.something() <mock.Mock object at 0x...> >>> mock_bar.other.thing() <mock.Mock object at 0x...> >>> manager.method_calls [('foo.something', (), {}), ('bar.other.thing', (), {})]
Using the “soft comparisons” feature of mock 0.7.0 we can make the final assertion about the expected calls less verbose:
>>> expected_calls = [('foo.something',), ('bar.other.thing',)] >>> manager.method_calls == expected_calls True
To make them even less verbose I would like to add a new call object to mock 0.8.0. You can see the issues I expect to work on for 0.8.0 in the issues list.
call would look...> >>> mock.bar.baz(a=3, b=6) <mock.Mock object at 0x...> >>>...> >>> mock_bar.other.thing() <mock.Mock object at 0x...> >>> manager.method_calls == [call.foo.something(), call.bar.other.thing()] True
Sometimes you may need to make assertions about some of the arguments in a call to mock, but either not care about some of the arguments or want to pull them individually out of Mock.call_args and make more complex assertions on them.
To ignore certain arguments you can pass in objects that compare equal to everything. Calls to Mock.assert_called_with() and Mock.assert_called_once_with() will then succeed no matter what was passed in.
Here’s an example implementation:
>>> class _ANY(object): ... def __eq__(self, other): ... return True ... >>> ANY = _ANY()
And an example of using it:
>>> mock = Mock(return_value=None) >>> mock('foo', bar=object()) >>> mock.assert_called_once_with('foo', bar=ANY)
Using the same basic concept as the ANY pattern above we can implement matchers to do more complex assertions on objects used as arguments to mocks.
Suppose we expect some object to be passed to a mock that by default compares equal based on object identity (which is the Python default for user defined classes). To use Mock: ((<__main__.Foo object at 0x...>,), {}) Called with: ((<_). | http://www.voidspace.org.uk/python/mock/0.7/examples.html | CC-MAIN-2015-48 | en | refinedweb |
There are presently a number of issues and limitations with how theclocksource and sched_clock() interaction works today. Configurationstend to be grouped in to one of the following: - Platform provides a low rated clocksource (< 100) and prefers to use jiffies for sched_clock() due to reliability concerns. - Platform provides its own clocksource and sched_clock() that wraps in to it. - Platform uses a generic clocksource (ie, drivers/clocksource/) combined with the generic jiffies-backed sched_clock(). - Platform supports a generic highly-rated clocksource but ends up having to use the jiffies sched_clock() anyways. - Platform supports multiple highly-rated clocksources.In the first case, simply using the rating information is sufficient tofigure out the proper course of action. In the second case, very few ofthese do anything outside of the regular cyc2ns() work on the preferredclocksource, so it tends to be more about having access to the referenceclocksource data structures more than really wanting to do any specialcalculations in sched_clock().The last few cases are presently what we are faced with on sh, and whichalso impacts other drivers/clocksource drivers (while acpi_pm seems tohave alternate recourse for sched_clock(), ARM/AVR32/SH do not). In thesecases multiple clocksources can be provided, and the availability ofthese will often depend on runtime constraints (pinmux and so forth), inwhich case link time determination is simply not sufficient. While theseclocksources can be highly rated and can offer excellent granularity, thejiffies clocksource is still used as a fallback given the inability tosprinkle sched_clock() wrappers in the drivers themselves. Also, whilesched_clock() could be moved in to struct clocksource itself, this doesnot help the case where sched_clock() is called in to repeatedly wellbefore a preferred clocksource has been determined and made available(printk times and so on), so extra logic is needed regardless.This patch does the only thing I could think of to address most ofthese in one shot, abusing the current clocksource pointer and forcingsched_clock() to read from it directly as soon as it becomes available(and assuming that is is rated highly enough). This does add the cost ofthe rating test on systems that only have the jiffies clocksource, but Ithink this is acceptable collateral damage given that jiffies are notvery granular to begin with.Signed-off-by: Paul Mundt <lethal@linux-sh.org>--- kernel/sched_clock.c | 10 ++++++++++ 1 file changed, 10 insertions(+)diff --git a/kernel/sched_clock.c b/kernel/sched_clock.cindex e1d16c9..59bbeeb 100644--- a/kernel/sched_clock.c+++ b/kernel/sched_clock.c@@ -30,6 +30,7 @@ #include <linux/percpu.h> #include <linux/ktime.h> #include <linux/sched.h>+#include <linux/clocksource.h> /* * Scheduler clock - returns current time in nanosec units.@@ -38,6 +39,15 @@ */ unsigned long long __attribute__((weak)) sched_clock(void) {+ /*+ * Use the current clocksource when it becomes available later in+ * the boot process, and ensure that it has a high enough rating+ * to make it suitable for general use.+ */+ if (clock && clock->rating >= 100)+ return cyc2ns(clock, clocksource_read(clock));++ /* Otherwise just fall back on jiffies */ return (unsigned long long)(jiffies - INITIAL_JIFFIES) * (NSEC_PER_SEC / HZ); } | https://lkml.org/lkml/2009/5/26/29 | CC-MAIN-2015-48 | en | refinedweb |
>
I previously posted an example that allows you to build a WiX-based MSI that will install a Windows Vista Media Center application and create a custom start menu strip. However, there is a limitation in this example (that was pointed out in this post on the Media Center Sandbox discussion forum) that affects the ability to install the application on 64-bit operating systems. This blog post describes the limitations in my previous sample and presents a modified version of that sample that will allow you to build both 32-bit and 64-bit MSIs in order to work around the limitations.
Description of the problem with my previous example
As this forum post describes, you have to directly set registry entries in order to add custom strips to the Media Center start menu (which means that you have to author RegistryKey and RegistryValue elements in WiX). However, if you create a 32-bit MSI and then try to install it on a 64-bit OS, the registry entries will get written to the WOW64 hive (HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft). The 64-bit version of Windows Vista Media Center looks in the 64-bit registry hive and not the WOW64 registry hive when looking for custom start menu strips to load. Therefore, the custom start menu strip will not appear in the Media Center start menu on a 64-bit OS in my previous example.
Example that can be used to solve this problem
To solve this issue, it is necessary to create separate 32-bit and 64-bit installers. It is a little bit tricky to configure all of the settings and attributes that are necessary to create a 64-bit MSI just by reading through WiX and Windows Installer documentation, so I decided to create a WiX 3.0-based example that can be used to build 32-bit and 64-bit MSIs from the same WiX source (WXS) file.
You can download this example from. I started from my previous 32-bit-only example, and added 64-bit build support. While this sample happens to install a Windows Vista Media Center application, it is intended to help demonstrate the general concepts required to create 64-bit MSIs in WiX.
Changes made in this example to enable 64-bit builds
The new sample includes a single WXS file that is processed twice in order to build 2 different MSIs (one 32-bit and one 64-bit). In order to create a single WXS file that can build both types of MSI, I introduced a WiX pre-processor variable to pass in the name of the processor architecture, and then I added some if/then/else blocks to conditionally set some of the necessary MSI attributes based on whether the MSI being created will be 32-bit or 64-bit.
If you look in the setup.wxs file in the example I posted, you can see all of the changes that I made to enable building a 64-bit MSI by looking for sections of the file that are enclosed in if statements such as the following:
<?if $(var.ProcessorArchitecture)=x64 ?> <Package Description="!(loc.Package_Description)" Comments="!(loc.Package_Comments)" InstallerVersion="200" Compressed="yes" Platforms="x64" /><?else ?> <Package Description="!(loc.Package_Description)" Comments="!(loc.Package_Comments)" InstallerVersion="200" Compressed="yes" /><?endif ?>
<?if $(var.ProcessorArchitecture)=x64 ?> <Package Description="!(loc.Package_Description)" Comments="!(loc.Package_Comments)" InstallerVersion="200" Compressed="yes" Platforms="x64" /><?else ?> <Package Description="!(loc.Package_Description)" Comments="!(loc.Package_Comments)" InstallerVersion="200" Compressed="yes" /><?endif ?>
In order to set the ProcessorArchitecture variable, I added the following command line parameter when calling candle.exe to compile the WXS file:
"%WIX_BUILD_LOCATION%\candle.exe" setup.wxs -dProcessorArchitecture=%PROCARCH% -out "setup_%PROCARCH%.wixobj"
"%WIX_BUILD_LOCATION%\candle.exe" setup.wxs -dProcessorArchitecture=%PROCARCH% -out "setup_%PROCARCH%.wixobj"
In addition, I added a second set of commands to call candle.exe and light.exe twice - one with the ProcessorArchitecture value set to x86 and the other with the ProcessorArchitecture value set to x64.
Specific differences between a 32-bit MSI and a 64-bit MSI
The following are the changes that I made in order to be able to create both 32-bit and 64-bit MSIs in WiX:
Where to read more about 64-bit issues related to Windows Installer
When working on this example, I relied heavily on the information in this post on Heath Stewart's blog and the links to Windows Installer MSDN topics that are included in it. If you are looking for more detailed information about how Windows Installer works behind the scenes in 64-bit scenarios, I encourage you to check out this blog post and also the other topics in Heath's 64-bit blog category.
<update date="3/23/2009"> Fixed broken link to sample download location. </update>
Question:?
Answer:. few people.
Important.
A while back, I posted a list of possible log files for .NET Framework 3.5 and Visual Studio 2008 setup. Since then, I've realized that there are some sets of log files missing from that list, so I decided to create a separate blog post with information about setup log files that are specific to the .NET Framework 3.5 family of products. This family includes the following:
The following is a list of log files that can be produced by all of the above setup packages. In all of the cases below, the logs are created by default, and you do not need to specify any verbose logging settings or registry values to cause the logs to be produced. Also, you can find the %temp% directory by clicking on the Windows start menu, typing %temp% and pressing Enter.
.NET Framework 2.0 SP1 and SP2 setup log files
The following is a complete list of log files that can be produced during .NET Framework 2.0 SP1 and SP2 setup. This list may vary depending on what OS you are installing on, what processor architecture, and what prerequisite components were already installed on the system prior to running .NET Framework 2.0 SP1 and SP2 setup.
Logs produced by the .NET Framework 2.0 SP1 and SP2 setup wrapper:
Logs produced by the packages chained during .NET Framework 2.0 SP1 and SP2 setup:
.NET Framework 3.0 SP1 and SP2 setup log files
The following is a complete list of log files that can be produced during .NET Framework 3.0 SP1 and SP2 setup. This list may vary depending on what OS you are installing on, what processor architecture, and what prerequisite components were already installed on the system prior to running .NET Framework 3.0 SP1 and SP2 setup.
Logs produced by the .NET Framework 3.0 SP1 and SP2 setup wrapper:
Logs produced by the packages chained during .NET Framework 3.0 SP1 and SP2 setup:
.NET Framework 3.5 and 3.5 SP1 setup log files
The following is a complete list of log files that can be produced during .NET Framework 3.5 and 3.5 SP1 setup. This list may vary depending on what OS you are installing on, what processor architecture, and what prerequisite components were already installed on the system prior to running .NET Framework 3.5 and 3.5 SP1 setup.
Logs produced by the .NET Framework 3.5 and 3.5 SP1 setup wrapper:
Logs produced by the packages chained during .NET Framework 3.5 and 3.5 SP1 setup:
Setup log files for other .NET Framework products
I have written separate blog posts about log file locations for other .NET Framework products not listed above. Here they are for your reference in case you need them:
<update date="8/24/2008"> Updated list of .NET Framework 3.0 SP1 log files </update>
<update date="4/13/2009"> Clarified that the list of logs in this post is applicable to 2.0 SP2, 3.0 SP2 and 3.5 SP1 as well. </update>>
<update date="4/17/2008"> Added a note indicating that the issue in this post can affect the .NET Framework 1.0 and 1.1 setup on Windows Vista and not just Windows XP SP2 </update>> | http://blogs.msdn.com/b/astebner/default.aspx?PageIndex=5&PostSortBy=MostViewed | CC-MAIN-2015-48 | en | refinedweb |
; Original function mame: multirember&co
(define (multico a lat col)
(cond
((null? lat) (col '() '()))
((eq? (car lat) a)
(multico a
(cdr lat)
(lambda (newlat seen)
(col newlat
(cons (car lat) seen)))))
(else
(multico a
(cdr lat)
(lambda (newlat seen)
(col (cons (car lat) newlat)
seen))))
)
)
; An usage example of multico:
(define menu '(ham tuna beer tuna beer))
(define (count1 x y) (length x))
(multico 'tuna menu count1) ; Output: 3
def splitmap(el, sequence, process):
l1 = []
l2 = []
for x in sequence:
if el == x:
l2.append(x)
else:
l1.append(x)
return process(l1, l2)
menu = "ham tuna beer tuna beer".split()
count1 = lambda x, y: len(x)
print splitmap("tuna", menu, count1)
def splitmap(el, sequence, process):
l1, l2 = [], []
for x in sequence:
((l1, l2)[el == x]).append(x)
return process(l1, l2)
def splitmap(el, sequence, process)
process sequence.split{|x| x==el}
end
def splitmap(el, seq, coll):
if not seq:
return coll([], [])
elif seq[0] == el:
return splitmap(el, seq[1:],
lambda s1, s2: coll(s1, seq[0:1] + s2))
else:
return splitmap(el, seq[1:],
lambda s1, s2: coll(seq[0:1] + s1, s2))
import sys
from random import randint
from memory import memory
sys.setrecursionlimit(10000)
print memory() # 1.7 MB
seq2 = [randint(1, 5) for _ in xrange(2000)]
def count12(x, y):
print memory() # 18 MB
return [len(x), len(y)]
print splitmap(2, seq2, count12)
(define (splitter x seq l1 l2)
(cond
((null? seq) (cons l1 (cons l2 '())) )
((eq? (car seq) x)
(splitter x
(cdr seq)
l1
(cons (car seq) l2)
))
(else
(splitter x
(cdr seq)
(cons (car seq) l1)
l2
))
)
)
(define (multico2 a lat col)
(apply col (splitter a lat '() '())))
(define menu '(ham tuna beer tuna beer food))
(define (count1 x y) (length x))
(multico2 'tuna menu count1) ; Output: 3
.
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g)
(/ d g))
)
) | http://leonardo-m.livejournal.com/tag/computer+science | crawl-001 | en | refinedweb |
#include <GRadioGroup.h>
Inheritance diagram for GRadioGroup:.
[inline, virtual]
Returns the wide char text associated with this view.
On Win32 the wide characters are 16 bits, on unix systems they are 32-bit characters..
false
[virtual]
Sets the font for this control.
The lifetime of the font passed in is the responsibility of the caller. The GView object assumes the pointer will be valid at all times. | http://www.memecode.com/lgi/docs/classGRadioGroup.html | crawl-001 | en | refinedweb |
- 1) How many memory layers are in the shared pool?
Ans: The shared pool portion of the SGA contains three major areas: library cache(contains parsed sql statements,cursor information,execution plans), dictionary cache (contains cache -user account information,priveleges information,datafile,segment and extent information), buffers for parallel execution messages, and control structure.
2) How do you find out from the RMAN catalog if a particular archive log has been backed-up?
Ans: list archivelog all;
3) How can you tell how much space is left on a given file system and how much space each of the file system’s subdirectories take-up?
Ans: df -kh and du-sh
4) Define the SGA and:
i) How you would configure SGA for a mid-sized OLTP environment?
ii) What is involved in tuning the SGA?
Ans: SGA: The System Global Area (SGA) is a group of shared memory areas that are dedicated to an Oracle “instance” (an instance is your database programs and RAM). All Oracle processes use the SGA to hold information. The SGA is used to store incoming data (the data buffers as defined by thedb_cache_size parameter), and internal control information that is needed by the database. You control the amount of memory to be allocated to the SGA by setting some of the Oracle “initialization parameters”. These might include db_cache_size, shared_pool_size and log_buffer.
- i) 40% of RAM can be used for sizing SGA rest is reserved for OS and others in 64 bit machine and in 32 bit machine max SGA configured can be 1.5GB only.
- ii) Check the statspack report. Check hit ratio of Data buffer. If it is less than 90%, then we need to increase the Data buffer. Check hit ratio of Shared pool. If it is less than 95%, then we need to increase the Shared pool. Check log buffer. If redo buffer allocation retries/redo entries is greater than 1%, then we need to increase log_buffer.
5) What is the cache hit ratio, what impact does it have on performance of an Oracle database and what is involved in tuning it?
Ans:
Buffer cache hit ratio: It calculates how often a requested block has been found in the buffer cache without requiring disk access. This ratio is computed using data selected from the dynamic performance view V$SYSSTAT. The buffer cache hit ratio can be used to verify the physical I/O as predicted by V$DB_CACHE_ADVICE.
sql> select name, value From v$sysstat Where name in (‘db block gets’, ‘consistent gets’, ‘physical reads’);
The cache-hit ratio can be calculated as follows: Hit ratio = 1 – (physical reads / (db block gets + consistent gets)) If the cache-hit ratio goes below 90% then: increase the initialisation parameter DB_CACHE_SIZE.
Library cache hit ratio: It calculates how often the parsed representation of the statement can be reused. It also known as soft parse.
sql> select namespace, pins, pinhits, reloads, invalidations from v$librarycache order by namespace;
Library Cache Hit Ratio = sum(pinhits) / sum(pins)
Dictionary cache hit ratio:It is a measure of the proportion of requests for information from the data dictionary, the collection of database tables and views containing reference information about the database, its structures, and its users. On.
6) Other than making use of the statspack utility, what would you check when you are monitoring or running a health check on an Oracle 8i or 9i database?
Ans: Daily Monitoring activities and check different logs for any sort of errors.
7) How do you tell what your machine name is and what is its IP address?
Ans: hostname, uname -n and ifconfig
8) How would you go about verifying the network name that the local_listener is currently using?
Ans: lsnrctl stat or ps-eaf|grep tns
Inclined to build a profession as Oracle DBA Developer?
Then here is the blog post on Oracle DBA Training.
9) You have 4 instances running on the same UNIX box. How can you determine which shared memory and semaphores are associated with which instance?
Ans:
SQL> oradebug setmypid
SQL> oradebug ipc
SQL>oradebug tracfile_name
Also you can check the spfile. The parameters will start with instance_name. parameter_name naming.
10) What view(s) do you use to associate a user’s SQLPLUS session with his o/s process?
Ans: v$process and v$session
sql> select a.spid from v$process a, v$session b where a.addr = b.addr and b.audsid=userenv(‘sessionid’);
11) What is the recommended interval at which to run statspack snapshots, and why?
Ans: Should be in minutes (15-20 mins approx) because where the time between the two snapshots is measured in hours, the events that caused serious performance issues for 20 minutes during peak processing don’t look so bad when they’re spread out over an 8-hour window. It’s also true with STATSPACK that measuring things over too long of a period tends to level them off over time. Nothing will stand out and strike you as being wrong.
12) What spfile/init.ora file parameter exists to force the CBO to make the execution path of a given statement use an index, even if the index scan may appear to be calculated as more costly?
Ans: OPTIMIZER_INDEX_COST_ADJ= FORCE
13) Assuming today is Monday, how would you use the DBMS_JOB package to schedule the execution of a given procedure owned by SCOTT to start Wednesday at 9AM and to run subsequently every other day at 2AM.
Ans:?
Ans: 00 02 * * * /test/test.sh
15)In which dictionary table or view would you look to determine at which time a snapshot or MVIEW last successfully refreshed?
Ans : SQL> SELECT MVIEW_NAME,LAST_REFRESH_DATE from USER_MVIEWS;
16) How would you best determine why your MVIEW couldn’t FAST REFRESH?
Ans: Possibly by checking the MVIEW LOG for errors.
17) How would you begin to troubleshoot an ORA-3113 error?
Ans: End of File Communication Error. Check Alert Logfile. CheckNetwrok Latency. Check sqlnet.ora file has expire_time = 0, delete unwanted files and check the swap and temp spaces.
18) Which dictionary tables and/or views would you look at to diagnose a locking issue?
Ans: v$lock, v$session, v$process
19) An automatic job running via DBMS_JOB has failed. Knowing only that “it’s failed”, how do you approach troubleshooting this issue?
Ans:Check the log and possible reason for the JOB failed.
20) How would you extract DDL of a table without using a GUI tool?
Ans: select dbms_metadata.get_ddl('OBJECT','OBJECT_NAME') from dual;
21) You’re getting high “busy buffer waits” - how can you find what’s causing it?
Ans:;
22) What query tells you how much space a tablespace named “test” is taking up, and how much space is remaining?
Ans:
SET SERVEROUTPUT ON SET LINESIZE 1000 SET FEEDBACK OFF
SET LINESIZE 1000
SET FEEDBACK OFF
rem column dummy noprintcolumn pct_used format 999.9 heading "%|Used"
column name format a25 heading "Tablespace Name"
column Kbytes format 999,999,999 heading "MBytes"
column used format 999,999,999 heading "Used(MB)"
column free format 999,999,999 heading "Free(MB)"
column largest format 999,999,999 heading "Largest"
break on report
compute sum of kbytes on report
compute sum of free on report
compute sum of used on report
set pagesize 100
select nvl(b.tablespace_name,
nvl(a.tablespace_name,'UNKOWN')) name,(kbytes_alloc/1024) kbytes,
((kbytes_alloc-nvl(kbytes_free,0))/1024) used,(nvl(kbytes_free,0)/1024) free,
((kbytes_alloc-nvl(kbytes_free,0))/kbytes_alloc)*100 "%used",
nvl(largest,0)/1024 largest
from ( select sum(bytes)/1024 Kbytes_free,
max(bytes)/1024 largest, tablespace_name
from sys.dba_free_space group by tablespace_name ) a,
( select sum(bytes)/1024 Kbytes_alloc, tablespace_name
from sys.dba_data_files group by tablespace_name )b
where a.tablespace_name (+) = b.tablespace_name
order by 1
/
23) Database is hung. Old and new user connections alike hang on impact. What do you do? Your SYS SQLPLUS session is able to connect.
Ans: Log into the system and find whether there are any deadlocks in the system using the following query.
select 'SID ' || l1.sid ||' is blocking ' || l2.sid blocking from v$lock l1, v$lock l2 where l1.block =1 and l2.request > 0 and l1.id1=l2.id1 and l1.id2=l2.id2 /
from v$lock l1, v$lock l2
where l1.block =1 and l2.request > 0
and l1.id1=l2.id1
and l1.id2=l2.id2
/
If so kill the processes caught in deadlock
alter system kill session 'SID,SERIAL#' immediate;
Also find out which wait events exist in the system using following commands and go in detail as to what events are causing these waits and take appropriate actions.
select event,count(*) from v$session group by event
/
select u.sid,u.serial#, u.username,p.spid,to_char(u.logon_time,'DD-MON-YYYY:HH24:MI:SS') from v$session u, v$session w,v$process p where u.sid = w.sid and w.event like '%&a%' and u.paddr = p.addr
/
24) Database crashes. Corruption is found scattered among the file system neither of your doing nor of Oracle’s. What database recovery options are available? Database is in archive log mode.
Ans: First of all secure all the archives and all the backups you have on the tape or other system. Then run fschk to check the filesystem. If the corruption is detected at the filesystem level and is not recoverable by fschk format the file system and restore the database through RMAN.
25) How do you increase the OS limitation for open files (LINUX and/or Solaris)?
Ans: Set the file-max parameter is /etc/sysctl.conf to the number you want.Save the file and execute it by using command /etc/sysctl.conf-p
26) Provide an example of a shell script which logs into SQLPLUS as SYS, determines the current date, changes the date format to include minutes & seconds, issues a drop table command, displays the date again, and finally exits.
Ans:
export ORACLE_BASE=/oracle
export ORACLE_HOME=/oracle/ora10g
export ORACLE_SID=ora10g
export path=$ORACLE_HOME/lib
sqlplus sys as sysdba << EOF
@/oracle/date.sql
exit;
Now the contents of /oracle/date.sql
select SYSDATE from dual;
select to_char(SYSDATE,'dd-mon-yyyy hh24:mi:ss') from dual;
drop table tablename cascade constraints;
select to_char(SYSDATE,'dd-mon-yyyy hh24:mi:ss') from dual;
/
Interested in mastering Oracle DBA Certification ?
Learn more about Oracle DBA Tutorials in this blog post.
27) Explain how you would restore a database using RMAN to Point in Time?
Ans:
restore database
until time "to_date('Aug 27 2001 02:00:00','Mon DD YYYY HH24:MI:SS')";
recover database
28) How does Oracle guarantee data integrity of data changes?
Ans: Oracle exadata training Bangalore enables you to define and enforce data integrity constraints like PRIMARY KEY CONSTRAINTS, FOREIGN KEY CONSTRAINTS and UNIQUE CONSTRAINTS.
29) Which environment variables are absolutely critical in order to run the OUI?
Ans: ORACLE_BASE, ORACLE_HOME, ORACLE_SID,path and library path
30) What SQL query from v$session can you run to show how many sessions are logged in as a particular user account?
Ans: select count(1) from v$session where USERNAME='username';
31) TABLESPACE is not specified for a user?
a. TEMP
b. DATA
c. SYSTEM
d. ROLLBACK
Answer: c
32) User SCOTT creates an index with this statement: CREATE INDEX emp_indx on employee (empno). In which tablespace would be the index created?
a. SYSTEM tablespace
b. SCOTTS default tablespace
c. Tablespace with rollback segments
d. Same tablespace as the EMPLOYEE table.
Answer: b
33) Which data dictionary view shows the available free space in a certain tablespace?
A. DBA_EXTENTS
B. V$FREESPACE
C. DBA_FREE_SPACE
D. DBA_TABLESPACE
E. DBA_FREE_EXTENTS
Answer: c
34) Which method increase the size of a tablespace?
A. Add a datafile to a tablespace.
B. Use the ALTER TABLESPACE command to increase the MINEXTENTS for the tablespace.
C. Use the ALTER TABLESPACE command to increase the MAXEXTENTS for the tablespace.
D. Use the ALTER TABLESPACE command to increase the MINIMUM EXTENT for the tablespace.
Answer: a
35) What does the command ALTER DATABASE . . . RENAME DATAFILE do? (8-37) (Not proper description of the ans.)
A. It copies a data file.
B. It updates the control file.
C. It copies a data file and updates the control file.
D. It copies a data file, deletes the obsolete file, and updates the control file.
Answer: b
36) Can you drop objects from a read-only tablespace?
A. No
B. Yes
C. Only when using the DBA role
D. Only when the tablespace is online
Answer: b
37) SYSTEM TABLESPACE can be made off-line.
a) Yes
b) No
Answer: b
38) Datadictionary can span across multiple Tablespaces.
a) TRUE
b) FALSE
Answer: b
39) Multiple Tablespaces can share a single datafile.
a) TRUE
b) FALSE
Answer: b
40) All datafiles related to a Tablespace are removed when the Tablespace is dropped?
a) TRUE
b) FALSE
Answer: b
41) In which situation would you need to create a new control file for an existing database?
A. When all redo-log files are lost.
B. When MAXLOGMEMBERS needs to be changed.
C. When RECOVERY_PARALLELISM needs to be changed.
D. When the name of the parameter file needs to be changed
Answer: b
42) When configuring a database for ARCHIVELOG mode, you use an initialisation parameter to specify which action?
A. The size of archived log files.
B. How frequently log files will be archived.
C. That the database is in ARCHIVELOG mode.
d. To Store Archive log Files
Answer: d
43) Which command creates a text backup of the control file?
A. ALTER DATABASE BACKUP CONTROLFILE TO TRACE;
B. ALTER DATABASE BACKUP CONTROLFILE TO BACKUP;
C. ALTER DATABASE BACKUP CONTROLFILE TO filename;
D. ALTER DATABASE BACKUP CONTROLFILE TO TEXT filename;
Answer: a
44) You are configuring a database for ARCHIVELOG mode. Which initialization parameter should you use?
A. LOG_ARCHIVE_SIZE
B. ARCHIVELOG_MODE
C. LOG_ARCHIVE_DEST
Answer: c
45) How does a DBA specify multiple control files?
A. With the ADD CONTROLFILE command.
B. By using the files in the STARTUP command.
C. With the MULTIPLEX control file command.
D. By listing the files in the CONTROL_FILES parameter.
Answer: d
46) Which dynamic view should a DBA query to obtain information about the different sections of the control file?
A. V$CONTROLFILE
B. DBA_CONTROLFILE
C. V$CONTROLFILE_RECORD_SECTION
D. DBA_CONRTOLFILE_RECORD_SECTION
Answer: c
47) Which statements about online redo log members in a group are true?
A. All files in all groups are the same size.
B. All members in a group are the same size.
C. The rollback segment size determines the member size.
D. Differently size of transactions requires that the DBA should differently sized members.
Answer: b
What are the Common Oracle DBA.
For In-depth knowledge on Oracle DBA click on: | https://tekslate.com/oracle-dba-interview-questions-answers | CC-MAIN-2020-16 | en | refinedweb |
CodingForums
>
Client side development
>
XML
> whats different between xml and html?
PDA
View Full Version :
whats different between xml and html?
mattover-matter
03-31-2003, 09:37 PM
what is new about xml from html except ending tags?
<br />
liorean
03-31-2003, 10:10 PM
That question is asked the wrong way - the question you should be asking is what's the difference between sgml and xml.
You see, xml is a meta language, or a descriptor language. It defines the syntax and vocabulary of files written in xml languages. DTD/schema are the vocabulary part of xml, while xml well-formedness is the syntax part. What the xml file does is actually to connect the vocabulary with well-formedness and the data/document it is to describe. Stylesheets are the document-related styling (CSS, FO), as in html, and the data-related transformation (XSLT). Xml is in itself a stricter subset of sgml.
HTML, on the other hand, is a document language - it's a given vocabulary that can be used with either xml or sgml.
In a way, you can say that an html document is an instance of the sgml class, while an xhtml document is an instance of the xml class - if you talk object oriented programming. That parallel doesn't work entirely, though, since the xml and sgml verions of html share their member definitions.
cg9com
04-05-2003, 08:50 AM
to knock out some basic questions, go over this:
XML + HTML = XHTML
Tails
04-05-2003, 08:42 PM
Um, when I make a file with all those ending tag rules xhtml explained and gave it an xml extention, I get a visual map of tags. Then when I look at already made xml files (winamp 3 had one, why and what the heck it does, I don't know), it had weird stuff like phoney made up tags that seemed to serve no purpose. What is xml exactly? I'm trying to fill in the gap of the equation xml + html = xhtml
liorean
04-05-2003, 09:03 PM
XML is a set of tools for defining a language, and some grammatics for it such as that all elements have to be closed, which SGML doesn't require. HTML is a set of "keywords" in the form of elements, attributes, entity references and their semantic meaning, The semantic meaning is lost to the technology, however, because you can't validate that you are using a tag for it's intended purpose by the validation system DTDs provide.
In other words, the <>, </>, <!-- -->, <!>, <??>, &#nnnn; are what is provided by XML, and the standard for HOW to make them get a meaning, not what their meaning actually is.
What HTML, SVG, MathML, SOAP, RDF DocBook etc. adds to it, is the actual meaning - they add tags, attributes, entity references and legal attribute values. On that, they can also add default behavior, but this is - like in the case of semantic meaning - nothing that is provided with the language definition, but only provided by human readable specifications.
Tails: If you're using IE, I'm not surprised. IE's XML engine doesn't have any knowledge of the XHTML namespace. That's what I meant by that default behavior can be provided, but isn't programmatically inherent to the language.
cg9com
04-05-2003, 09:09 PM
Originally posted by Tails
I'm trying to fill in the gap of the equation xml + html = xhtml
from w3schools ():
XML was designed to describe data and focus on what data is.
HTML was designed to display data and focus on how data looks.
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved. | http://www.codingforums.com/archive/index.php/t-17423.html | CC-MAIN-2017-26 | en | refinedweb |
There is a reference to
#include "GEN_Types.h"
in IMG_Pixmap.h .
Where is this header file found?
(Public.h ???)
GEN_Types.h ..... ??
Compiling, libraries, modules, coding guidelines and porting
Moderators: jesterKing, stiv
Post Reply
1 post • Page 1 of 1
Post Reply
1 post • Page 1 of 1
Who is online
Users browsing this forum: No registered users and 1 guest | https://www.blender.org/forum/viewtopic.php?t=917 | CC-MAIN-2017-26 | en | refinedweb |
The purpose of this IPython notebook is to get you started in using Python (actually, the interactive variant called IPython)calculations assuming this is your first exposure to Python.
from IPython.core.display import HTML HTML(open("styles/custom.css", "r").read())
The first step is to obtain a working IPython environment. The easiest approach is to sign up for a free account on a cloud-based service such as Wakari.io. You'll need internet connectivity to access your work, but there's nothing to install, no software to maintain, and you can work with nothing more than a browser on a Chromebook or tablet.
Alternatively, you can install an IPython environment on your laptop. There are at least two excellent and free packages available:
There are differences between these packages, particularly in the methods used to download and maintain additional Python libraries. In both cases the process for downloading and installing the software are well documented and easy to follow. You should allow about 10-30 minutes for the installation depending on your experience and connection speed.
After installing, be sure to check for updates before proceeding further. With the Anaconda package this is done by executing the following two commands in a terminal window:
> conda update conda > conda update anaconda
IPython notebooks (like this one) are simply files in a directory with a
.ipynb suffix. They can be stored in any directory, including a Dropbox or Google Drive directory.
To start a notebook session, open a terminal window and navigate to the directory where you will be keeping your notebooks. Then execute the following statement at the command line:
> ipython notebook --pylab=inline
The terminal window will show information indicating start up of an ipython session, then browser window will open listing notebooks in your current directory. At this point your options are
New Notebookbutton, or
An IPython notebook consists of cells that hold headings, text, or python code. The user interface is relatively self-explanatory. Take a few minutes now to open, rename, and save a new notebook.
Here's a quick overview of IPython notebooks prepared by the team that created the software.
from IPython.display import YouTubeVideo YouTubeVideo("H6dLGQw9yFQ",560,315)
Python is an elegant and modern language for programming and problem solving that has found increasing use by engineers and scientists. In the next few cells we'll demonstrate some basic Python functionality.
Basic arithmetic functions
a = 12 b = 2 print "a + b = ", a + b print "a**b = ", a**b print "a/b = ", a/b
a + b = 14 a**b = 144 a/b = 6
Calling a builtin function
sin(2atenation x = [1, 2, 3, 4]; y = [5, 6, 7, 8]; x + y
[1, 2, 3, 4, 5, 6, 7, 8]
# Two ways to sum a list of numbers print sum(x) print reduce(add,x)
10 10
# Two ways to add a two lists of numbers print add(x,y) print map(add,x,y)
[ 6 8 10 12] [6, 8, 10, 12].
for x in xList: print "x =",x, " sin(x) = ",
{'H2O': 18.02, 'CO2': 44.01, 'CH4': 16.04, 'O2': 32.0}
We can a value to an existing dictionary.
mw['C8H18'] = 114.23 print mw
{'H2O': 18.02, 'CO2': 44.01, 'CH4': 16.04, 'O2': 32.0, 'C8H18': 114.23} CO2 is 44.01 The molar mass of CH4 is 16.04 The molar mass of O2 is 32.00 The molar mass of C8H18 is 114.23
IPython notebooks include plotting functionality very similar to Matlab's. Here are some examples.
x = linspace(0,10) y = sin(x) z = cos(x) plot(x,y,'b',x,z,'r') xlabel('Radians'); ylabel('Value'); title('Plotting Demonstration') legend(['Sin','Cos']) grid()
plot(y,z) axis('equal')
(-1.0, 1.0, -1.0, 1.0)
subplot(2,1,1) plot(x,y) title('Sin(x)') subplot(2,1,2) plot(x,z) title('Cos(x)')
<matplotlib.text.Text at 0x10808ea50> and select the first solution f = sym.solve(eqn,P)[0] # Use the sympy plot function to plot sym.plot(f,(V,1,10),xlabel='Volume m**3',ylabel='Pressure Pa')
<sympy.plotting.plot.Plot at 0x108f05750>
Python offers a full range of programming language features, and there is a seemingly endless range of packages for scientific and engineering computations. Here are some suggestions on places you can go for more information on programming
Interative learning
On-line tutorials, books, etc.
Books
Official documentation, examples, and galleries.
Engineering applications | http://nbviewer.jupyter.org/github/jckantor/ESTM60203/blob/master/notebooks/Getting%20Started%20with%20IPython.ipynb | CC-MAIN-2017-26 | en | refinedweb |
go to bug id or search bugs for
Description:
------------
I'm currently developing a binding for D-BUS based on native PHP. For that reason I need to talk to abstract namespace sockets. It seems like PHP is handling these socket type differently than D-BUS. I can't connect to the abstract socket.
I asked for help on the php-general mailing list and got some helpful responses for further investigation:
After that I asked on the D-BUS mailing list for clarification how D-BUS implements abstract namespace support:
As pointed out by Havoc on the dbus mailing list I think the problem is here:
or in the stream version of this API (not sure if it uses the same functions).
- I'm wondering why 108 is hardcoded here (in the connect function). A constant might be better?
- "If the connect() or listen() just does sizeof(struct sockaddr_un) then it will always get a bunch of trailing garbage bytes in the abstract name." (quoted Havoc here)
- Even if their is no NUL byte to mark the end of the string PHP should only use non-nul byte characters for the path (or better: the string that has been given by the programmer.) If a programmer want's to fill up sun_path with NUL bytes, it should be added to the PHP code and not "assumed".
I'm not a C programmer - so the code in sockets.c might just do what I wrote - I'm sorry for any inconveniences in this case.
This seems to be a regression of bug #16121
Reproduce code:
---------------
<?php
// use env to find a current abstract D-BUS socket
$fp = fsockopen ("unix://\x00/tmp/dbus-whatever",0);
if ($fp) { fclose ($fp); }
?>
Expected result:
----------------
A connect with \x00/tmp/dbus-whatever (without added NUL bytes until the maximum sun path length is reached).
Actual result:
--------------
fsockopen:
fsockopen(): unable to connect to unix://:0 (Connection refused)
for unix://\x00/tmp/dbus-whatever which is a bit strange because I expected at least the error message "fsockopen() [function.fsockopen]: unable to connect to unix://[NUL byte]/tmp/dbus-whatever:0 (Connection refused)"
stream_socket_client:
stream_socket_client: unable to connect to unix://\0/tmp/hald-local/dbus-ZniNmvr5O0 (Connection refused) in ...
socket_connect:
Warning: socket_connect(): unable to connect
[22]: Invalid argument in ...
I can garantuee that the arguments are right - removing the NUL byte from socket_connect allows me to connect to a non-abstract socket.
Add a Patch
Add a Pull Request
The problem here is definitely the sockaddr length being passed by php. Here's what php does according to strace:
connect(3, {sa_family=AF_FILE, path=@/tmp/dbus-8qswtYDtSn}, 110) = -1 ECONNREFUSED (Connection refused)
And here's what a working C++ program does:
connect(3, {sa_family=AF_FILE, path=@/tmp/dbus-8qswtYDtSn}, 23) = 0
Notice the only difference is 110 vs 23. The "@" sign is displayed by strace to mean an abstract socket (first character of the path is null); when connecting to an abstract socket, the path= variable is not displayed in quotes like it normally would be.
23 = sizeof(sa_family) + length(path)
This bug has been fixed in CVS.
Snapshots of the sources are packaged every three hours; this change
will be in the next snapshot. You can grab the snapshot at.
Thank you for the report, and for helping us make PHP better.
Both ext/sockets/ and streams implementations are fixed now. | https://bugs.php.net/bug.php?id=44127 | CC-MAIN-2017-26 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.