The further notes use links to the textbook Physics, Pearson Education Canada 2009
Chemistry Zumdahl, 7 ed. Houghton Mifflin Company Boston New York
Алхимия как род науки появилась до Химии. При дворах богатых вельмож иногда по приглашению Алхимики организовывали свои лаборатории.
Современная Химия изучает процессы круговорота химических элементов в природе. Хороший пример – из семени произрастает растение. Растение является фабрикой берущей из почвы воду и из воздуха углекислый газ и производящей белки, жиры, крахмал, сахар, витамины.
Понятие структуры и иерархии элементов, которое использовали Алхимики, есть и в современной химии. В молекуле ДНК, которую изучает биологическая химия 4 уровня представления структур.
На каждом из уровней молекула может подвергаться воздействию путем изменения физических параметров. Например при нагревание белок из яйца меняет свой цвет и становиться твердым, а при взбивании с сахаром – так же меняются физические свойства. Если мы поместим в печку взбитый с сахаром белок то получим хрупкое печенье. Изначально в белке нет большого содержания сахара, но человек может добавить сахар добытый благодаря переработке сахарного тростника.
Часть химических реакций протекает гораздо лучше при наличие катализаторов (специальных химических соединений, ускорящих реакцию), электричества или определенных физических параметров (давление, плотность, температура, объем, наличие электрического потенциала или магнитного поля, ультразвука).
Например в известной реакции химического маятника Белоусова-Жаботинского (автоколебательная реакция ферриин ↔ ферроин), если заморозить раствор в определенной цветовой фазе (вязкость при этом возрастет), то химический маятник можно тормозить и ускорять магнитным полем. Такое воздействие может быть ключем к управлению биологическими химическими процессами.
Сейчас выпускается множество искусственных веществ, которые вырабатываются из нефти, газа и каменного угля. Именно из каменного угля с использованием дополнительной энергии в Моде алхимия мы можем получить искусственный Бриллиант идентичный обычному алмазу, добываемому в шахтах.
Попробуем создать Бриллиант с помощью алхимического оборудования. Для этого надо разложить химический элемент содержщий карбон (каменный уголь) на составляющие. Выбрать 8 стаков по 64 карбона и при наличии прибора Химический Синтезатор синтезировать брильянт, выложив их по кругу.
Надо разделять состояние вещества. Газообразное, жидкое и твердое. Так же огонь мы относим к четвертому состоянию – плазма. Жидкие и газообразные вещества состоят из молекул. Вещества с кристаллическими решетками (например, кварц) состоят из атомов (кремния, связанные химически с атомами кислорода).
Одинаковыми ли физическими свойствами обладают кристаллы сахара полученные из различных источников – из сахарного тростника, из алхимической машины или колдуньи (страница 25 химического учебника)?
Современные машины по преобразованию веществ и энергии строятся из сверхчистых веществ (вещества, в которых доля примеси – доля посторонних атомов и молекул в которых не привышает одной миллионной процента 1/1 000 000). Такая чистота вещества необходима чтобы микроявления, такие как поглощение фотона стали заметны на микроуровне. При подобной чистоте на один миллиметр материала попадает не более 100 атомов примеси.
Именно поэтому каждая алхимическая машина состоит из кристалла, блока кристалов, либо редких минералов типа обсидиана, которые можно добыть только с помощью алмазной кирки (на которую уходит 3 алмаза). Для своей работы по преобразованию веществ большинство алхимических установок требует эенргии.
Каждая алхимическая машина должна быть подключена к источнику Майнкрафт RF энергии.
На 3 странице учебника Химии можно посмотреть типичные химические уравнения для Электролизера.
Сколько молекул воды потребуется для получения одной молекулы водорода и одной молекулы кислорода?
С помощью этого устройства можно разлагать металлы в кислотной среде с помощью увеличения скорости движения йонов под действием электрического тока.
Требуется 2 кварцевых блока (8 блоков кварцевой руды), 2 слитка золота, 4 слитка железа и 1 поршень.
Алхимический растворитель веществ или химическая цинтрифуга. Позволяет разлагать любые вещества на составляющие химические чистые вещества. Для постройки этой машины нужно 2 поршня, 6 слитков железа, Magma block ( 4 Magna cream).
Magma ball состоит из Огненного порошка и Рисового шарика.
Для получения Рисового шарика требуется металлическое ведро на которое уходит 3 слитка железа, но ведро многоразовое его можно использовать для доения коров, доставки воды в кофе машину (хотя у нас есть специальная машина для выкачивания воды из водоема – можно сказать насос водный), для переноса Лавы в печь или для лавого генератора энергии.
Вот так можно приготовить Рисовое тесто для Рисового шарика.
Вещества в природе не являются чистыми. Обычно это смесь веществ. Тип смеси бывает различный например суспензия или раствор.
Хороший пример смеси это молоко, под микроскопом видно что это частички жира плавающие в жидкости (p. 490 учебника по Химии).
В смесях физические свойства отдельных веществ сохрняются. Вещества в смеси порошка можно разделить если одно вещество тонет в воде а другое плавает, или если одно притягивается магнитом а на другое вещество магнитное поле не действует (Страница 26 учебника по Химии).
Можно с помощью фильтра выделить из раствора сахар?
Физическими явлениями называют те при которых не происходит преврашение одних веществ в другие. Химический комбинатор напротив создан именно для превращения одних веществ в другие химическим (алхимическим игровым) путем.
Пример химической реакции в Майнкрафте, если мы возмем дерево и обозжем его в печи, то мы получим каменный уголь. Древесина сгорая превращаеся в воду и углекислый газ. Кроме того, в этой реакции после затрат энергии на возгарание, происходит выделение энергии достаточное для самоподдержания реакции горения до тех пор пока не закончиться уголь. Таким образом с помощью алхимических установок можно получить больше ресурсов и больше энергии, чем с помощю обычных ванильных печей или обычного крафтинга. Газ и примеси из смесей улавливаюся в алхимических установках и формируют побочные блоки вещества. Побочные вещества так же можно использовать в разнообразных химических превращениях веществ.
Химический синтезатор веществ требует для постройки 1 бриллиант (не волнуйтесь с помощью этой машины вы можете сделать столько бриллиантов на сколько у вас хватит угля и других материалов его содержащих), 1 блок Обсидиана (если вы построите этот прибор то сможете сгенирировать любое количество блоков Обсидиана если у вас будут исходные химические вещества для него), 1 Поршень и 6 слитков железа.
Обсидиа́н или вулканическое стекло — магматическая горная порода, состоящая из вулканического стекла при содержании воды не более 1 %; однородное вулканическое стекло, прошедшее через быстрое охлаждение расплавленных горных пород. Более богатые водой вулканические стёкла, вспучивающиеся при нагревании, относят к перлитам.
Обсидиан состоит из
Оксида Магния (страница 58 учебника по Химии)
Хлорида Калия
Оксида Аллюминия
Диоксида Кремния
И, возможно, других примесей, от которых зависит цвет конкретного образца обсидиана.
Алмаз (Бриллиант) состоит только из Атомов Углерода (на странице 244 учебника по Химии можно посмотреть на кристаллическую решетку алмаза).
Испаритель используется для получения молекул вещества из раствора (не путать со смесью) с помощью их кристаллизации путем испарения связывающей их жидкости раствора. Или другими словами установка осуществляющая процесс фазового перехода жидкого теплоносителя в паробразное и газообразное состояние за счет подвода внешней энергии. Если процесс происходит на поверхности – то это испарение, если во всей глубине жидкости с образованием паровых пузырьков – то это называется кипение.
Чем смесь отличается от раствора (страница 25 учебника по химии)?
Испаритель – просто каменная ванна заполненная нагреваемой водой и покрытая металлическим сосудом вогнутой формы в которой под воздействием энергии нагревателя (может быть огонь или электрическая энергия. Для микронагревания хорошо подходит лазерный нагреватель.
В результате работы испарителя на стенках металлического сосуда образуются кристаллы вырастающие из раствора налитого в сосуд.
Если перемешать сахор с водой – то мы получим раствор. Кристаллы сахара можно получить обратно из раствора сахара испарив воду. Кроме того на вкус это сладкая жидкость.
Частички сахара не возможно увидеть в растворе сахара под микроскопом. Так как сахар разделяется на молекулы, которые распределяются между молекулами воды.
Загадочность химических реакций образовли позволили Алхимикам стяжать денежные средства у покровителей и образовать культы и окультные учения наподобие Герметической философии (страница 39, 40, 46, 47 учебника Химии).
Можно ли сфотографировать атомы и молекулы (страница 2 учебника Химии)?
Изумрудная скрижаль гласит: «То, что находится внизу, аналогично тому, что находится наверху». Действительно нижний мир в Майнкрафте аналогичен верхнему. Для того чтоб попаст в нижний мир, надо построить портал из Обсидина и запустить реакцию горения с помощью огнива.
Ответы:
одинаковыми
2 молекулы воды.
Сахар выделить фильтрованием из раствора нельзя.
В растворе вещество раздроблено на отдельные молекулы.
Сфотографировать можно атомы будут выглядеть как расплывчатые пятна, а молекулы как сочетания таких пятен.
Для фотографирования нужен Микроскоп – который можно найти в нашем моде Minechem v6.
https://drive.google.com/file/d/19hfwx_TQqHoNURyEpq4Si7Vpv2VmJ7sX/view?usp=sharing
In PostgreSQL, we create the insikt database and restore the tables from the dump.
Keystore db
Also is needed restore the keystore db.
We need in our local restore it from a dump with
pg_restore -h {ip} -U postgres -W insikt1.sql -d insikt
Note: Database must be already created
systemctl enable systemd-resolved
systemctl start systemd-resolved
https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html
sudo docker run -p 9200: 9200 -p 9300: 9300 -e “discovery.type = single-node” docker.elastic.co/elasticsearch/elasticsearch∗.6.15
After this we need to go to Kibana though browser in IP_SERVER: 5601
Once Kibana is loaded go to the sidebar menu and click on Dev Tools.
You will see kibana console
Open kibana (/ app / kibana # / dev_tools / console? _G = ())
Dev Tools – Console
Insert script code
PUT demo
{
“settings”: {
“number_of_shards”: 6,
“number_of_replicas”: 1,
“analysis”: {
“analyzer”: {
“default”: {
“type”: “standard”,
“tokenizer”: “lowercase”,
“filter”: [
“asciifolding”
]
}
}
},
“index.requests.cache.enable”: true
},
“mappings”: {
“tweet”: {
“_source”: {
“enabled”: true
},
“properties”: {
“analysis”: {
“properties”: {
“threatScore”: {
“type”: “long”,
“doc_values”: true
},
“concepts”: {
“properties”: {
“concept”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“docSentiment”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“emotions”: {
“properties”: {
“emotion”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“entities”: {
“type”: “nested”,
“properties”: {
“entity”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“entityType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“type”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“hashtags”: {
“properties”: {
“text”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“keyIdeas”: {
“properties”: {
“keyIdea”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“topics”: {
“type”: “nested”,
“properties”: {
“topic”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“category”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
}
}
},
“createdAt”: {
“type”: “date”,
“index”: true,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“detectedLang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“geoLocation”: {
“properties”: {
“latitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
}
}
},
“coordinates”: {
“index”: true,
“type”: “geo_point”
},
“geoname”: {
“properties”: {
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“geonameid”: {
“type”: “integer”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“hashtagEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“idLong”: {
“type”: “long”,
“doc_values”: true
},
“mediaEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“mediaURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“mediaURLHttps”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
},
“place”: {
“properties”: {
“boundingBoxCoordinates”: {
“properties”: {
“latitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
}
}
},
“boundingBoxType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“country”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“fullName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“placeType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“retweetedStatus”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“index”: true,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“geoLocation”: {
“properties”: {
“latitude”: {
“type”: “double”,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“doc_values”: true
}
}
},
“hashtagEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“mediaEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“mediaURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“mediaURLHttps”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
},
“place”: {
“properties”: {
“boundingBoxCoordinates”: {
“properties”: {
“latitude”: {
“type”: “double”,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“doc_values”: true
}
}
},
“boundingBoxType”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“country”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“fullName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“placeType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“source”: {
“type”: “keyword”,
“index”: true
},
“symbolEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: true
}
}
},
“text”: {
“type”: “keyword”,
“index”: true
},
“urlEntities”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“user”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“description”: {
“type”: “keyword”,
“index”: true
},
“favouritesCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“followersCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“friendsCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“lang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“location”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“fields”: {
“raw”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“profileImageUrl”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“statusesCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“userMentionEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“id”: {
“type”: “long”,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
}
}
},
“savedAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“source”: {
“type”: “keyword”,
“index”: true
},
“symbolEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”
}
}
},
“text”: {
“type”: “keyword”,
“index”: true
},
“unifiedText”: {
“type”: “text”,
“index”: true
},
“unifiedUrls”: {
“type”: “keyword”
},
“urlEntities”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“user”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“description”: {
“type”: “keyword”,
“index”: true
},
“favouritesCount”: {
“type”: “long”,
“doc_values”: true
},
“followersCount”: {
“type”: “long”,
“doc_values”: true
},
“friendsCount”: {
“type”: “long”,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“lang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“location”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“fields”: {
“raw”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“profileImageUrl”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“statusesCount”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“urlEntity”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
}
}
},
“userMentionEntities”: {
“properties”: {
“end”: {
“type”: “long”
},
“id”: {
“type”: “long”
},
“name”: {
“type”: “keyword”
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“start”: {
“type”: “long”
}
}
}
}
}
}
}
sudo apt install python-pytest python-elasticsearch
Inside the script, I switched the ES_CONN variable to the IP address 172.18.0.2
python test_smoke.py
Check
GET demo / _search
{
“query”: {
match_all: {}
}
}
There is a file in the tmp / pyalerts directory, you need to comment out the creation of indexes (if this file is used for the first time)
mysql-tested.sql
Run the command, write to the password request: test
mysql -h 172.18.0.4 -u test -p insikt <mysql-tested.sql
Then go to the MySQL console and create 2 more tables:
mysql -h 172.18.0.4 -u test -p insikt
CREATE TABLE language (id INT auto_increment PRIMARY KEY, name text, status tinyint (1));
CREATE TABLE network_analysis (id INT auto_increment PRIMARY KEY, project_id VARCHAR (256) DEFAULT NULL, start date, end date, source varchar (1000), status tinyint (4));
sudo docker logs deploy_backend_1
sudo docker logs deploy_frontend_1
sudo docker ps
Container list
ps axf
you can see the list of converters in the process
docker restart – restart the container in memory
docker update – with updating parameters
sudo docker exec -it {container_name} bash
go inside the container
DB_PASS_POSTGRESQL = “Pbdivbknn123”
Setting up postgress on locahost
How to allow remote connections to PostgreSQL database server
register listen_addresses = ‘*’ in /etc/postgres/10/main/postgres.conf
As well as valid IP addresses from which the inputs to the BD are in the /etc/postgres/10/main/pg_hbd.conf file
In the docker-composet.yml file for accessing Kafke containers in broker service environment variables:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT: // broker: 29092, PLAINTEXT_HOST: // broker: 9092
for external access to kafka without a container:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT: // broker: 29092, PLAINTEXT_HOST: // localhost: 9092
System restart
cd deploy
sudo docker-compose down – cut down all containers
sudo docker stop {container name} – stop
sudo docker rm {container name} – delete
sudo docker-compose up -d – run all containers from the docker-composet.yml file
https://streamparse.readthedocs.io/en/stable/quickstart.html
The script for the automatic installation of Storm from the local Linux system via ssh is located in the ~ / tmp / supervisord / storm / storm.py directory
You also need an archive with the Storm distribution version 1.0.6 – c.tar.gz
and the demon archive for running Storm called supervisord – s.tar.gz.
In addition, there is also Oracle Java – jdk-8u192-linux-x64.tar.gz
Both archives are saved in ~ / tmp / supervisord /
To install Java, use the command:
apt install default-jdk
Then for the bundle we put Oracle Java in the / usr / lib / jvm directory next to OpenJdk, sometimes the original Java is more suitable.
To use Oracle Java, it is enough to set the environment variable in the necessary configs:
JAVA_HOME = / usr / lib / jvm / jdk1.8.0_192
Add path PATH = ”/ opt / storm / current / bin: $ PATH” to ~ / .profile
To start storm type:
sudo /etc/init.d/supervisor start
To stop Stopm, the same command as above, with the word stop.
storm version
http://ip:8080/index.html
https://github.com/technomancy/leiningen#leiningen
You do not have to create an additional bin directory in the ~ home directory.
cd ~
mkdir bin
cd ~ / bin
or
cd ~ / .local / bin
wget https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein
chmod + x ~ / bin / lein
or
chmod + x ~ / .local / bin
Further
lein version
sudo pip3 install streamparse
sparse quickstart wordcount
cd wordcount
In the project.clj file, you need to change the version of Storm in line 6:
: dependencies [[org.apache.storm / storm-core “1.0.6”]
Check the performance:
sparse run
To run the task on the Storm cluster, and not on the local library, use the command (IPs configuration is required in the config.json file):
sparse submit
For the first acquaintance with the capabilities of neural networks, this link is suitable:
https://www.tensorflow.org/tutorials/keras/classification?hl=en
Copy the NLP_Engine_v2.tar.gz archive to any place on the disk where there is free space.
Unzip to the same directory. This is important as the model is voluminous:
tar -zxvf NLP_Engine_v2.tar.gz -C.
The extreme point in the command means to unzip to the current directory.
Then you need to install the necessary Python packages:
sudo pip3 install nltk numpy regex stanfordnlp joblib lmdb vaderSentiment polyglot pycld2 morfessor keras tensorflow sklearn elasticsearch pandas
sudo apt install python3-mysql.connector python3-pycurl
Then go to the NLP_Engine_v2 directory and execute the command:
source env / bin / activate
Pay attention to the nlp directory. This is the python module that analyzes.
After that, you need to write the paths for the local python module nlp:
nano nlp_engine / src / bolts / tweet_analysis.py
In another file, you need to correct the environment variables, in principle, if you run through the container, you need to do this in the docker-compose.yml file.
nano nlp_engine/src/spouts/tweets.py
Then go to the nlp_engine directory and run the command:
sparse run
To run on the Storm cluster, you need to adjust the IP addresses in the config.json file and use the command:
sparse submit
To run machine analysis, go to the directory … and run srun.sh
This command can be used to deflate a site. The resulting directories can be used to test containers for parsing to isolate information.
To compile a map or site index, in principle, you can use the standard features of Storm.
If you successfully filter this content, then it can be used to train the neural network.
wget -m -l 10 -e robots = off -p -k -E –reject-regex “wp” –no-check-certificate -U = “Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 68.0.3440.106 Safari / 537.36 “forum.katera.ru
A trained neural network can be used to generate messages to maintain dialogue. For any questions, immediately give a link to the source on this forum.
В PostgreSQL создаём базу данных insikt и востанавливаем таблицы из дампа.
Keystore db
Also is needed restore the keystore db.
We need in our local restore it from a dump with
pg_restore -h 75.126.254.59 -U postgres -W insikt1.sql -d insikt
Note: Database must be already created
systemctl enable systemd-resolved
systemctl start systemd-resolved
https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html
sudo docker run -p 9200:9200 -p 9300:9300 -e “discovery.type=single-node” docker.elastic.co/elasticsearch/elasticsearch:5.6.15
After this we need to go to Kibana though browser in IP_SERVER:5601
Once Kibana is loaded go to the sidebar menu and click on Dev Tools.
You will see kibana console
Открываем kibana (/app/kibana#/dev_tools/console?_g=())
Dev Tools – Console
Вставляем код скрипта
PUT demo
{
“settings”: {
“number_of_shards”: 6,
“number_of_replicas”: 1,
“analysis”: {
“analyzer”: {
“default”: {
“type”: “standard”,
“tokenizer”: “lowercase”,
“filter”: [
“asciifolding”
]
}
}
},
“index.requests.cache.enable”: true
},
“mappings”: {
“tweet”: {
“_source”: {
“enabled”: true
},
“properties”: {
“analysis”: {
“properties”: {
“threatScore”: {
“type”: “long”,
“doc_values”: true
},
“concepts”: {
“properties”: {
“concept”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“docSentiment”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“emotions”: {
“properties”: {
“emotion”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“entities”: {
“type”: “nested”,
“properties”: {
“entity”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“entityType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“type”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“hashtags”: {
“properties”: {
“text”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“keyIdeas”: {
“properties”: {
“keyIdea”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“topics”: {
“type”: “nested”,
“properties”: {
“topic”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“category”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
}
}
},
“createdAt”: {
“type”: “date”,
“index”: true,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“detectedLang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“geoLocation”: {
“properties”: {
“latitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
}
}
},
“coordinates”: {
“index”: true,
“type”: “geo_point”
},
“geoname”: {
“properties”: {
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“geonameid”: {
“type”: “integer”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“hashtagEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“idLong”: {
“type”: “long”,
“doc_values”: true
},
“mediaEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“mediaURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“mediaURLHttps”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
},
“place”: {
“properties”: {
“boundingBoxCoordinates”: {
“properties”: {
“latitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“index”: true,
“doc_values”: true
}
}
},
“boundingBoxType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“country”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“fullName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“placeType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“retweetedStatus”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“index”: true,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“geoLocation”: {
“properties”: {
“latitude”: {
“type”: “double”,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“doc_values”: true
}
}
},
“hashtagEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“mediaEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“mediaURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“mediaURLHttps”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
},
“place”: {
“properties”: {
“boundingBoxCoordinates”: {
“properties”: {
“latitude”: {
“type”: “double”,
“doc_values”: true
},
“longitude”: {
“type”: “double”,
“doc_values”: true
}
}
},
“boundingBoxType”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“country”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“countryCode”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“fullName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“placeType”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“source”: {
“type”: “keyword”,
“index”: true
},
“symbolEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”,
“index”: true
}
}
},
“text”: {
“type”: “keyword”,
“index”: true
},
“urlEntities”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“user”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“description”: {
“type”: “keyword”,
“index”: true
},
“favouritesCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“followersCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“friendsCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“lang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“location”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“fields”: {
“raw”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
}
}
},
“profileImageUrl”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“statusesCount”: {
“type”: “long”,
“index”: true,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“userMentionEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“id”: {
“type”: “long”,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
}
}
}
}
},
“savedAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“source”: {
“type”: “keyword”,
“index”: true
},
“symbolEntities”: {
“properties”: {
“end”: {
“type”: “long”,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“text”: {
“type”: “keyword”
}
}
},
“text”: {
“type”: “keyword”,
“index”: true
},
“unifiedText”: {
“type”: “text”,
“index”: true
},
“unifiedUrls”: {
“type”: “keyword”
},
“urlEntities”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“user”: {
“properties”: {
“createdAt”: {
“type”: “date”,
“doc_values”: true,
“format”: “dateOptionalTime”
},
“description”: {
“type”: “keyword”,
“index”: true
},
“favouritesCount”: {
“type”: “long”,
“doc_values”: true
},
“followersCount”: {
“type”: “long”,
“doc_values”: true
},
“friendsCount”: {
“type”: “long”,
“doc_values”: true
},
“id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“lang”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“location”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“name”: {
“type”: “keyword”,
“index”: true,
“fields”: {
“raw”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
},
“profileImageUrl”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“statusesCount”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“urlEntity”: {
“properties”: {
“displayURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“end”: {
“type”: “long”,
“doc_values”: true
},
“expandedURL”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
},
“start”: {
“type”: “long”,
“doc_values”: true
},
“url”: {
“type”: “keyword”,
“index”: false,
“doc_values”: true
}
}
}
}
},
“userMentionEntities”: {
“properties”: {
“end”: {
“type”: “long”
},
“id”: {
“type”: “long”
},
“name”: {
“type”: “keyword”
},
“screenName”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“start”: {
“type”: “long”
}
}
}
}
}
}
}
sudo apt install python-pytest python-elasticsearch
Внутри скрипта переключил переменную ES_CONN на IP адресс 172.18.0.2
python test_smoke.py
Проверка
GET demo/_search
{
“query”: {
“match_all”: {}
}
}
В директории tmp/pyalerts есть фай, надо закоментить создание индексов (если этот файл используеться впервые)
mysql-tested.sql
Выполнить команду, на запрос пароля написать : test
mysql -h 172.18.0.4 -u test -p insikt < mysql-tested.sql
Затем зайти в консоль MySQL и создать еще 2 таблицы:
mysql -h 172.18.0.4 -u test -p insikt
CREATE TABLE language (id INT auto_increment PRIMARY KEY, name text, status tinyint(1));
CREATE TABLE network_analysis (id INT auto_increment PRIMARY KEY,project_id VARCHAR(256) DEFAULT NULL, start date, end date, source varchar(1000), status tinyint(4));
sudo docker logs deploy_backend_1
sudo docker logs deploy_frontend_1
sudo docker ps
Список контейнеров
ps axf
можно посмотреть список контерйнеров в процессе
docker restart – рестарт контейнера в памяти
docker update – с обновлением параметров
sudo docker exec -it {container_name} bash
заходим внутрь контейнера
DB_PASS_POSTGRESQL = “Pbdivbknn123”
Настройка postgress на locahost
https://bosnadev.com/2015/12/15/allow-remote-connections-postgresql-database-server/
прописать listen_addresses = ‘*’ в /etc/postgres/10/main/postgres.conf
А так же допустимые IP адреса с которых входм в BD в файле /etc/postgres/10/main/pg_hbd.conf
В файле docker-composet.yml для доступа к Kafke контейнеров в переменных окружения сервиса broker:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://broker:9092
для внешнего доступа к кафке без контейнера :
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092
Перезапуск системы
cd deploy
sudo docker-compose down – вырубаем все контейнеры
sudo docker stop {имя контейнера} – остановить
sudo docker rm {имя контейнера} – удалить
sudo docker-compose up -d – запускаем все контейнеры из docker-composet.yml файла
https://streamparse.readthedocs.io/en/stable/quickstart.html
Скрипт для автоматической установки Storm с локальной Линукс системы через ssh находиться в каталоге ~/tmp/supervisord/storm/storm.py
Так же вам нужен архив с дистрибутивом Storm версии 1.0.6 – c.tar.gz
и архив демона для запуска Storm, который называеться supervisord – s.tar.gz.
Кроме того, там же находиться Oracle Java – jdk-8u192-linux-x64.tar.gz
Оба архива сохранены в ~/tmp/supervisord/
Для установки Java используем команду:
apt install default-jdk
Затем для комплекта положим Oracle Java в каталог /usr/lib/jvm рядом c OpenJdk, иногда оригинальный Java больше подходит.
Для использования Oracle Java достаточно задать переменную среды окружения в нужных конфигах:
JAVA_HOME=/usr/lib/jvm/jdk1.8.0_192
Добавить путь PATH=”/opt/storm/current/bin:$PATH” в файл ~/.profile
Для старта storm набрать:
sudo /etc/init.d/supervisor start
Для остановки Stopm такаяже команда как выше, со словом stop.
storm version
http://75.126.254.59:8080/index.html
https://github.com/technomancy/leiningen#leiningen
Можно не создавать дополнительный каталог bin в домашнем каталоге ~.
cd ~
mkdir bin
cd ~/bin
или
cd ~/.local/bin
wget https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein
chmod +x ~/bin/lein
или
chmod +x ~/.local/bin
далее
lein version
sudo pip3 install streamparse
sparse quickstart wordcount
cd wordcount
В файле project.clj надо изменить версию Storm в 6 строчке:
:dependencies [[org.apache.storm/storm-core “1.0.6”]
Проверим работоспособность:
sparse run
Для запуска задачи на кластере Storm, а не на локальной библиотеке используют команду (требуеться конфигурация IPs в файле config.json ):
sparse submit
Для первого знакомство с возможностями нейросетей подойдет вот эта ссылка:
https://www.tensorflow.org/tutorials/keras/classification?hl=ru
Скопировать архив NLP_Engine_v2.tar.gz в любое место на диске, где есть свободное место.
Разархивировать в той же директории. Это важно так как модель объёмная:
tar -zxvf NLP_Engine_v2.tar.gz -C .
Крайняя точка в команде обозначает разорхивировать в текущую директорию.
Затем надо установить необходимы Питон пакеты:
sudo pip3 install nltk numpy regex stanfordnlp joblib lmdb vaderSentiment polyglot pycld2 morfessor keras tensorflow sklearn elasticsearch pandas
sudo apt install python3-mysql.connector python3-pycurl
Затем зайти в каталог NLP_Engine_v2 и выполнит команду:
source env/bin/activate
Обратите внимание на каталог nlp. Это модуль питона который занимаеться анализом.
После этого надо прописать пути для местного питон модуля nlp:
nano nlp_engine/src/bolts/tweet_analysis.py
В другом файле надо подправить переменные среды окружения, в принципе, если запускать через контейнер, это нужно делать в docker-compose.yml файл.
nano nlp_engine/src/spouts/tweets.py
Затем перейдите в каталог nlp_engine и выполните команду:
sparse run
Для запуска на кластере Storm, надо корректировать IP адреса в файле config.json и использовать команду:
sparse submit
Для запуска машинного анализа заходим в каталог … и запускаем srun.sh
docker-compose.yml
| storm: image: storm:latestvolumes:- /home/ubuntu/deploy/storm/suite:/suiteenvironment:- POSTGRES_HOST=postgresql- POSTGRES_PORT=5432 – POSTGRES_DBNAME=inviso – POSTGRES_USER=postgres – POSTGRES_PASS=demo restart: always networks: default: ipv4_address: 172.18.0.25 |
Dockerfile
| FROM ubuntu
RUN mkdir -p /home/ubuntu WORKDIR /home/ubuntu RUN apt-get -y -q update && apt-get install -y wget sudo git libicu-dev python htop curl python3 python3-pip python3-pycurl #INSTALL JAVA 8 COPY jdk1.8.0_192 jdk1.8.0_192 RUN sudo mkdir -p /usr/lib/jvm RUN sudo ln -s /home/ubuntu/jdk1.8.0_192 /usr/lib/jvm/java-8-oracle #STORM COPY apache-storm-1.0.6 apache-storm-1.0.6 COPY nlp nlp COPY nlp_engine nlp_engine RUN sudo echo ‘JAVA_HOME=”/usr/lib/jvm/java-8-oracle”‘ >> /etc/environment RUN echo ‘PATH=”/home/ubuntu/apache-storm-1.0.6/bin:$PATH”‘ >> /etc/environment RUN sudo pip3 install -U git+https://github.com/aboSamoor/polyglot.git@master RUN sudo pip3 install mysql-connector kafka-python streamparse flask nltk numpy regex stanfordnlp joblib lmdb vaderSentiment pycld2 morfessor keras tensorflow sklearn elasticsearch pandas WORKDIR /home/ubuntu RUN wget https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein RUN sudo chmod +x lein RUN sudo cp /home/ubuntu/lein /usr/local/bin ENV JAVA_HOME /usr/lib/jvm/java-8-oracle ENV JAVACMD /usr/lib/jvm/java-8-oracle/bin/java ENV PATH “/home/ubuntu/apache-storm-1.0.6/bin:/usr/lib/jvm/java-8-oracle/bin/:$PATH” ENV LEIN_ROOT true COPY start.sh start.sh CMD bash start.sh |
start.sh
| #!/bin/bash
storm version lein version sparse quickstart wordcount sleep 50000 |
Эту команду можно применить для выкачивания сайта. Полученные директории можно использовать для тестирования контейнеров по парсингу для вычленения информации.
Для составления карты или индекса сайта, в принципе можно использовать стандартные возможности Storm.
Если удачно отфильтровать этот контент, то его можно использовать для обучения нейросетки.
wget -m -l 10 -e robots=off -p -k -E –reject-regex “wp” –no-check-certificate -U=”Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36″ forum.katera.ru
Обученную нейросетку, можно использовать для генерации сообщений для поддержания диалога. При любых вопросах сразу давать ссылку на первоисточних на этом форуме.
Categories (3) Deploy Inviso Created 12 days ago, last updated 8 days ago
Clone repository git clone https://github.com/InsiktIntelligence/insikt-deploy-entrega.git
Create Swarm Now we need to create the swarm nodes (master and slaves) and join them as a cluster Go to insikt-deploy-entrega directory and execute swarm.sh cd insikt-deploy-entrega/ bash swarm.sh
Note: Is recommended that all swarms must have 8GB of memory RAM. Actually in the file some nodes on the swarm have just 4GB because there’s not enough memory on the server which is deployed. Check result:
docker-machine ls
Expected output: Image
Swarm deployment We need to execute swarm.sh file. For this step we need: Configure aws CLI Match swarm certificates directory Check out in which directory is getting configuration source
Configure aws CLI Just execute the next command and follow the steps aws configure
Match swarm certificates directory
In the deploy.sh file, is needed that next constant can search swarm-1 cert
export DOCKER_CERT_PATH=”ABSOLUTE_PATH_TO_CERT”
Note: Normally, cert file is located on ~/.docker/machine/machines/swarm-1
Check out in which directory is getting configuration source
Currently, in the file which creates the services, the paths configuration source are harcoded.
This file is in insikt-deploy-entrega/insikt-swarm/ci/docker-staging.yml
A good example would be: configs:
frontendconfig:
file: /home/ubuntu/tmp/insikt-deploy-entrega/insikt-swarm/config/nginx/nginx.conf kibanaconfig: file: /home/ubuntu/tmp/insikt-deploy-entrega/insikt-swarm/config/kibana/kibana.yml elasticconfig: file: /home/ubuntu/tmp/insikt-deploy-entrega/insikt-swarm/config/elasticsearch/elasticsearch.yml logstashconfig: file: /home/ubuntu/tmp/insikt-deploy-entrega/insikt-swarm/config/logstash/logstash.conf
In this example, the /home/ubuntu/tmp path should be replaced for the good one.
Once all thiese prerequisites are done, we can deploy the services.
In the terminal execute:
eval $(docker-machine env swarm-1)
bash swarm.sh
If all went well, after execute it, the ending of the output in the terminal should be some thing like:
staging_elasticsearch
overall progress: 1 out of 1 tasks
1/1: running [==================================================>]
verify: Service converged
staging_database
overall progress: 1 out of 1 tasks
1/1: running [==================================================>]
verify: Service converged
Expose Swarm nodes
Using iptables
To expose the node to the outside, we need to forward the requests. This should be possible using iptables.
The file port_forward.sh in insikit-deploy-entrea/ adds the rules to iptables.
Note: Before use it, check that the variable wan_addr is your server WAN IP
How it works:
bash port_forward.sh IP_CONTAINER PORT_CONTAINER
Ex: bash port_forward.sh 192.168.99.100 9090
This command will forward the request from your_wan_ip_server:9090 to 192.168.99.100:9090 If does not work If does not work you need to check many things: iptables port forward option is enabled
Check if the option is allowed with sysctl net.ipv4.ip_forward Execute: sysctl net.ipv4.ip_forward Expected output: net.ipv4.ip_forward = 1
If is 0 you must need to execute: sysctl -w net.ipv4.ip_forward=1 printf “net.ipv4.ip_forward = 1” >> /etc/sysctl.conf
There is another firewall In Ubuntu servers must be probable that ufw is enabled. Check it with: Execute: ufw status Expected output: Status: inactive
If is active, execute ufw disable and restart the server.
Python alerts db We go to create the database for alerts in python. First we need to copy the repository git clone https://github.com/InsiktIntelligence/insikt-backend-pyalerts.git
To continue, we need to follow the next steps: Configuration values are retrieved from this config file. Application reads that config file from the path stored within environment variable INSIKT_APP_SETTINGS. If that variable is not set then relative path ../config/default.app.cfg is used. In order to provide your own values for config properties listed within default ./config/default.app.cfg file, make a copy of that file and set path to this copy as value for INSIKT_APP_SETTINGS environment variable. For example, you can create local copy of default config:
cd insikt-backend-pyalerts cp ./config/default.app.cfg ./config/be-local-dev-env.app.cfg export INSIKT_APP_SETTINGS=../config/be-local-dev-env.app.cfg
mysql -h 192.168.99.100 -u test -p insikt < mysql-tested.sql
This will instruct the Flask to read configs from your local copy of default config file. Note, your local copy will not be recognized by git, as there is a gitignore configuration to omit all copies of default config gile, except the default config itself. So, if you need to change some default configuration parameters you will need to edit ./config/default.app.cfg file and commit this changes. You also need to create a table language and network_analysis. CREATE TABLE language (id INT auto_increment PRIMARY KEY, name text, status tinyint(1)); CREATE TABLE network_analysis (id INT auto_increment PRIMARY KEY,project_id VARCHAR(256) DEFAULT NULL, start date, end date, source varchar(1000), status tinyint(4));
Keystore db Also is needed restore the keystore db. We need in our local restore it from a dump with
pg_restore -h 95.216.97.242 -U postgres -W insikt1.sql -d insikt
Note: Database must be already created
Create Elasticsearch demo index We need to expose Kibana with port_foward.sh file bash port_foward.sh 192.168.99.100 5601
After this we need to go to Kibana though browser in IP_SERVER:5601 Once Kibana is loaded go to the sidebar menu and click on Dev Tools. You will see kibana console Image
You need to copy this code to create the demo index.
PUT demo {
“settings”: { “number_of_shards”: 6, “number_of_replicas”: 1, “analysis”: { “analyzer”: { “default”: { “type”: “standard”, “tokenizer”: “lowercase”, “filter”: [ “asciifolding” ] } } }, “index.requests.cache.enable”: true }, “mappings”: { “tweet”: { “_source”: { “enabled”: true },
“properties”: { “analysis”: { “properties”: { “threatScore”: { “type”: “long”, “doc_values”: true }, “concepts”: { “properties”: { “concept”: { “type”: “keyword”, “index”: true, “doc_values”: true } } }, “docSentiment”: { “type”: “double”, “index”: true, “doc_values”: true },
“emotions”: { “properties”: { “emotion”: { “type”: “keyword”, “index”: true, “doc_values”: true } } }, “entities”: { “type”: “nested”, “properties”: { “entity”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “entityType”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “type”: { “type”: “keyword”, “index”: true, “doc_values”: true }
} }, “hashtags”: { “properties”: { “text”: { “type”: “keyword”, “index”: true, “doc_values”: true } } }, “keyIdeas”: { “properties”: { “keyIdea”: { “type”: “keyword”, “index”: true, “doc_values”: true } } },
“screenName”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “topics”: { “type”: “nested”, “properties”: { “topic”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “category”: { “type”: “keyword”, “index”: true, “doc_values”: true } } } } },
“createdAt”: { “type”: “date”, “index”: true, “doc_values”: true, “format”: “dateOptionalTime” }, “detectedLang”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “geoLocation”: { “properties”: { “latitude”: { “type”: “double”, “index”: true, “doc_values”: true }, “longitude”: { “type”: “double”, “index”: true, “doc_values”: true } } }, “coordinates”: {
“index”: true, “type”: “geo_point” }, “geoname”: { “properties”: { “countryCode”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “geonameid”: {
“type”: “integer”, “index”: true, “doc_values”: true }, “name”: {
“type”: “keyword”, “index”: true, “doc_values”: true } } },
“hashtagEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true }, “text”: { “type”: “keyword”, “index”: false, “doc_values”: true } } },
“id”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “idLong”: { “type”: “long”, “doc_values”: true }, “mediaEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “mediaURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “mediaURLHttps”: { “type”: “keyword”, “index”: false, “doc_values”: true },
“start”: { “type”: “long”, “doc_values”: true } } }, “place”: { “properties”: { “boundingBoxCoordinates”: { “properties”: { “latitude”: { “type”: “double”, “index”: true, “doc_values”: true }, “longitude”: { “type”: “double”, “index”: true, “doc_values”: true } } },
“boundingBoxType”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “country”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “countryCode”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “fullName”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“id”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “name”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “placeType”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } },
“retweetedStatus”: { “properties”: { “createdAt”: { “type”: “date”,
“index”: true, “doc_values”: true, “format”: “dateOptionalTime”
}, “geoLocation”: { “properties”: { “latitude”: {
“type”: “double”, “doc_values”: true },
“longitude”: { “type”: “double”, “doc_values”: true } } },
“hashtagEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true }, “text”: { “type”: “keyword”, “index”: true, “doc_values”: true } } }, “id”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“mediaEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “mediaURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “mediaURLHttps”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true } } },
“place”: { “properties”: { “boundingBoxCoordinates”: { “properties”: { “latitude”: { “type”: “double”, “doc_values”: true }, “longitude”: { “type”: “double”, “doc_values”: true } } }, “boundingBoxType”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “country”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“countryCode”: { “type”:”keyword”, “index”: true, “doc_values”: true }, “fullName”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “id”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “name”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“placeType”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } }, “source”: { “type”: “keyword”, “index”: true }, “symbolEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true },
“start”: { “type”: “long”, “doc_values”: true }, “text”: { “type”: “keyword”, “index”: true } } }, “text”: { “type”: “keyword”, “index”: true }, “urlEntities”: { “properties”: { “displayURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “end”: { “type”: “long”, “doc_values”: true },
“expandedURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } },
“user”: { “properties”: { “createdAt”: { “type”: “date”, “doc_values”: true, “format”: “dateOptionalTime” }, “description”: { “type”: “keyword”, “index”: true }, “favouritesCount”: { “type”: “long”, “index”: true, “doc_values”: true }, “followersCount”: { “type”: “long”, “index”: true, “doc_values”: true },
“friendsCount”: { “type”: “long”, “index”: true, “doc_values”: true }, “id”: {
“type”: “keyword”,
“index”: true,
“doc_values”: true
},
“lang”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “location”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“name”: { “type”: “keyword”, “index”: true, “fields”: { “raw”: { “type”: “keyword”, “index”: true, “doc_values”: true } } }, “profileImageUrl”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “screenName”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“statusesCount”: { “type”: “long”, “index”: true, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } }, “userMentionEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “id”: { “type”: “long”, “doc_values”: true },
“name”: { “type”: “keyword”, “index”: true }, “screenName”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true } } } } }, “savedAt”: { “type”: “date”, “doc_values”: true, “format”: “dateOptionalTime” },
“source”: { “type”: “keyword”, “index”: true }, “symbolEntities”: { “properties”: { “end”: { “type”: “long”, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true }, “text”: { “type”: “keyword” } } }, “text”: { “type”: “keyword”, “index”: true },
“unifiedText”: { “type”: “text”, “index”: true }, “unifiedUrls”: { “type”: “keyword” }, “urlEntities”: { “properties”: { “displayURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “end”: { “type”: “long”, “doc_values”: true }, “expandedURL”: { “type”: “keyword”, “index”: false, “doc_values”: true },
“start”: { “type”: “long”, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } }, “user”: { “properties”: { “createdAt”: { “type”: “date”, “doc_values”: true, “format”: “dateOptionalTime” }, “description”: { “type”: “keyword”, “index”: true },
“favouritesCount”: { “type”: “long”, “doc_values”: true }, “followersCount”: { “type”: “long”, “doc_values”: true }, “friendsCount”: { “type”: “long”, “doc_values”: true }, “id”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “lang”: { “type”: “keyword”, “index”: true, “doc_values”: true },
“location”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “name”: { “type”: “keyword”, “index”: true, “fields”: { “raw”: { “type”: “keyword”, “index”: false, “doc_values”: true } } }, “profileImageUrl”: { “type”: “keyword”, “index”: false, “doc_values”: true },
“screenName”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “statusesCount”: { “type”: “long”, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “urlEntity”: { “properties”: { “displayURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “end”: { “type”: “long”, “doc_values”: true },
“expandedURL”: { “type”: “keyword”, “index”: false, “doc_values”: true }, “start”: { “type”: “long”, “doc_values”: true }, “url”: { “type”: “keyword”, “index”: false, “doc_values”: true } } } } },
“userMentionEntities”: { “properties”: { “end”: { “type”: “long” }, “id”: { “type”: “long” }, “name”: { “type”: “keyword” }, “screenName”: { “type”: “keyword”, “index”: true, “doc_values”: true }, “start”: { “type”: “long” } } } } } }
}
Create a new project Once ES index is created is time to create a Inviso project.
Expose the frontend First we need to expose the Inviso frontend to login in the app.
bash port_forward.sh 192.168.99.100 443
And go to the next url: https://SERVER_IP
You will see the login screen Image Login with: User: parronator Password: 123456Aa
Once you are logged, follow the next steps to create a project Click on the button Add a new project Key project Fill the options project as you prefer, but twitter must be selected from Sources option Click on Create button
You will see a green toast pointing that project was created and you will redirect to projects dashboard with the new project created Image
Load test data
In insikt-deploy-entrega/ directory, there is a fille named test_smokees.py. You just need to execute it with:
python test_smokees.py
Note: If you get a “Magic numbers” error, you must delete the file with .pyc extension in the same directory as test_smokees.py file. You can use find . -name \*.pyc -delete Also inside test_smokees.py, delete: from insiktes import search, search2, search4, search_top, \ mysql_elk, get_id_list, get_source_list, get_top_list, notification To check if it works you just need to go to Dev Tools in Kibana and execute: GET demo/_search { “query”: { “match_all”: {} }
}
If worked, you must get results at in total of hits with at least 32 Image 0 comments
SOLID – Single responsibility, Open–closed, Leaf substitution, Interface segregation и Dependency inversion
SRP – Let’s take an example Active Oberon and take into account my classification of functions (first 4 levels).
const moduleA = {state: {}, - FSMmutations: {}, - switchactions: {}, - parsergetters: {}- repository} const moduleB = { state: {}, mutations: {}, actions: {}, getters: {} } const store = new Vuex.Store({ modules: { a: moduleA, b: moduleB } })store.state.a // -> module state moduleAstore.state.b // -> module state moduleB
SpringBootGraphQL/Feed.java at main · Ignat99/SpringBootGraphQL (github.com)
So, Lombok + Feing
https://objectcomputing.com/resources/publications/sett/january-2010-reducing-boilerplate-code-with-project-lombok
https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html
1. Object oriented ( the suffix is added to the roots КА)
2. FSM - state machine or (ЦА)
3. Parallel computing as Zenon (ЛА) ----------------------------------------------
4. Parsing (P)
5. Registers and DMA (ИТЬ)
6. Timing diagrams as in Buran (ТИ)
7. Data storage or writing to database(ХО)
Buran ciclogram:![]()
OCP – it’s easier to consider using the example of 3 multiplication tables among Old Believers (на, же, и)
на – normal multiplication of numbers
же – three-dimensional multiplication
и – time multiplication
If we want to implement all three multiplication tables, we will inherit from the class НА through class ЖЕ to the class И.
If we want to keep the interfaces, then this will be polymorphism.
LSP – this leaf-substitution principle will require some hierarchy of functions. For example, the stacking function will be common for all cells, but if the cells intersect, then contracts will be required to obtain the final result in the case of using leaf.
ISP – so that there are not many arguments in the constructor, it is better to refactor a large class in such a way that in each interface there is an implementation of only one level of the above, then at the upper levels (starting from Registered Transfers or Brokers or Tires or SOA/SOAP).
DIP – here we are talking about the interaction of objects \ perdmet through abstract interfaces, which, as it were, provide an interaction environment at each level. In fact, the complete set of these interfaces can be put into a matrix, and then optimized based on domain analysis (combined in pairs or three at a time, under the condition of uniformity of arguments in the constructor).
The object-oriented paradigm is a concept based on the C language precompiler, which combined variables and functions (methods) into a single structure. Moreover, due to the complication of linking, memory savings were achieved. In particular, various departments have been added for the new type of code. Later, mechanisms for dynamic linking of libraries and directives to the precompiler related to allocation in memory and the work of the garbage collector were added. In order to add modular architecture, the ability to define a namespace has been added. The combination of all these additions led to the emergence of templates, especially in conjunction with the implementation of the STL library – which was borrowed from Lisp and was very convenient in the 2000s for implementing vector and matrix objects.
Based on all these innovations, design patterns emerged.
So, for example, from the global variables of the SI – sigletons turned out. Their difference from just global variables is that in the additional Boost library, references to the allocated memory areas were automatically counted, and when the reference counter was zeroed, the object was automatically deleted.
Hashes were often used for associative storage of string data with access by a string key, so they began to make registries, which, however, could be combined into trees or pools. Now brokers are already used for this, since all this must still be done asynchronously and in a thread.
In particularly severe cases of full-text fast search, they now use ElasticSearch or PostgreSQL with a tree inverse index.
After the spread of local networks, the temptation arose to run functions on one microprocessor, and execute on another remote. This is how the patern factory came into being.
But there was a problem with long names of different classes on different machines, so the builder pattern arose. It’s just a chain of different operations that we can put into a conveyor or a factory method.
Etc. – lazy initialization, injected dependency, service locator. Adapter, bridge, linker, decorator, facade, single point of entry, opportunist, proxy. Chain of Responsibility, Action, Interpreter, Iterator, Mediator, Keeper, Listener, Bulletin Board, Sideboard, State, Strategy, Specification, Catheterization, Visitor and One-Time Visitor, Hierarchical Visitor (for working with trees and subtrees – just making sense of heap sort).
It arose on the basis of the LISP language, which became possible due to the presence of a hardware implementation of the FILO call address stack instead of a queue. This was done to reduce the size of the typed code, before that they practiced the sewing code on the FIFO. Later, not only return addresses, but also variables were transferred to the stack. This is how the Fort language arose, which is still perfectly used on processors with a stack architecture. In this language, we explicitly define the depth of the substack for variables.
As you know, real programmers do not use not only the stack, but also general registers. This is a joke, in fact, such a programmer was the only one, and apparently he was a genius.
Thus, if one function changes variables in another function, confusion can arise when these functions are called repeatedly when returning values from the stack at the return point of the function. To prevent this from happening, now hypervisors are used on AMD and Intel microprocessors, which save absolutely all state registers of the microprocessor automatically.
But you can do without a hypervisor if you define a complete list of passed arguments in the function and return all of them when the function finishes executing. Thus, the function does not in any way affect the environment and does not store any states inside itself.
A further development of this direction is free grammars, but unfortunately, their full implementations in the form of a Mealy automaton are quite cumbersome, in contrast to Markov chains of a Moore automaton. Therefore, we are waiting for the quantum computer to become personal and that’s where we will expand. Joke 🙂
Java is a very good programming language that supports multiple inheritance and many other features. We have been using it for 20 years since the creation of this language at Sun Microsystems. The main feature, according to the creators, of the language was a single microcode. Such a pseudo-assembler, somewhat close to the modern assembler of ARM microprocessors. As you might have guessed, these microprocessors were extensions of the stack architecture.
More precisely, it was scaling (when simple stacked microprocessors were put in several pieces in a line and a pipeline or RISC architecture was obtained). They also had more registers and a register window, that is, small changes in the addressing logic (in the MIPS architecture). But they did not have hardware instructions for multiplication and division.
Also, the Java language has a very large machine word, which makes it possible to allocate memory at the compilation stage. Which makes garbage collection easier. In general, these systems were created for the design of larger microprocessors, since the cost of addressing errors in memory while working in such programs is very high.
Unfortunately, the creator of the language made a mistake and we got a lot of JVMs of virtual machines and even families of virtual machines. And in general Java bytecode is not portable.
Java provides a new additional package in Java 8 called java.util.stream.
It is a Pipeline that does not store objects. You can use stream to filter, collect, print, and convert from one data structure to other etc.
https://www.javatpoint.com/kafka-streams-vs-spark-streaming
To save objects for 2 weeks (approximately), you can use Kafka.
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet)
https://www.javatpoint.com/collections-in-java
Two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap.
These are functionals when arguments of the same function are passed to the input of a function. This is especially developed in Kotlin. Such implementations also resemble JS.
https://www.javatpoint.com/kotlin-higher-order-function
It’s a good language, but building its implementation for SmartTV was a chore, since the options to the compiler compiler were tricky for a number of functions.
(I am for a creative approach to the task, otherwise it is too simple. As well as the idea to take everything ready. Be sure to add your own perspective based on your own experience.)
We have a list of airports in major cities. There may be our clients from these cities who will undergo remote training courses before arriving in Spain.
We have an Artificial Intelligence network that regularly analyzes all the statements of each of our students. We are developing a REST API service in Python that will analyze the received data and identify the demand for new training courses among residents of different age groups in different cities through advertising channels.
Let’s implement the following handlers in the service:
OPTIONS /:entity[/:id] Gets a list of methods available at the given URI. The server should respond with 200 OK with an additional Allow header: GET, POST, ...POST /importsGET /imports/$import_id/citizensPATCH /imports/$import_id/citizens/$citizen_idGET /imports/$import_id/citizens/birthdaysGET /imports/$import_id/towns/stat/percentile/agehttps://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=fortune&l=zijzen-1r
asyncpg — A fast PostgreSQL Database Client Library for Python/asyncio (1 000 000 line per second)
asyncpgsa — A python library wrapper around asyncpg for use with SQLAlchemy
aiohttp — as a library for writing an asynchronous framework service, since it generally works 2 times? faster.
aiohttp-spec — binds aiohttp handlers and schemas for data validation. As a bonus, it turned out to generate documentation in the format Swagger and display it in графическом интерфейсе.
aioamqp, a pure-Python AMQP 0-9-1 library using asyncio (source code, docs)
celery – alternative asynchronous library under Python
flask-restx — It is a flask framework with the ability to automatically generate documentation using Swagger.
Apache Kafka — Is an open-source distributed event streaming platform
SQLAlchemy allows you to decompose complex queries into parts, reuse them, generate queries with a dynamic set of fields (for example, a PATCH handler allows partial updating of an inhabitant with arbitrary fields or ElasticSearch reading) and focus directly on the business logic.
Alembic is a lightweight database migration tool for usage with the SQLAlchemy Database Toolkit for Python.
1:33:49 – How to write and test database migrations with Alembic – Alexander Vasin.
Docker (composer and swarm) or Kubernetes (k8s)
Ansible — For deployment, it allows declaratively describing the desired state of the server and its services, works via ssh and does not require special software.
pylint and pytest and unittest
PyCharm
python -m cProfile -o pick.prof -s tottime app.py — Python only profiler.
snakeviz pick.prof — web visualizer.
python3 -m vmprof app.py – profiles C functions.
Threadpool – for reading files asynchronously on Linux.
import tracemalloc
tracemalloc.start()
tracemalloc.take_snapshot()
mprof – graph of memory consumption over time.
Further optimization is to extract a fixed part from the file each time. For example 1024 lines.
uvloop — To connect data loops over the network with PostgreSQL.
Postman — generating API requests.
wget http://nodejs.org/dist/latest/node-v15.2.0-linux-x64.tar.gz
tar -xzf node-v15.2.0-linux-x64.tar.gz
ls mv node-v15.2.0-linux-x64 15.2.0
ln -s 15.2.0/ current
export PATH=”/home/ubuntu/.nodes/current/bin:$PATH”
rm node-v15.2.0-linux-x64.tar.gz
node –version
npm install
sudo apt install python3-pip
sudo pip3 install -e .[dev]
sudo env “PATH=/home/ubuntu/.nodes/current/bin:$PATH” inv assets
http://www.jennifergd.com/post/7/
sudo /etc/init.d/postgresql start
psql -U postgres -h localhost insikt
CREATE TABLE cities (id SERIAL PRIMARY KEY, name VARCHAR(256), city VARCHAR(50), country VARCHAR(50), iata VARCHAR(10), icao VARCHAR(10), latitude FLOAT, longitude FLOAT, altitude FLOAT, timezone FLOAT, dst VARCHAR(10), tz VARCHAR(50), type VARCHAR(50), source VARCHAR(50));
\copy cities(name, city, country, iata, icao, latitude, longitude, altitude, timezone, dst, tz, type, source) FROM 'airports.csv' DELIMITERS ',' CSV HEADER;
SELECT * FROM cities;
sudo apt-get install postgis
psql -U postgres -h localhost insikt
CREATE EXTENSION postgis;CREATE TABLE citiesgeo ( point_id SERIAL PRIMARY KEY, location VARCHAR(30), latitude FLOAT, longitude FLOAT, geo geometry(POINT) );
cities.csv
location, latitude, longitude
San Francisco, 37.773972, -122.43129
Seattle, 47.608013, -122.335167
Sacramento, 38.575764, -121.478851
Oakland, 37.804363, -122.271111
Los Angeles, 34.052235, -118.243683
Alameda, 37.7652, -122.2416
In PostgreSQL shell:
=# \copy citiesgeo(location, latitude, longitude) FROM ‘cities.csv’ DELIMITERS ‘,’ CSV HEADER;
COPY 6
=# SELECT * FROM citiesgeo;
point_id | location | latitude | longitude | geo
———-+—————+———–+————-+—–
1 | San Francisco | 37.773972 | -122.43129 |
2 | Seattle | 47.608013 | -122.335167 |
3 | Sacramento | 38.575764 | -121.478851 |
4 | Oakland | 37.804363 | -122.271111 |
5 | Los Angeles | 34.052235 | -118.243683 |
6 | Alameda | 37.7652 | -122.2416 |
(6 rows)
https://postgis.net/docs/ST_Point.html
=# UPDATE citiesgeo
SET geo = ST_Point(longitude, latitude);
UPDATE 6=# SELECT * FROM citiesgeo;
point_id | location | latitude | longitude | geo
———-+—————+———–+————-+——————————————–
1 | San Francisco | 37.773972 | -122.43129 | 0101000000E1455F419A9B5EC08602B68311E34240
2 | Seattle | 47.608013 | -122.335167 | 0101000000B3EC496073955EC07C45B75ED3CD4740
3 | Sacramento | 38.575764 | -121.478851 | 01010000000B2AAA7EA55E5EC0691B7FA2B2494340
4 | Oakland | 37.804363 | -122.271111 | 01010000007FA5F3E159915EC0658EE55DF5E64240
5 | Los Angeles | 34.052235 | -118.243683 | 0101000000D6E59480988F5DC0715AF0A2AF064140
6 | Alameda | 37.7652 | -122.2416 | 0101000000ACADD85F768F5EC01973D712F2E14240
(6 rows)
We make position in WGS84 format.
=# INSERT INTO citiesgeo (location, latitude, longitude, geo)
VALUES (‘San Rafael’, 37.9735, -122.5311, ST_Point(-122.5311, 37.9735));
INSERT 0 1=# INSERT INTO citiesgeo (location, latitude, longitude, geo)
VALUES (‘San Rafael’, 37.9735, -122.5311, ST_Point(-122.5311, 37.9735));
INSERT 0 1
https://postgis.net/docs/ST_DistanceSphere.html
=# SELECT * FROM citiesgeo WHERE ST_DistanceSphere(geo,(SELECT geo FROM citiesgeo WHERE location = ‘San Francisco’
)) < 83000;
point_id | location | latitude | longitude | geo
———-+—————+———–+————-+——————————————–
1 | San Francisco | 37.773972 | -122.43129 | 0101000000E1455F419A9B5EC08602B68311E34240
4 | Oakland | 37.804363 | -122.271111 | 01010000007FA5F3E159915EC0658EE55DF5E64240
6 | Alameda | 37.7652 | -122.2416 | 0101000000ACADD85F768F5EC01973D712F2E14240
7 | San Bruno | 37.6305 | -122.4111 | 0101000000AED85F764F9A5EC062105839B4D04240
8 | San Rafael | 37.9735 | -122.5311 | 0101000000F5B9DA8AFDA15EC0F853E3A59BFC4240
(5 rows)
ALTER TABLE cities ADD COLUMN geo geometry(POINT);
-# SET geo = ST_Point(longitude, latitude);
UPDATE 7698
sudo python3 setup.py install
screen -dmS abc
screen -r abc
./app.py
Ctr-a d
Some companies work using outdated technologies due to the fact that they hired specialists with limited experience or, more precisely, ordered their systems from outsourcers (for example, from Ukraine). Below is an example of such a deprecated docker-composer.yml MySQL + RabbitMQ configuration.
version: ‘3.4’
services:
database:
image: mysql:5.7.21
ports:
– 3306:3306
environment:
– MYSQL_ROOT_PASSWORD=test
– MYSQL_USER=test
– MYSQL_PASSWORD=test
– MYSQL_DATABASE=mysqltest
volumes:
# – data02:/var/lib/mysql
– /home/ubuntu/opt/docker-volumes/mysql:/var/lib/mysql
networks:
default:
ipv4_address: 172.18.0.4
# rabbitmq:
# image: rabbitmq:3.6.12-management
# hostname: rabbitmq
# volumes:
# – /home/ubuntu/opt/docker-volumes/rabbitmq:/var/lib/rabbitmq
# environment:
# – RABBITMQ_DEFAULT_PASS=admin
# – RABBITMQ_DEFAULT_USER=admin
# – RABBITMQ_DEFAULT_VHOST=/
# ports:
# – 5672:5672
# – 15672:15672
# networks:
# default:
# ipv4_address: 172.18.0.3
This is how kafka containers look like in Docker. Below are the installation instructions:
https://docs.confluent.io/current/quickstart/ce-docker-quickstart.html
Our server:
Then we test and create an asynchronous client.
https://github.com/Ignat99/restx2020
Since we have accumulated many layers and functions. For example API, ORM, business logic, Model, database schema, then for ease of maintenance we will distribute these functions in different modules. Everything could be left in one file. But since we have attached asynchronous processing and work with the Kafka Broker in dedicated threads that are synchronized through Kafka, it is better to separate the modules.
https://gist.github.com/RawToast/feab6b36d2592554d071
sudo psql -U postgres postgres
CREATE DATABASE sonar;
CREATE USER sonar WITH PASSWORD ‘verysecret’;
GRANT ALL PRIVILEGES ON DATABASE sonar TO sonar;
cd /opt
sudo wget https://binaries.sonarsource.com/CommercialDistribution/sonarqube-developer/sonarqube-developer-8.5.1.38104.zip
sudo unzip sonarqube-developer-8.5.1.38104.zip
sudo mv sonarqube-8.5.1.38104/ sonarqube
or
git clone https://github.com/SonarSource/sonarqube
cd sonarqube/
./gradlew build
or
sudo docker run -d –name sonarqube -p 9000:9000 -e SONARQUBE_JDBC_USERNAME=sonar
-e SONARQUBE_JDBC_PASSWORD=verysecret -e SONARQUBE_JDBC_URL=jdbc:postgresql://localhost:5432/sonar –net mynet sonarqube:7.5-community
sudo docker exec -it -u root sonarqube /bin/bash
sudo sysctl -w vm.max_map_count=262144
cd /opt/sonarqube
sh bin/linux-x86-64/sonar.sh start
netstat -tap
tcp6 0 0 [::]:9000 [::]:* LISTEN 5819/java
https://github.com/Ignat99/a_proxy
https://github.com/Ignat99/JSON_Test/blob/master/test_json.py
sudo pip3 install nose coverage nosexcover pylint
sudo pip3 install pylint_flask_sqlalchemy
sudo pip3 install pylint-flask
pylint –generate-rcfile > pylintrc
pylint passnfly/
To see duplicate lines and test coverage in SonarQube:
./coverage.sh
pytest -s –junitxml=pytests.xml –cov-report xml –cov-report term –cov-branch –cov=passnfly tests/

../sonar-scanner/bin/sonar-scanner -Dsonar.projectKey=passnfly1 -Dsonar.sources=. -Dsonar.host.url=http://75.126.254.59:9000 -Dsonar.login=cf56501e7eca2051eb7510911ceec0b4e8b1cf66
http://75.126.254.59:9000/dashboard?id=passnfly1
https://github.com/Ignat99/restx2020/blob/main/passnfly/api/aiokafka/todo.py
In this part of our backend, a special class of Threads in debug mode is implemented, which allows stopping the child from the parent thread based on its name.
As the identifier of the asynchronous process, we use the hash that we generated for the partition of this topic in Kafka.
https://github.com/Ignat99/restx2020/blob/main/passnfly/api/aiokafka/todo.py#L111
All this gives great flexibility up to managing the entire banned by using the REST API from one of the threads.
Here we make sure that one thread is launched per task.
https://github.com/Ignat99/restx2020/blob/main/passnfly/api/aiokafka/todo.py#L122
The duration of our stream can be up to 2 weeks and is limited by the Kafka settings. Every 2 weeks, the oldest data in our partition is released. If our service did not manage to process the data in 2 weeks (it can be reconfigured in Kafka), then this data should be stored in longer storages, such as S3 / Hadoop. There is an old driver for RabbitMQ, but it doesn’t work well.
https://docs.confluent.io/clients-confluent-kafka-python/current/index.html
https://kafka-python.readthedocs.io/en/master/usage.html
https://github.com/Ignat99/restx2020/tree/main/tests/api
https://riptutorial.com/flask/example/5622/testing-a-json-api-implemented-in-flask
https://flask.palletsprojects.com/en/1.1.x/testing/
Как Kafka стала былью / Блог компании Tinkoff / Хабр (habr.com)
Will help client.id for Producer and Consumer. It is best to use a combination of the application name and, for example, the topic name as the client.id value.
Kafka Producer has the acks parameter that allows you to configure after how many acknowledge the cluster leader should consider the message as successfully written. This parameter can take the following values:
0 – acknowledge will not be counted.
1 – default parameter, acknowledge only from 1 replica is required.
−1 – acknowledge from all synchronized replicas are required (cluster setting min.insync.replicas).
From the listed values, it can be seen that acks equal to -1 gives the strongest guarantees that the message will not be lost.
As we all know, distributed systems are unreliable. To protect against transient faults, Kafka Producer provides a retries parameter that allows you to set the number of retry attempts during delivery.timeout.ms. Since the retries parameter has a default value of Integer.MAX_VALUE (2147483647), the number of retransmissions of a message can be adjusted by changing only delivery.timeout.ms. In some cases, this will be more convenient due to the fact that Producer will make the maximum number of re-submissions within the specified time interval. We set the interval to 30 seconds.
Kafka — Idempotent Producer And Consumer | by Sheshnath Kumar | Medium
In the simplest case, for this on the Producer, you need to set the enable.idempotence parameter to true. Idempotency guarantees that only one message is written to a specific partition of one topic. The precondition for enabling idempotency is the values acks = all, retry> 0, max.in.flight.requests.per.connection ≤ 5. If these parameters are not specified by the developer, the above values will be automatically set.
Producer:
Consumer:
KIP-98 perf testing – Google Sheets
For 1K messages and transactions lasting 100ms, the producer bandwidth is reduced by:
3% compared to its performance when it is configured for at least once in-order delivery (acks = all, max.in.flight.requests.per.connection = 1),
by 20% compared to its operation when configured to at most once without respecting message order (acks = 1, max.in.flight.requests.per.connection = 5) is used by default.
Exactly Once Delivery and Transactional Messaging in Kafka – Google Docs
KIP-129: Streams Exactly-Once Semantics – Apache Kafka – Apache Software Foundation
Access control is configured on your cluster.
transactional.id.expiration.ms, which is configured on the Kafka cluster and has a default value of 7 days.
git clone https://github.com/edenhill/librdkafka
cd librdkafka/
git checkout v1.6.0-RC1
./configure
make
sudo make install
cd ../confluent-kafka-python/
git checkout v1.6.0-PRE4
python3 setup.py build
sudo python3 setup.py install
….
Finished processing dependencies for confluent-kafka==1.6.0
Clone repo to my github.com
git clone Ignat99/confluent-kafka-python: Confluent’s Kafka Python Client (github.com)
cd confluent-kafka-python/
git remote add upstream git://github.com/confluentinc/confluent-kafka-python
git fetch upstream
git checkout v1.6.0-PRE4
python3 setup.py build
sudo python3 setup.py install
…
Finished processing dependencies for confluent-kafka==1.6.0
git checkout -b enable_idempotence
This is where we make a change to the library and later return the pull request.
git push origin enable_idempotence
Вот это наш флагманский курс, в тексте программы курса есть ссылки на компании в Малаге, которым в данный момент нужны программисты:
Вы или ваши дети с нашей помощью спокойно и уверенно достигнут свою вершину, не запыхавшись по дороге.
В описании курса есть список компаний (в регионе Андалусия, город Малага), куда могут трудоустроится люди, которые прошли этот курс.
Либо самостоятельно купите премиум акаунт и прорешайте 1000 задач с этого сервиса https://leetcode.com/.
Обратите внимание на книгу “Cracking the Coding Interview”.
Средняя зарплата в Малаге у программиста 25 000 – 35 000 евро в год без вычета налогов. До этого времени вся работа в Испании была для специалистов в офисе. Но график обычно был гибкий, можно было работать и из дома.
Сейчас в большинстве компаний работать можно удаленно, в том числе из другой страны (особенно это будет актуально в течении следующих 6 месяцев и позже).
Нужно разрешение на работу, которое предоставляют эти компании в случае успешного прохождения собеседований и тестового задания.
Денег с первого контракта достаточно чтоб купить себе недвижимость во многих живописных уголках Испании:
Если у вас нет достаточных знаний для этого финального курса, вам нужно пройти еще пару курсов предварительно, которые дадут вам необходимый фундамент.
http://homedevice.pro/product-category/online-course/
telegram, skype: ignat_99
Или можно самостоятельно поступить в университеты в Испании:
После десяти лет жизни в Испании существует экзамен на получение гражданства Испании.
Рекомендуемый бесплатный курс разговорного испанского языка для прохождения интервью.
Вся грамматика испанского языка за 53 минуты
Chemistry Zumdahl, 7 ed. Houghton Mifflin Company Boston New York
Фосфор валентности 5 присоединяет по 4 атома Кислорода. Образуются следующие соединения (pages 914-918, 144 of a chemical textbook).
Оксид Фосфора (V) – P4O10
Метафосфорная кислота – (HPO3)4
Ортофосфорная кислота – H3PO4
Каждый атом фосфора заключен в Тетрайдер из 4 атомов Кислорода в этих соединениях. Реакция присоединения воды к Оксиду Фосфора (V) идет в несколько ступеней. Как трехосновная – Фосфорная Кислота относиться к слабым кислотам.
Фосфорная Кислота взаимодействует только с металлами расположенными в электрохимическом ряду напряжений левее вордорода (pages 333 – 335 of a chemical textbook).
K Ca Na Mg Al Zn Fe Ni Sn Pb (H2) Cu Hg Ag Pt Au
Соли Фосфорной Кислоты называются Фосфатами. В зависимости от количества добавленного к раствору Фосфорной Кислоты основания в ее молекулах могут заместиться металлами один, два или все три атома Водорода. Если все атомы Водорода замещены металлом, то соль называется просто Фосфатом.
Дигидрофосфаты: NaH2PO4, Ca(H2PO4)2, NH4H2PO4;
Гидрофосфаты: Na2HPO4, CaHPO4, (NH4)2HPO4;
Фосфаты: Na3PO4, Ca3(PO4)2.
Дигидрофосфаты всех металлов хорошо растворимы в воде. Фосфаты не растворимы в воде. Только Фосфаты щелочных металлов растворимы в воде. Все нерастворимые в воде Фосфаты растворяются при приливании сильных кислот. В этот момент они переходят в Дигидрофосфаты.
Ca3(PO4)2 + 4HNO3 = Ca(H2PO4)2 + 2Ca(NO3)2.
Реактивом на йоны PO43- служит Нитрат Серебра. При прибавлении его к раствору содержащему эти йоны,
образуется остаток фосфата серебра (pages 724 in textbook):
PO43- + 3Ag1+ = Ag3PO4.
Фосфат серебра ярко-желтого цвета и как все фосфаты, растворяется при добавлении раствора сильной кислоты.
Получаемые в промышленности ортофосфаты и метафосфаты используются в качестве фосфорных удобрений.
Chemistry Zumdahl, 7 ed. Houghton Mifflin Company Boston New York
(pages 159, 717, 720 of a chemical textbook)
Какие химические элементы замещают Hydroxylapatite в эмали зубов для борьбы с кариесом?
Вследствии высокой химической активности фосфор в свободном виде в природе не встречается. В земной коре он содержиться только в виде солей ортофосфорной кислоты, преимущественно в виде Phosphate Калия Ca3(PO4)2.
В виде соединения Hydroxylapatite Ca5(PO4)3OH фосфор входит в состав костной ткани человека и животных. Эта соль придает скелету твердость и обеспечивает до 50% состава ткани человека и до 70% веса.
Hydroxylapatite is the hydroxyl endmember of the complex apatite group. The OH− ion can be replaced by fluoride, chloride or carbonate, producing fluorapatite or chlorapatite. It crystallizes in the hexagonal crystal system.
В медицине синтетический Hydroxylapatite используется как наполнитель, замещающий часть утеренной кости и как покрытие инплантов способствующее нарастанию новой кости.
Так же соединения Фосфора входят в состав мышечной и нервной ткани человека и животных. Работа мозга, сокращения мышц связаны с химическим превращениями этих соединений. Фосфор играет исключительно большую роль во всех жизненных процессах.
Источником фосфора для человека и животных является растительная пища. Растения могут произростать при наличии фосфора в почве. В почву фосфор попадает при гниении остатков растений и животных. Таким образом в природе происходит кругооборот Фосфора. В круговороте Фосфора посредниками между почвой и растениями выступают бактерии. Фосфоробактерии превращают органические соединения фосфора, которые не подходят для растений в неорганические – Phosphate.
При интенсивном сельском хозяйстве необходимо вносить в почву навоз и искусственные (минеральные) удобрения.
В нашем Моде в Майнкрафте Hydroxylapatite можно получить из Костей Скелетов или белого красителя.
Fluoride, fluorapatite – Ca5(PO4)3F, and calcium fluoride CaF2.