
science_freaks: Из чего делают самый дорогой кофе?
- но за такую цену у меня сразу начинается амфибиотропная асфиксия
(Добавлена цитата к закладке Flow Steering - NVIDIA Docs) |
(Добавлена закладка Карта - Unit Tester - Base Defense - Карты StarCraft 2 StarCraft2) |
||
(не показано 40 промежуточных версий этого же участника) | |||
Строка 2: | Строка 2: | ||
<listfeed name="Закладки У Виталия" date="^\s*(?:\[[^\:]*\]\s*)?%d\s+%b,\s*%H:%M:%S:\s*" headingdate="%Y" /> | <listfeed name="Закладки У Виталия" date="^\s*(?:\[[^\:]*\]\s*)?%d\s+%b,\s*%H:%M:%S:\s*" headingdate="%Y" /> | ||
<!--BookmarkHeadings:"%Y", "%B %Y"--><!--BookmarkDate:%d %B, %H:%M:%S:--> | <!--BookmarkHeadings:"%Y", "%B %Y"--><!--BookmarkDate:%d %B, %H:%M:%S:--> | ||
+ | |||
+ | == 2025 == | ||
+ | |||
+ | === января 2025 === | ||
+ | |||
+ | * 15 января, 22:18:39: [http://instarcraft.ru/load/karta_unit_tester/1-1-0-10 Карта - Unit Tester - Base Defense - Карты StarCraft 2 StarCraft2] | ||
+ | |||
+ | == 2024 == | ||
+ | === ноября 2024 === | ||
+ | |||
+ | * 22 ноября, 19:35:50: [https://downloads.scality.com/artesca-ova/doc/general_introduction.html Introducing ARTESCA — ARTESCA 2.2.5 documentation] | ||
+ | * 02 ноября, 23:36:06: [https://www.youtube.com/watch?v=e8gU7-nF350&t=2227s Денис Ефаров — Hadoop 3: Erasure coding catastrophe - YouTube] | ||
+ | |||
+ | === октября 2024 === | ||
+ | |||
+ | * 31 октября, 11:28:18: [https://yandex.com/games/app/153846 Cute Snake io (by JulGames) - play online for free on Yandex Games] | ||
+ | |||
+ | === сентября 2024 === | ||
+ | |||
+ | * 21 сентября, 02:01:08: [https://pikabu.ru/story/kinkazhu_neponyatnaya_meshanina_iz_zhivotnyikh_raznyikh_vidov_obrazuyut_semi_iz_3_vzroslyikh_zhivotnyikh_dlya_chego_8437968 Кинкажу: Непонятная мешанина из животных разных видов. Образуют семьи из 3 взрослых животных. Для чего? | Пикабу] | ||
+ | * 21 сентября, 02:01:01: [https://bad-good.ru/2016/may/clean-iron.html Химические процессы и тонкости восстановления ржавого железа путем электролиза (08.05.2016).] | ||
+ | * 18 сентября, 01:37:42: [https://pagefind.app/ Pagefind | Pagefind — Static low-bandwidth search at scale] | ||
+ | * 15 сентября, 18:23:51: [https://github.com/cloudcannon/pagefind CloudCannon/pagefind: Static low-bandwidth search at scale] | ||
+ | * 09 сентября, 15:21:05: [https://docusaurus.io/ Build optimized websites quickly, focus on your content | Docusaurus] | ||
+ | * 09 сентября, 15:21:01: [https://lunrjs.com/ Lunr: A bit like Solr, but much smaller and not as bright] | ||
+ | * 09 сентября, 15:20:29: [https://typesense.org/ Typesense | Open Source Alternative to Algolia + Pinecone] | ||
+ | |||
+ | === августа 2024 === | ||
+ | |||
+ | * 11 августа, 13:27:53: [https://docs.victoriametrics.com/stream-aggregation/ Streaming aggregation] | ||
+ | * 11 августа, 13:26:08: [https://www.opennet.ru/opennews/art.shtml?num=60808 Microsoft открыл код хранилища Garnet, совместимого с Redis] | ||
+ | * 11 августа, 13:23:31: [https://docs.saunafs.com/ SaunaFS documentation overview | SaunaFS Documentation] | ||
+ | * 11 августа, 13:21:52: [https://sibylfs.github.io/ Introduction · GitBook] | ||
+ | * 11 августа, 13:20:04: [https://github.com/dCache/dcache dCache/dcache: dCache - a system for storing and retrieving huge amounts of data, distributed among a large number of heterogenous server nodes, under a single virtual filesystem tree with a variety of standard access methods] | ||
+ | * 11 августа, 13:16:09: [https://www.tadviser.ru/index.php/%D0%9A%D0%BE%D0%BC%D0%BF%D0%B0%D0%BD%D0%B8%D1%8F:ITG_(INLINE_Technologies_Group)#.D0.9B.D0.B8.D0.BA.D0.B2.D0.B8.D0.B4.D0.B0.D1.86.D0.B8.D1.8F_.D1.8E.D1.80.D0.BB.D0.B8.D1.86.D0.B0 ITG (INLINE Technologies Group)] | ||
+ | |||
+ | === июня 2024 === | ||
+ | |||
+ | * 19 июня, 14:52:16: [https://forward.com/news/562504/yaroslav-hunka-anthony-rota-canada-ukraine-nazis/ Why Canada honored a Ukrainian man who fought under the Nazis – The Forward] | ||
+ | |||
+ | === мая 2024 === | ||
+ | |||
+ | * 30 мая, 15:03:57: [https://github.com/DavidS95/Smokeless_UMAF DavidS95/Smokeless_UMAF] | ||
+ | * 25 мая, 11:03:39: [https://github.com/vrolife/modern_laptop vrolife/modern_laptop: Redmi Book Pro 14/15 2022 锐龙版/Ryzen Linux 键盘驱动/keyboard driver] | ||
+ | * 10 мая, 01:18:34: [https://github.com/anishathalye/porcupine anishathalye/porcupine: A fast linearizability checker written in Go 🔎] | ||
+ | * 07 мая, 23:44:12: [https://vk.com/@vmk_surv_guide-mmp Разоблачение кафедры ММП] | ||
+ | |||
+ | === апреля 2024 === | ||
+ | |||
+ | * 18 апреля, 12:00:39: [https://highscalability.com/gossip-protocol-explained/ Gossip Protocol Explained - High Scalability -] | ||
+ | * 05 апреля, 13:19:39: [https://xanmod.org/ XanMod Kernel] | ||
+ | * 02 апреля, 18:16:40: [https://docs.nvidia.com/gpudirect-storage/overview-guide/ NVIDIA GPUDirect Storage Overview Guide - NVIDIA Docs] | ||
+ | *: <html><span class="token string">"rdma_dev_addr_list"</span> <span class="token builtin class-name">:</span> <span class="token punctuation">[</span><span class="token string">"192.168.0.12"</span><span class="token punctuation">]</span></html> | ||
+ | <!-- NEXT BOOKMARK --> | ||
+ | |||
+ | === марта 2024 === | ||
+ | |||
+ | * 28 марта, 19:57:17: [https://www.sophon.ai/ SOPHGO] | ||
+ | * 24 марта, 12:21:11: [https://vz.ru/columns/2017/10/4/889507.html ВЗГЛЯД / Святослав Голиков: Маршрут транзита исламских боевиков через Украину не случаен :: Автор Святослав Голиков] | ||
+ | |||
+ | === февраля 2024 === | ||
+ | |||
+ | * 21 февраля, 12:29:29: [https://manticoresearch.com/ Manticore Search] | ||
+ | * 01 февраля, 02:06:00: [https://generalarcade.com/croteams-serious-drm/ Croteam's "serious" DRM | General Arcade] | ||
+ | * 01 февраля, 00:03:05: [http://www.revolucia.ru/gaydar_mk.htm Аркадий Гайдар. Сказка про военную тайну, Мальчиша-Кибальчиша и его твердое слово. Библиотека газеты РЕВОЛЮЦИЯ] | ||
+ | |||
+ | === января 2024 === | ||
+ | |||
+ | * 29 января, 13:15:36: [https://www.weave.works/blog/weave-gossip-dns/ Weave ‘Gossip’ DNS] | ||
+ | * 26 января, 00:04:46: [https://mr_goldberg.gitlab.io/goldberg_emulator/ https://mr_goldberg.gitlab.io/goldberg_emulator/] | ||
+ | * 26 января, 00:04:37: [https://gitlab.com/Mr_Goldberg/goldberg_emulator Goldberg / goldberg_emulator · GitLab] | ||
+ | * 19 января, 15:26:18: [https://www.opendnssec.org/softhsm/ OpenDNSSEC » SoftHSM] | ||
+ | * 18 января, 19:30:25: [https://www.ev3.cloud/ru/ ОТВ - Главная] | ||
+ | * 18 января, 13:01:53: [https://www.authelia.com/ Authelia - The Single Sign-On Multi-Factor portal for web apps] | ||
== 2023 == | == 2023 == | ||
+ | === декабря 2023 === | ||
+ | |||
+ | * 23 декабря, 11:32:59: [https://www.visualcapitalist.com/cp/how-americans-spend-their-money-2022/ How Americans Spend Their Money, By Generation] | ||
+ | * 07 декабря, 23:20:43: [https://github.com/ytsaurus/ytsaurus/blob/main/yt/yt/core/misc/fenwick_tree.h ytsaurus/yt/yt/core/misc/fenwick_tree.h at main · ytsaurus/ytsaurus] | ||
+ | * 07 декабря, 19:22:51: [https://en.wikipedia.org/wiki/Fenwick_tree Fenwick tree - Wikipedia] | ||
+ | * 06 декабря, 17:16:44: [https://github.com/efficient/epaxos efficient/epaxos] | ||
+ | * 02 декабря, 00:26:17: [https://openobserve.ai/ OpenObserve | Open Source Observability Platform for Logs, Metrics, Traces, and More – Your Ultimate Dashboard for Alerts and Insights] | ||
+ | |||
=== ноября 2023 === | === ноября 2023 === | ||
На мои закладки можно подписаться по RSS — просто кликните по ссылке.
First of all, we must get wallet's public key. We will NOT use tonapi.io
or similar services as there are no reasons why we may rely on their answer. We will parse walletStateInit
.
/remove-lifecycle rotten
Have the same problem with 1.19.0 and rook resources getting deleted, namely the mon deployments and services, the mgr deployments, the osd deployments and, most annoyingly, the mon endpoint configmap and dashboard password secret - making rook create new cluster from scratch and creating a lot of manual work for me to recover the cluster
tell me if you need more information
This method is best if you need to perform additional filtering:
Use the trim
, atrim
, setpts
, asetpts
, and concat
filters:
ffmpeg -i input -filter_complex \ "[0:v]trim=60:65,setpts=PTS-STARTPTS[v0]; \ [0:a]atrim=60:65,asetpts=PTS-STARTPTS[a0]; \ [0:v]trim=120:125,setpts=PTS-STARTPTS[v1]; [0:a]atrim=120:125,asetpts=PTS-STARTPTS[a1]; \ [v0][a0][v1][a1]concat=n=2:v=1:a=1[out]" \ -map "[out]" output.mkv
setpts
and asetpts
will prevent a jerky output due to presentation timestamp issues.
Make sure to use a recent version. See the FFmpeg Download page for links to builds for Windows, OS X, and Linux.
hello, as a man of non-white background (a mix of brown, black, and white), the removal of "slave" and "blacklist" from the source code itself feels racist. i'm pretty aware of these terms and their context is obvious, i don't think anyone thinks of racial supremacy when writing source code. but we talk about orphans and other concepts. metaphors are useful for discussion. if you want to clean the source code and make it more readable, that's cool. but acting like myself and other PoC (people of colour) can not understand the subtleties of language and that these are not being used as racist terms actually makes us feel rather cast out and viewed as inferior. that being said, i understand the context of these changes comes from white developers who would rather not be associated with the concepts. it is a murky thing, but be honest when making decisions. because acting like you are saving me is feeling rather patronising. |
When sending the access token in the HTTP request URI, the client adds the access token to the request URI query component as defined by "Uniform Resource Identifier (URI): Generic Syntax" [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.), using the access_token parameter.
Thanks, but the syslog driver now does what I want.
For the record and just in case someone also needs this, here's my setup on a Ubuntu system.
docker-compose.yml
[...]
log_driver: "syslog"
log_options:
tag: "web"
/etc/rsyslog.d/30-docker-container
# Log docker messages to one file per container $template
DockerFileName,"/var/log/docker/%syslogtag:R,ERE,1,DFLT:docker/(.*)\[--end%.log"
# Log messages usually already contain a timestamp, so only log the raw message
$template DockerLog,"%msg%\n" :syslogtag,startswith,"docker/" ?DockerFileName;DockerLog
# Do not pollute default syslog with docker messages
& ~
/etc/logrotate.d/docker-container
/var/log/docker/*.log {
rotate 2
weekly
missingok
notifempty
delaycompress
compress
postrotate
reload rsyslog >/dev/null 2>&1 || true
endscript
}
This gives me one logfile per container tag, for example /var/log/docker/web.log
.
В первый месяц он написал: «Отреверсил AWDL. Чувствую расширение сознания и единение со всем остальным миром». Мастер взглянул на запись и швырнул её в урну.
Во второй месяц ученик написал: «Наконец я обнаружил уязвимости в этом проприетарном протоколе». Мастер был разочарован.
В третьем письме ученик с энтузиазмом объяснил: «Тайна AirDrop предстала моему изумлённому взору». Мастер зевнул.
В следующем письме была новая мысль: «Закрытость протокола негативно сказывается на его безопасности». В отчаянии мастер развёл руками.
После этого письма прошёл один месяц, потом другой, потом целый год. Учитель решил напомнить своему ученику о том, что уже пора сообщить о духовном прогрессе. Ученик ответил: «Да кому это нужно?» После этих строк на лице мастера появилась улыбка.
— Наконец-то до него дошло, — сказал он.
Did someone say frameworks?
Frameworks make everything easy!
Just use druffle to interface with puffle, which needs duffle to compile luffle, which enables drabble to build babble, which needs dabble to compile dribble, which enables puffle to fluffle the socksifier.
each framework introduces between s , and mSec of latency, consumes 100’s of Mb of memory to do it’s small trivial task, and has at least 3 severe vulnerabilities.
вашими бы устами да овнеца черпануть...
такое ощущение, что мелкософт во главе с Кумар Наcpалом Ипать Раджой - окончательно потерял ориентировку и ползет на ощупь - сам не понимая, куда и зачем.
It is close to 25 million lines of C code.
What an unimaginable horror! You can't change a single line of code in the product without breaking 1000s of existing tests. Generations of programmers have worked on that code under difficult deadlines and filled the code with all kinds of crap.
Very complex pieces of logic, memory management, context switching, etc. are all held together with thousands of flags. The whole code is ridden with mysterious macros that one cannot decipher without picking a notebook and expanding relevant pats of the macros by hand. It can take a day to two days to really understand what a macro does.
Sometimes one needs to understand the values and the effects of 20 different flag to predict how the code would behave in different situations. Sometimes 100s too! I am not exaggerating.
The only reason why this product is still surviving and still works is due to literally millions of tests!
Here is how the life of an Oracle Database developer is:
- Start working on a new bug.
- Spend two weeks trying to understand the 20 different flags that interact in mysterious ways to cause this bag.
- Add one more flag to handle the new special scenario. Add a few more lines of code that checks this flag and works around the problematic situation and avoids the bug.
- Submit the changes to a test farm consisting of about 100 to 200 servers that would compile the code, build a new Oracle DB, and run the millions of tests in a distributed fashion.
- Go home. Come the next day and work on something else. The tests can take 20 hours to 30 hours to complete.
- Go home. Come the next day and check your farm test results. On a good day, there would be about 100 failing tests. On a bad day, there would be about 1000 failing tests. Pick some of these tests randomly and try to understand what went wrong with your assumptions. Maybe there are some 10 more flags to consider to truly understand the nature of the bug.
- Add a few more flags in an attempt to fix the issue. Submit the changes again for testing. Wait another 20 to 30 hours.
- Rinse and repeat for another two weeks until you get the mysterious incantation of the combination of flags right.
- Finally one fine day you would succeed with 0 tests failing.
- Add a hundred more tests for your new change to ensure that the next developer who has the misfortune of touching this new piece of code never ends up breaking your fix.
- Submit the work for one final round of testing. Then submit it for review. The review itself may take another 2 weeks to 2 months. So now move on to the next bug to work on.
- After 2 weeks to 2 months, when everything is complete, the code would be finally merged into the main branch.
The above is a non-exaggerated description of the life of a programmer in Oracle fixing a bug. Now imagine what horror it is going to be to develop a new feature. It takes 6 months to a year (sometimes two years!) to develop a single small feature (say something like adding a new mode of authentication like support for AD authentication).
The fact that this product even works is nothing short of a miracle!
I don't work for Oracle anymore. Will never work for Oracle again!
Из этого следует что:
1) Если долго плыть на трупе своего врага, можно увидеть себя, сидящим на берегу.
2)Если притвориться трупом и поплыть по реке, то можно узнать, кто считает тебя своим врагом.
3)Если два взаимных врага одновременно сели у реки, они увидят плывущие трупы друг друга.
4)Если по реке ничего не плывет — проверь, не озеро ли это.
There is no need to have a webserver to serve the preseed file. You can use the already existing TFTP server for that. For example this is my PXE config for a "Debian Jessie Preseed" installation:
KERNEL debian/jessie/amd64/linux
APPEND auto=true priority=critical vga=788 initrd=debian/jessie/amd64/initrd.gz DEBCONF_DEBUG=5 DEBIAN_FRONTEND=text url=tftp://192.168.1.30/preseed/debian-jessie.preseed --
And the line url=tftp://192.168.1.30/preseed/debian-jessie.preseed
points to the TFTP server and the location of the preseed file.
UPD: С версии Firefox 53 для копирования кириллических URL из адресной строки используйте настройку:
browser.urlbar.decodeURLsOnCopy = true
Не ругай меня, родная, что накодил тут г..на я :D
На самом деле это обычные нормальные инженеры, понимающие что происходит и как делается за пределами узкой области их текущей ответственности.
Само явление растёт от безысходности на фоне массового нежелания недоадминов понимать как пишутся программы и массового нежелания недопрограммистов понимать как их поделия будут жить в реальном мире.
В такой ситуации нормальные инженеры из обоих лагерей, по сути обладающие примерно одинаковым набором навыков, объединяются в некое пересекающееся подмножество с красивым маркетинговым названием что бы дороже продать себя и улучшить жизнь.
Pisi Linux - это дистрибутив со скользящим обновлением ( rolling release ), являющийся форком основанного на Pisi дистрибутива Pardus Linux.
Чего? Кто кого форкнул? Кто основан на писе?
COMAR MUDUR PISI YALI KAPTAN
— State your name and occupation.
— YALI COMAR MUDUR, KAPTAN PISI.
//Джей и Молчаливый Боб в Турции
“We dont stop playing because we get old. We get old because we stop playing.”
- Some dead guy
Но что делать если зуд нестерпимый, контроллер залочен, а никакой микросхемы для реанимации под рукой нету? Тут иногда прокатывает метод пальца. Прикол в том, что на тело человека наводится весьма нефиговая наводка частотой примерно 50Гц. Всякий кто хватался за щупы осциллографа руками помнит какие шняги тут же возникают на экране — вот это оно! А почему бы эту наводку не заюзать как тактовый сигнал? Так что припаиваешь к выводу XTAL1 провод, хватаешься за него рукой, и жмешь на чтение или запись контроллера :) Предупреждаю сразу, метод работает через жопу, далеко не с первого раза, читает долго и порой с ошибками, но на перезапись FUSE битов в нужную сторону должно хватить. Пару раз у меня такой фокус получался.
There are a lot of posts complaining about operator overloading.
I felt I had to clarify the «operator overloading» concepts, offering an alternative viewpoint on this concept.
This argument is a fallacy.
It is as easy to obfuscate code in C or Java through functions/methods than it is in C++ through operator overloads:
// C++
T operator + (const T & a, const T & b) // add ?
{
T c ;
c.value = a.value - b.value ; // substract !!!
return c ;
}
// Java
static T add (T a, T b) // add ?
{
T c = new T() ;
c.value = a.value - b.value ; // substract !!!
return c ;
}
/* C */
T add (T a, T b) /* add ? */
{
T c ;
c.value = a.value - b.value ; /* substract !!! */
return c ;
}
For another example, let’s see the Cloneable
interface in Java: http://download.oracle.com/javase/7/docs/api/java/lang/Cloneable.html
You are supposed to clone the object implementing this interface. But you could lie. And create a different object. In fact, this interface is so weak you could return another type of object altogether, just for the fun of it:
class MySincereHandShake implements Cloneable
{
public Object clone()
{
return new MyVengefulKickInYourHead() ;
}
}
As the Cloneable
interface can be abused/obfuscated, should it be banned on the same grounds C++ operator overloading are supposed to be?
We could overload the toString()
method of a MyComplexNumber
class to have it return the stringified hour of the day. Should the toString()
overloading be banned, too? We could sabotage MyComplexNumber.equals
to have it return a random value, modify the operands… etc. etc. etc..
In Java, as in C++, or whatever language, the programmer must respect a minimum of semantics when writing code. This means implementing a add
function that adds, and Cloneable
implementation method that clones, and a ++
operator than increments.
Now that we know that code can be sabotaged even through the pristine Java methods, we can ask ourselves about the real use of operator overloading in C++?
We’ll compare below, for different cases, the «same» code in Java and C++, to have an idea of which kind of coding style is clearer.
// C++ comparison for built-ins and user-defined types
bool isEqual = A == B ;
bool isNotEqual = A != B ;
bool isLesser = A < B ;
bool isLesserOrEqual = A <= B ;
// Java comparison for user-defined types
boolean isEqual = A.equals(B) ;
boolean isNotEqual = ! A.equals(B) ;
boolean isLesser = A.comparesTo(B) < 0 ;
boolean isLesserOrEqual = A.comparesTo(B) <= 0 ;
Please note that A and B could be of any type in C++, as long as the operator overloads are provided. In Java, when A and B are not primitives, the code can become very confusing, even for primitive-like objects (BigInteger, etc.)…
// C++ container accessors, more natural
value = myArray[25] ; // subscript operator
value = myVector[25] ; // subscript operator
value = myString[25] ; // subscript operator
value = myMap[«25»] ; // subscript operator
myArray[25] = value ; // subscript operator
myVector[25] = value ; // subscript operator
myString[25] = value ; // subscript operator
myMap[«25»] = value ; // subscript operator
// Java container accessors, each one has its special notation
value = myArray[25] ; // subscript operator
value = myVector.get(25) ; // method get
value = myString.charAt(25) ; // method charAt
value = myMap.get(«25») ; // method get
myArray[25] = value ; // subscript operator
myVector.set(25, value) ; // method set
myMap.set(«25», value) ; // method set
In Java, we see that for each container to do the same thing (access its content through an index or identifier), we have a different way to do it, which is confusing.
In C++, each container uses the same way to access its content, thanks to operator overload.
The examples below use a Matrix
object, found using the first links found on Google for «Java Matrix object" and «c++ Matrix object":
// C++ YMatrix matrix implementation on CodeProject
// http://www.codeproject.com/KB/architecture/ymatrix.aspx
// A, B, C, D, E, F are Matrix objects;
E = A * (B / 2) ;
E += (A - B) * (C + D) ;
F = E ; // deep copy of the matrix
// Java JAMA matrix implementation (seriously…)
// http://math.nist.gov/javanumerics/jama/doc/
// A, B, C, D, E, F are Matrix objects;
E = A.times(B.times(2)) ;
E.plusEquals(A.minus(B).times(C.plus(D))) ;
F = E.copy() ; // deep copy of the matrix
And this is not limited to matrices. The BigInteger
and BigDecimal
classes of Java suffer from the same confusing verbosity, whereas their equivalent in C++ are as clear as built-in types.
// C++ Random Access iterators
++it ; // move to the next item
--it ; // move to the previous item
it += 5 ; // move to the next 5th item (random access)
value = *it ; // gets the value of the current item
*it = 3.1415 ; // sets the value 3.1415 to the current item
(*it).foo() ; // call method foo() of the current item
// Java ListIterator<E> «bi-directional» iterators
value = it.next() ; // move to the next item & return the value
value = it.previous() ; // move to the previous item & return the value
it.set(3.1415) ; // sets the value 3.1415 to the current item
// C++ Functors
myFunctorObject(«Hello World», 42) ;
// Java Functors ???
myFunctorObject.execute(«Hello World», 42) ;
// C++ stream handling (with the << operator)
stringStream << "Hello " << 25 << « World» ;
fileStream << "Hello " << 25 << « World» ;
outputStream << "Hello " << 25 << « World» ;
networkStream << "Hello " << 25 << « World» ;
anythingThatOverloadsShiftOperator << "Hello " << 25 << « World» ;
// Java concatenation
myStringBuffer.append("Hello ").append(25).append(« World») ;
Ok, in Java you can use MyString = "Hello " + 25 + « World» ;
too… But, wait a second: This is operator overloading, isn’t it? Isn’t it cheating???
:-D
The same generic code modifying operands should be usable both for built-ins/primitives (which have no interfaces in Java), standard objects (which could not have the right interface), and user-defined objects.
For example, calculating the average value of two values of arbitrary types:
// C++ primitive/advanced types
template<typename T>
T getAverage(const T & p_lhs, const T & p_rhs)
{
return (p_lhs + p_rhs) / 2 ;
}
int intValue = getAverage(25, 42) ;
double doubleValue = getAverage(25.25, 42.42) ;
complex complexValue = getAverage(cA, cB) ; // cA, cB are complex
Matrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix
// Java primitive/advanced types
// It won’t really work in Java, even with generics. Sorry.
How that we saw fair comparisons between C++ code using operator overloading, and the same code in Java, we can know discuss the «operator overloading» as a concept.
Even outside of computer science, there are operator overloading: For example, in mathematics, operators like +
, -
, *
, etc. are overloaded.
Indeed, the signification of +
, -
, *
, etc. changes depending on the types of the operands (numerics, vectors, quantum wave functions, matrices, etc.).
Most of us, as part of our science courses, learned multiple significations for operators, depending on the types of the operands. Did we find them confusing, them?
This is the most important part of operator overloading: Like in mathematics, or in physics, the operation depends on its operands' types.
So, know the type of the operand, and you will know the effect of the operation.
In C, the real behavior of an operator will change according to its operands. For example, adding two integers is different than adding two doubles, or even one integer and one double. There is even the whole pointer arithmetic domain (without casting, you can add to a pointer an integer, but you cannot add two pointers…).
In Java, there is no pointer arithmetics, but someone still found string concatenation without the +
operator would be ridiculous enough to justify an exception in the «operator overloading is evil» creed.
It’s just that you, as a C (for historical reasons) or Java (for personal reasons, see below) coder, you can’t provide your own.
In C++, operator overloading for built-in types is not possible (and this is a good thing), but user-defined types can have user-defined operator overloads.
As already said earlier, in C++, and to the contrary to Java, user-types are not considered second-class citizens of the language, when compared to built-in types. So, if built-in types have operators, user types should be able to have them, too.
The truth is that, like the toString()
, clone()
, equals()
methods are for Java (i.e. quasi-standard-like), C++ operator overloading is so much part of C++ that it becomes as natural as the original C operators, or the before mentioned Java methods.
Combined with template programming, operator overloading becomes a well known design pattern. In fact, you cannot go very far in STL without using overloaded operators, and overloading operators for your own class.
Operator overloading should strive to respect the semantics of the operator. Do not substract in a +
operator (as in «do not substract in a add
function», or «return crap in a clone
method»).
Cast overloading can be very dangerous because they can lead to ambiguities. So they should really be reserved for well defined cases. As for &&
and ||
, do not ever overload them unless you really know what you’re doing, as you’ll loose the the short circuit evaluation that the native operators &&
and ||
enjoy.
Because James Gosling said so:
I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++.
James Gosling. Source: http://www.gotw.ca/publications/c_family_interview.htm
Please compare Gosling’s text above with Stroustrup’s below:
Many C++ design decisions have their roots in my dislike for forcing people to do things in some particular way […] Often, I was tempted to outlaw a feature I personally disliked, I refrained from doing so because I did not think I had the right to force my views on others.
Bjarne Stroustrup. Source: The Desing and Evolution of C++ (1.3 General Background)
Some objects would greatly benefit from operator overloading (concrete or numerical types, like BigDecimal, complex numbers, matrices, containers, iterators, comparators, parsers etc.).
In C++, you can profit from this benefit because of Stroustrup’s humility. In Java, you’re simply screwed because of Gosling’s personal choice.
The reasons for not adding operator overloading now in Java could be a mix of internal politics, allergy to the feature, distrust of developers (you know, the saboteur ones that seem to haunt Java teams…), compatibility with the previous JVMs, time to write a correct specification, etc..
So don’t hold your breath waiting for this feature…
Yeah…
While this is far from being the only difference between the two languages, this one never fails to amuse me.
Apparently, the C# folks, with their «every primitive is a struct
, and a struct
derives from Object», got it right at first try.
А сигналом рожать перелетное потомство является количество саранчи на поле. И определяет его саранча на глаз — по числу саранчиных рыл. Поэтому достаточно расставить вокруг саранчи кучку зеркал, как она решит, что пора сваливать. Научно доказанный факт.
Вы понимаете, да? Саранча оглядывается и думает: «Блять, какое ужасное мудачье! Пора валить из этой страны!» А вокруг — зеркала, зеркала, зеркала…
>5-дневное путешествие по России на военном сверхзвуковом самолёте
Камаз-самалёт?
science_freaks: Из чего делают самый дорогой кофе?
The merge program supplied with RCS gives more complete conflict markers than the default install if you give it the -A option. For your .hgrc:
[merge-tools] filemerge.executable = /usr/bin/merge filemerge.args = -A $local $base $other
See also MergingManuallyInEditor.
![]() |
|
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
return x*(1.5f - xhalf*x*x);
}