text
stringlengths 1
1.04M
| language
stringclasses 25
values |
|---|---|
In big breaking news former Prime Minister of Japan Shinzo Abe has been shot while he was campaigning for the Parliament elections. According to the Japanese media, Shinzo was shot in the chest twice at around 11. 30 am local time in Nara.
Post firing Shinzo Abe collapsed on the ground and was bleeding. Reuters confirmed that Shinzo Abe was undergoing treatment at Nara Medical University Hospital yet his condition is unknown.
Meanwhile the police arrested a person in connection with this attack on ex-PM and the local police say that the shooter appears to be in his 40s. The suspect is a former maritime self defence force member and his intentions behind attacking the ex-PM are yet to be known.
This incident sparked a shocker response internationally while Japan PM Fumio Kishida cancelled his poll campaign and rushed to Tokyo. He might be visiting the hospital where Shinzo Abe is getting treatment.
Also with this incident, the political parties in Japan have called off their campaign for the next two days.
|
english
|
{"LifesavingMisfortune": ["FateWorseThanDeath", "UnluckilyLucky", "SerendipitousSurvival", "UnwittingInstigatorOfDoom", "DisabilitySuperpower", "NecessaryFail", "HappilyFailedSuicide", "GirlInTheTower", "ElectiveMonarchy", "BullyingADragon", "DownplayedTrope", "FreakLabAccident", "PersonalityMerge", "KarmaHoudini", "BeCareFulWhatYouWishFor", "MrSmith", "PleaseShootTheMessenger", "BMovie", "ContrivedCoincidence", "PersonalityMerge", "KarmaHoudini", "UriahGambit", "EvilUncle", "VillainCred", "TookALevelInBadass", "CruelTwistEnding", "CatchPhrase", "SerialKiller", "BadBoss", "MexicanStandoff", "PapaWolf", "VillainOfTheWeek", "EnsembleCast", "DivineIntervention", "AbsurdPhobia", "DivineIntervention", "TheJudge", "InvoluntaryGroupSplit", "SoleSurvivor", "FromBadToWorse", "BrainwashedAndCrazy", "OlympusMons", "TongueTrauma", "EyeScream", "DevouredByTheHorde", "FromBadToWorse", "FromBadToWorse", "JustBeforeTheEnd", "ThePlague", "MeanBoss", "EncyclopediaExposita", "AfterTheEnd", "TheMedic", "DirtyCoward", "EatenAlive", "HarsherInHindsight", "UrbanLegends", "JukeboxMusical", "SurvivorsGuilt", "HarsherInHindsight"]}
|
json
|
<filename>linked_article_tropes/linked_trope_dict_from_PoliticallyMotivatedTeacher.json
{"PoliticallyMotivatedTeacher": ["AuthorFilibuster", "StrawmanU", "AuthorTract", "Anvilicious", "HippieTeacher", "SadistTeacher", "StrawCharacter", "ReasonableAuthorityFigure", "TruthInTelevision", "ObviouslyEvil", "BackToSchool", "StrawFeminist", "TropeCodifier", "TheReasonYouSuckSpeech", "StrawCharacter", "HollywoodAtheist", "NayTheist", "WarIsGlorious", "ForegoneConclusion", "WarIsHell", "FantasticRacism", "TalkingAnimal", "FantasticRacism", "TyrantTakesTheHelm", "WhatDoYouMeanItsNotPolitical", "SocialDarwinist", "FauxHorrific", "ScoutOut", "SchoolPlay", "YourTerroristsAreOurFreedomFighters", "StrawmanPolitical", "UrbanLegends", "HollywoodAtheist", "HippieTeacher", "HippieTeacher", "Transgender", "MoralGuardians", "HippieTeacher"]}
|
json
|
India is growing at a faster pace and it has become the most preferred destination for investments and opportunities in the world, Vice President Jagdeep Dhankhar said today.
Recently, India has surpassed its colonial masters and has become the fifth-largest economy in the world, he said. The Vice President also exuded confidence that India will become the third-largest economy on the global horizon by the end of the decade.
"India is on the rise as never before. The rise of India is unstoppable, and we are the most favoured destination globally for investments and opportunities," he said here at the National Handicrafts Award ceremony.
The handicraft sector holds a huge potential for growth, particularly in the rural and semi-urban areas, he noted.
Jagdeep Dhankhar also suggested that professionals from IITs (Indian Institutes of Technology) and IIMs (Indian Institutes of Management) can help the industry in promoting its growth and branding of products.
Branding is key to fetch good prices, he said, adding it is only the handicraft sector where huge value addition is possible.
As India will get the G20 presidency from December 1, it will also give an opportunity to showcase handicraft items to the world.
Unlike many other sectors, this industry requires less capital and resources, and it helps create huge job opportunities and forex earnings.
(Except for the headline, this story has not been edited by NDTV staff and is published from a syndicated feed. )
|
english
|
{
"backup_data_uid": "446b8a46ba22d02d",
"backup_module_uid": "1dc07ee0f4742028",
"backup_module_uoa": "package",
"data_name": "spack-nalu-wind"
}
|
json
|
package network.cycan.model;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.CaseFormat;
import io.swagger.annotations.ApiModelProperty;
/**
* 分页参数
*
* @param <T>
* @author liuq
* @since 2020-05-15
*/
public class PageParam<T> extends Page<T> {
private static final long serialVersionUID = -1658166454440173166L;
@ApiModelProperty(hidden = true)
private String records;
@ApiModelProperty(value = "column:排序字段;asc:true正序,false倒序")
private List<OrderItem> orders = new ArrayList<>();
@ApiModelProperty(hidden = true)
private long total;
@ApiModelProperty(value = "每页显示条数,默认 10")
private long size;
@ApiModelProperty(value = "当前页")
private long current;
/**
* <p>如果排序字段传的是对象的属性,使用此方法转成数据库表字段
*
* <p>有@TableField注解的转成注解的value,没有的驼峰转下划线
*
* @param clz 有排序字段对应属性的对象
*/
public void changeOrders(Class<?> clz) {
for (OrderItem orderItem : getOrders()) {
try {
String column = orderItem.getColumn();
Field field = getField(clz, column);
TableField tableField = field.getAnnotation(TableField.class);
if (tableField == null) {
column = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, column);
} else {
column = tableField.value();
}
orderItem.setColumn(column);
} catch (Exception e) {
continue;
}
}
}
/**
* 递归获得类属性
*
* @param clz 类
* @param column 属性名
* @return Field
* @throws Exception 异常
*/
public Field getField(Class<?> clz, String column) throws Exception {
Field field;
try {
field = clz.getDeclaredField(column);
} catch (NoSuchFieldException e) {
Class<?> clzSuper = clz.getSuperclass();
if (Object.class == clzSuper) {
throw e;
} else {
field = getField(clzSuper, column);
}
}
return field;
}
}
|
java
|
export let dotPatterns: { x: number; y: number }[][];
export let charToIndex: number[];
export function init() {
let p = 0;
let d = 32;
let pIndex = 0;
dotPatterns = [];
for (let i = 0; i < letterCount; i++) {
let dots = [];
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 4; x++) {
if (++d >= 32) {
p = letterPatterns[pIndex++];
d = 0;
}
if ((p & 1) > 0) {
dots.push({ x, y });
}
p >>= 1;
}
}
dotPatterns.push(dots);
}
const charStr = "()[]<>=+-*/%&_!?,.:|'\"$@#\\urdl";
charToIndex = [];
for (let c = 0; c < 128; c++) {
let li = -2;
if (c == 32) {
li = -1;
} else if (c >= 48 && c < 58) {
li = c - 48;
} else if (c >= 65 && c < 90) {
li = c - 65 + 10;
} else {
const ci = charStr.indexOf(String.fromCharCode(c));
if (ci >= 0) {
li = ci + 36;
}
}
charToIndex.push(li);
}
}
const letterCount = 66;
const letterPatterns = [
0x4644aaa4,
0x6f2496e4,
0xf5646949,
0x167871f4,
0x2489f697,
0xe9669696,
0x79f99668,
0x91967979,
0x1f799976,
0x1171ff17,
0xf99ed196,
0xee444e99,
0x53592544,
0xf9f11119,
0x9ddb9999,
0x79769996,
0x7ed99611,
0x861e9979,
0x994444e7,
0x46699699,
0x6996fd99,
0xf4469999,
0x2224f248,
0x26244424,
0x64446622,
0x84284248,
0x40f0f024,
0x0f0044e4,
0x480a4e40,
0x9a459124,
0x000a5a16,
0x640444f0,
0x80004049,
0x40400004,
0x44444040,
0x0aa00044,
0x6476e400,
0xfafa61d9,
0xe44e4eaa,
0x24f42445,
0xf244e544,
0x00000042
];
|
typescript
|
Congress leader Digvijaya Singh Monday launched an indirect attack on the judiciary for calling the Central Bureau of Investigation a "caged parrot".
The Congress leader said such comments "belittle" national institutions.
"CBI is a parrot in a cage, a bench calls IB (Intelligence Bureau) a chicken. . . Now, I have put a question to the people in general - are we not belittling our institutions? " the Congress general secretary asked reporters.
The Supreme Court dubbed the CBI a "caged parrot" last week, while making observations after the investigation agency submitted an affidavit on the government's interference in its probe report on coal block allocations.
The Bangalore bench of the Central Administrative Tribunal (CAT) said Sunday that the Information Bureau (IB) was like a "chicken", while hearing a petition from a woman Indian Police Service officer who sought revocation of the move to send her back to her original cadre, ending her deputation to the IB.
When reporters asked Digvijaya Singh for his reaction to the analogy between institutions and fowl, he said: "I will also request you to get access to all those who are calling institutions chicken or parrot, you should get reaction from them as well. "
|
english
|
Day 2 round-up: Bangladesh were sliding towards a massive innings defeat after the West Indies completely dominated the second day of the first Test match at the Sir Vivian Richards Stadium in Antigua on Thursday. After Kraigg Brathwaite’s seventh Test hundred anchored the West Indies first innings total of 406 to give the home side a first innings lead of 363, Shannon Gabriel compensated for a wicketless effort on the opening day with figures of four for 36 to reduce the visitors to 62 for six in their second turn at the crease by the close of play.
Routed for just 43, their lowest-ever Test innings total, in the first innings, the Bangladeshis still need another 301 runs just to make the West Indies bat again going into day three. That looks an impossible prospect in conditions which are completely alien to them and in which the home side’s quartet of fast bowlers has revelled. But for a no-ball delivered by Miguel Cummins in the last over of the day when he could have claimed the wicket of Mahmudullah, the West Indies would have had the option of requesting an additional half-hour at the end of the day to finish off the match. It leaves Mahmudullah to resume on the third morning with wicketkeeper-batsman Nurul Hasan, although it will be merely delaying the inevitable given the struggles of the Bangladeshis in coping with the pace and bounce of their West Indian opponents in seamer-friendly conditions. Jason Holder took the other two wickets, sharing the new ball with the fiery Gabriel in the absence of Kemar Roach, who initiated the demolition of the Bangladesh first innings with outstanding figures of five for eight but was troubled by what appeared to be a muscular strain at the back of his right knee during that effort. He showed no discomfort though in an innings of 33 and a partnership of 58 with Shai Hope for the eighth wicket. However the bulk of the batting effort for the West Indies was provided by the erstwhile Brathwaite, who occupied the crease for over seven hours – from before lunch on day one to just after lunch on day two – in compiling 121. Hope ensured the West Indies middle-order didn't buckle completely. Resuming at the overnight position of 201 for two with Brathwaite and nightwatchman Devendra Bishoo at the crease, they suffered a mini-collapse in early afternoon when losing three wickets for 16 runs. That was the only period in the Test match so far when the Bangladeshis appeared to be holding any sort of initiative as spinners Mehidy Hasan and Shakib al Hasan posed significant challenges. However Hope showed his class in an innings of 67 and by the time he was ninth out with the score at 400, the only question was whether or not the West Indies could have been as ruthless as in the first innings to finish the match inside two days. Gabriel’s raw pace was too hot to handle for the Bangladesh top-order as he claimed the prized scalps of Tamim Iqbal, Mominul Haque, Mushfiqur Rahim and captain Shakib al Hasan to lift his tally of Test wickets in this Caribbean season to 24 in four matches.
|
english
|
This week a beautiful and uplifting hand painted sign featuring David Bowie's lyrics 'We Could Be Heroes Just for One Day' which had been cheering up a drab brick wall overlooking a railway in the village was washed off by the council.
The outpouring of dismay by local residents at this action showed how well loved this upbeat peice of street art had become and how utterly out of touch and phillistine the council were in removing it. Alledgedly it was done because of a 'complaint'. This petition is to show how much the complainant in question is in the minority and to call for:
THIS STREET ART TO BE IMMEDIATELY REINSTATED.
Arguments have been posited that 'permissions werent sought' and that the village is a 'conservation area' yet the artwork was on an ugly old wall overlooking a railway. If anything it cheered up the place and gave many people a much needed boost.
In addition the sign was surrounded by victorian built pubs and houses - a period in time when utilitarian things like walls and sides of houses were routinely subject to hand painted signs. So ironically this artwork is actually not only in keeping with the area but is actually part of a grand tradition of signwriting.
|
english
|
<gh_stars>0
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
.box-side-bar {
background: #30100d;
padding-bottom: 50px;
}
.box-side-bar-flex {
display: flex;
justify-content: center;
align-items: center;
}
.divice {
display: flex;
}
.side-bar {
display: block;
position: relative;
width: 300px;
min-height: 750px;
background: #091921;
box-shadow: -10px -10px 15px rgba(255, 255, 255, 0.02),
10px 10px 15px rgba(0, 0, 0, 0.15);
border-radius: 20px;
transition: all 0.5s cubic-bezier(0.39, 0.575, 0.565, 1);
margin-top: 50px;
}
.side-bar .title {
display: flex;
justify-content: space-evenly;
margin: 30px;
}
.side-bar > .title > .logo {
font-size: 1.5rem;
font-weight: 600;
color: #e74c3c;
}
.side-bar ul {
width: 90%;
list-style: none;
margin: 35px auto 10px;
}
.side-bar ul .btn-side-bar {
color: rgba(250, 240, 230, 0.575);
text-decoration: none;
display: block;
margin: 20px 0;
font-size: 18px;
font-weight: 400;
padding: 10px 25px;
border-radius: 6px;
position: relative;
}
.media-icons {
margin-top: 50px;
display: flex;
justify-content: center;
color: #e74c3c;
}
.media-icons a {
margin: 0 4px;
font-size: 17px;
cursor: pointer;
height: 40px;
width: 40px;
border-radius: 50%;
text-align: center;
line-height: 40px;
text-decoration: none;
position: relative;
box-shadow: inset -10px -10px 15px rgba(255, 255, 255, 0.02),
inset 10px 10px 15px rgba(0, 0, 0, 0.15);
mix-blend-mode: luminosity;
}
.media-icons a:hover {
box-shadow: inset -10px -10px 15px rgba(255, 255, 255, 0.02),
inset 10px 10px 15px rgba(0, 0, 0, 0.15);
mix-blend-mode: normal;
}
s .side-bar ul .btn-side-bar:hover:before {
border-radius: 6px;
}
.side-bar ul .btn-side-bar:hover {
color: #e74c3c;
}
.media-icons a:hover:before {
border-radius: 50%;
}
.media-icons a:hover {
color: brown;
}
.media-icons a:nth-child(1) {
color: #4267b2;
}
.media-icons a:nth-child(2) {
color: #1da1f2;
}
.media-icons a:nth-child(3) {
color: #e1306c;
}
.media-icons a:nth-child(4) {
color: #ff0000;
}
.btn-side-bar {
position: relative;
font-size: 17px;
color: rgba(250, 240, 230, 0.575);
border-radius: 50%;
text-align: center;
line-height: 37px;
cursor: pointer;
transition: all 0.3s ease-in-out;
box-shadow: -7px -7px 10px rgba(255, 255, 255, 0.03),
7px 7px 10px rgba(0, 0, 0, 0.15);
}
.button {
height: 37px;
width: 37px;
}
.btn-side-bar.cancel {
position: relative;
left: 10px;
}
.bars {
position: absolute;
left: 15px;
top: 15px;
}
#check {
display: none;
}
#check:checked ~ .side-bar {
left: -100%;
}
.body-content {
position: relative;
padding: 20px;
transform-style: preserve-3d;
transform: translateZ(-1000px);
display: none;
transition: all 0.2s cubic-bezier(0.68, -0.25, 1, 1);
}
.body-content p {
margin: 10px 0;
padding: 10px;
font-size: 16px;
font-weight: 500;
text-align: center;
border-top: 0.7px solid gray;
color: rgba(250, 240, 230, 0.575);
}
.body-content input[type="date"] {
padding: 8px 20px;
margin: 5px;
outline: none;
}
.body-content input[type="text"] {
padding: 5px;
outline: none;
margin-left: 5px;
}
.body-content input[type="date"] {
margin-top: 5px;
}
.body-content select {
margin: 5px;
outline: none;
width: 200px;
height: 50px;
font-size: 14px;
padding: 8px 10px;
}
.body-content input[type="checkbox"] {
margin-bottom: 10px;
}
.body-content label {
color: rgba(250, 240, 230, 0.575);
}
.body-content input[type="radio"] {
margin: 10px 0;
}
.body-content button[type="submit"] {
padding: 5px 25px;
border-radius: 50px;
outline: none;
margin: 10px 5px;
color: rgba(250, 240, 230, 0.575);
font-size: 10px;
transition: 0.4s linear all;
overflow: hidden;
background-image: linear-gradient(30deg, #bb291b 50%, transparent 50%);
background-size: 500px;
background-position: 0%;
background-repeat: no-repeat;
border: 2px solid #bb291b;
}
.body-content button[type="submit"]:hover {
color: #000;
background-position: 100%;
}
.body-content .to-date {
margin-right: 18px;
}
.body-content input[type="range"] {
height: 10px;
margin: 10px 0;
width: 100%;
/* -webkit-appearance: none; */
outline: none;
background: #f2f2f2;
border-radius: 25px;
box-shadow: inset 0px 0px 4px rgba(0, 0, 0, 0.2);
}
#open-sort,
#opent-filters,
#open-where-to-watch {
display: none;
}
#open-sort:checked ~ .ver-1,
#opent-filters:checked ~ .ver-2,
#open-where-to-watch:checked ~ .ver-3 {
position: relative;
transform: translateZ(0);
display: block;
box-shadow: inset -7px -7px 10px rgba(255, 255, 255, 0.03),
inset 7px 7px 10px rgba(0, 0, 0, 0.15);
}
#open-sort:checked ~ .btn-sort,
#opent-filters:checked ~ .btn-filters,
#open-where-to-watch:checked ~ .btn-where-to-watch {
box-shadow: inset -7px -7px 10px rgba(255, 255, 255, 0.03),
inset 7px 7px 10px rgba(0, 0, 0, 0.15);
color: rgb(8, 253, 216);
text-shadow: 0 0 1.5px #2058c7;
}
.submit {
margin: 10px;
text-align: center;
}
.btn-submit {
margin-top: 25px;
color: rgba(250, 240, 230);
font-size: 16px;
padding: 10px 50px;
border-radius: 50px;
outline: none;
transition: 0.4s linear all;
overflow: hidden;
background-image: linear-gradient(30deg, #bb291b 50%, transparent 50%);
background-size: 500px;
background-position: 0%;
background-repeat: no-repeat;
border: 2px solid #bb291b;
}
.btn-submit:hover {
color: #000;
background-position: 100%;
}
.film-box .film-data {
position: relative;
text-align: center;
margin-top: 50px;
width: 250px;
height: 375px;
transform-style: preserve-3d;
/* transform: translateX(1500px); */
transition: all 1s cubic-bezier(0.19, 1, 0.22, 1);
cursor: pointer;
}
.film-box .film-data img {
border-radius: 10px;
object-fit: cover;
width: 250px;
height: 375px;
}
.film-box .film-content {
position: absolute;
bottom: 100%;
top: 0;
left: 0;
right: 0;
background: #0919219a;
color: linen;
transition: all 0.5s ease;
border-radius: 10px;
overflow: hidden;
}
.film-box .film-content h4 {
color: linen;
}
.film-box .film-content .film-title {
margin-top: 30%;
cursor: pointer;
margin-bottom: 20px;
text-shadow: 3px 3px 10px rgb(117, 30, 17);
font-weight: 500;
color: #e74c3c;
font-size: 1.5rem;
}
.film-box .film-data:hover > .film-content {
bottom: 0;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 40px;
border: 1px solid #888;
width: 80%;
border-radius: 20px;
}
.modal-content > .span {
display: inline-flex;
}
/* The Close Button */
.close {
color: #aaaaaa;
position: absolute;
right: 10px;
top: 5px;
font-size: 28px;
font-weight: bold;
}
.modal-content .film-data {
display: flex;
}
.modal-content .film-data .film-content {
position: relative;
bottom: 0;
}
.modal-content .film-data img {
margin-right: 10px;
max-width: 200px;
}
|
css
|
Zebrafish embryos are used for evaluating the toxicity of chemical compounds. They develop externally and are sensitive to chemicals, allowing detection of subtle phenotypic changes. The experiment only requires a small amount of compound, which is directly added to the plate containing embryos, making the testing system efficient and cost-effective.
The zebrafish is a widely used vertebrate model organism for the disease and phenotype-based drug discovery. The zebrafish generates many offspring, has transparent embryos and rapid external development. Zebrafish embryos can, therefore, also be used for the rapid evaluation of toxicity of the drugs that are precious and available in small quantities. In the present article, a method for the efficient screening of the toxicity of chemical compounds using 1-5-day post fertilization embryos is described. The embryos are monitored by stereomicroscope to investigate the phenotypic defects caused by the exposure to different concentrations of compounds. Half-maximal lethal concentrations (LC50) of the compounds are also determined. The present study required 3-6 mg of an inhibitor compound, and the whole experiment takes about 8-10 h to be completed by an individual in a laboratory having basic facilities. The current protocol is suitable for testing any compound to identify intolerable toxic or off-target effects of the compound in the early phase of drug discovery and to detect subtle toxic effects that may be missed in the cell culture or other animal models. The method reduces procedural delays and costs of drug development.
Drug development is an expensive process. Before a single chemical compound is approved by the Food and Drug Administration (FDA) and European Medicines Agency (EMA) several thousand compounds are screened at a cost of over one billion dollars1. During the preclinical development, the largest part of this cost is required for the animal testing2. To limit the costs, researchers in the field of drug development need alternative models for the safety screening of chemical compounds3. Therefore, in the early phase of the drug development, it would be very beneficial to use a method that can rapidly evaluate the safety and toxicity of the compounds in a suitable model. There are several protocols that have been used for the toxicity screening of chemical compounds involving animal and cell culture models but there is not a single protocol that is validated and is in common use4,5. Existing protocols using zebrafish vary in length and have been used by individual researchers who evaluated the toxicity as per their convenience requirement6,7,8,9,10,11,12.
In the recent past, the zebrafish has emerged as a convenient model for the evaluation of the toxicity of chemical compounds during embryonic development6,7. The zebrafish has many in-built advantages for the evaluation of chemical compounds13. Even large-scale experiments are amenable, as a zebrafish female can lay batches of 200-300 eggs, which develop rapidly ex vivo, do not need external feeding for up to a week and are transparent. The compounds can be added directly into the water, where they can (depending on the nature of the compound) diffuse through the chorion, and after hatching, through the skin, gills and mouth of larvae. The experiments do not require copious amounts of chemical compounds14 due to the small size of the embryo. Developing zebrafish embryos express most of the proteins required to achieve the normal developmental outcome. Therefore, a zebrafish embryo is a sensitive model to assess whether a potential drug can disturb the function of a protein or signaling molecule that is developmentally significant. The organs of the zebrafish become functional between 2-5 dpf15, and compounds that are toxic during this sensitive period of embryonic development induce phenotypic defects in zebrafish larvae. These phenotypic changes can be readily detected using a simple microscope without invasive techniques11. Zebrafish embryos are widely used in toxicological research due to their much greater biological complexity compared to in vitro drug screening using cell culture models16,17. As a vertebrate, the genetic and physiologic makeup of zebrafish is comparable to humans and hence toxicities of chemical compounds are similar between zebrafish and humans8,18,19,20,21,22. Zebrafish is, thus, a valuable tool in the early phase of drug discovery for the evaluation of toxicity and safety of the chemical compounds.
In the present article, we provide a detailed description of the method used for evaluating the safety and toxicity of carbonic anhydrase (CA) inhibitor compounds using 1-5-day post fertilization (dpf) zebrafish embryos by a single researcher. The protocol involves exposing zebrafish embryos to different concentrations of chemical inhibitor compounds and studying the mortality and phenotypic changes during the embryonic development. At the end of the exposure to the chemical compounds, the LC50 dose of the chemical is determined. The method allows an individual to carry out efficient screening of 1-5 test compounds and takes about 8-10 h depending on the experience of the person with the method (Figure 1). Each of the steps required to assess the toxicity of the compounds is outlined in Figure 2. The evaluation of toxicity of CA inhibitors requires 8 days, and includes setting up of mating pairs (day 1); collection of embryos from breeding tanks, cleaning and transferring them to 28.5 °C incubator (day 2); distribution of the embryos into the wells of a 24-well plate and addition of diluted CA inhibitor compounds (day 3); phenotypic analysis and imaging of larvae (day 4-8), and determination of LC50 dose (day8). This method is rapid and efficient, requires a small amount of the chemical compound and only basic facilities of the laboratory.
Subscription Required. Please recommend JoVE to your librarian.
The zebrafish core facility at Tampere University has an establishment authorization granted by the National Animal Experiment Board (ESAVI/7975/04.10.05/2016). All the experiments using zebrafish embryos were performed according to the Provincial Government of Eastern Finland, Social and Health Department of Tampere Regional Service Unit protocol # LSLH-2007-7254/Ym-23.
- Place 2-5 adult male zebrafish and 3-5 adult female zebrafish into mating tanks overnight. (Breeding is induced in the morning by automatic dark and light cycle overnight).
- Set up several crosses to obtain enough embryos for assessing the toxicity of more than two chemical compounds. For the evaluation of toxicity, each concentration needs a minimum of 20 embryos23.
- To avoid handling stress to the animals, allow the animals to rest for 2 weeks before using the same individuals for breeding.
- Collect the embryos, the next day before noon, using a fine-mesh strainer and transfer them onto a Petri dish containing E3 embryo medium [5.0 mM NaCl, 0.17 mM KCl, 0.33 mM CaCl2, 0.33 mM MgSO4, and 0.1% w/v Methylene Blue].
- Remove debris using a plastic Pasteur pipette (e.g., food and solid waste). Examine each batch of embryos under the stereomicroscope to remove the unfertilized/dead embryos (identified by their opaque appearance).
- Keep the embryos at 28.5 °C in an incubator. Examine the embryos, the next morning, under a stereomicroscope and remove any unhealthy or dead embryos. Also, replace the old E3 medium with fresh E3 medium.
NOTE: Zebrafish embryos are always maintained at 28.5 °C under laboratory conditions.
- Carefully transfer 1 embryo into each well of a 24-well plate containing enough E3 medium to cover the embryos.
- Take out the vials containing inhibitor compounds stored at 4 °C.
NOTE: Depending on the properties of the compound, these are stored at different temperatures.
- Weigh the compound(s) using an analytical balance that can weigh a few milligrams (mg) of the compound accurately.
- Prepare at least 250 μL (100 mM) of stock solution for each compound in an appropriate solvent (e.g., E3 water or Dimethyl sulfoxide (DMSO), based on the solubility properties of the compounds.
NOTE: The above steps can be done a day before the start of the experiment at a convenient time and stored at 4 °C).
- Make serial dilutions of the stock solutions (e. g., 10 μM, 20 μM, 50 μM, 100 μM, 150 μM, 300 μM and 500 μM) using E3 water in 15 mL centrifuge tubes.
NOTE: The concentrations and number of serial dilutions vary from one compound to another compound depending on their toxicity levels.
- From the 24 well plate containing embryos, remove E3 water from the wells using a Pasteur pipette and a 1 mL pipette (containing 1 dpf embryos) one row at a time.
- Distribute 1 mL of each diluent in each well (starting from lower and moving to higher concentration) into the wells of 24-well plate.
- Set up a control group from the same batch of embryos and add the corresponding amount of diluent.
- Label 24-well plates with the name and concentration of the compound and keep the plates at 28.5 °C in an incubator.
- Examine the embryos under a stereomicroscope for parameters 24 h after exposure to the chemical compounds.
- Note the parameters such as mortality, hatching, heartbeat, utilization of yolk sack, swim bladder development, movement of the fish, pericardial edema, and shape of the body23.
- Take the larvae exposed to each concentration of the compound and lay them sideways in a small Petri dish containing 3% high molecular weight methyl cellulose using a metal probe.
NOTE: The 3% methyl cellulose (high molecular with) is a viscous liquid needed for embedding the fish with a required orientation for microscopic examination. For orienting the fish in this liquid, a metal probe is needed.
- Take the images using stereomicroscope attached to a camera. Save the images in a separate folder each day till the end of the experiment.
- Enter all the observations in a table each day either in an online table or on a printed sheet.
- If the compounds are neurotoxic, the 4 to 5 dpf larvae may show altered swim pattern, make a record of such changes either by capturing a short (30 s to 1 min) video of the larvae exhibiting abnormal movement pattern.
- After 5 days of exposure to the chemical compounds, note the concentration at which half of the embryos die for calculating the half maximal lethal concentration 50 (LC50) of each chemical.
NOTE: The LC50 is the concentration at which 50% of the embryos die at the end of 5 days of exposure to a chemical compound. Use a minimum of 20 embryos for testing the toxicity of each concentration of a compound23.
- Construct a curve for mortality of embryos for all the concentrations using a suitable program.
Subscription Required. Please recommend JoVE to your librarian.
The critical part of the evaluation of toxicity is testing different concentrations of one or multiple chemical compounds in a single experiment. In the beginning, select the compounds for evaluation of toxicity, the number of concentrations to test for each compound, and accordingly, make a chart (Figure 3). We used a unique color for each compound to organize the samples (Figure 3). The use of solvent resistant marker and labeling at the bottom or sides of the plates is important to avoid mix-up later. If the compounds induce any phenotypic defects in the larvae exposed to different concentrations of inhibitors, the defects are recorded every 24 h over the period of 1-5 dpf (Figure 4A,B,C,D). The embryos treated with a known CA IX inhibitor at a concentration of 500 μM did not show any apparent phenotypic changes in the 1-5 days of exposure to the chemical compound (Figure 4B). Figure 4C and Figure 4D shows the embryos treated with β-CA inhibitors that induced various phenotypic defects unhatched embryos even at day 3 (arrow head), curved body structure (arrow), unutilized yolk sack and pericardial edema (arrow head) and absence of otolith sacs in the larvae at 5 days after treatment with chemical compound (arrow). In another study, the embryos treated with CA inhibitor (Figure 4E) shows the absence of otolith sacs and swim bladder (arrow heads). In our study, (Figure 4C,D), we documented phenotypic defects (fragile embryos and absence of pigmentation) even after day 1 of exposure to CA inhibitors. The phenotypic analyses showed that some of the inhibitor compounds are lethal and cannot be developed as drugs for human use (Figure 4C,D and Table 1).
The experiments identified a representative compound which induced minimal or no phenotypic changes during embryonic development and showed a high LC50 dose (Figure 5), suggesting that the compound is safe for further characterization and can be potentially developed into a drug candidate for human use16. Looking at still images of larvae exposed to the compound showed no phenotypic defects (Figure 4B). However, the same compound was found to be neurotoxic and induced ataxia in the larvae after 5-days of exposure to the CA inhibitor (Figure 6). This phenotype could only be detected by directly observing the swimming behavior of the zebrafish larvae under the microscope. These studies suggested that the neural development of zebrafish larvae is sensitive to the compound16,17.
Figure 1: Time in hours required for the rapid screening of chemical compounds using zebrafish embryos: In one set of experiments, a person with hands-on experience can screen about 5 chemical compounds (each compound requiring a minimum of 6 dilutions) using zebrafish embryos in 24-well plates. In total, it takes about 8-10 h from the setting up of crosses to performing LC50 determination over a period of 8 days.
Figure 2: Chart showing the breakdown of toxicity evaluation of chemical compounds. Toxicity screening of chemical compounds requires 8 days and can be broken down into five steps. (Day 1) Consists of setting up of zebrafish mating pairs in tanks. (Day 2) Involves collecting embryos from the mating tanks into Petri dishes followed by keeping them at a 28.5 °C incubator for overnight. (Day 3) Examination of embryos using a stereomicroscope and cleaning the embryos. Distribution of the embryos into 24-well plates and adding the dilutions of the test compounds. (Day 4-8) Phenotypic analyses of larvae for developmental defects. Swim pattern study and LC50 determination was performed on the last day of exposure to compounds. Please click here to view a larger version of this figure.
Figure 3: Schematic presentation of experiments involved in toxicity evaluation. The toxicity evaluation consists of preparing tabulated chart containing information about chemical compounds, dilutions of the compounds and parameters to be assessed. Making the dilution of stock solutions to the desired concentrations in 15 mL centrifuge tubes (the dilution from one tube to be added to each row of the 24-well plate). A 24-well plate marked with a water proof marker with the name of the test compound, concentration in each row, and date of exposure. Examination and imaging of embryos by transferring the larvae onto a small Petri dish containing 3% high molecular weight methyl cellulose. Please click here to view a larger version of this figure.
Figure 4: Example of phenotypic analysis of the larvae in the control and test compound treated groups. (A) Phenotypic analyses of the control group larvae not treated with any compound showed no phenotypic defect under a microscope. (B) Larvae treated with 500 μM CA inhibitor (known inhibitor of carbonic anhydrase IX showed no observable phenotypic defects. (C, D) The developing larvae treated with β-CA inhibitor with concentrations of 250 μΜ and 125 μM respectively. The compounds induced phenotypic defects such as curved body, pericardial edema, and unutilized yolk sac (arrows and arrow heads). Panels A and B has been modified from Aspatwar et al16. The panels C, D and E show previously unpublished images, which were obtained using a different microscope. Please click here to view a larger version of this figure.
Figure 5: Determination of lethal concentration 50 (LC50) using 1-5 dpf zebrafish larvae. Toxicity assessment using zebrafish embryos allows researchers to determine the minimum lethal concentration of the chemical compound at the end of the experiment. The LC50 concentration of the compound (a known CA IX inhibitor) was 3.5 mM. The high LC50 concentration allows further characterization of the compound. This figure has been modified from Aspatwar et al.16. Please click here to view a larger version of this figure.
Figure 6: An example of swim pattern analysis in both untreated (A) and inhibitor treated (B) groups of larvae. The zebrafish larvae treated in panel B with 300 μM test inhibitor compound (a known inhibitor of human carbonic anhydrase IX) showed an abnormal (ataxic) movement pattern (arrow heads), suggesting that the compound induces neurotoxicity in the developing embryos. The arrowheads point to the normal curvature of the tail during swimming. In panel A the arrows point to the normal curvature of the tail during swimming. This figure has been modified from Aspatwar et al.16. Please click here to view a larger version of this figure.
Table 1: A summary of the safety and toxicity of the compounds screened. The toxicity evaluation experiment helps the researcher to reach a conclusion about the safety of the tested chemical compounds. The LC50 concentration allows to define safe concentration for further characterization. A researcher can decide if the compound is lethal even after 24 h of exposure of embryos to the compound under investigation. In our example, a subtle effect on swimming due to neurotoxicity is the significant information, which is helpful for setting up further experiments. Accordingly, based on the toxicity screening, we were able to use safe concentrations of the CA inhibitor for further characterization in vivo24.
Subscription Required. Please recommend JoVE to your librarian.
In vitro toxicity test using cultured cells can detect survival and morphological studies of the cells providing limited information about the toxicity induced by the test compound. The advantage of toxicity screening of chemical compounds using zebrafish embryos is rapid detection of chemically induced phenotypic changes in a whole animal during embryonic development in a relevant model organism. Approximately 70% of protein-coding human genes have orthologs counterparts in the zebrafish genome25. Genetic pathways controlling the signal transduction and development are highly conserved between human and zebrafish26, and, therefore, chemical compounds are likely to have similar toxic effects in humans25.
Zebrafish are at the forefront of toxicological research and have already been extensively used to detect toxins in water samples and to study the mechanism of action of environmental toxins and their effects on the animal27. In this article, we show the use of developing zebrafish embryos to evaluate the toxicity of potential compounds at the early phase of drug discovery. Our rapid and multifaceted toxicity assessment is based on 1) changes in the phenotype of the organism (hatching, otolith sacs, pericardial edema, yolk sac utilization, notochord development, heartbeat, swim bladder development, movement) during embryonic development over a period of 5 days, and 2) determination of the lethal concentration (LC50). Reasonable hours of hands-on work (8-10 h divided over 8 days) is enough to determine the toxicity profile of a compound using this procedure. For newly synthesized compounds that are available in limited amounts, toxicity can be evaluated using a minimum of 3 mg of the compound. No special equipment is required. The procedure is, thus, a rapid and low-cost way to evaluate the toxic effects of any compound that can potentially be developed into the drug for human use.
The quality of the batch of embryos has a great impact on the outcome of the experiment. The quality of eggs (including the rate of fertilization) is not obvious immediately after collection from the breeding tanks (0-4 hpf). For obtaining only normally developing embryos for the experiments, before adding compounds, we allow the embryos to remain at 28.5 °C for 24 h after the collection from the breeding tanks. After 24 hpf, any dead or unhealthy-looking embryos are discarded. In addition to this, it is advisable to have a mock-treated group of embryos in each experiment to further control for the quality of the batch of eggs used in the experiment as well as to see the baseline mortality to accurately determine LC50.
A mock-treated group is also needed to control for the toxicity of the vehicle of choice. Many chemicals are insoluble in water and DMSO is often used as the vehicle for the delivery of the test compounds. DMSO is generally well tolerated by the embryos in lower (0.1%) concentrations28. Sometimes, the compounds are not completely soluble even in DMSO and the solution appears cloudy making it difficult for the evaluation of the toxicity. In such cases, to get the stock solution of the compound completely soluble and clear, adding a drop of 0.1% NaOH will solve the problem. Appropriate control groups need to be set up for assessing the toxicity of the compound accurately. If other vehicles are used, their inherent toxicity might affect the experiment.
Each well of a 24-well plate contains from 1-10 embryos submerged in a total volume of 1 mL. If the test compound is available only in small amounts, it may be necessary to use up to 10 embryos per well for evaluating its toxicity. It is highly recommended that only 1 embryo per well should be used for each analysis16,24,29. The plate is stored at 28.5 °C incubator for 5 days. Sometimes significant evaporation is observed causing a marked change in the concentration of the compound in a given well16. By sealing the 24-well plates with paraffin films from all sides, placing embryos only in the middle wells and filling the other wells along the rims with water, the problems caused by evaporation can be avoided. In our earlier studies, we did not observe any evaporation of the diluents of the chemicals from 24-well plates24,29. Also, if the compound in question is known to be unstable under ambient temperatures, daily changes of water with fresh compound will be needed for reliable results.
The swim pattern of zebrafish larvae is analyzed after the 5 days of exposure to the compound. The wells of a 24-well plate containing 5 dpf larvae are not ideal for the purpose due to the limited size of the well. Therefore, for accurate analysis of swim pattern, the larvae need to be transferred to a Petri dish containing 50 mL of E3 water and can settle for 2 min before the analysis. In our study, only two inhibitors showed the effect on swim pattern16 among the 52 α-CA and β-CA inhibitors screened for safety and toxicity, based on our experience this test can detect subtle changes including mild ataxic movement of the larvae.
This study demonstrated that the only limitation to the current method is physical dexterity. This concern can be overcome through repetition, as the skill of a person improves with practice. Once the expertise is achieved the evaluation of compounds using zebrafish embryos is ethical, easy, efficient and informative. We, therefore, expect that such a rapid assay using zebrafish embryos will become a popular tool for the in vivo toxicity screening in the early phase of drug development.
Subscription Required. Please recommend JoVE to your librarian.
No potential conflict of interest was reported by the authors.
The work was supported by grants from Sigrid Juselius Foundation (SP, MP), Finnish Cultural Foundation (AA, MH), Academy of Finland (SP, MP), Orion Farmos Foundation (MH), Tampere Tuberculosis Foundation (SP, MH and MP) and Jane and Aatos Erkko Foundation (SP and MP). We thank our Italian and French collaborators, Prof. Supuran, and Prof. Winum, for providing carbonic anhydrase inhibitors for safety and toxicity evaluation for anti-TB and anti-cancer drug development purposes. We thank Aulikki Lehmus and Marianne Kuuslahti for the technical assistance. We also thank Leena Mäkinen and Hannaleena Piippo for their help with the zebrafish breeding and collection of embryos. We sincerely thank Harlan Barker for critical evaluation of the manuscript and insightful comments.
|Balance (Weighing scale)
|Balance (Weighing scale)
|Pipette (1 mL and 200 μL)
- Amaouche, N., Casaert Salome, H., Collignon, O., Santos, M. R., Ziogas, C. Marketing authorization applications submitted to the European Medicines Agency by small and medium-sized enterprises: an analysis of major objections and their impact on outcomes. Drug Discovery Today. 23 (10), 1801-1805 (2018).
- Garg, R. C., Bracken, W. M., Hoberman, A. M. Reproductive and developmental safety evaluation of new pharmaceutical compounds. Reproductive and Developmental Toxicology. Gupta, R. C. , Elsevier. Boston, MA, USA. 89-109 (2011).
- Lee, H. Y., Inselman, A. L., Kanungo, J., Hansen, D. K. Alternative models in developmental toxicology. Systems Biology in Reproductive Medicine. 58 (1), 10-22 (2012).
- Gao, G., Chen, L., Huang, C. Anti-cancer drug discovery: update and comparisons in yeast, Drosophila, and zebrafish. Current Molecular Pharmacology. 7 (1), 44-51 (2014).
- Brown, N. A. Selection of test chemicals for the ECVAM international validation study on in vitro embryotoxicity tests. European Centre for the Validation of Alternative Methods. Alternatives to Laboratory Animals. 30 (2), 177-198 (2002).
- Selderslaghs, I. W., Van Rompay, A. R., De Coen, W., Witters, H. E. Development of a screening assay to identify teratogenic and embryotoxic chemicals using the zebrafish embryo. Reproductive Toxicology. 28 (3), Elmsford, N.Y. 308-320 (2009).
- Brannen, K. C., Panzica-Kelly, J. M., Danberry, T. L., Augustine-Rauch, K. A. Development of a zebrafish embryo teratogenicity assay and quantitative prediction model. Birth Defects Research Part B Developmental and Reproductive Toxicology. 89 (1), 66-77 (2010).
- Hermsen, S. A., van den Brandhof, E. J., van der Ven, L. T., Piersma, A. H. Relative embryotoxicity of two classes of chemicals in a modified zebrafish embryotoxicity test and comparison with their in vivo potencies. Toxicology in Vitro. 25 (3), 745-753 (2011).
- Lessman, C. A. The developing zebrafish (Danio rerio): a vertebrate model for high-throughput screening of chemical libraries. Birth Defects Research. Part C, Embryo Today: Reviews. 93 (3), 268-280 (2011).
- Lantz-McPeak, S., et al. Developmental toxicity assay using high content screening of zebrafish embryos. Journal of Applied Toxicology. 35 (3), 261-272 (2015).
- Truong, L., Harper, S. L., Tanguay, R. L. Evaluation of embryotoxicity using the zebrafish model. Methods in Molecular Biology. 691, 271-279 (2011).
- Rodrigues, G. C., et al. Design, synthesis, and evaluation of hydroxamic acid derivatives as promising agents for the management of Chagas disease. Journal of Medicinal Chemistry. 57 (2), 298-308 (2014).
- Kanungo, J., Cuevas, E., Ali, S. F., Paule, M. G. Zebrafish model in drug safety assessment. Current Pharmaceutical Design. 20 (34), 5416-5429 (2014).
- Peterson, R. T., Link, B. A., Dowling, J. E., Schreiber, S. L. Small molecule developmental screens reveal the logic and timing of vertebrate development. Proceedings of the National Academy of Sciences of the United States of America. 97 (24), 12965-12969 (2000).
- Stainier, D. Y., Fishman, M. C. The zebrafish as a model system to study cardiovascular development. Trends in Cardiovascular Medicine. 4 (5), 207-212 (1994).
- Aspatwar, A., et al. Nitroimidazole-based inhibitors DTP338 and DTP348 are safe for zebrafish embryos and efficiently inhibit the activity of human CA IX in Xenopus oocytes. Journal of Enzyme Inhibition and Medicinal Chemistry. 33 (1), 1064-1073 (2018).
- Rami, M., et al. Hypoxia-targeting carbonic anhydrase IX inhibitors by a new series of nitroimidazole-sulfonamides/sulfamides/sulfamates. Journal of Medicinal Chemistry. 56 (21), 8512-8520 (2013).
- Spitsbergen, J. M., Kent, M. L. The state of the art of the zebrafish model for toxicology and toxicologic pathology research--advantages and current limitations. Toxicologic Pathology. , Suppl 31. 62-87 (2003).
- Teraoka, H., et al. Induction of cytochrome P450 1A is required for circulation failure and edema by 2,3,7,8-tetrachlorodibenzo-p-dioxin in zebrafish. Biochemical and Biophysical Research Communications. 304 (2), 223-228 (2003).
- Zon, L. I., Peterson, R. T. In vivo drug discovery in the zebrafish. Nature Reviews Drug Discovery. 4 (1), 35-44 (2005).
- Hill, A. J., Teraoka, H., Heideman, W., Peterson, R. E. Zebrafish as a model vertebrate for investigating chemical toxicity. Toxicological Sciences. 86 (1), 6-19 (2005).
- Kari, G., Rodeck, U., Dicker, A. P. Zebrafish: an emerging model system for human disease and drug discovery. Clinical Pharmacology and Therapeutics. 82 (1), 70-80 (2007).
- Gourmelon, A., Delrue, N. Validation in Support of Internationally Harmonised OECD Test Guidelines for Assessing the Safety of Chemicals. Advances in Experimental Medicine and Biology. 856, 9-32 (2016).
- Aspatwar, A., et al. beta-CA-specific inhibitor dithiocarbamate Fc14-584B: a novel antimycobacterial agent with potential to treat drug-resistant tuberculosis. Journal of Enzyme Inhibition and Medicinal Chemistry. 32 (1), 832-840 (2017).
- Kazokaite, J., Aspatwar, A., Kairys, V., Parkkila, S., Matulis, D. Fluorinated benzenesulfonamide anticancer inhibitors of carbonic anhydrase IX exhibit lower toxic effects on zebrafish embryonic development than ethoxzolamide. Drug and Chemical Toxicology. 40 (3), 309-319 (2017).
- Howe, K., et al. The zebrafish reference genome sequence and its relationship to the human genome. Nature. 496 (7446), 498-503 (2013).
- Granato, M., Nusslein-Volhard, C. Fishing for genes controlling development. Current Opinion in Genetics & Development. 6 (4), 461-468 (1996).
- Bambino, K., Chu, J. Zebrafish in Toxicology and Environmental Health. Current Topics in Developmental Biology. 124, 331-367 (2017).
- Goldsmith, P. Zebrafish as a pharmacological tool: the how, why and when. Current Opinion in Pharmacology. 4 (5), 504-512 (2004).
|
english
|
With sliding continuously, the Indian rupee plunged by 3 paise to 73. 64 versus the US dollar on Friday.
The rupee fell since the demand of importers for the American currency has increased.
Besides constant demand of the American currency from importers, a sink in the domestic equity markets in the opening trade also mulls over on the local unit, according to traders.
However, the losses in the Indian currency were partial as the greenback weakened contrary to some currencies overseas.
On Thursday, the Foreign Exchange market remained closed on account of “Dussehra”.
The domestic currency had closed lower by 13 paise to 73. 61 against the greenback on Wednesday.
Meanwhile, the S&P BSE Sensex traded low at 411. 85 points or 1. 18% to 34,367. 73 while the broader Nifty dropped to 136 points or 1. 30% to trade at 10,317. 05.
|
english
|
Twenty people, including a Delhi Police head constable, have died so far in the riots that broke out on 24th February in Maujpur and Jafrabad areas of Delhi’s North East district.
Since then there have been incidents of stone-pelting, houses, factories and entire slums being burnt, violence against protestors, and incidents of targeted violence against people from the Muslim community.
Several reporters narrated in first-person accounts how men wearing saffron tilaks raised ‘Jai Shri Ram’ slogans as they burned down vehicles and shops.
Amidst all the hatred, chaos and violence, some instances of unity, love and brotherhood have emerged. Many have come together to step up donation camps for victims injured in the riots.
View this post on InstagramA post shared by (@indiatimesinsta)
From Whatsapp, Facebook and Twitter, Good Samaritans are using all channels to procure some of the most basic needs for people who have lost homes in the violence. From Sanitary pads, Diapers, Soaps, Dupattas, Blankets, Toothbrush you name it people are sending in Whatsapp forwards and tweeting out locations where you can drop these items for the victims.
Here are some ways in which people are arranging donations for riot victims:
Apart from donations, during the clashes, residents of the affected helped each other selflessly. Residents of Yamuna Vihar formed a human chain to ensure that school children are escorted safely amidst violence.
Locals form a human chain to escort schoolchildren to safety.
Many Gurudwara managements in the area made adequate arrangements for accommodation and langar fort the affected people. The Sikh community in North Delhi, including a Gurdwara in Majnoo Ka Tila offered to help the injured and the needy on Monday, February 24.
.
In Seelampur, Dalits blocked the roads against aggressive mobs and secured the area to give shelter to their Muslim neighbours.
According to a report by India Today, even a local BJP ward councillor from Yamuna Vihar came forward to help a Muslim family. The report states that long-time friend of the family, came to the rescue and prevented the mob from causing harm.
Delhi may be festered in anti –Muslim and CAA violence at but its these gestures that give us hope and faith even in difficult times.
|
english
|
Vienna: External Affairs Minister S Jaishankar has slammed the slow pace of the UN reforms, saying those who are enjoying the benefits of permanent membership are not in a hurry to see reforms.
India has been at the forefront of efforts at the UN to push for urgent long-pending reform of the Security Council, emphasising that it rightly deserves a place at the UN high table as a permanent member.
“You will have a situation when the world’s most populous country is not among the permanent members of the security council, what does it say about the state of the UN”, Jaishankar said in an interview to Austria’s national broadcaster ORF on Monday.
“So my sense is, it will take some time, hopefully not too much time. I can see a growing body of opinion among UN members who believe that they must be changed. It’s not just us,” Jaishankar said.
The five permanent members are Russia, the UK, China, France and the United States and these countries can veto any substantive resolution.
“You have entire Africa and Latin America left out, with developing countries vastly underrepresented. This was an organisation invented in 1945. It’s 2023,” he added.
There has been growing demand to increase the number of permanent members to reflect the contemporary global reality.
Jaishankar arrived in Austria from Cyprus and is on the second leg of his two-nation tour.
This is the first EAM-level visit from India to Austria in the last 27 years, and it takes place against the backdrop of 75 years of diplomatic relations between the two countries in 2023.
On Sunday, while addressing members of the Indian diaspora here in the Austrian capital, Jaishankar said a 77-year-old organisation like the United Nations needs a “refresh”, asserting that pushing for a major overhaul in the top global body is an important part of New Delhi’s foreign policy.
|
english
|
<filename>vendor/gomod.garykim.dev/nc-talk/room/room.go
// Copyright (c) 2020 <NAME> <<EMAIL>>, All Rights Reserved
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package room
import (
"context"
"errors"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/monaco-io/request"
"gomod.garykim.dev/nc-talk/constants"
"gomod.garykim.dev/nc-talk/ocs"
"gomod.garykim.dev/nc-talk/user"
)
var (
// ErrEmptyToken is returned when the room token is empty
ErrEmptyToken = errors.New("given an empty token")
// ErrRoomNotFound is returned when a room with the given token could not be found
ErrRoomNotFound = errors.New("room could not be found")
// ErrUnauthorized is returned when the room could not be accessed due to being unauthorized
ErrUnauthorized = errors.New("unauthorized error when accessing room")
// ErrNotModeratorInLobby is returned when the room is in lobby mode but the user is not a moderator
ErrNotModeratorInLobby = errors.New("room is in lobby mode but user is not a moderator")
// ErrUnexpectedReturnCode is returned when the server did not respond with an expected return code
ErrUnexpectedReturnCode = errors.New("unexpected return code")
// ErrTooManyRequests is returned if the server returns a 429
ErrTooManyRequests = errors.New("too many requests")
// ErrLackingCapabilities is returned if the server lacks the required capability for the given function
ErrLackingCapabilities = errors.New("lacking required capabilities")
// ErrForbidden is returned if the user is forbidden from accessing the requested resource
ErrForbidden = errors.New("request forbidden")
// ErrUnexpectedResponse is returned if the response from the Nextcloud Talk server is not formatted as expected
ErrUnexpectedResponse = errors.New("unexpected response")
)
// TalkRoom represents a room in Nextcloud Talk
type TalkRoom struct {
User *user.TalkUser
Token string
}
// Message represents a message to be sent
type Message struct {
Message string
ActorDisplayName string
ReplyTo int
}
func (t *Message) toParameters() map[string]string {
return map[string]string{
"message": t.Message,
"actorDisplayName": t.ActorDisplayName,
"replyTo": strconv.Itoa(t.ReplyTo),
}
}
// NewTalkRoom returns a new TalkRoom instance
// Token should be the Nextcloud Room Token (e.g. "<PASSWORD>" if the room URL is https://cloud.mydomain.me/call/d6zoa2zs)
func NewTalkRoom(tuser *user.TalkUser, token string) (*TalkRoom, error) {
if token == "" {
return nil, ErrEmptyToken
}
if tuser == nil {
return nil, user.ErrUserIsNil
}
return &TalkRoom{
User: tuser,
Token: token,
}, nil
}
// SendMessage sends a string message in the Talk room
func (t *TalkRoom) SendMessage(msg string) (*ocs.TalkRoomMessageData, error) {
return t.SendComplexMessage(&Message{Message: msg})
}
// SendComplexMessage sends a Message type message in the talk room
func (t *TalkRoom) SendComplexMessage(msg *Message) (*ocs.TalkRoomMessageData, error) {
url := t.User.NextcloudURL + constants.BaseEndpoint + "chat/" + t.Token
client := t.User.RequestClient(request.Client{
URL: url,
Method: "POST",
Params: msg.toParameters(),
})
res, err := client.Do()
if err != nil {
return nil, err
}
if res.StatusCode() != 201 {
return nil, ErrUnexpectedReturnCode
}
msgInfo, err := ocs.TalkRoomSentResponseUnmarshal(&res.Data)
if err != nil {
return nil, err
}
return &msgInfo.OCS.TalkRoomMessage, err
}
// DeleteMessage deletes the message with the given messageID on the server.
//
// Requires "delete-messages" capability on the Nextcloud Talk server
func (t *TalkRoom) DeleteMessage(messageID int) (*ocs.TalkRoomMessageData, error) {
// Check for required capability
capable, err := t.User.Capabilities()
if err != nil {
return nil, err
}
if !capable.DeleteMessages {
return nil, ErrLackingCapabilities
}
url := t.User.NextcloudURL + constants.BaseEndpoint + "/chat/" + t.Token + "/" + strconv.Itoa(messageID)
client := t.User.RequestClient(request.Client{
URL: url,
Method: "DELETE",
})
res, err := client.Do()
if err != nil {
return nil, err
}
if res.StatusCode() != http.StatusOK && res.StatusCode() != http.StatusAccepted {
return nil, ErrUnexpectedReturnCode
}
msgInfo, err := ocs.TalkRoomSentResponseUnmarshal(&res.Data)
if err != nil {
return nil, err
}
return &msgInfo.OCS.TalkRoomMessage, nil
}
// ReceiveMessages starts watching for new messages
func (t *TalkRoom) ReceiveMessages(ctx context.Context) (chan ocs.TalkRoomMessageData, error) {
c := make(chan ocs.TalkRoomMessageData)
err := t.TestConnection()
if err != nil {
return nil, err
}
url := t.User.NextcloudURL + constants.BaseEndpoint + "chat/" + t.Token
requestParam := map[string]string{
"lookIntoFuture": "1",
"includeLastKnown": "0",
}
lastKnown := ""
res, err := t.User.GetRooms()
if err != nil {
return nil, err
}
for _, r := range *res {
if r.Token == t.Token {
lastKnown = strconv.Itoa(r.LastReadMessage)
break
}
}
go func() {
for {
if ctx.Err() != nil {
return
}
if lastKnown != "" {
requestParam["lastKnownMessageId"] = lastKnown
}
client := t.User.RequestClient(request.Client{
URL: url,
Params: requestParam,
Timeout: time.Second * 60,
})
res, err := client.Resp()
if err != nil {
continue
}
// If it seems that we no longer have access to the chat for one reason or another, stop the goroutine and set error in the next return.
if res.StatusCode == http.StatusNotFound {
_ = res.Body.Close()
c <- ocs.TalkRoomMessageData{Error: ErrRoomNotFound}
return
}
if res.StatusCode == http.StatusUnauthorized {
_ = res.Body.Close()
c <- ocs.TalkRoomMessageData{Error: ErrUnauthorized}
return
}
if res.StatusCode == http.StatusTooManyRequests {
_ = res.Body.Close()
c <- ocs.TalkRoomMessageData{Error: ErrTooManyRequests}
return
}
if res.StatusCode == http.StatusForbidden {
_ = res.Body.Close()
c <- ocs.TalkRoomMessageData{Error: ErrForbidden}
return
}
if res.StatusCode == http.StatusOK {
lastKnown = res.Header.Get("X-Chat-Last-Given")
data, err := ioutil.ReadAll(res.Body)
_ = res.Body.Close()
if err != nil {
continue
}
message, err := ocs.TalkRoomMessageDataUnmarshal(&data)
if err != nil {
continue
}
for _, msg := range message.OCS.TalkRoomMessage {
c <- msg
}
continue
}
_ = res.Body.Close()
}
}()
return c, nil
}
// TestConnection tests the connection with the Nextcloud Talk instance and returns an error if it could not connect
func (t *TalkRoom) TestConnection() error {
if t.Token == "" {
return ErrEmptyToken
}
url := t.User.NextcloudURL + constants.BaseEndpoint + "chat/" + t.Token
requestParam := map[string]string{
"lookIntoFuture": "0",
"includeLastKnown": "0",
}
client := t.User.RequestClient(request.Client{
URL: url,
Params: requestParam,
Timeout: time.Second * 30,
})
res, err := client.Do()
if err != nil {
return err
}
switch res.StatusCode() {
case http.StatusOK:
return nil
case http.StatusNotModified:
return nil
case http.StatusNotFound:
return ErrRoomNotFound
case http.StatusPreconditionFailed:
return ErrNotModeratorInLobby
}
return ErrUnexpectedReturnCode
}
|
go
|
He will take over from Bazmi Husain, who has been named by the ABB Group as its global chief technology officer. Husain has been leading the Indian business since 2011.
Prior to this appointment, Sharma was global managing director for ABB’s low voltage systems business unit and was based in Malaysia. He started his career working for ABB in India and has also worked in Germany and Switzerland.
Download The Economic Times News App to get Daily Market Updates & Live Business News.
|
english
|
{"generated_at": "2017-01-27T09:37:33.244285", "required_by": ["horae.properties", "horae.reports", "horae.search", "horae.ticketing", "horae.dashboard"], "requires": ["setuptools", "grok", "zope.principalannotation", "horae.auth", "horae.core", "horae.layout", "horae.timeaware"], "package": "horae.lifecycle"}
|
json
|
{"Id":2288,"Name":"Nishikigoi Support Aircraft (Standard)","GroupName":null,"Class":"Nishikigoi Support Aircraft","Variant":"(Standard)","Tonnage":240,"BattleValue":1524,"Technology":{"Id":1,"Name":"Inner Sphere","Image":null,"SortOrder":0},"Cost":0,"Rules":"Experimental","TROId":207,"TRO":"XTRBoondocks","RSId":207,"RS":"XTRBoondocks","EraIcon":"https://i.ibb.co/4jf2wfz/era7-jihad.png","DateIntroduced":"3071","EraId":14,"EraStart":3068,"ImageUrl":"https://i.ibb.co/8YKLhhC/koi-ryu-trva.png","IsFeatured":true,"IsPublished":true,"Release":1.00,"Type":{"Id":24,"Name":"Support Vehicle","Image":"NonStandard.gif","SortOrder":6},"Role":{"Id":110,"Name":"Missile Boat","Image":null,"SortOrder":4},"BFType":"SV","BFSize":3,"BFMove":"12\"g","BFTMM":2,"BFArmor":3,"BFStructure":17,"BFThreshold":0,"BFDamageShort":3,"BFDamageMedium":4,"BFDamageLong":4,"BFDamageExtreme":0,"BFOverheat":0,"BFPointValue":52,"BFAbilities":"AFC,AMP,BAR,C81.5,IF4,MHQ8,TUR(3/4/4,IF4)","Skill":4,"FormatedTonnage":"240"}
|
json
|
<gh_stars>100-1000
{
"symbol": "HEX",
"address": "0x2b591e99afE9f32eAA6214f7B7629768c40Eeb39",
"decimals": 8,
"name": "HEX",
"ens_address": "",
"website": "https://hex.win",
"logo": {
"src": "https://ipfs.io/ipfs/QmXt29juPFuD8uuSu4XicskqjGCCBpLJgU5JzxvUcPDd7h",
"width": "128",
"height": "128",
"ipfs_hash": "QmXt29juPFuD8uuSu4XicskqjGCCBpLJgU5JzxvUcPDd7h"
},
"support": {
"email": "",
"url": "https://t.me/HEXcrypto"
},
"social": {
"blog": "",
"chat": "https://t.me/HEXcrypto",
"facebook": "https://www.facebook.com/HEXcrypto",
"forum": "",
"github": "https://github.com/bitcoinHEX",
"gitter": "",
"instagram": "https://www.instagram.com/HEXcrypto",
"linkedin": "",
"reddit": "https://www.reddit.com/r/HEXcrypto",
"slack": "",
"telegram": "https://t.me/HEXcrypto",
"twitter": "https://twitter.com/HEXCrypto",
"youtube": "https://youtube.com/HexCrypto"
}
}
|
json
|
OnePlus is preparing to unveil a new product portfolio on February 7th at its official Cloud 11 event. Although OnePlus has confirmed the launch of four devices, a recent leak revealed that a fifth device, the OnePlus 11R, will join the party at the event. And now, the OnePlus Pad, the company's first-ever tablet, is also confirmed to be unveiled.
The Chinese smartphone manufacturer has reportedly confirmed that its first tablet will be revealed at the event. Before the official confirmation, the leaks allegedly confirmed the tablet's existence, and MySmartPrice and OnLeaks even shared design renders and specifications for the upcoming device.
Coming to the device, the official poster for the OnePlus Pad shows a green color along with an alleged 11. 6-inch display with thin bezels and a slim design, as well as a single camera on the back with an LED flash. According to the tipsters, the device will also be available in black. The camera module is located in the center of the ostensibly metal unibody chassis, as opposed to the top-left position found on most phones and tablets. For the time being, no information about the camera's specifications or the device's internals has leaked.
What Other Devices Will Oneplus Launch?
As for other devices, the OnePlus 11 will be the highlight of the event, with a 6. 7-inch display, the latest Qualcomm Snapdragon 8 Gen 2 chipset, and a 50MP triple-camera setup. Other confirmed entries include the OnePlus TV 65 Q2 Pro and the OnePlus Buds Pro 2, which will be available in Green and Black colors and is expected to be an improvement over its predecessor.
In addition, the company will release its first-ever mechanical keyboard, a teaser for which was released a few days ago. Finally, the OnePlus 11R is expected to be unveiled at the event. The device is expected to have a 6. 7-inch 120Hz display, a Snapdragon 8+ Gen 1 processor, a 50MP triple camera setup, and a 5,000mAh battery with support for 100W fast charging.
Google's sudden and unexpected entry into the tablet industry with the introduction of the as-yet-unsold Pixel tablet last year caught everyone by surprise. Subsequently, both Xiaomi and Realme introduced their own tablets, while Samsung has been selling tablets from its Tab A series for some time. While there is no word on the price of the OnePlus Tab, it will face stiff competition from the aforementioned players when it launches, and the cost will play a significant role in its success.
|
english
|
<reponame>hpc-chile/2019-10-08-webgl2<gh_stars>1-10
body
{
align-content: center;
align-items: center;
font-family: sans-serif;
background: linear-gradient(rgb(110, 182, 101), white) no-repeat;
}
h1
{
text-align: center;
}
ul
{
padding: 20px;
list-style-type: none;
}
li
{
margin: 0.5rem;
}
a, a:active, a:link, a:hover
{
font-weight:bold;
text-decoration: none;
color:rgb(0, 75, 75);
}
a:hover
{
color:black;
}
.backButton
{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.content
{
align-content: center;
text-align: center;
}
|
css
|
<gh_stars>0
#include <math.h>
#include <cmath>
#include <RcppEigen.h>
#include <Rcpp.h>
#include <iostream>
#include <vector>
#include <Eigen/Core>
#include <iostream>
// [[Rcpp::depends(RcppEigen)]]
typedef Eigen::Triplet<float> T; //tripleta para rellenar matrices sparse
typedef Eigen::MappedSparseMatrix<float> MSpMat; //alias para matriz sparse
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorXd; //alias para vector sparse
using namespace Rcpp;
// [[Rcpp::export]]
Eigen::SparseMatrix<float> Kernel_float ( NumericMatrix M, int h, int w, double distancia, double sigJ, double sigd)
{
// Funcion para calcular la matriz de similaridades de todos los puntos de una imagen
// input: w: altura en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES
// h: ancho en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES
// distancia: limite de la vecindad del pixel a considerar
// M: imagen de 2 dimensiones (EN ESCALA DE GRISES)
// sigJ: sigma para kernel gaussiano, de la imagen
// sigd: sigma para kernell gaussiano, de las distancias
//output: W, similaridad calculada, sparse
int i, j, k, l = 0 ;
float vecindad = (float)distancia;
float d2 = 0.;
float calculo = 0.;
std::vector<T> tripletList; //inicializamos tripleta
tripletList.reserve((int)floor(h*h*w*w*.1));
//comienza calculo de matriz de similaridades
for(i=0; i < h; i++)
{
for(j=0; j< w; j++ )
{
for(k=0; k<h; k++)
{
for(l=0; l<w; l++)
{
d2 = (float)(pow(i-k,2)+pow(j-l,2));
if(d2 <= vecindad)
{
calculo = (float) (exp(-pow(M(j,i)-M(l,k),2)/(2*pow(sigJ,2))-d2/(2*pow(sigd,2))));
tripletList.push_back(T((j)*h+i, (l)*h+k, calculo ));
}
}
}
}
}
//termina calculo de matriz de similaridades
Eigen::SparseMatrix<float> W(h*w, h*w); //construccion de matriz de similaridades
W.setFromTriplets(tripletList.begin(), tripletList.end());
return(W);
}
|
cpp
|
Why you can trust TechRadar We spend hours testing every product or service we review, so you can be sure you’re buying the best. Find out more about how we test.
Here’s how the Lenovo Yoga 910 performed in our suite of benchmark tests:
GeekBench 3: 3,674 (single-core); 7,890 (multi-core)
The Lenovo Yoga 910 comes ready to get work done, and it ran flawlessly through multiple days of punishing tasks in our testing. There isn’t the slightest hint of slowness, even while editing multiple photos in Photoshop with a dozen websites open in both Firefox and Chrome, and yet another app streaming Google Play Music.
Although it’s great that the Lenovo Yoga 910 is powerful enough to keep up with our daily tasks, it doesn’t do so without protest. The laptop’s fans kick on regularly and loudly, even with a simple process such as a web browser. What’s more, the notebook gets noticeably warm on our lap, even with the cooling system operating at full blast.
The Yoga series has had a history of turning in lower benchmark numbers and better battery life in our testing; however, that trend doesn’t continue this time around.
Lenovo’s top 2-in-1 bests everyone – that includes the and – in the graphics department with the highest 3DMark scores. However, it has a markedly lower score in PCMark 8 and other processor-testing benchmarks than HP’s rivaling hybrid and Razer’s Ultrabook.
We attribute these results to the fact that Lenovo may have tuned the integrated graphics on it’s 2-in-1 to better help it drive 4K screen, whereas the Blade Stealth is only QHD+ and the Spectre x360 features a Full HD display. 3DMark puts every machine on a level playing ground by running the tests at Full HD, allowing the Yoga 910 to pull ahead.
PCMark 8 and the other CPU-taxing benchmarks make no such accommodation, and so the Ultra HD resolution ends up hurting the convertible’s overall scores elsewhere. For instance, the Yoga 910’s results sit about even with and follow the same trends as the .
Lenovo rates the Yoga 910 for 10 hours of battery life with its new 79 Watt-hour cells, but it really should cut that estimate in half. The convertible laptop lasted an average of 4 hours and 23 minutes through the grueling PCMark 8 battery test, and then only nine minutes longer on our more conservative movie test.
We were also only able to put in about four hours of work – with an extra 30 minutes if we lowered the screen brightness – before we had to plug in the notebook.
That’s far less than the nine-hour marathon the managed to run on our movie benchmark. Sure, HP’s 13-inch convertible has a far lower screen resolution, but even its bigger, 4K with discrete graphics lasted a full hour longer.
Despite packing denser energy cells, they simply can’t keep up with the greater energy demands of the Lenovo Yoga 910’s 4K display and near-constantly running fans.
In an age of the ever-thinning , Lenovo dares to swim against the current to bring us an 2-in-1 laptop that’s bigger, badder and still a tiny bit thinner. What’s more, it doesn’t sacrifice a quality typing experience nor all its legacy USB ports to get there.
The added screen real estate and bump up in resolution rivals even the ’s spacious, sharp display. Add a solid pair of speakers to back up the visuals, and the Lenovo Yoga 910 is one of the best 2-in-1 devices for watching video.
Unfortunately, for all the good that comes with the Yoga’s latest revision, battery life takes a dramatic hit. How hot and loud this laptop runs, as well as almost always requiring maximum screen brightness, are both knocks against the Lenovo Yoga 910.
The Lenovo Yoga series has been a rollercoaster of admirable innovations and disappointments. The was a feat of engineering marred by poor performance and poorer battery life. Short after, the was a resounding improvement, adding more battery life and processing power. Unfortunately, the Yoga 910 feels like both an improvement and misstep for the storied laptop line.
On one hand, it’s one of Lenovo’s best designs yet, packing a 14-inch screen into a 13-inch chassis. On the other, we wish the machine’s thermals were more refined. The larger, sharper display would have been a welcome addition if it didn’t come at such a cost to battery life.
Ultimately, the Lenovo Yoga 910 is an undeniably unique 2-in-1 laptop in a sea of homogeneous hybrids. It’s sleek styling and gorgeous, larger display are well worth your attention. However, if you’re looking for something a little cheaper and longer lasting, the HP Spectre x360 (both the 13- and 15-inch versions) may better suit your needs.
Kevin Lee was a former computing reporter at TechRadar. Kevin is now the SEO Updates Editor at IGN based in New York. He handles all of the best of tech buying guides while also dipping his hand in the entertainment and games evergreen content. Kevin has over eight years of experience in the tech and games publications with previous bylines at Polygon, PC World, and more. Outside of work, Kevin is major movie buff of cult and bad films. He also regularly plays flight & space sim and racing games. IRL he's a fan of archery, axe throwing, and board games.
|
english
|
Conduct and Interpret a Factor AnalysisWhat is the Factor Analysis?
The Factor Analysis is an explorative analysis. Much like the cluster analysis grouping similar cases, the factor analysis groups similar variables into dimensions. This process is also called identifying latent variables. Since factor analysis is an explorative analysis it does not distinguish between independent and dependent variables.
Factor Analysis reduces the information in a model by reducing the dimensions of the observations. This procedure has multiple purposes. It can be used to simplify the data, for example reducing the number of variables in predictive regression models. If factor analysis is used for these purposes, most often factors are rotated after extraction. Factor analysis has several different rotation methods—some of them ensure that the factors are orthogonal. Then the correlation coefficient between two factors is zero, which eliminates problems of multicollinearity in regression analysis.
Factor analysis is also used in theory testing to verify scale construction and operationalizations. In such a case, the scale is specified upfront and we know that a certain subset of the scale represents an independent dimension within this scale. This form of factor analysis is most often used in structural equation modeling and is referred to as Confirmatory Factor Analysis. For example, we know that the questions pertaining to the big five personality traits cover all five dimensions N, A, O, and I. If we want to build a regression model that predicts the influence of the personality dimensions on an outcome variable, for example anxiety in public places, we would start to model a confirmatory factor analysis of the twenty questionnaire items that load onto five factors and then regress onto an outcome variable.
Factor analysis can also be used to construct indices. The most common way to construct an index is to simply sum up the items in an index. In some contexts, however, some variables might have a greater explanatory power than others. Also sometimes similar questions correlate so much that we can justify dropping one of the questions completely to shorten questionnaires. In such a case, we can use factor analysis to identify the weight each variable should have in the index.
for Video:
|
english
|
const webpack = require('webpack');
const path = require('path');
module.exports = ({ mode }) => ({
entry: path.resolve('./src/index.ts'),
mode,
output: {
filename: './index.js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'commonjs'
},
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
externals: {
react: {
commonjs: "react",
commonjs2: "react",
amd: "React",
root: "React"
},
},
module: {
rules: [
{test: /\.ts(x?)$/, loader: "ts-loader"}
]
}
});
|
javascript
|
Motegi (Japan), Aug 24 (IANS)
A gearbox issue cost Indian driver Narain Karthikeyan a strong finish after an incident-packed Super Formula fourth round that concluded at the Twin Ring Motegi.
Pitstop issues, racing incidents and a torrential downpour made it one of the most action-packed races of the season, although the Indian didn't get the opportunity to experience most of it.
"After catching up to the competition massively in limited time, the crazy rain-hit race was the best opportunity to get a solid result out of it but unfortunately we didn't get that far," Karthikeyan said.
Starting 12th on the grid, Karthikeyan executed a lightning getaway to gain two places on the tight and twisty circuit.
Running strong in the top-10, Karthikeyan pitted on Lap 13, pushing hard on his in-lap and jumped Kunimoto during the pit stop. Exiting the pits on cold tyres, the Indian drove on the limit and closed upon his old Formula 1 rival Vitantonio Liuzzi.
Meanwhile, he had also been battling an intermittent gearbox issue since Lap 10 which was affecting the downshift under braking. As the laps ticked past, the problem worsened and resultantly he went off track under braking while battling with the Italian Liuzzi on Lap 20.
Two laps later the gearbox went completely belly-up, leaving the car stuck in fifth gear and forcing Narain into the pits for retirement.
"Most of the track is made up of slow, second gear corners so it was impossible to continue. So far we haven't had a normal, clean weekend in the season but that can be expected in a championship as intense and closely competitive as this," said Karthikeyan.
"Almost everything is new, so obviously we can't expect everything to fall in place right from the start. Just having the pace isn't enough. We need to be able to put the weekend together which hopefully will happen in the upcoming races."
Three rounds remain in the season with two scheduled in September at Autopolis and Sportsland SUGO followed by the finale at the Suzuka Circuit in November.
Karthikeyan currently sits in 11th position out of 20 drivers with 4.5 points in four rounds.
|
english
|
import { NotionCache } from '@nishans/cache';
import { NotionOperations } from '@nishans/operations';
import { INotionCache } from '@nishans/types';
import { NotionCore } from '../../libs';
import { default_nishan_arg, o } from '../utils';
afterEach(() => {
jest.restoreAllMocks();
});
it(`get space_views`, async () => {
const cache: INotionCache = {
...NotionCache.createDefaultCache(),
user_root: new Map([ [ 'user_root_1', { space_views: [ 'space_view_1' ] } as any ] ]),
space_view: new Map([ [ 'space_view_1', { alive: true } as any ] ])
};
const user_root = new NotionCore.Api.UserRoot({
...default_nishan_arg,
cache,
id: 'user_root_1'
});
const space_view = await user_root.getSpaceView('space_view_1');
expect(space_view.getCachedData()).toStrictEqual({ alive: true });
});
it(`update space_views`, async () => {
const cache: INotionCache = {
...NotionCache.createDefaultCache(),
space_view: new Map([ [ 'space_view_1', { alive: true } as any ] ]),
user_root: new Map([ [ 'user_root_1', { space_views: [ 'space_view_1' ] } as any ] ])
},
executeOperations = jest.spyOn(NotionOperations, 'executeOperations').mockImplementationOnce(async () => undefined);
const user_root = new NotionCore.Api.UserRoot({
...default_nishan_arg,
cache,
id: 'user_root_1'
});
const space_view = await user_root.updateSpaceView([ 'space_view_1', { joined: false } ]);
expect(space_view.getCachedData()).toStrictEqual({
alive: true,
joined: false
} as any);
expect(executeOperations.mock.calls[0][0]).toStrictEqual([
o.sv.u('space_view_1', [], {
joined: false
})
] as any);
});
|
typescript
|
package br.com.java8.watch;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
/**
*
* @author Renato
*/
public class WatchPath {
public static void main(String[] args) {
final Path path = Paths.get("watch");
watchFile(path);
}
private static void watchFile(final Path path) throws RuntimeException {
try (final WatchService watchService = path.getFileSystem().newWatchService()) {
path.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
final WatchKey watchKey = watchService.poll(1, TimeUnit.SECONDS);
if (watchKey != null) {
watchKey.pollEvents()
.stream()
.forEach(e -> System.out.println(e.context()));
}
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
java
|
Nithya Menen is back to Mollywood!
'Mersal' actress Nithya Menen who was last seen in the Dulquer Salmaan starrer film '100 days of love' is all set to make her comeback in Mollywood. After working together in Karmayogi and Poppins, Nithya Menen is once again teaming up director V.K. Prakash. Titled 'Pranaa', the upcoming movie will feature the actress in the female lead.
The movie is a multi-lingual made in four languages-Hindi, Kannada, Telugu and Malayalam. Touted to be a thriller which deals with a social issue, Pranaaa will discuss writer’s freedom and growing intolerance, says VK Prakash.
The movie's cinematography is by P.C. Sreeram and sound design by Resul Pookutty. With the lyrics written by Rajesh Jayaram, Pranaa's music department will be handled by Lui Bancui. More details on the cast will be revealed soon!
Follow us on Google News and stay updated with the latest!
|
english
|
U-19 World Cup: Team India announce 17-man squad, Yash Dhull to lead the side in West Indies – The BCCI on Sunday confirmed that Yash Dhull will join the likes of Virat Kohli, Dinesh Karthik, Ishan Kishan and Prithvi Shaw among others in leading India at a U-19 World Cup. With the tournament set to kick start in less than a month’s time, India have announced a 17-man contingent for the same, with five standby players in line with the COVID-19 situation. Follow Insidesport.in for all U-19 World Cup updates.
The All-India Junior Selection Committee has picked India’s squad for the upcoming ICC Under 19 Men’s Cricket World Cup to be played in the West Indies from 14th January to 5th February 2022 across four host countries. The 14th edition of the tournament will see 16 teams competing for the trophy in 48 matches.
India are the most successful team having won four titles in 2000, 2008, 2012 and 2018. India have also been runner-up in 2016 and in the previous edition of the tournament held in 2020 in New Zealand. Yash Dhull and Co. would hope to add an unprecedented fifth title to India’s list of honours when they touchdown in the Caribbean.
|Yash Dhull (Captain)
|UTCA (Chandigarh)
|SK Rasheed (vice-captain)
|Dinesh Bana (WK)
|Aaradhya Yadav (WK)
|UTCA (Chandigarh)
The format will see the top two teams from each of the four groups advance to the Super League while the remaining teams feature in the Plate across 23 days of competition. India U19 are placed in Group B. India kick off their campaign on January 15th against South Africa, while will play their final group game against Uganda a week later.
|
english
|
they are like a faulty bow.(A)
because of their insolent tongue.(B)
They will be ridiculed for this in the land of Egypt.(C)
13 Though they offer sacrificial gifts[a](A)
and eat the flesh,(B)
the Lord does not accept them.
Now he will remember their guilt(C)
and punish their sins;(D)
they will return to Egypt.(E)
3 They will not stay in the land of the Lord.
Instead, Ephraim will return to Egypt,(A)
and they will eat unclean food(B) in Assyria.(C)
6 The calf itself will be taken to Assyria(A)
as an offering to the great king.[a](B)
Ephraim will experience shame;(C)
Israel will be ashamed of its counsel.(D)
The Christian Standard Bible. Copyright © 2017 by Holman Bible Publishers. Used by permission. Christian Standard Bible®, and CSB® are federally registered trademarks of Holman Bible Publishers, all rights reserved.
|
english
|
package com.imooc.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
/**
* @author gusuchen
* Created in 2018-01-13 22:31
* Description: 地铁站信息表
* Modified by:
*/
@Accessors(chain = true)
@Data
@Entity
@Table(name = "subway_station")
@NoArgsConstructor
public class SubwayStation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 所属地铁线id
@Column(name = "subway_id")
private Long subwayId;
// 站点名称
private String name;
}
|
java
|
/**
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package JavaBitcoin;
/**
* A chain listener register with the block chain for notifications when a
* new block is stored in a database or the chain head is updated.
*/
public interface ChainListener {
/**
* Notifies the listener when a new block is stored in the database
*
* @param storedBlock The stored block
*/
public void blockStored(StoredBlock storedBlock);
/**
* Notifies the listener when the block status changes
*
* @param storedBlock The stored block
*/
public void blockUpdated(StoredBlock storedBlock);
/**
* Notifies the listener when the chain head is updated
*/
public void chainUpdated();
}
|
java
|
It has been confirmed that John Cena will challenge Roman Reigns at SummerSlam for the WWE Universal Championship. The Leader of the Cenation got his match after an interesting turn of events on this week's episode of SmackDown.
John Cena made his return to WWE at Money in the Bank with one thing on his mind: face Roman Reigns at SummerSlam for the WWE Universal Championship.
Unfortunately for Cena, The Head of the Table was not too interested in accepting his challenge, and instead chose to accept that of The Prince, Finn Balor. The contract signing was set for tonight and would have seen the match between Reigns and Balor confirmed if it were not for some unexpected interruptions.
Finn Balor was about to sign the contract, but was rudely interrupted by Baron Corbin who attempted to steal the contract away from The Prince. However, this prompted John Cena to come out and in turn steal the contract from Baron Corbin, before putting his own name on the dotted line.
There was a lot of confusion following the segment, with many questioning whether it was a legit contract signing, considering that Finn Balor's name was on the contract.
It was later confirmed by WWE officials Adam Pearce and Sonya Deville that since Cena's name was on the dotted line, it will officially be John Cena vs. Roman Reigns for the Universal Championship at SummerSlam.
It was originally expected that John Cena would be on his way following SummerSlam. WWE announced the Summer of Cena, which was expected to last all the way till the Biggest Party of the Summer.
However, it looks like this is no longer the plan, as the Leader of the Cenation is expected to stay on well after SummerSlam. The 16-time world champion has been advertised to make an appearance at Madison Square Garden in New York on September 10th, 2020.
Things have certainly gotten very interesting in the lead up to SummerSlam. Are you content with John Cena facing Roman Reigns? Or will there be another swerve from WWE Creative? Let us know in the comments section below.
|
english
|
The tradition of Dalit theatre in Gujarati is as old as the bhavai folk form of Gujarat and has existed since the tenth century. However, it was only created and received attention as a separate category after India’s Independence, especially after the 1970s, with the rise of the Dalit movement in India. During this period, two major trends were visible: plays based on history, myths and legends, and social plays. Most of these plays were published first and performed later or were not performed at all. Dalit theatre in Gujarati is dense and diverse. The broad umbrella term ‘Dalit theatre’ is meant only to categorise and not to homogenise.
Even within the Gujarati Dalit community, which has a shared goal to get rid of caste oppression, there exist different positions and different levels of radicalism. Playwrights like Mohan Parmar and Harish Mangalam provide a peaceful picture of the caste conflict; in their plays, things seem to resolve at the end. The implicit suggestion is that peaceful and harmonious living is possible between people belonging to different castes. Parmar and Mangalam seem to be siding with the argument that as long as Dalits can live with dignity and respect, harmonious living with the larger Hindu society is possible. On the other hand, playwrights like Harshad Parmar, Raju Solanki and Dalpat Chauhan are more radical in their position which is revealed through their plays that indicate an impossibility of any kind of truce. They oppose the entire structure of caste, and their plays indicate that the only way to eradicate caste is through some sort of revolution—at home, street or the royal court. Their position, at least as revealed through their plays, is for an ontologically different category for Dalits, separate from the larger Hindu structure.
The state of emergency imposed by the then prime minister Indira Gandhi in 1975 and the anti-reservation agitations in 1981 and 1985 all over the country fuelled the Dalit movement. What began with poetry soon encapsulated other forms of writing, like stories, novels, dramas and autobiographies. The period was dominated by Suresh Joshi, with his modernist stance and focus on formal and structural elements of literature. Several of his students and followers populated this period with works that showed finesse and expertise in exploring limits of both language and literary form. From this period of aadhunik yug (era of high modernism), there was a shift to what is termed as anu-aadhunik yug (post-modern era) in Gujarati literary historiography. The rise of Dalit writing marked a clear departure from the Suresh Joshi school of thought, and the focus was reoriented on social context and content in literary works with social realism being the major mode of writing.
As far as drama is concerned, the gap between commercial and amateur or serious theatre existed then as it does now. Drama was and still is a marginal form compared to other forms of writing like poetry and short story. Not many plays by Dalit writers were performed, and those that were closed after a few shows. If anything, this reveals the casteist nature of performance practices in Gujarati theatre. Plays dealing with the issues of caste were written mostly for publication, and cultural institutions like Gujarat Dalit Sahitya Academy and literary journals like Hayati dedicated to Dalit writing encouraged, patronised and published them.
Often, historically marginalised communities assert their voice and identity by invoking heroic figures from history and legends. In the Dalit community, Veer Mayo and Dr B.R. Ambedkar are Dalit heroes who are often invoked, and their life stories are recounted as glorious examples of the resistance of the Dalit community against caste oppression.
The legend of Veer Mayo, where the prefix ‘veer’ stands for brave, has been passed on orally from generation to generation right from the twelfth century. The main premise of the legend goes thus: ‘Siddhraj Jaysinh, an illustrious King of Solanki dynasty in the 11th century built a lake called sahastraling. But there were no springs of water in it. The story goes that according to the soothsayers, it needed a human sacrifice. Megh Mayo offered himself for the sacrifice on the condition that the humiliation of Dalits is reduced.’[2] Since there is no historical evidence available, nobody is sure of the facts of the event.
As is often the case in India, history overlaps with folktales. Keeping the story of Megh Mayo as the central premise, several Dalit Gujarati authors have written plays. Krishnachandra Parmar’s play Tipe Tipe Shonit Aapya (Drop by Drop, I Gave My Blood) modifies the magic element in the legend. Parmar portrays Mayo as an architect of the Sahastraling lake. The construction of the lake is so complex that it requires toiling for several days; Mayo devotes himself to its construction and because of the constant hard work that it demands, his health deteriorates, and he eventually dies of tuberculosis. As one can see, Parmar is more interested in the industrious Mayo as opposed to the martyr Mayo.
Shivabhai Parmar’s Maya ni Mahanta (The Greatness of Mayo), while keeping the legend as it is, includes the historical contexts and reasons for the curse on the Sahastraling lake. Mayo is not the protagonist but is one of the main characters in a play full of other more developed characters. Mayo’s final act of sacrifice is what makes him great and provides the play its title.
Shrikant Verma’s Veer Mayo (Brave Mayo), collected in his book Triveni Sangam, dramatises the legend as it is but stresses upon the caste discrimination of the society as well as the state. In the play, eventually, King Siddhraj Jaysingh transforms and is enlightened about the evils of caste.
Dalpat Chauhan’s Patan ne Gondre (At the Borders of Patan), included in his book Anaryavart, is arguably the most nuanced dramatisation of the legend of Mayo and the most scathing critique of the caste structure. Mayo is portrayed as a revolutionary who enlightens the people who had internalised the oppression and were not even aware that they were ill-treated and that they can raise their voice. Mayo inspires the people and is ready to mobilise them against the state; however, Munjal Mehta, the Brahmin minister of Siddhraj Jaysingh, comes up with a conspiracy regarding the Sahastraling lake which requires sacrifice by Mayo. Mayo understands what is going to happen to him, so he puts forth his conditions for the sacrifice, which includes eradication of discrimination and vindication of the dignity of Dalits.
Like Mayo, Babasaheb Ambedkar is another stalwart upheld as a figure of resistance in plays by Dalit authors. Since the events of Babasaheb’s life are quite well known, we do not find major innovations or exciting interplay of perspectives in plays that are based on his life. Babaldas Chavda has written a children’s play and three full-length plays based on Ambedkar’s life. Baalak Bhimrao Ambedkar (The Child Bhimrao Ambedkar) is a children’s play where Ambedkar’s childhood incidents are dramatised. Chavda’s other three plays, Andhkaar (Darkness), Kraanti-rath (The chariot of revolution) and Betaaj Badshah (A crownless King), include events from Ambedkar’s personal and political life up until his death.
Similarly, Jayanti Makwana’s Yug-Purush (Representative of an Era) and Alok Anand’s Krantiveer Ambedkar (The Brave Revolutionary Ambedkar) are also based on well-known incidents from Ambedkar’s life.
Social plays include the ones set in a modern, contemporary India; they also comprise street plays that were published and enjoyed a ‘literary’ life beyond the performance space.
Contemporary social plays are usually shorter in length and mostly one-act compared to the full-length historical-mythological plays. The reason behind the more elaborate historical-mythological plays could be that myths come with an already existing structure and story, while social plays demand a new story and structure to be created.
In most Indian vernacular languages, Dalit writing had gained momentum by the 1970s, and Gujarati Dalit writing was no different. The anti-reservation agitations in the 1980s only acted as a fuel for the already burgeoning field of Dalit writing. Raju Solanki’s Brahmanvaad ni Barakhadi (Alphabets of Brahmanism), a very political street play that ran for over 25 shows, uses anti-caste agitation as a backdrop and exposes the oppressive regimes of Brahmanism.
Mohan Parmar’s Bahishkaar (Boycott) presents two central female characters, Monghi and Kanaklata, a Dalit and a high caste woman, respectively. Monghi works as a sweeper in the colony Kanaklata lives in; she is treated badly and insulted by Kanaklata following which she stops working at her house. Kanaklata has to face her relatives’ ire due to the untidiness of the house as it was only because of Monghi that the house was clean. Kanaklata realises her mistake and apologises to Monghi, and the play ends on a peaceful note. Monghi in Gujarati means ‘expensive or high-priced’; using Monghi as a central character, Parmar hints at the high price the upper castes pay if they do not treat the Dalits in a dignified manner. Another way of reading the play is that the dignity and self-respect of Dalits are not cheap; their pride cannot be bought easily.
Harish Mangalam takes a developmental issue as the central theme of his play Lyo Chonp Paado (Now Switch on the Light). Set in a village in post-Independence India, the play depicts the harsh realities that many villages face even today. In the play, in a village with limited power supply, electricity does not reach a Dalit household because the upper-caste people do not let it happen as sharing power supply with everyone would mean they would get less of it. The conflict exacerbates and eventually becomes a burning issue. In the end, the government gives in and increases the power supply which provides electricity to Dalit households first and to the Savarna households only later.
Other notable social plays include Dalpat Chauhan’s Harifai (Competition), Kanti Makwana’s Aabhadchet (Untouchability), Sitaram Barot’s Tirango (Tricolour) and B. Kesharshivam’s Raam ni Moorti (Rama’s Idol).
There is also Meeta Bapodara’s Swapna (Dreams) which gives us a glimpse into medieval Gujarat. She creates an imaginary village where, once a year, a person from any caste is allowed to be a Brahmin. Prabhu and Babu, a Dalit couple, struggle to make ends meet despite doing manual labour for almost the entire village. Prabhu’s only dream is to be made Brahmin one day, so he can elevate his family and bring about radical changes. The play ends on a tragic note as the Prabhu and Babu die and their son inherits their dreams.
A play that deals with the ideas of pollution and Brahminical snobbery, Keshubhai Desai’s Gobar Gondaji is a story of a conflict between an upper-caste couple and a Dalit man which follows what happens after the Dalit man accidentally touches an upper-caste woman.
Other notable plays by non-Dalit writers are Rajendra Mehta’s Nakalank (Spotless), Durgesh Shukla’s Punaragman (The Return) and Gaurishankar Chaturvedi’s Garibo na beli (The Patron of the Poor).
[2] Gaijan, Dalit Literary Tradition in Gujarat: A Critical Study, 197.
[3] Chauhan, Gujarati Dalit Sahitya ni Kedie, 54.
Baradi, Hasmukh. History of Gujarati Theatre. Delhi: National Book Trust, 1998.
———. Harifai. Ahmedabad: Gujarati Dalit Sahitya Academy, 2000.
Chavda, Babaldas. Betaaj Badshah. Ahmedabad, 2005.
Dave, Jagdish. 'Social Plays: 1851–1900.' In Natak Budreti: Introspecting 150 years of Gujarati Theatre, 127–129. Ahmedabad, 2007.
Dharwadker, Aparna. Theatres of Independence: Drama, Theory and Urban Performance in India Since 1947.Iowa: University of Iowa Press, 2009.
Gaijan, M.B. Dalit Literary Tradition in Gujarat: A Critical Study. Ahmedabad: Gujarati Dalit Sahitya Academy, 2007.
Gandhi, Hiren. 'Development Oriented Theatre: Challenges and Prospects.' Natak Budreti: Introspecting 150 years of Gujarati theatre, 130–134. Ahmedabad, 2007.
Joshi, Umashankar. Saapna Bhara. Ahmedabad: Gurjar Prakashan, 1936.
Mangalam, Harish. Gujarati Dalit Ekankiyaan. Ghaziabaad: Sahitya Sansthaan, 2011.
———. ‘Sacchai ni Najare’. In Gujarati Dalit Sahitya ni kedie, edited by Dalpat Chauhan. Ahmedabad: Gurjar Prakashan, 2015.
———, ed. Hayati. Ahmedabad: Gujarati Dalit Sahitya Academy, 2002.
Parmar, Mohan. Bahishkar. Ahmedabad: Rannade Prakashan, 2004.
Parmar, Krishnachandra. Tipe Tipe Shonit Aapya, 1986. Ahmedabad.
Verma, Shrikant. Triveni Sangam. Ahmedabad, 1977.
Yashaschandra, Sitanshu. ‘Rang Che’—An Anthology of Post-Independence Gujarati Plays. New Delhi: National Book Trust, 2010.
|
english
|
<reponame>Xtuden-com/airwaves
{
"id": "d1519-1",
"text": "SPECIAL DEVICES CENTER\nOFFICE OF NAVAL RESEARCH\nHUMAN ENGINEERING DEPARTMENT\nTECHNICAL REPORTS ON\nINSTRUCTIONAL FILM AND INSTRUCTIONAL TELEVISION\nGovernment activities may obtain copies without charge by submitting re¬\nquest to the Commanding Officer and Director, Special Devices Center, Port\nWashington, N. Y., Attn: Code 2121.\nNongovernment activities may purchase copies from the Department of Commerce,\nOffice of Teclinical Services, Washington 25, D. C.\nINSTRUCTIONAL FILM RESEARCH REPORTS\n(PENNSYLVANIA STATE\nUNIVERSITY)\nTitle\nSPECDEVCEN\nTechnical\nReport No.\nDept, of\nCommerce\nPB No.\nPrice\nInstructional Film Production, Utiliza¬\ntion and Research in Great Britain,\nCanada, Australia\n269-7-1\n105782\n$ .75\nMusic in Motion Pictures: Review of\nLiterature With Implications for In¬\nstructional Films\n269-7-2\n105783\n.50\nThe Relative Effectiveness of Massed\nVersus Spaced Film Presentation\n269-7-3\n105784\n1.00\nCommentary Variations: Level of Ver¬\nbalization, Personal Reference, and\nPhase Relations in Instructional Films\non Perceptual-Motor Tasks\n269-7-4\n105785\n1.00\nEffects of Learner Representation in\nFilm-Mediated Perceptual Motor-Learning\n269-7-5\n105786\n1.00\nLearning Theories and Instructional\nFilm Research\n269-7-6\n105787\n.25\nRelationship of Length and Fact Frequen¬\ncy to Effectiveness of Instructional\nMotion Pictures\n269-7-7\n105788\n.50\nContributions of Film Introductions and\nFilm Summaries to Learning from Instruc¬\ntional Films\n269-7-8\n105789\n.75\nThe Effect of Attention Gaining Devices\non Film-Mediated Learning\n269-7-9\n105790\n.75\nThe Effects of Prestige and Identifica¬\ntion Factors on Attitude Restructuring\nand Learning from Sound Films\n269-7-10\n105791\n.50"
}
|
json
|
<filename>hooks/before_platform_add/setup_android_assets.js
#!/usr/bin/env node
process.exit(0);
var path = require( "path" ),
fs = require( "fs" ),
shell = require( "shelljs" ),
rootdir = process.argv[ 2 ],
androidroot = rootdir + "/platforms/android",
iconroot = rootdir + "/assets/icon/android",
screenroot = rootdir + "/assets/screen/android";
try {
fs.lstatSync( androidroot ).isDirectory();
console.log( "android platform already exists. skipping." );
}
catch( e ) {
//icon renaming to phonegap Android directories and filenames
[ "", "-hdpi", "-ldpi", "-mdpi", "-xhdpi" ].forEach( function( item ) {
shell.mkdir( "-p", iconroot + "/drawable" + item );
shell.exec( "cp " + iconroot + "/*" + item + ".png " + iconroot + "/drawable" + item + "/icon.png", {silent:true} );
});
shell.rm( iconroot + "/*.png" );
//splashscreen renaming to phonegap Android directories and filenames
[ "", "-hdpi", "-ldpi", "-mdpi", "-xhdpi" ].forEach( function( item ) {
shell.mkdir( "-p", screenroot + "/drawable" + item );
shell.exec( "cp " + screenroot + "/*" + item + "-p*.png " + screenroot + "/drawable" + item + "/splash.png", {silent:true} );
shell.exec( "cp " + screenroot + "/*" + item + "-l*.png " + screenroot + "/drawable" + item + "/splash_landscape.png", {silent:true} );
});
shell.rm( screenroot + "/*.png" );
}
process.exit(0);
|
javascript
|
<reponame>asarraf/GraceCrawler<gh_stars>0
{
"title":"Jericho",
"genre":"Drama",
"creators":["<NAME>","<NAME>","<NAME>"],
"cast":["<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","<NAME> Jr.","<NAME>","<NAME>","<NAME>"],
"country_of_origin":"United States",
"seasons":2,
"episodes":29,
"start_date":"Wed Sep 20 00:00:00 EDT 2006",
"end_date":"Tue Mar 25 00:00:00 EDT 2008"
}
|
json
|
<reponame>YirangDevs/Back
package com.api.yirang.email.application;
import com.api.yirang.auth.application.intermediateService.UserService;
import com.api.yirang.auth.domain.user.model.User;
import com.api.yirang.common.support.generator.RandomGenerator;
import com.api.yirang.email.dto.EmailNotifiableRequestDto;
import com.api.yirang.email.dto.EmailValidationRequestDto;
import com.api.yirang.email.dto.EmailValidationResponseDto;
import com.api.yirang.email.dto.*;
import com.api.yirang.email.exception.*;
import com.api.yirang.email.model.Email;
import com.api.yirang.email.repository.EmailRepository;
import com.api.yirang.email.util.Validation;
import com.google.common.hash.Hashing;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Service
@Transactional
@RequiredArgsConstructor
public class EmailService {
private final UserService userService;
private final JavaMailSender javaMailSender;
private final MailContentHelper mailContentHelper;
private final EmailRepository emailRepository;
private static final String EMAIL_HOST = "<EMAIL>";
private static final String SENDER_NAME = "Yirang";
private static final String MATCHING_MAIL_TITLE = "[Yirang 재가봉사] 매칭완료 안내 메일입니다.";
private static final String VERIFY_MAIL_TITLE = "[Yirang 재가봉사] 본인 이메일을 인증해주세요";
private static final String WITHDRAW_MAIL_TITLE = "[Yirang 재가봉사] 회원탈퇴 안내 메일입니다.";
// Volunteer Email
private static final String ACTIVITY_GUIDE_TITLE = "[Greensignal 재가봉사] 봉사 안내 메일입니다.";
private static final String ACTIVITY_RECOMMEND_TITLE = "[Greesignal 재가봉사] 선호지역의 추천 봉사 메일입니다.";
// Privates
void sendEmail(String toEmail, String subject, String content){
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setFrom(EMAIL_HOST, SENDER_NAME);
helper.setTo(toEmail);
helper.setSubject(subject);
helper.setText(content, true);
}
catch (Exception ex){
throw new CustomMessagingException();
}
javaMailSender.send(message);
}
public void sendMatchingEmail(Long userId,
List<MatchingMailContent> matchingMailContents){
User user = userService.findUserByUserId(userId);
final String toEmail = user.getEmail();
final String subject = MATCHING_MAIL_TITLE;
final String content = mailContentHelper.generateMatchingMailContent(matchingMailContents);
sendEmail(toEmail, subject, content);
}
public void sendWithdrawEmail(Long userId,
UserWithdrawMailContent userWithdrawMailContent,
List<MatchingMailContent> matchingMailContentList) {
User user = userService.findUserByUserId(userId);
final String toEmail = user.getEmail();
final String subject = WITHDRAW_MAIL_TITLE;
final String content = mailContentHelper.generateWithdrawMailContent(userWithdrawMailContent, matchingMailContentList);
sendEmail(toEmail, subject, content);
}
public void sendGuideEmail(
Long userId,
ActivityGuideMailContent activityGuideMailContent
)
{
User user = userService.findUserByUserId(userId);
final String toEmail = user.getEmail();
final String subject = ACTIVITY_GUIDE_TITLE;
final String content = mailContentHelper.generateGuideEmailContent(activityGuideMailContent);
sendEmail(toEmail, subject, content);
}
public void sendFailEmail(
Long userId
)
{
User user = userService.findUserByUserId(userId);
final String toEmail = user.getEmail();
final String subject = ACTIVITY_GUIDE_TITLE;
final String content = mailContentHelper.generateFailEmailContent(user.getRealname());
sendEmail(toEmail, subject, content);
}
public void sendRegionRecommendEmail(
Long userId,
NoticeRecommendMailContent noticeRecommendMailContent
)
{
User user = userService.findUserByUserId(userId);
final String toEmail = user.getEmail();
final String subject = ACTIVITY_RECOMMEND_TITLE;
final String content = mailContentHelper.generateNoticeRecommendEmailContent(user.getRealname(), noticeRecommendMailContent);
sendEmail(toEmail, subject, content);
}
public void sendVerificationEmail(Long userId){
// User 찾기
User user = userService.findUserByUserId(userId);
// Email 찾기
Email email = emailRepository.findEmailByUser_UserId(userId).orElseThrow(new EmailNullException(userId));
// 이미 검증이 된 Email 인 경우 에러
if (email.getValidation().isValid()){
throw new EmailAlreadyValidException();
}
// Email이 비었거나 Null 이면 에러
if (user.getEmail() == null || user.getEmail().equals("")){
throw new EmailAddressNullException();
}
// Certification 생성하기
String certificationNumbers = RandomGenerator.RandomStringOfNumbersWithLength(6);
// Email 업데이트 하기
emailRepository.updateEmailCertificationWithUserId(userId, Hashing.sha256().hashString(certificationNumbers, StandardCharsets.UTF_8).toString());
final String toEmail = user.getEmail();
final String subject = VERIFY_MAIL_TITLE;
final String content = mailContentHelper.generateVerifyMailContent(user, certificationNumbers);
sendEmail(toEmail, subject, content);
}
public EmailValidationResponseDto checkMyValidation(Long userId) {
User user = userService.findUserByUserId(userId);
Email email = findEmailByUserId(userId);
return new EmailValidationResponseDto(email.getValidation());
}
public void verifyMyEmail(Long userId, EmailValidationRequestDto emailValidationRequestDto) {
User user = userService.findUserByUserId(userId);
Email email = emailRepository.findEmailByUser_UserId(userId).orElseThrow(new EmailNullException(userId));
String certification = Hashing.sha256().hashString(emailValidationRequestDto.getCertificationNumbers(), StandardCharsets.UTF_8).toString();
// 이미 검증이 되어있는 경우
if (email.getValidation().isValid()){
throw new EmailAlreadyValidException();
}
// 만약 Certification number가 일치 하지 않으면 Error
if (!email.getCertificationNumbers().equals(certification)){
throw new EmailCertificationFailException();
}
// 다 괜찮으면 validation_YES로 바꾸기
emailRepository.updateEmailVerificationWithUserId(userId, Validation.VALIDATION_YES);
}
// Simple CRUD operations
public Email findEmailByUserId(Long userId){
return emailRepository.findEmailByUser_UserId(userId).orElseThrow(new EmailNullException(userId));
}
public void changeMyNotification(Long userId, EmailNotifiableRequestDto emailNotifiableRequest) {
User user = userService.findUserByUserId(userId);
Email email = findEmailByUserId(userId);
emailRepository.updateEmailNotificationWithUserId(userId, emailNotifiableRequest.getNotifiable());
}
}
|
java
|
Conor McGregor has seemingly made a promise to his fans regarding his highly-anticipated UFC comeback. It comes at a time when he's set the combat sports community abuzz by hinting at a potential rematch against boxing legend Floyd Mayweather Jr.
McGregor's most recent combat sports contest witnessed him suffer a leg injury and lose to Dustin Poirier via first-round TKO in a lightweight MMA bout in July 2021. For several months, the consensus was that the Irishman's injury hiatus would end in 2023, and he'd face rival TUF coach Michael Chandler in his comeback fight.
However, 'The Notorious' hasn't re-entered the USADA testing pool yet and recently appeared to turn his attention from the possible Chandler matchup to a potential fight against newly-crowned BMF champion Justin Gaethje.
Taking to Twitter, McGregor has now suggested that the UFC may not be interested in booking him against Chandler. The MMA icon indicated several other more intriguing opponents for his comeback fight.
Furthermore, McGregor tweeted, hinting that he could fight retired boxing great Floyd Mayweather Jr. in a rematch in the boxing ring. They previously clashed in a professional boxing bout in August 2017, with Mayweather winning via 10th-round TKO. McGregor tweeted a video of himself sparring and wrote:
"Don’t forget, I played ping pong with Floyd’s head. I carried him! In the rematch I am going to use this style of attack but alongside a more destructive set of shots on top also. B4, it was just ping pong, this time it’s ping pong and babe Ruth with a baseball bat. KO incoming."
Soon after he hinted at a rematch against Mayweather, several fans criticized him and implored him to focus on his UFC return instead. On that note, McGregor posted another tweet, whereby he seems to have reassured his fans that he's working on his comeback fight. The 35-year-old tweeted a video of himself hitting a boxing bag and wrote:
"I’ll start recording my work again to share with you all while we get this next fight on and set. It’s coming I promise. All my real fans, the fans of the real fighter, it’s coming, I promise!"
What's next for former UFC champion Conor McGregor?
Former UFC featherweight and lightweight champion Conor McGregor is regarded as one of the biggest box office draws in combat sports history. Since a fight against him generally brings lucrative pay, there's no shortage of opponents for him.
Michael Chandler has been the frontrunner to fight Conor McGregor in his comeback matchup. However, as noted, McGregor has hinted at fighting BMF champion Justin Gaethje and teasing a boxing rematch against Floyd Mayweather Jr.
Moreover, after the Jake Paul-Nate Diaz boxing match on August 5th, 2023, Conor McGregor lambasted longtime rival Nate Diaz and dared him to return to the UFC to complete their trilogy. That said, McGregor's comeback opponent and date haven't been officially announced yet.
|
english
|
---
layout: full-width
title: Pricing Plans
---
<div class="pricing">
<div class="header">
<h1>Pricing Plans</h1>
<p>Simple & transparent plans for all Serverless developers. Get started for free or <a href="mailto:{{ site.sales_email }}">contact sales</a>.</p>
<a class="announcement" href="{% link _posts/2020-03-17-managing-your-seed-costs.md %}">
<span>
<span class="content">
Learn how to manage your Seed costs
</span>
<i class="fa fa-angle-right" aria-hidden="true"></i>
</span>
</a>
</div>
<div class="table">
<div class="row">
<div class="individual">
<div class="cost">
<p class="header">
Individual
</p>
<div class="numbers">
<div>
<p><span>$</span>0</p>
<p>per month</p>
</div>
<p>Free forever</p>
</div>
<a class="action signup" {% include signup-link.html %}>
Sign up for free
</a>
</div>
</div>
<div class="startup">
<div class="cost">
<p class="header">
Team
</p>
<div class="numbers">
<div>
<p><span>$</span>30</p>
<p>per month</p>
</div>
<p>3 users + $10 per user / mo</p>
</div>
<a class="action start" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
</div>
</div>
</div>
<div class="row">
<div class="enterprise">
<div class="cost">
<p class="header">
Enterprise
</p>
<div class="numbers">
<div>
<p><span>$</span>600</p>
<p>per month</p>
</div>
<p>10 users + $15 per user / mo</p>
</div>
<a class="action upgrade" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
</div>
</div>
</div>
</div>
<div class="comparison">
<div class="list">
<div class="header">
<div> </div>
<div class="individual">
<h6>Individual</h6>
<div class="cost">
<p>$0</p>
<p>per month</p>
</div>
</div>
<div class="team">
<h6>Team</h6>
<div class="cost">
<p>$30</p>
<p>per month</p>
</div>
</div>
<div class="enterprise">
<h6>Enterprise</h6>
<div class="cost">
<p>$600</p>
<p>per month</p>
</div>
</div>
</div>
<div class="section">
<h6 class="name">Members</h6>
<div class="feature">
<div class="name">
<span class="title expand">Users</span>
<p>The number of users included in the plan.</p>
</div>
<div>1</div>
<div>3</div>
<div>10</div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Additional users</span>
<p>Add additional users to the account.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div>$10 per user / month</div>
<div>$15 per user / month</div>
</div>
</div>
<div class="section">
<h6 class="name">Fully-Managed CI/CD</h6>
<div class="feature">
<div class="name">
<span class="title expand">Concurrent builds</span>
<i class="fa fa-bullhorn expand" aria-hidden="true"></i>
<p>Deploy all the services in your monorepo app concurrently, at no extra charge! <a href="#concurrency">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><b>Unlimited</b></div>
<div><b>Unlimited</b></div>
<div><b>Unlimited</b></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Build minutes</span>
<p>The amount of time it takes for a build to complete, rounded up to the nearest minute.</p>
</div>
<div>500</div>
<div>4500</div>
<div>30000</div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Additional minutes</span>
<p>Add additional build minutes to your account.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div>$10 / month for 1500</div>
<div>$10 / month for 1500</div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Incremental deploys</span>
<i class="fa fa-bullhorn expand" aria-hidden="true"></i>
<p>Seed will only deploy the services and Lambda functions that've been updated. <a href="{% link _docs/what-are-incremental-deploys.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Deploy phases</span>
<i class="fa fa-bullhorn expand" aria-hidden="true"></i>
<p>Deploy the interdependent services in your monorepo app in separate phases. <a href="{% link _docs/configuring-deploy-phases.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Multi-region deployments</span>
<p>Deploy your app to multiple regions with ease. <a href="{% link _docs/multi-region-deployments.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Slack & email notifications</span>
<p>Get Slack or email notification on the status of your builds.</p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Custom build webhooks</span>
<p>Setup webhooks to be triggered once your builds complete. <a href="{% link _docs/adding-build-notifications.md %}#custom-webhooks">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">CI/CD integration</span>
<p>Configure Seed to deploy after completing the build jobs in CircleCI, Travis CI, or GitHub Actions. <a href="{% link _docs/connect-your-own-ci.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">API custom domains</span>
<p>Configure custom domains for your API endpoints. <a href="{% link _docs/configuring-custom-domains.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">High-performance builds</span>
<p>Configure your builds to run in high performance machines. <a href="{% link _docs/build-machine-types.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Run Docker commands</span>
<p>Run Docker commands in your build processes. <a href="{% link _docs/docker-commands-in-your-builds.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">GitHub Enterprise</span>
<p>Add your GitHub Enterprise repos in Seed. <a href="{% link _docs/enabling-github-enterprise.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#github-enterprise">Add-on</a></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">GitLab Self-Managed</span>
<p>Add your GitLab Self-Managed repos in Seed. <a href="{% link _docs/enabling-gitlab-self-managed.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#gitlab-self-managed">Add-on</a></div>
</div>
</div>
<div class="section">
<h6 class="name">Logging & Monitoring</h6>
<div class="feature">
<div class="name">
<span class="title expand">Real-time monitoring</span>
<p>Get real-time error alerts for all your Lambda functions without any code changes.</p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Monitored events</span>
<i class="fa fa-bullhorn expand" aria-hidden="true"></i>
<p>That's right! Lambda monitoring in Seed is free and unlimited.</p>
</div>
<div><b>Unlimited</b></div>
<div><b>Unlimited</b></div>
<div><b>Unlimited</b></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Logs and metrics</span>
<p>View live logs and metrics to debug and monitor the health of your app. <a href="{% link _docs/viewing-logs.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Weekly reports</span>
<p>Get weekly email reports with the latency of your APIs and the top errors in your Lambda functions. <a href="{% link _docs/viewing-app-reports.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
</div>
<div class="section">
<h6 class="name">Security & Access Control</h6>
<div class="feature">
<div class="name">
<span class="title expand">Audit logs</span>
<p>Get a complete log of all the actions applied to your organization in Seed. <a href="{% link _docs/audit-logs-in-seed.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Single-sign on</span>
<p>Allow the members of your organization to login to Seed with your SAML based SSO provider.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#single-sign-on">Add-on</a></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Mandatory 2FA</span>
<p>Require that all the members of your organization enable 2 factor authentication on Seed. <a href="{% link _docs/enabling-mandatory-two-factor-auth.md %}">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Role-based access</span>
<p>Restrict the stages that members in your organization have access to. <a href="{% link _docs/adding-organization-members.md %}#member-roles">Learn more <i class="fa fa-angle-right" aria-hidden="true"></i></a></p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
</div>
<div class="section">
<h6 class="name">Billing Options</h6>
<div class="feature">
<div class="name">
<span class="title expand">Billing role</span>
<p>Billing roles only have access to your billing settings in Seed.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Invoice billing</span>
<p>Pay your bills on Seed via invoices, rather than using a credit card.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Custom contract</span>
<p>Sign a custom agreement with the terms and policies that work best for your enterprise.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-check-circle" aria-hidden="true"></i></div>
</div>
</div>
<div class="section">
<h6 class="name">Support</h6>
<div class="feature">
<div class="name">
<span class="title expand">Support</span>
<p>Community support is available anytime <a href="https://discourse.serverless-stack.com/">via our forums</a>. Email support is available via <a href="mailto:{{ site.email }}">{{ site.email }}</a>.</p>
</div>
<div>Community</div>
<div>Email</div>
<div>Email</div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Priority support</span>
<p>Priority support ensures that your support requests are triaged appropriately by our staff. Available 5 days a week over email and chat.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#priority-support">Add-on</a></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Support SLA</span>
<p>Get premium support and guaranteed response times by adding a support SLA to your plan.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#support-sla">Add-on</a></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Uptime SLA</span>
<p>Get guaranteed performance and stability by adding our uptime SLA to your plan.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#uptime-sla">Add-on</a></div>
</div>
<div class="feature">
<div class="name">
<span class="title expand">Concierge onboarding</span>
<p>Our engineers will work with your team to ensure that your project is set up the right way on Seed. And without any downtime.</p>
</div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><i class="fa fa-times-circle" aria-hidden="true"></i></div>
<div><a href="#concierge-onboarding">Add-on</a></div>
</div>
</div>
</div>
</div>
<div id="concurrency" class="concurrency">
<div class="container">
<div class="icon">
<i class="fa fa-exchange" aria-hidden="true"></i>
</div>
<div class="copy">
<h4>Why build concurrency matters</h4>
<p>Traditional CIs are not well-suited for Serverless apps that have multiple services. They charge you extra to deploy them concurrently. This means that if your app has 5 services and each service takes 2 minutes to deploy; your entire app will take 5 x 2 minutes = 10 minutes to deploy, when using one concurrent build server.</p>
<p>Seed on the other hand, will deploy all your services concurrently. So the entire deployment will take only 2 minutes. At no extra cost!</p>
</div>
</div>
</div>
<div class="opening-action">
<p>Sign up for a free account. And upgrade when you are ready. Or <a href="mailto:{{ site.sales_email }}">contact sales</a> if you have custom needs.</p>
<div class="controls">
<a class="sales" href="mailto:{{ site.sales_email }}">
Contact Sales
</a>
</div>
</div>
<div class="addons">
<hr id="enterprise-add-ons" />
<h4>Enterprise Add-Ons</h4>
<p>Upgrade right from <a href="{{ site.console_url }}{{ site.upgrade }}">your console</a>. Or <a href="mailto:{{ site.sales_email }}">contact us</a> if you need any help.</p>
<div class="list">
<div id="github-enterprise" class="addon">
<div class="icon">
<i class="fa fa-git" aria-hidden="true"></i>
</div>
<h6>GitHub Enterprise</h6>
<p>Add apps connected to your GitHub Enterprise repos in Seed.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
GitHub Enterprise
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Private Build IPs
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>100</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="gitlab-self-managed" class="addon">
<div class="icon">
<i class="fa fa-git" aria-hidden="true"></i>
</div>
<h6>GitLab Self-Managed</h6>
<p>Add apps connected to your GitLab Self-Managed repos in Seed.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
GitLab Self-Managed
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Private Build IPs
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>100</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="single-sign-on" class="addon">
<div class="icon">
<i class="fa fa-key" aria-hidden="true"></i>
</div>
<h6>Single Sign-On</h6>
<p>Sign in to Seed using your SAML based SSO provider.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
SAML SSO
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Okta
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Integration Support
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>500</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="priority-support" class="addon">
<div class="icon">
<i class="fa fa-life-ring" aria-hidden="true"></i>
</div>
<h6>Priority Support</h6>
<p>Priority response for all support requests. Available from 9 AM - 5 PM PST on business days.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
9 AM - 5 PM
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
8 hr response time
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Priority response
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>500</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="support-sla" class="addon">
<div class="icon">
<i class="fa fa-life-ring" aria-hidden="true"></i>
</div>
<h6>Support SLA</h6>
<p>Guaranteed response time of 4 hours between 6 AM - 6 PM PST on business days. Business critical responses in 1 hour.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
6 AM - 6 PM
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
4 hr response time
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
1 hr business critical
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>4000</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="uptime-sla" class="addon">
<div class="icon">
<i class="fa fa-calendar-check-o" aria-hidden="true"></i>
</div>
<h6>Uptime SLA</h6>
<p>Seed build servers and web console backed by a 99.99% SLA.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
99.99%
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Build Servers
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Web Console
</span>
</div>
<div class="price">
<div class="numbers">
<span><span>$</span>2000</span>
<span>/ month</span>
</div>
<a class="action signup" href="{{ site.console_url }}{{ site.upgrade }}">
Upgrade
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Contact sales</a>
</p>
</div>
</div>
<div id="concierge-onboarding" class="addon">
<div class="icon">
<i class="fa fa-puzzle-piece" aria-hidden="true"></i>
</div>
<h6>Concierge Onboarding</h6>
<p>Ensure that your projects are configured on Seed the right way.</p>
<hr />
<div class="features">
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Migration plans
</span>
<span>
<i class="fa fa-check-circle" aria-hidden="true"></i>
Connect existing pipelines
</span>
</div>
<div class="price">
<a class="action learn" href="{% link concierge-onboarding.md %}">
Learn more <i class="fa fa-chevron-right" aria-hidden="true"></i>
</a>
<p class="email">
<a href="mailto:{{ site.sales_email }}">Get a quote</a>
</p>
</div>
</div>
</div>
</div>
<div class="contact">
<p>Need some help putting together the right plan?</p>
<div class="controls">
<a class="sales" href="mailto:{{ site.sales_email }}">
Contact Sales
</a>
</div>
</div>
<div class="faq">
<hr />
<h4>Frequently Asked Questions</h4>
<div class="list">
<ul class="fa-ul">
<li>
<span class="fa-li" ><i class="fa fa-chevron-right"></i></span>
<p>
What are build minutes?
</p>
<p>
Build minutes is the amount of time a build process takes to complete, rounded up to the nearest minute. There is a monthly limit on the total number of build minutes per account. For example, the Individual plan has a limit of 500 build minutes per month.
</p>
</li>
<li>
<span class="fa-li" ><i class="fa fa-chevron-right"></i></span>
<p>
How are build minutes calculated on an account?
</p>
<p>
The Team plan gives you 1500 build minutes per user on the account. So if your account has 10 users; it has a limit of 10 x 1500 build minutes = 15 000 build minutes per month. If you need more build minutes on your account, simply add another user to the account.
</p>
<p>
If you have custom requirements, feel free to <a href="mailto:{{ site.email }}">contact us</a>.
</p>
</li>
<li>
<span class="fa-li" ><i class="fa fa-chevron-right"></i></span>
<p>
What happens if I go over the build minutes limit?
</p>
<p>
For most cases the build minutes limit is more than enough. However, if you do go over the limit, we'll send you an email. Your account will still function normally, giving you a chance to upgrade your account. If you are significantly above the limit, you won't be able to trigger any new builds. But don't worry, it'll be back to normal once you upgrade your account or when the limit resets for the next month.
</p>
</li>
<li>
<span class="fa-li" ><i class="fa fa-chevron-right"></i></span>
<p>
What happens if I decide to move away from Seed?
</p>
<p>
You are not locked-in to using Seed in any way. We deploy to your AWS account on your behalf. So if you decide to move away at any point, your deployments will still work just as before.
</p>
</li>
<li>
<span class="fa-li" ><i class="fa fa-chevron-right"></i></span>
<p>
What if I have some Enterprise requirements not listed here?
</p>
<p>
No worries, we can figure out how to get you setup. Just <a href="mailto:{{ site.email }}">send us an email</a> with your requirements and we'll schedule a call with one of our engineers.
</p>
</li>
</ul>
</div>
<p>Feel free to <a href="mailto:{{ site.email }}">contact us</a> if you have any questions about our plans or features.</p>
</div>
</div>
|
html
|
{"attackers":[{"character_id":2113558071,"corporation_id":98550292,"damage_done":8689,"final_blow":true,"security_status":4.9,"ship_type_id":47466,"weapon_type_id":31876}],"killmail_id":71244075,"killmail_time":"2018-07-14T10:30:19-07:00","solar_system_id":30003600,"victim":{"alliance_id":99001333,"character_id":95536761,"corporation_id":625591217,"damage_taken":8689,"items":[{"flag":92,"item_type_id":31047,"quantity_destroyed":1},{"flag":16,"item_type_id":33101,"quantity_dropped":1},{"flag":11,"item_type_id":2048,"quantity_destroyed":1},{"flag":22,"item_type_id":17500,"quantity_dropped":1},{"flag":5,"item_type_id":12805,"quantity_dropped":2000},{"flag":31,"item_type_id":3082,"quantity_dropped":1},{"flag":13,"item_type_id":10190,"quantity_dropped":1},{"flag":29,"item_type_id":23025,"quantity_dropped":33},{"flag":5,"item_type_id":32014,"quantity_destroyed":8},{"flag":5,"item_type_id":32014,"quantity_dropped":1},{"flag":14,"item_type_id":10190,"quantity_dropped":1},{"flag":20,"item_type_id":4833,"quantity_dropped":1},{"flag":27,"item_type_id":3082,"quantity_dropped":1},{"flag":27,"item_type_id":23025,"quantity_dropped":33},{"flag":16,"item_type_id":28668,"quantity_dropped":32},{"flag":28,"item_type_id":3082,"quantity_dropped":1},{"flag":15,"item_type_id":2605,"quantity_dropped":1},{"flag":28,"item_type_id":23025,"quantity_dropped":33},{"flag":19,"item_type_id":5975,"quantity_dropped":1},{"flag":5,"item_type_id":23025,"quantity_dropped":1800},{"flag":31,"item_type_id":23025,"quantity_destroyed":33},{"flag":5,"item_type_id":28668,"quantity_dropped":35},{"flag":93,"item_type_id":31047,"quantity_destroyed":1},{"flag":94,"item_type_id":31185,"quantity_destroyed":1},{"flag":29,"item_type_id":3082,"quantity_dropped":1},{"flag":87,"item_type_id":23707,"quantity_dropped":5},{"flag":30,"item_type_id":3082,"quantity_destroyed":1},{"flag":12,"item_type_id":11269,"quantity_destroyed":1},{"flag":21,"item_type_id":3244,"quantity_destroyed":1},{"flag":5,"item_type_id":12801,"quantity_destroyed":1000},{"flag":30,"item_type_id":23025,"quantity_dropped":33}],"position":{"x":-4.41652915725771e+11,"y":-2.293124716952417e+10,"z":-4.5057653790072394e+11},"ship_type_id":17722}}
|
json
|
/**
* Copyright 2015 CANAL+ Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import config from "../../../config";
import log from "../../../log";
import {
Adaptation,
areSameContent,
ISegment,
Period,
Representation,
} from "../../../manifest";
import takeFirstSet from "../../../utils/take_first_set";
import BufferedHistory, {
IBufferedHistoryEntry,
} from "./buffered_history";
import { IChunkContext } from "./types";
/** Information stored on a single chunk by the SegmentInventory. */
export interface IBufferedChunk {
/**
* Complete size of the pushed chunk, in bytes.
* Note that this does not always reflect the memory imprint of the segment in
* memory:
*
* 1. It's the size of the original container file. A browser receiving that
* segment might then transform it under another form that may be more or
* less voluminous.
*
* 2. It's the size of the full chunk. In some scenarios only a sub-part of
* that chunk is actually considered (examples: when using append
* windows, when another chunk overlap that one etc.).
*/
chunkSize : number | undefined;
/**
* Last inferred end in the media buffer this chunk ends at, in seconds.
*
* Depending on if contiguous chunks were around it during the first
* synchronization for that chunk this value could be more or less precize.
*/
bufferedEnd : number|undefined;
/**
* Last inferred start in the media buffer this chunk starts at, in seconds.
*
* Depending on if contiguous chunks were around it during the first
* synchronization for that chunk this value could be more or less precize.
*/
bufferedStart : number|undefined;
/** Supposed end, in seconds, the chunk is expected to end at. */
end : number;
/**
* If `true` the `end` property is an estimate the `SegmentInventory` has
* a high confidence in.
* In that situation, `bufferedEnd` can easily be compared to it to check if
* that segment has been partially, or fully, garbage collected.
*
* If `false`, it is just a guess based on segment information.
*/
precizeEnd : boolean;
/**
* If `true` the `start` property is an estimate the `SegmentInventory` has
* a high confidence in.
* In that situation, `bufferedStart` can easily be compared to it to check if
* that segment has been partially, or fully, garbage collected.
*
* If `false`, it is just a guess based on segment information.
*/
precizeStart : boolean;
/** Information on what that chunk actually contains. */
infos : IChunkContext;
/**
* If `true`, this chunk is only a partial chunk of a whole segment.
*
* Inversely, if `false`, this chunk is a whole segment whose inner chunks
* have all been fully pushed.
* In that condition, the `start` and `end` properties refer to that fully
* pushed segment.
*/
partiallyPushed : boolean;
/**
* If `true`, the segment as a whole is divided into multiple parts in the
* buffer, with other segment(s) between them.
* If `false`, it is contiguous.
*
* Splitted segments are a rare occurence that is more complicated to handle
* than contiguous ones.
*/
splitted : boolean;
/**
* Supposed start, in seconds, the chunk is expected to start at.
*
* If the current `chunk` is part of a "partially pushed" segment (see
* `partiallyPushed`), the definition of this property is flexible in the way
* that it can correspond either to the start of the chunk or to the start of
* the whole segment the chunk is linked to.
* As such, this property should not be relied on until the segment has been
* fully-pushed.
*/
start : number; // Supposed start the segment should start from, in seconds
}
/** information to provide when "inserting" a new chunk into the SegmentInventory. */
export interface IInsertedChunkInfos {
/** The Adaptation that chunk is linked to */
adaptation : Adaptation;
/** The Period that chunk is linked to */
period : Period;
/** The Representation that chunk is linked to. */
representation : Representation;
/** The Segment that chunk is linked to. */
segment : ISegment;
/** Estimated size of the full pushed chunk, in bytes. */
chunkSize : number | undefined;
/**
* Start time, in seconds, this chunk most probably begins from after being
* pushed.
* In doubt, you can set it at the start of the whole segment (after
* considering the possible offsets and append windows).
*/
start : number;
/**
* End time, in seconds, this chunk most probably ends at after being
* pushed.
*
* In doubt, you can set it at the end of the whole segment (after
* considering the possible offsets and append windows).
*/
end : number;
}
/**
* Keep track of every chunk downloaded and currently in the linked media
* buffer.
*
* The main point of this class is to know which chunks are already pushed to
* the corresponding media buffer, at which bitrate, and which have been garbage-collected
* since by the browser (and thus may need to be re-loaded).
* @class SegmentInventory
*/
export default class SegmentInventory {
/**
* Keeps track of all the segments which should be currently in the browser's
* memory.
* This array contains objects, each being related to a single downloaded
* chunk or segment which is at least partially added in the media buffer.
*/
private _inventory : IBufferedChunk[];
private _bufferedHistory : BufferedHistory;
constructor() {
const { BUFFERED_HISTORY_RETENTION_TIME,
BUFFERED_HISTORY_MAXIMUM_ENTRIES } = config.getCurrent();
this._inventory = [];
this._bufferedHistory = new BufferedHistory(BUFFERED_HISTORY_RETENTION_TIME,
BUFFERED_HISTORY_MAXIMUM_ENTRIES);
}
/**
* Reset the whole inventory.
*/
public reset() : void {
this._inventory.length = 0;
}
/**
* Infer each segment's `bufferedStart` and `bufferedEnd` properties from the
* TimeRanges given.
*
* The TimeRanges object given should come from the media buffer linked to
* that SegmentInventory.
*
* /!\ A SegmentInventory should not be associated to multiple media buffers
* at a time, so each `synchronizeBuffered` call should be given a TimeRanges
* coming from the same buffer.
* @param {TimeRanges}
*/
public synchronizeBuffered(buffered : TimeRanges) : void {
const inventory = this._inventory;
let inventoryIndex = 0; // Current index considered.
let thisSegment = inventory[0]; // Current segmentInfos considered
const { MINIMUM_SEGMENT_SIZE } = config.getCurrent();
/** Type of buffer considered, used for logs */
const bufferType : string | undefined = thisSegment?.infos.adaptation.type;
const rangesLength = buffered.length;
for (let i = 0; i < rangesLength; i++) {
if (thisSegment === undefined) { // we arrived at the end of our inventory
return;
}
// take the i'nth contiguous buffered TimeRange
const rangeStart = buffered.start(i);
const rangeEnd = buffered.end(i);
if (rangeEnd - rangeStart < MINIMUM_SEGMENT_SIZE) {
log.warn("SI: skipped TimeRange when synchronizing because it was too small",
bufferType, rangeStart, rangeEnd);
continue;
}
const indexBefore = inventoryIndex; // keep track of that number
// Find the first segment either within this TimeRange or completely past
// it:
// skip until first segment with at least `MINIMUM_SEGMENT_SIZE` past the
// start of that range.
while (thisSegment !== undefined &&
(takeFirstSet<number>(thisSegment.bufferedEnd, thisSegment.end)
- rangeStart) < MINIMUM_SEGMENT_SIZE)
{
thisSegment = inventory[++inventoryIndex];
}
// Contains infos about the last garbage-collected segment before
// `thisSegment`.
let lastDeletedSegmentInfos : { end : number;
precizeEnd : boolean; } |
null = null;
// remove garbage-collected segments
// (Those not in that TimeRange nor in the previous one)
const numberOfSegmentToDelete = inventoryIndex - indexBefore;
if (numberOfSegmentToDelete > 0) {
const lastDeletedSegment = // last garbage-collected segment
inventory[indexBefore + numberOfSegmentToDelete - 1];
lastDeletedSegmentInfos = {
end: takeFirstSet<number>(lastDeletedSegment.bufferedEnd,
lastDeletedSegment.end),
precizeEnd: lastDeletedSegment.precizeEnd,
};
log.debug(`SI: ${numberOfSegmentToDelete} segments GCed.`, bufferType);
inventory.splice(indexBefore, numberOfSegmentToDelete);
inventoryIndex = indexBefore;
}
if (thisSegment === undefined) {
return;
}
// If the current segment is actually completely outside that range (it
// is contained in one of the next one), skip that part.
if (rangeEnd -
takeFirstSet<number>(thisSegment.bufferedStart, thisSegment.start)
>= MINIMUM_SEGMENT_SIZE
) {
guessBufferedStartFromRangeStart(thisSegment,
rangeStart,
lastDeletedSegmentInfos,
bufferType);
if (inventoryIndex === inventory.length - 1) {
// This is the last segment in the inventory.
// We can directly update the end as the end of the current range.
guessBufferedEndFromRangeEnd(thisSegment, rangeEnd, bufferType);
return;
}
thisSegment = inventory[++inventoryIndex];
// Make contiguous until first segment outside that range
let thisSegmentStart = takeFirstSet<number>(thisSegment.bufferedStart,
thisSegment.start);
let thisSegmentEnd = takeFirstSet<number>(thisSegment.bufferedEnd,
thisSegment.end);
const nextRangeStart = i < rangesLength - 1 ? buffered.start(i + 1) :
undefined;
while (thisSegment !== undefined &&
(rangeEnd - thisSegmentStart) >= MINIMUM_SEGMENT_SIZE &&
(nextRangeStart === undefined ||
rangeEnd - thisSegmentStart >= thisSegmentEnd - nextRangeStart))
{
const prevSegment = inventory[inventoryIndex - 1];
// those segments are contiguous, we have no way to infer their real
// end
if (prevSegment.bufferedEnd === undefined) {
prevSegment.bufferedEnd = thisSegment.precizeStart ? thisSegment.start :
prevSegment.end;
log.debug("SI: calculating buffered end of contiguous segment",
bufferType, prevSegment.bufferedEnd, prevSegment.end);
}
thisSegment.bufferedStart = prevSegment.bufferedEnd;
thisSegment = inventory[++inventoryIndex];
if (thisSegment !== undefined) {
thisSegmentStart = takeFirstSet<number>(thisSegment.bufferedStart,
thisSegment.start);
thisSegmentEnd = takeFirstSet<number>(thisSegment.bufferedEnd,
thisSegment.end);
}
}
}
// update the bufferedEnd of the last segment in that range
const lastSegmentInRange = inventory[inventoryIndex - 1];
if (lastSegmentInRange !== undefined) {
guessBufferedEndFromRangeEnd(lastSegmentInRange, rangeEnd, bufferType);
}
}
// if we still have segments left, they are not affiliated to any range.
// They might have been garbage collected, delete them from here.
if (thisSegment != null) {
log.debug("SI: last segments have been GCed",
bufferType, inventoryIndex, inventory.length);
inventory.splice(inventoryIndex, inventory.length - inventoryIndex);
}
if (bufferType !== undefined && log.getLevel() === "DEBUG") {
log.debug(`SI: current ${bufferType} inventory timeline:\n` +
prettyPrintInventory(this._inventory));
}
}
/**
* Add a new chunk in the inventory.
*
* Chunks are decodable sub-parts of a whole segment. Once all chunks in a
* segment have been inserted, you should call the `completeSegment` method.
* @param {Object} chunkInformation
*/
public insertChunk(
{ period,
adaptation,
representation,
segment,
chunkSize,
start,
end } : IInsertedChunkInfos
) : void {
if (segment.isInit) {
return;
}
const bufferType = adaptation.type;
if (start >= end) {
log.warn("SI: Invalid chunked inserted: starts before it ends",
bufferType, start, end);
return;
}
const inventory = this._inventory;
const newSegment = { partiallyPushed: true,
chunkSize,
splitted: false,
start,
end,
precizeStart: false,
precizeEnd: false,
bufferedStart: undefined,
bufferedEnd: undefined,
infos: { segment, period, adaptation, representation } };
// begin by the end as in most use cases this will be faster
for (let i = inventory.length - 1; i >= 0; i--) {
const segmentI = inventory[i];
if ((segmentI.start) <= start) {
if ((segmentI.end) <= start) {
// our segment is after, push it after this one
//
// Case 1:
// prevSegment : |------|
// newSegment : |======|
// ===> : |------|======|
//
// Case 2:
// prevSegment : |------|
// newSegment : |======|
// ===> : |------| |======|
log.debug("SI: Pushing segment strictly after previous one.",
bufferType, start, segmentI.end);
this._inventory.splice(i + 1, 0, newSegment);
i += 2; // Go to segment immediately after newSegment
while (i < inventory.length && inventory[i].start < newSegment.end) {
if (inventory[i].end > newSegment.end) {
// The next segment ends after newSegment.
// Mutate the next segment.
//
// Case 1:
// prevSegment : |------|
// newSegment : |======|
// nextSegment : |----|
// ===> : |------|======|-|
log.debug("SI: Segment pushed updates the start of the next one",
bufferType, newSegment.end, inventory[i].start);
inventory[i].start = newSegment.end;
inventory[i].bufferedStart = undefined;
inventory[i].precizeStart = inventory[i].precizeStart &&
newSegment.precizeEnd;
return;
}
// The next segment was completely contained in newSegment.
// Remove it.
//
// Case 1:
// prevSegment : |------|
// newSegment : |======|
// nextSegment : |---|
// ===> : |------|======|
//
// Case 2:
// prevSegment : |------|
// newSegment : |======|
// nextSegment : |----|
// ===> : |------|======|
log.debug("SI: Segment pushed removes the next one",
bufferType, start, end, inventory[i].start, inventory[i].end);
inventory.splice(i, 1);
}
return;
} else {
if (segmentI.start === start) {
if (segmentI.end <= end) {
// In those cases, replace
//
// Case 1:
// prevSegment : |-------|
// newSegment : |=======|
// ===> : |=======|
//
// Case 2:
// prevSegment : |-------|
// newSegment : |==========|
// ===> : |==========|
log.debug("SI: Segment pushed replace another one",
bufferType, start, end, segmentI.end);
this._inventory.splice(i, 1, newSegment);
i += 1; // Go to segment immediately after newSegment
while (i < inventory.length && inventory[i].start < newSegment.end) {
if (inventory[i].end > newSegment.end) {
// The next segment ends after newSegment.
// Mutate the next segment.
//
// Case 1:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|--|
log.debug("SI: Segment pushed updates the start of the next one",
bufferType, newSegment.end, inventory[i].start);
inventory[i].start = newSegment.end;
inventory[i].bufferedStart = undefined;
inventory[i].precizeStart = inventory[i].precizeStart &&
newSegment.precizeEnd;
return;
}
// The next segment was completely contained in newSegment.
// Remove it.
//
// Case 1:
// newSegment : |======|
// nextSegment : |---|
// ===> : |======|
//
// Case 2:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|
log.debug("SI: Segment pushed removes the next one",
bufferType, start, end, inventory[i].start, inventory[i].end);
inventory.splice(i, 1);
}
return;
} else {
// The previous segment starts at the same time and finishes
// after the new segment.
// Update the start of the previous segment and put the new
// segment before.
//
// Case 1:
// prevSegment : |------------|
// newSegment : |==========|
// ===> : |==========|-|
log.debug("SI: Segment pushed ends before another with the same start",
bufferType, start, end, segmentI.end);
inventory.splice(i, 0, newSegment);
segmentI.start = newSegment.end;
segmentI.bufferedStart = undefined;
segmentI.precizeStart = segmentI.precizeStart &&
newSegment.precizeEnd;
return;
}
} else {
if (segmentI.end <= newSegment.end) {
// our segment has a "complex" relation with this one,
// update the old one end and add this one after it.
//
// Case 1:
// prevSegment : |-------|
// newSegment : |======|
// ===> : |--|======|
//
// Case 2:
// prevSegment : |-------|
// newSegment : |====|
// ===> : |--|====|
log.debug("SI: Segment pushed updates end of previous one",
bufferType, start, end, segmentI.start, segmentI.end);
this._inventory.splice(i + 1, 0, newSegment);
segmentI.end = newSegment.start;
segmentI.bufferedEnd = undefined;
segmentI.precizeEnd = segmentI.precizeEnd &&
newSegment.precizeStart;
i += 2; // Go to segment immediately after newSegment
while (i < inventory.length && inventory[i].start < newSegment.end) {
if (inventory[i].end > newSegment.end) {
// The next segment ends after newSegment.
// Mutate the next segment.
//
// Case 1:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|--|
log.debug("SI: Segment pushed updates the start of the next one",
bufferType, newSegment.end, inventory[i].start);
inventory[i].start = newSegment.end;
inventory[i].bufferedStart = undefined;
inventory[i].precizeStart = inventory[i].precizeStart &&
newSegment.precizeEnd;
return;
}
// The next segment was completely contained in newSegment.
// Remove it.
//
// Case 1:
// newSegment : |======|
// nextSegment : |---|
// ===> : |======|
//
// Case 2:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|
log.debug("SI: Segment pushed removes the next one",
bufferType, start, end, inventory[i].start, inventory[i].end);
inventory.splice(i, 1);
}
return;
} else {
// The previous segment completely recovers the new segment.
// Split the previous segment into two segments, before and after
// the new segment.
//
// Case 1:
// prevSegment : |---------|
// newSegment : |====|
// ===> : |--|====|-|
log.warn("SI: Segment pushed is contained in a previous one",
bufferType, start, end, segmentI.start, segmentI.end);
const nextSegment = { partiallyPushed: segmentI.partiallyPushed,
/**
* Note: this sadly means we're doing as if
* that chunk is present two times.
* Thankfully, this scenario should be
* fairly rare.
*/
chunkSize: segmentI.chunkSize,
splitted: true,
start: newSegment.end,
end: segmentI.end,
precizeStart: segmentI.precizeStart &&
segmentI.precizeEnd &&
newSegment.precizeEnd,
precizeEnd: segmentI.precizeEnd,
bufferedStart: undefined,
bufferedEnd: segmentI.end,
infos: segmentI.infos };
segmentI.end = newSegment.start;
segmentI.splitted = true;
segmentI.bufferedEnd = undefined;
segmentI.precizeEnd = segmentI.precizeEnd &&
newSegment.precizeStart;
inventory.splice(i + 1, 0, newSegment);
inventory.splice(i + 2, 0, nextSegment);
return;
}
}
}
}
}
// if we got here, we are at the first segment
// check bounds of the previous first segment
const firstSegment = this._inventory[0];
if (firstSegment === undefined) { // we do not have any segment yet
log.debug("SI: first segment pushed", bufferType, start, end);
this._inventory.push(newSegment);
return;
}
if (firstSegment.start >= end) {
// our segment is before, put it before
//
// Case 1:
// firstSegment : |----|
// newSegment : |====|
// ===> : |====|----|
//
// Case 2:
// firstSegment : |----|
// newSegment : |====|
// ===> : |====| |----|
log.debug("SI: Segment pushed comes before all previous ones",
bufferType, start, end, firstSegment.start);
this._inventory.splice(0, 0, newSegment);
} else if (firstSegment.end <= end) {
// Our segment is bigger, replace the first
//
// Case 1:
// firstSegment : |---|
// newSegment : |=======|
// ===> : |=======|
//
// Case 2:
// firstSegment : |-----|
// newSegment : |=======|
// ===> : |=======|
log.debug("SI: Segment pushed starts before and completely " +
"recovers the previous first one",
bufferType, start, end , firstSegment.start, firstSegment.end);
this._inventory.splice(0, 1, newSegment);
while (inventory.length > 1 && inventory[1].start < newSegment.end) {
if (inventory[1].end > newSegment.end) {
// The next segment ends after newSegment.
// Mutate the next segment.
//
// Case 1:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|--|
log.debug("SI: Segment pushed updates the start of the next one",
bufferType, newSegment.end, inventory[1].start);
inventory[1].start = newSegment.end;
inventory[1].bufferedStart = undefined;
inventory[1].precizeStart = newSegment.precizeEnd;
return;
}
// The next segment was completely contained in newSegment.
// Remove it.
//
// Case 1:
// newSegment : |======|
// nextSegment : |---|
// ===> : |======|
//
// Case 2:
// newSegment : |======|
// nextSegment : |----|
// ===> : |======|
log.debug("SI: Segment pushed removes the next one",
bufferType, start, end, inventory[1].start, inventory[1].end);
inventory.splice(1, 1);
}
return;
} else {
// our segment has a "complex" relation with the first one,
// update the old one start and add this one before it.
//
// Case 1:
// firstSegment : |------|
// newSegment : |======|
// ===> : |======|--|
log.debug("SI: Segment pushed start of the next one",
bufferType, start, end, firstSegment.start, firstSegment.end);
firstSegment.start = end;
firstSegment.bufferedStart = undefined;
firstSegment.precizeStart = newSegment.precizeEnd;
this._inventory.splice(0, 0, newSegment);
return;
}
}
/**
* Indicate that inserted chunks can now be considered as a complete segment.
* Take in argument the same content than what was given to `insertChunk` for
* the corresponding chunks.
* @param {Object} content
*/
public completeSegment(
content : { period: Period;
adaptation: Adaptation;
representation: Representation;
segment: ISegment; },
newBuffered : TimeRanges
) : void {
if (content.segment.isInit) {
return;
}
const inventory = this._inventory;
const resSegments : IBufferedChunk[] = [];
for (let i = 0; i < inventory.length; i++) {
if (areSameContent(inventory[i].infos, content)) {
let splitted = false;
if (resSegments.length > 0) {
splitted = true;
if (resSegments.length === 1) {
log.warn("SI: Completed Segment is splitted.", content);
resSegments[0].splitted = true;
}
}
const firstI = i;
let segmentSize = inventory[i].chunkSize;
i += 1;
while (i < inventory.length &&
areSameContent(inventory[i].infos, content))
{
const chunkSize = inventory[i].chunkSize;
if (segmentSize !== undefined && chunkSize !== undefined) {
segmentSize += chunkSize;
}
i++;
}
const lastI = i - 1;
const length = lastI - firstI;
const lastEnd = inventory[lastI].end;
const lastBufferedEnd = inventory[lastI].bufferedEnd;
if (length > 0) {
this._inventory.splice(firstI + 1, length);
i -= length;
}
this._inventory[firstI].partiallyPushed = false;
this._inventory[firstI].chunkSize = segmentSize;
this._inventory[firstI].end = lastEnd;
this._inventory[firstI].bufferedEnd = lastBufferedEnd;
this._inventory[firstI].splitted = splitted;
resSegments.push(this._inventory[firstI]);
}
}
if (resSegments.length === 0) {
log.warn("SI: Completed Segment not found", content);
} else {
this.synchronizeBuffered(newBuffered);
for (const seg of resSegments) {
if (seg.bufferedStart !== undefined && seg.bufferedEnd !== undefined) {
this._bufferedHistory.addBufferedSegment(seg.infos,
seg.bufferedStart,
seg.bufferedEnd);
} else {
log.debug("SI: buffered range not known after sync. Skipping history.",
seg);
}
}
}
}
/**
* Returns the whole inventory.
*
* To get a list synchronized with what a media buffer actually has buffered
* you might want to call `synchronizeBuffered` before calling this method.
* @returns {Array.<Object>}
*/
public getInventory() : IBufferedChunk[] {
return this._inventory;
}
/**
* Returns a recent history of registered operations performed and event
* received linked to the segment given in argument.
*
* Not all operations and events are registered in the returned history.
* Please check the return type for more information on what is available.
*
* Note that history is short-lived for memory usage and performance reasons.
* You may not receive any information on operations that happened too long
* ago.
* @param {Object} context
* @returns {Array.<Object>}
*/
public getHistoryFor(context : IChunkContext) : IBufferedHistoryEntry[] {
return this._bufferedHistory.getHistoryFor(context);
}
}
/**
* Returns `true` if the buffered start of the given chunk looks coherent enough
* relatively to what is announced in the Manifest.
* @param {Object} thisSegment
* @returns {Boolean}
*/
function bufferedStartLooksCoherent(
thisSegment : IBufferedChunk
) : boolean {
if (thisSegment.bufferedStart === undefined ||
thisSegment.partiallyPushed)
{
return false;
}
const { start, end } = thisSegment;
const duration = end - start;
const { MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE,
MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE } = config.getCurrent();
return Math.abs(start - thisSegment.bufferedStart) <=
MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE &&
(thisSegment.bufferedEnd === undefined ||
thisSegment.bufferedEnd > thisSegment.bufferedStart &&
Math.abs(thisSegment.bufferedEnd - thisSegment.bufferedStart -
duration) <= Math.min(MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE,
duration / 3));
}
/**
* Returns `true` if the buffered end of the given chunk looks coherent enough
* relatively to what is announced in the Manifest.
* @param {Object} thisSegment
* @returns {Boolean}
*/
function bufferedEndLooksCoherent(
thisSegment : IBufferedChunk
) : boolean {
if (thisSegment.bufferedEnd === undefined ||
thisSegment.partiallyPushed)
{
return false;
}
const { start, end } = thisSegment;
const duration = end - start;
const { MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE,
MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE } = config.getCurrent();
return Math.abs(end - thisSegment.bufferedEnd) <=
MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE &&
thisSegment.bufferedStart != null &&
thisSegment.bufferedEnd > thisSegment.bufferedStart &&
Math.abs(thisSegment.bufferedEnd - thisSegment.bufferedStart -
duration) <= Math.min(MAX_MANIFEST_BUFFERED_DURATION_DIFFERENCE,
duration / 3);
}
/**
* Evaluate the given buffered Chunk's buffered start from its range's start,
* considering that this chunk is the first one in it.
* @param {Object} firstSegmentInRange
* @param {number} rangeStart
* @param {Object} lastDeletedSegmentInfos
*/
function guessBufferedStartFromRangeStart(
firstSegmentInRange : IBufferedChunk,
rangeStart : number,
lastDeletedSegmentInfos : { end : number; precizeEnd : boolean } |
null,
bufferType : string
) : void {
const { MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE } = config.getCurrent();
if (firstSegmentInRange.bufferedStart !== undefined) {
if (firstSegmentInRange.bufferedStart < rangeStart) {
log.debug("SI: Segment partially GCed at the start",
bufferType, firstSegmentInRange.bufferedStart, rangeStart);
firstSegmentInRange.bufferedStart = rangeStart;
}
if (!firstSegmentInRange.precizeStart &&
bufferedStartLooksCoherent(firstSegmentInRange))
{
firstSegmentInRange.start = firstSegmentInRange.bufferedStart;
firstSegmentInRange.precizeStart = true;
}
} else if (firstSegmentInRange.precizeStart) {
log.debug("SI: buffered start is precize start",
bufferType, firstSegmentInRange.start);
firstSegmentInRange.bufferedStart = firstSegmentInRange.start;
} else if (lastDeletedSegmentInfos !== null &&
lastDeletedSegmentInfos.end > rangeStart &&
(lastDeletedSegmentInfos.precizeEnd ||
firstSegmentInRange.start - lastDeletedSegmentInfos.end <=
MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE))
{
log.debug("SI: buffered start is end of previous segment",
bufferType,
rangeStart,
firstSegmentInRange.start,
lastDeletedSegmentInfos.end);
firstSegmentInRange.bufferedStart = lastDeletedSegmentInfos.end;
if (bufferedStartLooksCoherent(firstSegmentInRange)) {
firstSegmentInRange.start = lastDeletedSegmentInfos.end;
firstSegmentInRange.precizeStart = true;
}
} else if (firstSegmentInRange.start - rangeStart <=
MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE)
{
log.debug("SI: found true buffered start",
bufferType, rangeStart, firstSegmentInRange.start);
firstSegmentInRange.bufferedStart = rangeStart;
if (bufferedStartLooksCoherent(firstSegmentInRange)) {
firstSegmentInRange.start = rangeStart;
firstSegmentInRange.precizeStart = true;
}
} else if (rangeStart < firstSegmentInRange.start) {
log.debug("SI: range start too far from expected start",
bufferType, rangeStart, firstSegmentInRange.start);
} else {
log.debug("SI: Segment appears immediately garbage collected at the start",
bufferType, firstSegmentInRange.bufferedStart, rangeStart);
firstSegmentInRange.bufferedStart = rangeStart;
}
}
/**
* Evaluate the given buffered Chunk's buffered end from its range's end,
* considering that this chunk is the last one in it.
* @param {Object} firstSegmentInRange
* @param {number} rangeStart
* @param {Object} infos
*/
function guessBufferedEndFromRangeEnd(
lastSegmentInRange : IBufferedChunk,
rangeEnd : number,
bufferType? : string
) : void {
const { MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE } = config.getCurrent();
if (lastSegmentInRange.bufferedEnd !== undefined) {
if (lastSegmentInRange.bufferedEnd > rangeEnd) {
log.debug("SI: Segment partially GCed at the end",
bufferType, lastSegmentInRange.bufferedEnd, rangeEnd);
lastSegmentInRange.bufferedEnd = rangeEnd;
}
if (!lastSegmentInRange.precizeEnd &&
rangeEnd - lastSegmentInRange.end <= MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE &&
bufferedEndLooksCoherent(lastSegmentInRange))
{
lastSegmentInRange.precizeEnd = true;
lastSegmentInRange.end = rangeEnd;
}
} else if (lastSegmentInRange.precizeEnd) {
log.debug("SI: buffered end is precize end",
bufferType, lastSegmentInRange.end);
lastSegmentInRange.bufferedEnd = lastSegmentInRange.end;
} else if (rangeEnd - lastSegmentInRange.end <=
MAX_MANIFEST_BUFFERED_START_END_DIFFERENCE)
{
log.debug("SI: found true buffered end",
bufferType, rangeEnd, lastSegmentInRange.end);
lastSegmentInRange.bufferedEnd = rangeEnd;
if (bufferedEndLooksCoherent(lastSegmentInRange)) {
lastSegmentInRange.end = rangeEnd;
lastSegmentInRange.precizeEnd = true;
}
} else if (rangeEnd > lastSegmentInRange.end) {
log.debug("SI: range end too far from expected end",
bufferType, rangeEnd, lastSegmentInRange.end);
lastSegmentInRange.bufferedEnd = lastSegmentInRange.end;
} else {
log.debug("SI: Segment appears immediately garbage collected at the end",
bufferType, lastSegmentInRange.bufferedEnd, rangeEnd);
lastSegmentInRange.bufferedEnd = rangeEnd;
}
}
/**
* Pretty print the inventory, to easily note which segments are where in the
* current buffer.
*
* This is mostly useful when logging.
*
* @example
* This function is called by giving it the inventory, such as:
* ```js
* prettyPrintInventory(inventory);
* ```
*
* Let's consider this possible return:
* ```
* 0.00|A|9.00 ~ 9.00|B|45.08 ~ 282.08|B|318.08
* [A] P: gen-dash-period-0 || R: video/5(2362822)
* [B] P: gen-dash-period-0 || R: video/6(2470094)
* ```
* We have a first part, from 0 to 9 seconds, which contains segments for
* the Representation with the id "video/5" and an associated bitrate of
* 2362822 bits per seconds (in the Period with the id "gen-dash-period-0").
*
* Then from 9.00 seconds to 45.08 seconds, we have segments from another
* Representation from the same Period (with the id "video/6" and a bitrate
* of 2470094 bits per seconds).
*
* At last we have a long time between 45.08 and 282.08 with no segment followed
* by a segment from that same Representation between 282.08 seconds and 318.08
* seconds.
* @param {Array.<Object>} inventory
* @returns {string}
*/
function prettyPrintInventory(inventory : IBufferedChunk[]) : string {
const roundingError = 1 / 60;
const encounteredReps :
Partial<Record<string /* Period `id` */,
Partial<Record<string /* Representation `id` */,
string /* associated letter */ >>>> = {};
const letters : Array<{ letter : string;
periodId : string;
representationId : string | number;
bitrate? : number; }> = [];
let lastChunk : IBufferedChunk | null = null;
let lastLetter : string | null = null;
function generateNewLetter(infos : IChunkContext) : string {
const currentLetter = String.fromCharCode(letters.length + 65);
letters.push({ letter: currentLetter,
periodId: infos.period.id,
representationId: infos.representation.id,
bitrate: infos.representation.bitrate });
return currentLetter;
}
let str = "";
for (let i = 0; i < inventory.length; i++) {
const chunk = inventory[i];
if (chunk.bufferedStart !== undefined && chunk.bufferedEnd !== undefined) {
const periodId = chunk.infos.period.id;
const representationId = chunk.infos.representation.id;
const encounteredPeriod = encounteredReps[periodId];
let currentLetter : string;
if (encounteredPeriod === undefined) {
currentLetter = generateNewLetter(chunk.infos);
encounteredReps[periodId] = { [representationId]: currentLetter };
} else if (encounteredPeriod[representationId] === undefined) {
currentLetter = generateNewLetter(chunk.infos);
encounteredPeriod[representationId] = currentLetter;
} else {
currentLetter = encounteredPeriod[representationId] as string;
}
if (lastChunk === null) {
str += `${chunk.bufferedStart.toFixed(2)}|${currentLetter}|`;
} else if (lastLetter === currentLetter) {
if ((lastChunk.bufferedEnd as number) + roundingError < chunk.bufferedStart) {
str += `${(lastChunk.bufferedEnd as number).toFixed(2)} ~ ` +
`${chunk.bufferedStart.toFixed(2)}|${currentLetter}|`;
}
} else {
str += `${(lastChunk.bufferedEnd as number).toFixed(2)} ~ ` +
`${chunk.bufferedStart.toFixed(2)}|${currentLetter}|`;
}
lastChunk = chunk;
lastLetter = currentLetter;
}
}
if (lastChunk !== null) {
str += String(lastChunk.end.toFixed(2));
}
letters.forEach(letterInfo => {
str += `\n[${letterInfo.letter}] ` +
`P: ${letterInfo.periodId} || R: ${letterInfo.representationId}` +
`(${letterInfo.bitrate ?? "unknown bitrate"})`;
});
return str;
}
|
typescript
|
The next device from Apple is rumored to be the iPhone Mini, a smaller - and more importantly cheaper - version of its smartphone, and the release date may be in the summer.
There are plenty of reasons why Apple needs to start making the cheaper iPhone Mini, and the Morgan Stanley managing director of the PC hardware industry, Katy Huberty, points that out after meeting with Apple Chief Financial Officer Peter Oppenheimer.
Emerging markets like China and Brazil have snapped up the iPad Mini, according to her comments picked up by CNET.
"iPad Mini is expanding Apple's customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem," said Huberty.
Likewise, Chinese consumers are showing signs that they're willing to buy into the latest models of the iPhone instead of the smartphone's older generations.
Preparing for expanding markets as well as existing ones, she anticipates that new carrier partnerships will take place in Q2 2014 with NTT Docomo, T-Mobile, and China Mobile.
Outside of those emerging markets, Huberty notes that Apple's everyday consumers have been buying older versions of the iPhone.
"iPhone 4 demand surprised to the upside in the December quarter," she said.
She didn't speculate whether the reason for this is due to the lower price of the iPhone 4 and iPhone 4S or the lack of innovation in the iPhone 5.
In addition to saying that the iPhone Mini could launch in the summer, Huberty said that she expects that the iPad could be refreshed in the middle of the year.
I'm no analyst, but I think summer and middle of the year might happen at the same time.
Either way, rumors suggest that an iPad Mini 2 will roll out with a Retina display, and that iPad 5 will be completely redesigned.
Get the hottest deals available in your inbox plus news, reviews, opinion, analysis, deals and more from the TechRadar team.
|
english
|
The Dune universe continues to expand. With Denis Villeneuve’s film adaptation on the horizon, the saga’s caretakers have revealed more details about their upcoming graphic novels—along with a new book trilogy that should help get fans up to speed on Paul Atreides’ life before he ventured to Arrakis and changed the universe forever.
Dune series authors Kevin J. Anderson and Brian Herbert, the son of original Dune author Frank Herbert, announced a new trilogy of books in their ongoing series during a virtual panel at San Diego Comic-Con. The new series, starting with Dune: The Duke of Caladan, takes place one year before the events of Dune and explores the lives of Paul Atreides, his Bene Gesserit mother Lady Jessica, and Duke Atreides on the ocean planet of Caladan. The plan is to end the third book on the news that House Atreides is being relocated to Arrakis, so it directly sets up the events of the main story.
According to Anderson, the two of them had wanted to make a new Dune trilogy for a while but were busy working on the upcoming movie, and actually came up with the idea while the movie was being filmed. Their goal is for this new trilogy to be just as accessible for new readers as it would be for hardcore fans—to help audiences understand the characters and world before reading the first book or, perhaps, seeing the upcoming movie.
But it’s not the only Dune project in the works—Anderson and Brian Herbert also discussed Dune: House Atreides, a 12-issue comic book prequel series based on the 1999 novel by Anderson and Herbert (with illustrator Dev Pramanik and colorist Alex Guimarães). It’s been developed in tandem with a graphic novel retelling of Frank Herbert’s Dune, which has divided the story into three parts; both are set to debut before Villeneuve’s adaptation comes out in December. Set decades before the events of Dune, Dune: House Atreides centers around ecologist Pardot Kynes (the father of Liet Kynes, played by Sharon Duncan-Brewster in the upcoming film) as he tries to enact his vision of terraforming the desert planet of Arrakis. But we also spend time with other iconic characters, like Leto Atreides and Duncan Idaho.
During the SDCC panel, Anderson said it was one of the first books he and Brian Herbert worked on together, and he and Herbert were excited to see how the younger versions of these iconic characters were visually represented (for example, Baron Harkonnen is a lot leaner than his Dune counterpart). House Atreides is actually part of a trilogy, the others being House Harkonnen and House Corrino (they’ve also gotten reprints in anticipation of the graphic novel series). No word whether they’ll be creating graphic novels based on the other books in the trilogy, though I’m sure it’s possible given everything else they have in the works. Herbert expressed joy at all the projects they have in development, including some computer games, but emphasized the importance of keeping the integrity of his father’s work alive.
Dune: The Duke of Caladan comes out on October 13, Dune: House Atreides is set to launch on October 21, and the first issue of the Dune graphic novel trilogy coming out on October 27.
Villeneuve’s Dune, which stars Timothée Chalamet as Paul Atreides, Rebecca Ferguson as Lady Jessica and Zendaya as the Fremen warrior Chani, is currently slotted for December 18—though that could be subject to change because of the novel coronavirus pandemic.
For more, make sure you’re following us on our Instagram @io9dotcom.
|
english
|
So, below she was, losing 100 pounds in her diet regimen, but the nagging pain in her joints and also muscular tissues were making her inactive. So, it shows up that not liking alcohol consumption water, incorporated with her own love of fatty foods and also her desire to lose 100 pounds as rapidly as possible, were both major aspects that caused this dreadful crash. It is usually declared that drinking water can assist with weight loss - which's real. In this case, seek specialist aid. With the assistance of a terrific weight loss program like CHrissy Michaels, you'll have the ability to do this quickly! You can locate Chrissy Metz weight loss prior to and also after pictures on the web, and in some cases, you'll also see in the past and after videos of the same person or the exact same routine. First, take an appearance at the in the past and after pictures. Searching for Chrissy Metz weight loss before and after photos? Self-monitoring is an important variable in efficiently losing weight.
What is Pligg?
Pligg is an open source content management system that lets you easily create your own user-powered website.
|
english
|
Heroinware Nickname for multiplayer online games like EverQuest - dubbed EverCrack by hardcore players - that can become addictive and do serious damage to relationships and careers.
Micestronauts Rodents that would be sent into Earth orbit to study the effects of living - and reproducing - at reduced gravity. The project, proposed by the Mars Society, would yield data that could be used to help plan a long-term trip to the Red Planet.
Vokens Short for virtual tokens, the Web advertising gimmick du jour.
The little rich-media interruptions hover or crawl over a browser window, begging for your attention. Bravo Canada's Sex and the City page, for example, includes a floating, twirling pack of Extra Polar Ice gum.
Neo-Creo A person who's part of the neo-creationism, or "intelligent design," movement, which relies on science and logic rather than Scripture to argue that life is too complicated to have arisen by evolution.
- Gareth Branwyn (jargon@wiredmag.com)
|
english
|
/*
* Copyright (c) 2022 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
package org.opengauss.mppdbide.view.ui.visualexplainplan;
import org.opengauss.mppdbide.presentation.visualexplainplan.AbstractExplainPlanPropertyCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanNodePropertiesCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanOverAllPlanPropertiesCore;
import org.opengauss.mppdbide.presentation.visualexplainplan.ExplainPlanPresentation;
/**
*
* Title: class
*
* Description: The Class VisualExplainPlanUIPresentation.
*
* @since 3.0.0
*/
public class VisualExplainPlanUIPresentation {
private ExplainPlanPresentation presenter;
private String operationType;
private String tabID;
private Object operationObject;
/**
* Instantiates a new visual explain plan UI presentation.
*
* @param presentation the presentation
*/
public VisualExplainPlanUIPresentation(String TabID, ExplainPlanPresentation presentation) {
this.tabID = TabID;
this.presenter = presentation;
}
/**
* Gets the explain plan window handler.
*
* @return the explain plan window handler
*/
public String getExplainPlanTabId() {
return tabID;
}
/**
* Gets the presenter.
*
* @return the presenter
*/
public ExplainPlanPresentation getPresenter() {
return presenter;
}
/**
* Gets the operation type.
*
* @return the operation type
*/
public String getOperationType() {
return operationType;
}
/**
* Gets the operation object.
*
* @return the operation object
*/
public Object getOperationObject() {
return operationObject;
}
/**
* Sets the operation object.
*
* @param operationObject the new operation object
*/
public void setOperationObject(Object operationObject) {
this.operationObject = operationObject;
}
/**
* Sets the operation type.
*
* @param operationType the new operation type
*/
public void setOperationType(String operationType) {
this.operationType = operationType;
}
/**
* Gets the suitable property presenter.
*
* @return the suitable property presenter
*/
public AbstractExplainPlanPropertyCore getSuitablePropertyPresenter() {
if (this.getOperationType().equals(VisualExplainPlanConstants.VISUAL_EXPLAIN_OPTYPE_ALLPROPERTY)) {
return new ExplainPlanOverAllPlanPropertiesCore(this.presenter);
} else if (this.getOperationType().equals(VisualExplainPlanConstants.VISUAL_EXPLAIN_PERNODE_DETAILS)) {
return (ExplainPlanNodePropertiesCore) this.getOperationObject();
}
return null;
}
}
|
java
|
<reponame>d3x0r/upgrade-planner
{
"name": "upgrade-planner2",
"version": "1.6.1",
"title": "Upgrade Builder and Planner 1.6",
"author": "d3x0r & malk0lm & Klonan",
"description": "Automatically upgrade buildings by hand or with construction robots.",
"homepage": "https://forums.factorio.com/viewtopic.php?f=92&t=50975",
"factorio_version": "0.16",
"dependencies": ["base >= 0.15.31"]
}
|
json
|
{
"latest_version": [
"0.1"
],
"meta": {
"description": "does some stuff with things & stuff",
"homepage": "UNKNOWN",
"license": "Expat"
},
"versions": {}
}
|
json
|
Employees who have been engaged for serving in hospital wards in Golaghat Kushal Konwar Civil Hospital,
GOLAGHAT: Employees who have been engaged for serving in hospital wards in Golaghat Kushal Konwar Civil Hospital, on Thursday staged protest in front of the Superintendent's office room demanding regularization of jobs.
As many as 74 employees joined the protest programme leaving their duties. The employees staged protest for not providing proper monthly remuneration and not regularizing their job. All 74 employees have been appointed by the managing committee of the hospital in Grade IV post on temporary basis.
In this context, the protesters alleged that they have been serving in the hospital since 25 years with meagre money in the name of monthly salary. But till now the hospital authority did not take any initiative to regular their jobs. Few days back, the employees approached the Superintendent of the hospital, Dr Suren Tamuly and district administration for fulfilment of their demands. The hospital authority allegedly threatened to terminate them from their jobs and appoint new people.
|
english
|
<filename>src/route/modules/css-world.js<gh_stars>1-10
import layout from "@/layout";
export default [
{
path: "/css-world",
component: layout,
name: "css-world",
sort: 1,
children: [
{
path: "color",
name: "color",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/css-color/css-color"
),
meta: {
breadcrumbs: ["css-world", "color"]
}
},
{
path: "palette",
name: "palette",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/css-color/palette"
),
meta: {
breadcrumbs: ["css-world", "palette"]
}
},
{
path: "skill",
name: "skill",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/css-skill/css-skill"
),
meta: {
breadcrumbs: ["css-world", "skill"]
}
},
{
path: "skill-sticky",
name: "sticky",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/css-skill/sticky.vue"
),
meta: {
breadcrumbs: ["css-world", "css-sticky"]
}
},
{
path: "waterfall-flow",
name: "waterfall",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/waterfall-flow"
),
meta: {
breadcrumbs: ["css-world", "waterfall"]
}
},
{
path: "skill-2",
name: "skill-2",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/skill-2"
),
meta: {
breadcrumbs: ["css-world", "skill-2"]
}
},
{
path: "snow",
name: "snow",
component: () =>
import(/* webpackChunkName: "css-world" */ "@/views/css-world/snow"),
meta: {
breadcrumbs: ["css-world", "snow"]
}
},
{
path: "animation",
name: "animation",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/animation"
),
meta: {
breadcrumbs: ["css-world", "animation"]
}
},
{
path: "shape",
name: "shape",
component: () =>
import(
/* webpackChunkName: "css-world" */ "@/views/css-world/shape/shape"
),
meta: {
breadcrumbs: ["css-world", "shape"]
}
}
]
}
];
|
javascript
|
{
"builtTestProducts" : [
{
"binaryPath" : "\/Users\/lishuai\/Documents\/GitHub\/SS58Factory\/.build\/x86_64-apple-macosx\/debug\/SS58FactoryPackageTests.xctest\/Contents\/MacOS\/SS58FactoryPackageTests",
"packageName" : "SS58Factory",
"productName" : "SS58FactoryPackageTests"
}
],
"copyCommands" : {
},
"swiftTargetMap" : {
"C.SS58FactoryTests-debug.module" : "SS58FactoryTests"
},
"testDiscoveryCommands" : {
}
}
|
json
|
<reponame>ministryofjustice/mtp-api<gh_stars>1-10
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
('core', '0003_auto_20180404_1515'),
]
operations = [
migrations.CreateModel(
name='Token',
fields=[
('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')),
('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')),
('name', models.CharField(max_length=20, primary_key=True, serialize=False)),
('token', models.TextField()),
('expires', models.DateTimeField(blank=True, null=True)),
],
options={
'ordering': ('name',),
'permissions': (('view_token', 'Can view token'),),
},
),
]
|
python
|
{"code": "VGR037", "lang": "de", "description": "\nSparen der privaten Haushalte\n\nErl\u00e4uterung f\u00fcr folgende Statistik(en):\n81000 Volkswirtschaftliche Gesamtrechnungen des Bundes\n\nBegriffsinhalt:\nDas Sparen der privaten Haushalte wird wie folgt ermittelt:\n+ Verf\u00fcgbares Einkommen der privaten Haushalte\n(Ausgabenkonzept)\n- Konsumausgaben der privaten Haushalte\n+ Zunahme betrieblicher Versorgungsanspr\u00fcche\n= Sparen der privaten Haushalte\n\nSiehe auch Definition \"Verf\u00fcgbares Einkommen der privaten\nHaushalte (Ausgabenkonzept)\" und Definition \"Konsumausgaben\n(private Haushalte)\".\n\n\u00a9 Statistisches Bundesamt, Wiesbaden 2003", "name": "Sparen der privaten Haushalte", "type": "Merkmal"}
|
json
|
/*
* mathwidget.cpp
*
* Created on: Mar 24, 2014
* Author: schurade
*/
#include "mathwidget.h"
#include "../../../data/datasets/datasetscalar.h"
#include "../../../data/models.h"
#include "../../../data/vptr.h"
#include "../../../io/writer.h"
#include "../controls/sliderwithedit.h"
#include "../controls/sliderwitheditint.h"
#include "../controls/selectwithlabel.h"
MathWidget::MathWidget( DatasetScalar* ds, QWidget* parent ) :
m_dataset( ds )
{
m_layout = new QVBoxLayout();
m_modeSelect = new SelectWithLabel( QString( "mode" ), 1 );
m_modeSelect->insertItem( 0, QString("make binary") );
m_modeSelect->insertItem( 1, QString("add") );
m_modeSelect->insertItem( 2, QString("mult") );
m_modeSelect->insertItem( 3, QString("between thresholds") );
m_layout->addWidget( m_modeSelect );
connect( m_modeSelect, SIGNAL( currentIndexChanged( int, int ) ), this, SLOT( modeChanged( int ) ) );
m_sourceSelect = new SelectWithLabel( QString( "source dataset" ), 1 );
QList<QVariant>dsl = Models::d()->data( Models::d()->index( 0, (int)Fn::Property::D_DATASET_LIST ), Qt::DisplayRole ).toList();
for ( int k = 0; k < dsl.size(); ++k )
{
if ( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_TYPE ).toInt() == (int)Fn::DatasetType::NIFTI_SCALAR )
{
m_sourceSelect->addItem( VPtr<Dataset>::asPtr( dsl[k] )->properties().get( Fn::Property::D_NAME ).toString(), dsl[k] );
}
}
m_layout->addWidget( m_sourceSelect );
m_sourceSelect->hide();
m_arg = new SliderWithEdit( QString("arg") );
m_arg->setMin( -1000 );
m_arg->setMax( 1000 );
m_arg->setValue( 0 );
m_layout->addWidget( m_arg );
m_arg->hide();
QHBoxLayout* hLayout = new QHBoxLayout();
m_executeButton = new QPushButton( tr("execute") );
connect( m_executeButton, SIGNAL( clicked() ), this, SLOT( execute() ) );
hLayout->addStretch();
hLayout->addWidget( m_executeButton );
m_layout->addLayout( hLayout );
m_layout->addStretch();
setLayout( m_layout );
}
MathWidget::~MathWidget()
{
}
void MathWidget::modeChanged( int mode )
{
switch ( mode )
{
case 0:
m_sourceSelect->hide();
m_arg->hide();
break;
case 1:
m_sourceSelect->hide();
m_arg->show();
break;
case 2:
m_sourceSelect->hide();
m_arg->show();
break;
case 3:
m_sourceSelect->hide();
m_arg->hide();
break;
}
}
void MathWidget::execute()
{
std::vector<float> data = *( m_dataset->getData() );
int mode = m_modeSelect->getCurrentIndex();
float arg = m_arg->getValue();
float lowerThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_LOWER_THRESHOLD ).toFloat();
float upperThreshold = m_dataset->properties( "maingl" ).get( Fn::Property::D_UPPER_THRESHOLD ).toFloat();
switch ( mode )
{
case 0:
{
for ( unsigned int i = 0; i < data.size(); ++i )
{
if ( data[i] > lowerThreshold && data[i] < upperThreshold )
{
data[i] = 1.0;
}
else
{
data[i] = 0.0;
}
}
break;
}
case 1:
{
for ( unsigned int i = 0; i < data.size(); ++i )
{
data[i] += arg;
}
break;
}
case 2:
{
for ( unsigned int i = 0; i < data.size(); ++i )
{
data[i] *= arg;
}
break;
}
case 3:
{
for ( unsigned int i = 0; i < data.size(); ++i )
{
if ( data[i] < lowerThreshold || data[i] > upperThreshold )
{
data[i] = 0.0;
}
}
break;
}
}
Writer writer( m_dataset, QFileInfo() );
DatasetScalar* out = new DatasetScalar( QDir( "new dataset" ), data, writer.createHeader( 1 ) );
QModelIndex index = Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET );
Models::d()->setData( index, VPtr<Dataset>::asQVariant( out ), Qt::DisplayRole );
this->hide();
}
|
cpp
|
<filename>snippets/cpp/VS_Snippets_Winforms/System.Windows.Forms.ListView.InsertionMark/CPP/listviewinsertionmarkexample.cpp
//<Snippet1>
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class ListViewInsertionMarkExample: public Form
{
private:
ListView^ myListView;
public:
//<Snippet2>
ListViewInsertionMarkExample()
{
// Initialize myListView.
myListView = gcnew ListView;
myListView->Dock = DockStyle::Fill;
myListView->View = View::LargeIcon;
myListView->MultiSelect = false;
myListView->ListViewItemSorter = gcnew ListViewIndexComparer;
// Initialize the insertion mark.
myListView->InsertionMark->Color = Color::Green;
// Add items to myListView.
myListView->Items->Add( "zero" );
myListView->Items->Add( "one" );
myListView->Items->Add( "two" );
myListView->Items->Add( "three" );
myListView->Items->Add( "four" );
myListView->Items->Add( "five" );
// Initialize the drag-and-drop operation when running
// under Windows XP or a later operating system.
if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) )
{
myListView->AllowDrop = true;
myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag );
myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter );
myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver );
myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave );
myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop );
}
// Initialize the form.
this->Text = "ListView Insertion Mark Example";
this->Controls->Add( myListView );
}
private:
//</Snippet2>
// Starts the drag-and-drop operation when an item is dragged.
void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e )
{
myListView->DoDragDrop( e->Item, DragDropEffects::Move );
}
// Sets the target drop effect.
void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
{
e->Effect = e->AllowedEffect;
}
//<Snippet3>
// Moves the insertion mark as the item is dragged.
void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the client coordinates of the mouse pointer.
Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) );
// Retrieve the index of the item closest to the mouse pointer.
int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint );
// Confirm that the mouse pointer is not over the dragged item.
if ( targetIndex > -1 )
{
// Determine whether the mouse pointer is to the left or
// the right of the midpoint of the closest item and set
// the InsertionMark.AppearsAfterItem property accordingly.
Rectangle itemBounds = myListView->GetItemRect( targetIndex );
if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
{
myListView->InsertionMark->AppearsAfterItem = true;
}
else
{
myListView->InsertionMark->AppearsAfterItem = false;
}
}
// Set the location of the insertion mark. If the mouse is
// over the dragged item, the targetIndex value is -1 and
// the insertion mark disappears.
myListView->InsertionMark->Index = targetIndex;
}
//</Snippet3>
// Removes the insertion mark when the mouse leaves the control.
void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ )
{
myListView->InsertionMark->Index = -1;
}
// Moves the item to the location of the insertion mark.
void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the index of the insertion mark;
int targetIndex = myListView->InsertionMark->Index;
// If the insertion mark is not visible, exit the method.
if ( targetIndex == -1 )
{
return;
}
// If the insertion mark is to the right of the item with
// the corresponding index, increment the target index.
if ( myListView->InsertionMark->AppearsAfterItem )
{
targetIndex++;
}
// Retrieve the dragged item.
ListViewItem^ draggedItem = dynamic_cast<ListViewItem^>(e->Data->GetData( ListViewItem::typeid ));
// Insert a copy of the dragged item at the target index.
// A copy must be inserted before the original item is removed
// to preserve item index values.
myListView->Items->Insert( targetIndex, dynamic_cast<ListViewItem^>(draggedItem->Clone()) );
// Remove the original copy of the dragged item.
myListView->Items->Remove( draggedItem );
}
// Sorts ListViewItem objects by index.
ref class ListViewIndexComparer: public System::Collections::IComparer
{
public:
virtual int Compare( Object^ x, Object^ y )
{
return (dynamic_cast<ListViewItem^>(x))->Index - (dynamic_cast<ListViewItem^>(y))->Index;
}
};
};
[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::Run( gcnew ListViewInsertionMarkExample );
}
//</Snippet1>
|
cpp
|
<filename>examples/store/menu/mutations.ts
/*!
* Authors:
* jason <<EMAIL>>
*
* Licensed under the MIT License.
* Copyright (C) 2010-2017 UXmid Inc. All rights reserved.
*/
import { Mutation, MutationTree } from "vuex";
import { Type, ArgumentException, InvalidOperationException } from "uxmid-core";
import * as models from "../../models";
import State from "./state";
export function ADD(state: State, value: { path: string; items: Array<models.IMenuItem> }): void
{
if(!value.path)
{
throw new ArgumentException("path is invalid.");
}
let children: Array<models.IMenuItem>; // 子菜单列表
if(value.path !== "/")
{
// 根据路径查找父菜单
let parent = state.findItem(value.path);
if(parent)
{
if(Type.isArray(parent.children))
{
children = parent.children;
}
else
{
// 如果父菜单没有挂载 "children",则初始化一个子菜单数组
children = new Array<models.IMenuItem>();
parent.children = children;
}
}
else
{
throw new InvalidOperationException(`can't find path '${value.path}'`);
}
}
else
{
children = state.items;
}
children.push(...value.items);
}
export function REMOVE(state: State, path: string): void
{
if(path || path === "/")
{
throw new ArgumentException("path is invalid.");
}
let item = state.findItem(path);
if(!item)
{
// 如果没有根据路径找到菜单项,则直接退出
return;
}
// 根据路径查找菜单项
let items = state.items;
let index = path.lastIndexOf("/");
// 如果父菜单不是根菜单,则获取父菜单下的子菜单列表
if(index !== 0)
{
path = path.substring(0, index);
items = state.findItem(path).children;
}
// 移除菜单项
items.splice(items.indexOf(item), 1);
}
export default <MutationTree<State>>
{
ADD,
REMOVE
};
|
typescript
|
- Kids Nutrition (2-15 Yrs)
Iron Sucrose is used in the treatment of iron deficiency anemia.
Side Effects of Irosun are Taste change, Injection site reactions (pain, swelling, redness), Nausea, Decreased blood pressure, High blood pressure.
Iron Sucrose is an anti-anemic medication. It replenishes the iron stores in your body. Iron is vital for the formation of new red blood cells and hemoglobin, a substance that gives these cells the ability to transport oxygen.
Q. How long can I take Irosun 100mg Injection for?
Irosun 100mg Injection is used to regulate hemoglobin levels in the human body. It is usually given to patients who have iron deficient anemia or iron deficiency. The doctor may suggest using this medicine till the hemoglobin level becomes normal. Do consult your doctor to understand the usage of this medicine properly.
Q. How is Irosun 100mg Injection administered?
Irosun 100mg Injection should be administered under the supervision of a trained healthcare professional or a doctor only and should not be self-administered. The dose will depend on the condition you are being treated for and will be decided by your doctor. Follow your doctor’s instructions carefully to get maximum benefit from Irosun 100mg Injection.
Q. Can I take Irosun 100mg Injection for anemia and iron deficiency?
Yes, Irosun 100mg Injection can be taken for iron deficiency anemia and iron deficiency. However, its use for other types of anemia is not recommended. Take Irosun 100mg Injection in the dose and duration advised by your doctor.
Q. What types of food items should I take other than Irosun 100mg Injection?
You can consume food items that are rich in iron content (like red meat, pork, poultry and seafood). Other food items which contain rich iron content include beans, dark green leafy vegetables (like spinach), peas, dried fruit (raisins and apricots), iron-fortified cereals, breads and pastas. You can also try iron supplements (tablets or capsules) available at pharmacy stores for iron deficient anemia.
Q. Does Irosun 100mg Injection increase weight?
Yes, Irosun 100mg Injection can increase weight. Exercise regularly and take a balanced diet that includes whole grains, fresh fruits, vegetables and fat-free products. You should consult your doctor if you need any further help to manage your weight.
Alvizia Healthcare Pvt. Ltd.
|
english
|
<reponame>thupan/framework<filename>composer.json
{
"name": "thupan/framework",
"description": "Thupan PHP Framework",
"license": "MIT",
"authors": [
{
"name": "<NAME>",
"email": "<EMAIL>",
"homepage": "http://github.com/Eduardo-Vieira",
"role": "Developer"
},
{
"name": "<NAME>",
"email": "<EMAIL>",
"homepage": "http://gitlab.com/rexrod",
"role": "Developer"
},
{
"name": "<NAME>",
"email": "<EMAIL>",
"homepage": "http://github.com/luizschmitt",
"role": "Developer"
},
{
"name": "<NAME>",
"email": "<EMAIL>",
"homepage": "http://github.com/rodrixcornell",
"role": "Developer"
},
{
"name": "<NAME>",
"email": "<EMAIL>",
"homepage": "http://github.com/smithjunior",
"role": "Developer"
}
],
"require": {
"php": ">= 5.6",
"maximebf/debugbar": "1.10",
"twig/twig": "1.38.0",
"setasign/fpdf": "1.7",
"phpmailer/phpmailer": "6.1.6",
"intervention/image": "2.3",
"filp/whoops": "2.1.13"
},
"autoload": {
"psr-4": {
"Console\\": "src/Console/",
"Kernel\\": "src/Kernel/",
"Service\\": "src/Service/",
"Database\\": "src/Database/",
"Support\\": "src/Support/",
"Exception\\": "src/Exception/",
"Routing\\": "src/Routing/",
"Log\\": "src/Log/",
"Generator\\": "src/Generator/"
}
},
"minimum-stability": "dev"
}
|
json
|
//==============================================================================
// Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_ALONG_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_ALONG_HPP_INCLUDED
#include <nt2/include/functor.hpp>
/*!
* \ingroup core
* \defgroup core along
*
* \par Description
* Applies an index \c ind on \c expr along the \c i-th dimension
* by default \c i is the first non-singleton dimension of expr
*
* \par Header file
*
* \code
* #include <nt2/include/functions/along.hpp>
* \endcode
*
*
* \synopsis
*
* \code
* namespace boost::simd
* {
* template <class A0>
* typename meta::call<tag::along_(A0)>::type
* along(A0& expr, A1 const& ind, A2 const& i);
* }
* \endcode
*
* \param expr the expression to index
* \param ind the indexer
* \param i the dimension on which to index
*
* \return expr(_, ..., ind, ..., _) with \c ind at the \c i-th argument
*
*
**/
namespace nt2
{
namespace tag
{
struct along_ : ext::elementwise_<along_>
{
typedef ext::elementwise_<along_> parent;
};
}
NT2_FUNCTION_IMPLEMENTATION(nt2::tag::along_ , along, 2)
NT2_FUNCTION_IMPLEMENTATION_SELF(nt2::tag::along_ , along, 2)
NT2_FUNCTION_IMPLEMENTATION(nt2::tag::along_ , along, 3)
NT2_FUNCTION_IMPLEMENTATION_SELF(nt2::tag::along_ , along, 3)
}
#endif
|
cpp
|
/*
* Public API Surface of my-logger
*/
export * from './lib/my-logger.service';
export * from './lib/my-logger.component';
export * from './lib/my-logger.module';
|
typescript
|
// Copyright 2007-2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/client/ua.h"
#include <windows.h>
#include <atlstr.h>
#include <stdlib.h>
#include "base/rand_util.h"
#include "omaha/base/const_object_names.h"
#include "omaha/base/constants.h"
#include "omaha/base/debug.h"
#include "omaha/base/error.h"
#include "omaha/base/logging.h"
#include "omaha/base/program_instance.h"
#include "omaha/base/safe_format.h"
#include "omaha/base/utils.h"
#include "omaha/base/time.h"
#include "omaha/client/install_apps.h"
#include "omaha/client/install_self.h"
#include "omaha/client/client_metrics.h"
#include "omaha/common/app_registry_utils.h"
#include "omaha/common/command_line_builder.h"
#include "omaha/common/config_manager.h"
#include "omaha/common/const_goopdate.h"
#include "omaha/common/event_logger.h"
#include "omaha/common/goopdate_utils.h"
#include "omaha/common/ping.h"
// Design Notes:
// Following are the mutexes that are taken by the worker
// 1. SingleUpdateWorker. Only taken by the update worker.
// 2. SingleInstallWorker. This is application specific. Only taken by the
// install worker and for the specific application.
// 3. Before install, the install manager takes the global install lock.
// 4. A key thing to add to this code is after taking the install lock,
// to validate that the version of the applicaion that is present in the
// registry is the same as that we queried for. The reason to do this
// is to ensure that there are no races between update and install workers.
// 5. Termination of the worker happens because of four reasons:
// a. Shutdown event - Only applicable to the update worker. When this event
// is signalled, the main thread comes out of the wait. It then tries to
// destroy the contained thread pool, which causes a timed wait for the
// worker thread. The worker thread is notified by setting a
// cancelled flag on the worker.
// b. Install completes, user closes UI - Only applicable for the
// interactive installs. In this case the main thread comes out of
// the message loop and deletes the thread pool. The delete happens
// immediately, since the worker is doing nothing.
// c. User cancels install - Only applicable in case if interactive installs.
// The main thread sets the cancelled flag on the workerjob and comes out
// of the message loop. It then tries to delete the thread pool, causing
// a timed wait. The worker job queries the cancelled flag periodically
// and quits as soon as possible.
// d. The update worker completes - In this case we do not run on a thread
// pool.
// 6. There is a random delay before triggering the actual update check.
// This delay avoids the situation where many update checks could happen at
// the same time, for instance at the minute mark, when the client computers
// have their clocks synchronized.
namespace omaha {
namespace {
void WriteUpdateAppsStartEvent(bool is_machine) {
GoogleUpdateLogEvent update_event(EVENTLOG_INFORMATION_TYPE,
kWorkerStartEventId,
is_machine);
update_event.set_event_desc(_T("Update Apps start"));
ConfigManager& cm = *ConfigManager::Instance();
int au_check_period_ms = cm.GetAutoUpdateTimerIntervalMs();
int time_since_last_checked_sec = cm.GetTimeSinceLastCheckedSec(is_machine);
bool is_period_overridden = false;
int last_check_period_ms = cm.GetLastCheckPeriodSec(&is_period_overridden);
CString event_text;
SafeCStringFormat(&event_text,
_T("AuCheckPeriodMs=%d, TimeSinceLastCheckedSec=%d, ")
_T("LastCheckedPeriodSec=%d"),
au_check_period_ms, time_since_last_checked_sec, last_check_period_ms);
update_event.set_event_text(event_text);
update_event.WriteEvent();
}
// Ensures there is only one instance of /ua per session per Omaha instance.
bool EnsureSingleUAProcess(bool is_machine,
std::unique_ptr<ProgramInstance>* instance) {
ASSERT1(instance);
NamedObjectAttributes single_ua_process_attr;
GetNamedObjectAttributes(kUpdateAppsSingleInstance,
is_machine,
&single_ua_process_attr);
instance->reset(new ProgramInstance(single_ua_process_attr.name));
return !instance->get()->EnsureSingleInstance();
}
bool IsUpdateAppsHourlyJitterDisabled() {
DWORD value = 0;
if (SUCCEEDED(RegKey::GetValue(MACHINE_REG_UPDATE_DEV,
kRegValueDisableUpdateAppsHourlyJitter,
&value))) {
return value != 0;
} else {
return false;
}
}
} // namespace
// Returns false if "RetryAfter" in the registry is set to a time greater than
// the current time. Otherwise, returns true if the absolute difference between
// time moments is greater than the interval between update checks.
// Deals with clocks rolling backwards, in scenarios where the clock indicates
// some time in the future, for example next year, last_checked_ is updated to
// reflect that time, and then the clock is adjusted back to present.
// In the case where the update check period is not overriden, the function
// introduces an hourly jitter for 10% of the function calls when the time
// interval falls in the range: [LastCheckPeriodSec, LastCheckPeriodSec + 1hr).
// No update check is made if the "updates suppressed" period is in effect.
bool ShouldCheckForUpdates(bool is_machine) {
ConfigManager* cm = ConfigManager::Instance();
if (!cm->CanRetryNow(is_machine)) {
return false;
}
bool is_period_overridden = false;
const int update_interval = cm->GetLastCheckPeriodSec(&is_period_overridden);
if (0 == update_interval) {
ASSERT1(is_period_overridden);
OPT_LOG(L1, (_T("[ShouldCheckForUpdates returned 0][checks disabled]")));
return false;
}
const int time_since_last_check = cm->GetTimeSinceLastCheckedSec(is_machine);
bool should_check_for_updates = false;
if (ConfigManager::Instance()->AreUpdatesSuppressedNow()) {
should_check_for_updates = false;
} else if (time_since_last_check < update_interval) {
// Too soon.
should_check_for_updates = false;
} else if (update_interval <= time_since_last_check &&
time_since_last_check < update_interval + kSecondsPerHour) {
// Defer some checks if not overridden or if the feature is not disabled.
// Do not skip checks when errors happen in the RNG.
if (!is_period_overridden && !IsUpdateAppsHourlyJitterDisabled()) {
const int kPercentageToSkip = 10; // skip 10% of the checks.
unsigned int random_value = 0;
if (!RandUint32(&random_value)) {
random_value = 0;
}
should_check_for_updates = random_value % 100 < 100 - kPercentageToSkip;
} else {
should_check_for_updates = true;
}
} else {
ASSERT1(time_since_last_check >= update_interval + kSecondsPerHour);
should_check_for_updates = true;
}
CORE_LOG(L3, (_T("[ShouldCheckForUpdates returned %d][%u]"),
should_check_for_updates, is_period_overridden));
return should_check_for_updates;
}
// Always checks whether it should uninstall.
// Checks for updates of all apps if the required period has elapsed, it is
// being run on-demand, or an uninstall seems necessary. It will also send a
// self-update failure ping in these cases if necessary.
//
// Calls UpdateAllApps(), which will call IAppBundle::updateAllApps(), even in
// cases where an uninstall seems necessary. This allows an uninstall ping to
// be sent for any uninstalled apps. Because the COM server does not know about
// uninstall, the COM server will also do a final update check for the remaining
// app - should be Omaha. It's possible that this update check could result in
// a self-update, in which case the uninstall may fail and be delayed an hour.
// See http://b/2814535.
// Since all pings are sent by the AppBundle destructor, if the bundle has
// normal or uninstall pings need, the network request could delay the exiting
// of the COM server beyond the point where this client releases the IAppBundle.
// and launches /uninstall. This could cause uninstall to fail if the ping takes
// a long time.
//
// TODO(omaha): Test this method as it is very important.
HRESULT UpdateApps(bool is_machine,
bool is_interactive,
bool is_on_demand,
const CString& install_source,
const CString& display_language,
bool* has_ui_been_displayed) {
CORE_LOG(L1, (_T("[UpdateApps]")));
ASSERT1(has_ui_been_displayed);
WriteUpdateAppsStartEvent(is_machine);
std::unique_ptr<ProgramInstance> single_ua_process;
if (EnsureSingleUAProcess(is_machine, &single_ua_process)) {
OPT_LOG(L1, (_T("[Another worker is already running. Exiting.]")));
++metric_client_another_update_in_progress;
return GOOPDATE_E_UA_ALREADY_RUNNING;
}
VERIFY_SUCCEEDED(ConfigManager::Instance()->SetLastStartedAU(is_machine));
if (ConfigManager::Instance()->CanUseNetwork(is_machine)) {
VERIFY_SUCCEEDED(Ping::SendPersistedPings(is_machine));
}
// Generate a session ID for network accesses.
CString session_id;
VERIFY_SUCCEEDED(GetGuid(&session_id));
// A tentative uninstall check is done here. There are stronger checks,
// protected by locks, which are done by Setup.
size_t num_clients(0);
const bool is_uninstall =
FAILED(app_registry_utils::GetNumClients(is_machine, &num_clients)) ||
num_clients <= 1;
CORE_LOG(L4, (_T("[UpdateApps][registered apps: %u]"), num_clients));
if (is_uninstall) {
// TODO(omaha3): The interactive /ua process will not exit without user
// interaction. This could cause the uninstall to fail.
CORE_LOG(L1, (_T("[/ua launching /uninstall]")));
return goopdate_utils::LaunchUninstallProcess(is_machine);
}
const bool should_check_for_updates = ShouldCheckForUpdates(is_machine);
if (!(is_on_demand || should_check_for_updates)) {
OPT_LOG(L1, (_T("[Update check not needed at this time]")));
return S_OK;
}
// Waits a while before starting checking for updates. Usually, the wait
// is a random value in the range [0, 60000) miliseconds (up to one minute).
const int au_jitter_ms(ConfigManager::Instance()->GetAutoUpdateJitterMs());
if (au_jitter_ms > 0) {
OPT_LOG(L1, (_T("[Applying update check jitter][%d]"), au_jitter_ms));
::Sleep(au_jitter_ms);
}
HRESULT hr = UpdateAllApps(is_machine,
is_interactive,
install_source,
display_language,
session_id,
has_ui_been_displayed);
if (FAILED(hr)) {
CORE_LOG(LW, (_T("[UpdateAllApps failed][0x%08x]"), hr));
}
return hr;
}
} // namespace omaha
|
cpp
|
from .read_hdf5 import *
from .hdf5_api import *
|
python
|
<reponame>Liaojinghui/neo-rs
#![no_std]
#![deny(unsafe_code)]
// #![warn(missing_docs)]
#![allow(unused)]
pub use cipher::{self, BlockCipher, NewBlockCipher, generic_array::{typenum::UTerm, GenericArray}
};
pub use aes_soft::{Aes128, Aes192, Aes256};
use std::convert::TryInto;
use std::fmt::{self, Debug, Formatter};
use block_modes::{block_padding::Pkcs7, BlockMode, Ecb};
use hmac::{Hmac, Mac, NewMac};
use sha3::Sha3_256;
type U8Array<Size> = GenericArray<u8, Size>;
type HmacSha256 = Hmac<Sha3_256>;
type Aes256Ecb = Ecb<Aes256, Pkcs7>;
pub type KeySize = [u8; 32];
pub struct Aes {
aes: Aes256,
aes_varlen: Aes256Ecb,
key: KeySize,
}
impl Debug for Aes {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Aes")
.field("key", &self.key)
.finish()
}
}
impl Aes {
pub fn from_key(key: KeySize) -> Self {
let arr = GenericArray::from_slice(&key);
let blank = U8Array::<UTerm>::default();
let cipher = Aes256::new(&arr);
let varlen = Aes256Ecb::new(cipher.clone(), &blank);
Aes {
aes: cipher,
aes_varlen: varlen,
key,
}
}
pub fn from_pass(password: &[u8]) -> Self {
let mac = HmacSha256::new_varkey(password).expect("somehow the key was invalid length");
let password_hash = mac.finalize().into_bytes();
Self::from_key(password_hash.try_into().unwrap())
}
pub fn set_key(&mut self, key: KeySize) {
let arr = GenericArray::from_slice(&key);
let blank: cipher::generic_array::GenericArray<
u8,
cipher::generic_array::typenum::UTerm,
> = Default::default();
let cipher = Aes256::new(&arr);
let varlen = Aes256Ecb::new(cipher.clone(), &blank);
self.aes = cipher;
self.aes_varlen = varlen;
}
pub fn get_key(&self) -> KeySize {
self.key
}
pub fn encrypt(&self, data: Vec<u8>) -> Vec<u8> {
let cipher = self.aes_varlen.clone();
cipher.encrypt_vec(&data)
}
pub fn decrypt(&self, data: Vec<u8>) -> Vec<u8> {
let cipher = self.aes_varlen.clone();
cipher.decrypt_vec(&data).expect("Block mode error?")
}
}
|
rust
|
A subtle mental tendency that is ingrained in the mind, does not take long to break the trust. Earning and keeping faith is the most important thing for a human being. Never trust anyone completely. Thinking someone is a liar is another bad idea. Wise people are careful never to trust others unthinkingly. Even after their initial failures, successful people hold on to their ideals and goals and as a result, they can succeed in any situation.
At night they see the first face of success. The definition of the word "faith" is excellent. Successful people have faith. Actions should always precede words. Trust between husband and wife is necessary for a partnership to last because confidence strengthens the connection, which is a factor in many relationships. Never judge a person based on another's opinion; Always test them before you trust them.
Even if trust is built over time, it can be lost instantly. Even if the trust is broken, the scars are visible. With faith, life moves faster; With doubt, life moves slower. Although trusting someone involves risk, not depending is the most significant risk.
Furthermore, when someone is praised, he does not really believe it; Yet, when he is criticized, he accepts it. Additionally, telling the truth as opposed to a lie will indeed make someone cry as opposed to making them happy. The benefits accrued to him are even more. It is inappropriate for them to make promises, trust or use emotion.
I say something about my life. When I got married my husband was a complete stranger to me. Yet since marriage we have never doubted or mistrusted each other. My Husband trusts me a lot. No matter what I do he knows I will never break his trust. . But we have always trusted each other.
Because that is very scary. Our relationship is still beautiful because trust between us is vital. In this case, the association is more substantial.
|
english
|
India’s second mission to the moon, Chandrayan 2 will be launched on July 15, at 2,51am, the Indian Space Research Organisation (ISRO) announced on Wednesday.
The total mass of Chandrayaan 2 system is 3. 8 tons, has three modules — Orbiter, Lander (Vikram) and Rover (Pragyan), said ISRO and it costs Rs 603 crore.
The Orbiter and Lander modules will be interfaced mechanically and stacked together as an integrated module and accommodated inside the GSLV MK-III launch vehicle. The Rover is housed inside the Lander.
“After launch into earth bound orbit by GSLV MK-III, the integrated module will reach Moon orbit using Orbiter propulsion module and then, Lander will separate from the Orbiter and soft land at the predetermined site close to lunar South Pole,” the ISRO said.
Further, the Rover will roll out for carrying out scientific experiments on the lunar surface. Instruments are also mounted on Lander and Orbiter for carrying out scientific experiments.
The ISRO had earlier kept the launch window for the mission from July 9 to July 16.
|
english
|
{"event_timestamp":1468946931.565,"status":"Unresolved","hostname":"WIN-IA9NQ1GN8OI","digsig_result":"Signed","report_score":"75","watchlist_name":"google","observed_filename":["c:\\program files (x86)\\google\\update\\install\\{6742b686-6743-482c-8834-6871bc03634f}\\49.0.2623.110_49.0.2623.87_chrome_updater.exe","c:\\program files (x86)\\google\\update\\install\\{cd5468f4-c34c-4bfc-b2c8-ceade47ba338}\\49.0.2623.110_49.0.2623.87_chrome_updater.exe"],"feed_id":"-1","os_type":"Windows","other_hostnames":["JASON-WIN81-VM"],"unique_id":"be9bce96-05ed-49b0-8588-cdc67952456a","host_count":"2","ioc_confidence":"0.5","watchlist_id":"2812","ioc_type":"query","md5":"ACDDDCD662CF23936178DCDCE4473D18","feed_name":"My Watchlists","sensor_criticality":"3.0","alert_severity":"50.625","alert_type":"watchlist.hit.query.binary","created_time":"2016-07-19T16:48:36.520174Z","feed_rating":"3.0","observed_filename_total_count":"2"}
|
json
|
New Delhi: Jallianwala Bagh massacre on 13 April, a day to tribute Indians martyred who died in the act. Based on British government records, 379 people, including men, women, and children, were killed and 1,200 were injured in the indiscriminate firing ordered by Colonel Reginald Dyer.
Martial Law was declared in five districts following the Jallianwala Bagh massacre: Lahore, Amritsar, Gujranwala, Gujarat, and Lyallpore.
Around 50 British Indian Army soldiers, led by Colonel Reginald Dyer, opened fire on unarmed villagers gathered for Baishakhi at Amritsar’s Jallianwala Bagh. The crowd had gathered in Jallianwala Bagh to celebrate Baisakhi and to lament the arrest and deportation of two freedom activists, Satya Pal and Dr Saifuddin Kitchlew.
The soldiers opened fire on Colonel Dyer’s orders. The fire lasted roughly ten minutes. According to the British administration, 379 people were killed and 1,200 were injured in the Jallianwala Bagh massacre. According to some records, approximately a thousand people were slain. The Jallianwalah Bagh tragedy infuriated the Indian people, prompting Mahatma Gandhi to launch the Noncooperation Movement.
The act aroused considerable indignation in India and abroad, fueling India’s drive for independence, and even moderate nationalists began to take a more militant posture in their demands. As a protest against the British colonial authority, Rabindranath Tagore abandoned the honours bestowed upon him, including a knighthood. In revenge, freedom fighter Udham Singh assassinated Michael O’Dwyer, the then lieutenant-governor of Punjab and a strident defender of Reginald Dyer. Following the slaughter, the Indian government established the Hunter Commission to investigate the incidents and unrest in Punjab. In 2019, a museum was established in the region to remember those who died and to provide an honest description of what happened.
In 2019, more than a century after the massacre, British High Commissioner to India Dominic Asquith visited the Jallianwala Bagh National Memorial and paid tribute to those who died.
|
english
|
The New Orleans Pelicans will host the Phoenix Suns at Smoothie King Center on March 15th.
The Phoenix Suns will head into this away fixture on the back of a 140-111 blowout win against the LA Lakers. Winning even without some key players in their rotation, the Suns showed their dominance as the first-seed with the best record in the league.
The New Orleans Pelicans are also coming off a win. Registering a 130-105 win against the Houston Rockets, the Pelicans notched a much-needed victory to snap a four-game losing streak.
The Suns have a few key players to mention in their injury report ahead of Tuesday's game.
Phoenix were dealt a shocking blow when Chris Paul fractured his thumb before the All-Star break. He is expected to be out until mid-April at least.
Joining him on the injury report, Cameron Johnson has missed the last few games with a quad injury. While he has been listed as day-to-day, he may miss the upcoming game.
Long-term injuries on the roster will see Suns big men Dario Saric and Frank Kaminsky remain out of the rotation. There is no timeline for their return.
The Pels fell upon tough times with injuries after their success following the All-Star break. With a number of key players out of the rotation, they haven't been in the best state.
Recent injuries have seen the star duo of Brandon Ingram and CJ McCollum out of the rotation. Ingram suffered a hamstring injury and is due to be re-evaluated. He has been listed as out for the upcoming game.
McCollum is expected to return from medical protocols but has been listed as questionable.
Long-term injuries on the roster include recent addition Larry Nance join the report with a knee injury alongside Kira Lewis Jr. and Zion Williamson.
The oddsmakers have favored Phoenix to win by a decent margin in this matchup. Both teams will feature two key players missing from their regular rotation.
But even with the homecourt advantage, New Orleans doesn't have the necessary tools to take on the Suns. While also considering the Pelicans' form as of late, Phoenix have the upper hand.
- Phoenix have three of their last five games without Chris Paul and Cameron Johnson.
- The Suns rank 5th in offensive rating (114.0) and 2nd in defensive rating (105.8).
- Devin Booker has been averaging 26.7 points and 8.3 assists per game in his last 10 outings.
Click here to bet on Devin Booker scoring 28+ points and leading Phoenix to a win.
- The Pelicans have won one game in their last five outings.
- CJ McCollum may return to the lineup.
- Jonas Valanciunas has averaged 17.5 points and 11.4 rebounds in the last 10 games.
Click here to bet on Jonas Valanciunas scoring the first basket of the game against the Suns.
The Suns have had a well-established lineup without Paul and Johnson. Cameron Payne has given the side some great minutes in the starting backcourt alongside Devin Booker.
With the frontcourt trio of Mikal Bridges, Jae Crowder and Deandre Ayton remaining unchanged, the Suns will also have a lot of depth to support their starting rotation.
Players such as Aaron Holiday, Torrey Craig, JaVale McGee and Bismack Biyombo may see a lot of burn.
The Pelicans have quite a shorthanded roster considering the absences of CJ McCollum and Brandon Ingram. While McCollum is questionable, Devonte' Graham will continue to start at point guard alongside Naji Marshall in the backcourt.
The frontcourt trio will see no changes as Herbert Jones starts at small forward alongside Jaxson Hayes at power forward and Jonas Valanciunas at center.
The bench rotation may see significant minutes from players such as Jose Alvarado, Willy Hernangomez and Trey Murphy III.
Click here to register on FanDuel SB and bet on the Suns vs Pelicans game.
Check out all NBA Trade Deadline 2024 deals here as big moves are made!
|
english
|
// #define NDEBUG
#include <cassert>
#include <cstdio>
#include <cstring>
#include <climits>
#include <array>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long i64;
#define NMAX 200000
#define S 100
template <typename T>
struct ReversedVector {
vector<T> data;
size_t size() const {
return data.size();
}
void extend() {
data.push_back(T());
}
T &operator[](const size_t i) {
return data[data.size() - i];
}
const T &operator[](const size_t i) const {
return data[data.size() - i];
}
};
typedef array<i64, S + 1> SArray;
struct Data {
ReversedVector<SArray> dp;
size_t size() const {
return dp.size();
}
void extend() {
dp.extend();
for (int i = 0; i <= S; i++) {
if (i < dp.size())
dp[1][i] = dp[1 + i][i] + 1;
else
dp[1][i] = 1;
}
}
i64 query(int x, int d) {
if (d <= S)
return dp[x][d];
i64 ret = 0;
for (; x <= dp.size(); x += d) {
ret += dp[x][0];
}
return ret;
}
Data &operator+=(const Data &b) {
for (int i = 1; i <= b.size(); i++) {
for (int j = 0; j <= S; j++) {
dp[i][j] += b.dp[i][j];
}
}
return *this;
}
};
static int n;
static vector<int> G[NMAX + 10];
static int father[NMAX + 10];
static int dep[NMAX + 10];
static int top[NMAX + 10];
static int nxt[NMAX + 10];
static Data dat[NMAX + 10];
static i64 ans[NMAX + 10];
static i64 suf[NMAX + 10];
void dfs(int u, int dist) {
suf[dist]++;
for (int v : G[u]) {
dfs(v, dist + 1);
dep[u] = max(dep[u], dep[v] + 1);
}
}
void decompose(int u) {
nxt[u] = 0;
for (int v : G[u]) {
if (dep[v] + 1 == dep[u]) {
nxt[u] = v;
break;
}
}
if (nxt[u]) {
top[nxt[u]] = top[u];
decompose(nxt[u]);
}
for (int v : G[u]) {
if (v == nxt[u])
continue;
top[v] = v;
decompose(v);
}
}
void initialize() {
scanf("%d", &n);
for (int v = 2; v <= n; v++) {
int u;
scanf("%d", &u);
father[v] = u;
G[u].push_back(v);
}
dfs(1, 0);
top[1] = 1;
decompose(1);
}
void solve(int u) {
if (nxt[u])
solve(nxt[u]);
Data &cur = dat[top[u]];
for (int v : G[u]) {
if (v == nxt[u])
continue;
solve(v);
for (int d = 1; d <= dat[v].size(); d++) {
ans[d] += dat[v].query(d, d) * cur.query(d, d);
}
cur += dat[v];
}
cur.extend();
}
int main() {
// freopen("gcd.in", "r", stdin);
initialize();
solve(1);
for (int i = n - 1; i >= 1; i--) {
suf[i] += suf[i + 1];
for (int j = i + i; j < n; j += i) {
ans[i] -= ans[j];
}
}
for (int i = 1; i < n; i++) {
printf("%lld\n", ans[i] + suf[i]);
}
return 0;
}
|
cpp
|
#ifndef BVH_HPP
#define BVH_HPP
#include "AABB.hpp"
#include "Hitable.hpp"
#include "Ray.hpp"
#include <vector>
/*
* 层次包围体BHV:用AABB实现
* 这里认为层次包围盒也是一个Hitable
* 其作用是一个容器,能够高效处理光线和物体是否相交
*/
class BVHNode : public Hitable
{
public:
BVHNode() {}
// BVHNode(Hitable **l, int n, float time0, float time1);
BVHNode(std::vector<shared_ptr<Hitable>> &l,size_t start, size_t end, float time0, float time1);
virtual bool bounding_box(float t0, float t1, AABB &output_box) const override;
virtual bool hit(const Ray &r, float t_min, float t_max, Hit &rec) const override;
/*data*/
shared_ptr<Hitable> left_c; //左孩子,为了通用性,指针为Hitbale
shared_ptr<Hitable> right_c; //右孩子
AABB box;
};
#endif
|
cpp
|
<reponame>Ryebread4/Rustionary
{"word":"dipterocarpus","definition":"A genus of trees found in the East Indies, some species of which produce a fragrant resin, other species wood oil. The fruit has two long wings."}
|
json
|
package algorithms.a301_to_a350.a337_HouseRobberIII_Medium;
/**
* Created by 31798 on 2016/9/14.
*/
public class SolutionNotEfficientEnough {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
int robThis = root.val;
if (root.left != null) {
robThis += rob(root.left.left) + rob(root.left.right);
}
if (root.right != null) {
robThis += rob(root.right.left) + rob(root.right.right);
}
int leaveThis = rob(root.left) + rob(root.right);
return Math.max(leaveThis, robThis);
}
}
|
java
|
import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only'
import * as bitcoin from 'bitcoinjs-lib'
import * as ghost from 'bitcoinjs-lib'
import * as next from 'bitcoinjs-lib'
import abi from 'human-standard-token-abi'
import ethLikeHelper from 'common/helpers/ethLikeHelper'
import EVM_CONTRACTS_ABI from 'common/helpers/constants/EVM_CONTRACTS_ABI'
import erc20Like from 'common/erc20Like'
import config, { initExternalConfig } from 'helpers/externalConfig'
import helpers, { constants as privateKeys, utils } from 'helpers'
import actions from 'redux/actions'
import SwapApp, { constants } from 'swap.app'
import SwapAuth from 'swap.auth'
import SwapRoom from 'swap.room'
import SwapOrders from 'swap.orders'
import {
TurboMaker,
TurboTaker,
ETH2BTC,
BTC2ETH,
ETHTOKEN2BTC,
BTC2ETHTOKEN,
GHOST2ETH,
ETH2GHOST,
ETHTOKEN2GHOST,
GHOST2ETHTOKEN,
//GHOST2BTC,
//BTC2GHOST,
NEXT2ETH,
ETH2NEXT,
ETHTOKEN2NEXT,
NEXT2ETHTOKEN,
//NEXT2BTC,
//BTC2NEXT,
BNB2BTC,
BTC2BNB,
BSCTOKEN2BTC,
BTC2BSCTOKEN,
MATIC2BTC,
BTC2MATIC,
MATICTOKEN2BTC,
BTC2MATICTOKEN,
ARBITRUM2BTC,
BTC2ARBITRUM,
} from 'swap.flows'
import {
BtcSwap,
EthSwap,
BnbSwap,
MaticSwap,
ArbitrumSwap,
GhostSwap,
NextSwap,
EthTokenSwap,
BscTokenSwap,
MaticTokenSwap,
} from 'swap.swaps'
import metamask from 'helpers/metamask'
import { default as bitcoinUtils } from '../../../common/utils/coin/btc'
import { default as nextUtils } from '../../../common/utils/coin/next'
initExternalConfig()
const repo = utils.createRepo()
utils.exitListener()
let _inited = false
const onInit = (cb) => {
const _wait = () => {
if (_inited) {
cb()
} else {
setTimeout(_wait, 100)
}
}
_wait()
}
const createSwapApp = async () => {
await metamask.web3connect.onInit(async () => {
const web3 = actions.eth.getWeb3()
const NETWORK = process.env.MAINNET ? `MAINNET` : `TESTNET`
SwapApp.setup(
{
network: process.env.MAINNET ? 'mainnet' : 'testnet',
env: {
web3,
getWeb3: actions.eth.getWeb3,
web3bnb: actions.bnb.getWeb3(),
getWeb3Bnb: actions.bnb.getWeb3,
web3Matic: actions.matic.getWeb3(),
getWeb3Matic: actions.matic.getWeb3,
web3Arbitrum: actions.arbeth.getWeb3(),
getWeb3Arbitrum: actions.arbeth.getWeb3,
bitcoin,
ghost,
next,
coininfo: {
ghost: {
main: helpers.ghost.networks.mainnet,
test: helpers.ghost.networks.testnet,
},
next: {
main: helpers.next.networks.mainnet,
test: helpers.next.networks.mainnet,
},
},
storage: window.localStorage,
sessionStorage: window.sessionStorage,
metamask,
isBinance: !!config.binance,
isTest: !!config.isTest,
},
// White list (Список адресов btc довереных продавцов)
// whitelistBtc: [],
services: [
new SwapAuth({
// TODO need init swapApp only after private keys created!!!!!!!!!!!!!!!!!!!
eth: localStorage.getItem(privateKeys.privateKeyNames.eth),
// for evm compatible blockchains use eth private key
bnb: localStorage.getItem(privateKeys.privateKeyNames.eth),
matic: localStorage.getItem(privateKeys.privateKeyNames.eth),
arbeth: localStorage.getItem(privateKeys.privateKeyNames.eth),
btc: localStorage.getItem(privateKeys.privateKeyNames.btc),
ghost: localStorage.getItem(privateKeys.privateKeyNames.ghost),
next: localStorage.getItem(privateKeys.privateKeyNames.next),
}),
new SwapRoom({
repo,
config: {
Addresses: {
Swarm: [config.pubsubRoom.swarm],
},
},
}),
new SwapOrders(),
],
swaps: [
new EthSwap({
address: config.swapContract.eth,
abi: EVM_CONTRACTS_ABI.NATIVE_COIN_SWAP,
fetchBalance: (address) => actions.eth.fetchBalance(address),
estimateGasPrice: () => ethLikeHelper.eth.estimateGasPrice(),
sendTransaction: ({ to, amount }) => actions.eth.send({ to, amount }),
}),
new BnbSwap({
address: config.swapContract.bnb,
abi: EVM_CONTRACTS_ABI.NATIVE_COIN_SWAP,
fetchBalance: (address) => actions.bnb.fetchBalance(address),
estimateGasPrice: () => ethLikeHelper.bnb.estimateGasPrice(),
sendTransaction: ({ to, amount }) => actions.bnb.send({ to, amount }),
}),
...(config?.opts?.blockchainSwapEnabled?.matic
? [
new MaticSwap({
address: config.swapContract.matic,
abi: EVM_CONTRACTS_ABI.NATIVE_COIN_SWAP,
fetchBalance: (address) => actions.matic.fetchBalance(address),
estimateGasPrice: () => ethLikeHelper.matic.estimateGasPrice(),
sendTransaction: ({ to, amount }) => actions.matic.send({ to, amount }),
}),
]
: []),
...(config?.opts?.blockchainSwapEnabled?.arbeth
? [
new ArbitrumSwap({
address: config.swapContract.arbitrum,
abi: EVM_CONTRACTS_ABI.NATIVE_COIN_SWAP,
fetchBalance: (address) => actions.arbeth.fetchBalance(address),
estimateGasPrice: () => ethLikeHelper.arbeth.estimateGasPrice(),
sendTransaction: ({ to, amount }) => actions.arbeth.send({ to, amount }),
}),
]
: []),
new BtcSwap({
fetchBalance: (address) =>
bitcoinUtils.fetchBalance({
address,
NETWORK,
}),
fetchUnspents: (address) =>
bitcoinUtils.fetchUnspents({
address,
NETWORK,
}),
broadcastTx: (txRaw) =>
bitcoinUtils.broadcastTx({
txRaw,
NETWORK,
}),
fetchTxInfo: (hash) =>
bitcoinUtils.fetchTxInfo({
hash,
NETWORK,
}),
checkWithdraw: (scriptAddress) =>
bitcoinUtils.checkWithdraw({
scriptAddress,
NETWORK,
}),
estimateFeeValue: (options) =>
bitcoinUtils.estimateFeeValue({
...options,
NETWORK,
}),
fetchTxInputScript: (options) =>
bitcoinUtils.fetchTxInputScript({
...options,
NETWORK,
}),
sendTransaction: ({ to, amount }) => actions.btc.sendTransaction({ to, amount }),
}),
new GhostSwap({
fetchBalance: (address) => actions.ghost.fetchBalance(address),
fetchUnspents: (scriptAddress) => actions.ghost.fetchUnspents(scriptAddress),
broadcastTx: (txRaw) => actions.ghost.broadcastTx(txRaw),
fetchTxInfo: (txid) => actions.ghost.fetchTxInfo(txid),
checkWithdraw: (scriptAddress) => actions.ghost.checkWithdraw(scriptAddress),
estimateFeeValue: ({ inSatoshis, speed, address, txSize }) =>
helpers.ghost.estimateFeeValue({ inSatoshis, speed, address, txSize }),
}),
new NextSwap({
fetchBalance: (address) =>
nextUtils.fetchBalance({
address,
NETWORK,
}),
fetchUnspents: (address) =>
nextUtils.fetchUnspents({
address,
NETWORK,
}),
broadcastTx: (txRaw) =>
nextUtils.broadcastTx({
txRaw,
NETWORK,
}),
fetchTxInfo: (hash) =>
nextUtils.fetchTxInfo({
hash,
NETWORK,
}),
checkWithdraw: (scriptAddress) =>
nextUtils.checkWithdraw({
scriptAddress,
NETWORK,
}),
estimateFeeValue: (options) =>
nextUtils.estimateFeeValue({
...options,
NETWORK,
}),
fetchTxInputScript: (options) =>
nextUtils.fetchTxInputScript({
...options,
NETWORK,
}),
}),
// Ether
...Object.keys(config.erc20).map(
(key) =>
new EthTokenSwap({
name: key,
tokenAbi: abi,
address: config.swapContract.erc20,
//@ts-ignore
decimals: config.erc20[key].decimals,
tokenAddress: config.erc20[key].address,
fetchBalance: (address) =>
actions.erc20.fetchBalance(
address,
config.erc20[key].address,
config.erc20[key].decimals
),
//@ts-ignore
estimateGasPrice: ({ speed } = {}) => erc20Like.erc20.estimateGasPrice({ speed }),
abi: EVM_CONTRACTS_ABI.TOKEN_SWAP,
})
),
// Binance
...Object.keys(config.bep20).map(
(key) =>
new BscTokenSwap({
name: key,
tokenAbi: abi,
address: config.swapContract.bep20,
//@ts-ignore
decimals: config.bep20[key].decimals,
tokenAddress: config.bep20[key].address,
fetchBalance: (address) =>
actions.bep20.fetchBalance(
address,
config.bep20[key].address,
config.bep20[key].decimals
),
//@ts-ignore
estimateGasPrice: ({ speed } = {}) => erc20Like.bep20.estimateGasPrice({ speed }),
abi: EVM_CONTRACTS_ABI.TOKEN_SWAP,
})
),
// Matic
...Object.keys(config.erc20matic).map(
(key) =>
new MaticTokenSwap({
name: key,
tokenAbi: abi,
address: config.swapContract.erc20matic,
//@ts-ignore
decimals: config.erc20matic[key].decimals,
tokenAddress: config.erc20matic[key].address,
fetchBalance: (address) =>
actions.erc20matic.fetchBalance(
address,
config.erc20matic[key].address,
config.erc20matic[key].decimals
),
//@ts-ignore
estimateGasPrice: ({ speed } = {}) =>
erc20Like.erc20matic.estimateGasPrice({ speed }),
abi: EVM_CONTRACTS_ABI.TOKEN_SWAP,
})
),
],
flows: [
TurboMaker,
TurboTaker,
ETH2BTC,
BTC2ETH,
BNB2BTC,
BTC2BNB,
...(config?.opts?.blockchainSwapEnabled?.matic ? [MATIC2BTC, BTC2MATIC] : []),
ARBITRUM2BTC,
BTC2ARBITRUM,
// GHOST2BTC,
// BTC2GHOST,
GHOST2ETH,
ETH2GHOST,
//NEXT2BTC,
//BTC2NEXT,
NEXT2ETH,
ETH2NEXT,
...Object.keys(config.bep20).map((key) => BSCTOKEN2BTC(key)),
...Object.keys(config.bep20).map((key) => BTC2BSCTOKEN(key)),
...Object.keys(config.erc20matic).map((key) => MATICTOKEN2BTC(key)),
...Object.keys(config.erc20matic).map((key) => BTC2MATICTOKEN(key)),
...Object.keys(config.erc20).map((key) => ETHTOKEN2BTC(key)),
...Object.keys(config.erc20).map((key) => BTC2ETHTOKEN(key)),
...Object.keys(config.erc20).map((key) => ETHTOKEN2GHOST(key)),
...Object.keys(config.erc20).map((key) => GHOST2ETHTOKEN(key)),
...Object.keys(config.erc20).map((key) => ETHTOKEN2NEXT(key)),
...Object.keys(config.erc20).map((key) => NEXT2ETHTOKEN(key)),
],
},
true
)
window.SwapApp = SwapApp.shared()
_inited = true
})
}
export { createSwapApp, onInit }
|
typescript
|
import Dexie from 'dexie';
// Database inherits from the Dexie class to handle all database logic for the
// todo app.
// NOTE: For an app like this where the database interactions are pretty
// simple, it's not strictly necessary to subclass Dexie, but I personally
// prefer the subclassing pattern over having a global Dexie database class
// in order to structure all the database logic in a single class.
export class Database extends Dexie {
constructor() {
// run the super constructor Dexie(databaseName) to create the IndexedDB
// database.
super('database');
// create the todos store by passing an object into the stores method. We
// declare which object fields we want to index using a comma-separated
// string; the ++ for the index on the id field indicates that "id" is an
// auto-incrementing primary key, while the "done" field is just a regukar
// IndexedDB index.
this.version(1).stores({
todos: '++id,done',
});
// we can retrieve our todos store with Dexie.table, and then use it as a
// field on our Database class for convenience; we can now write code such
// as "this.todos.add(...)" rather than "this.table('todos').add(...)"
this.todos = this.table('todos');
}
// getTodos retrieves all todos from the todos object store in a defined
// order; order can be:
// - forwardOrder to get the todos in forward chronological order
// - reverseOrder to get the todos in reverse chronological order
// - unfinishedFirstOrder to get the todos in reverse chronological order
async getTodos(order) {
// In Dexie, we create queries by chaining methods, such as orderBy to
// sort by an indexed field, and reverse to reverse the order we retrieve
// data in. The toArray method returns a promise that resolves to the array
// of the items in the todos store.
let todos = [];
switch (order) {
case forwardOrder:
todos = await this.todos.orderBy('id').toArray();
break;
case reverseOrder:
todos = await this.todos.orderBy('id').reverse().toArray();
break;
case unfinishedFirstOrder:
todos = await this.todos.orderBy('done').toArray();
break;
default:
// as a default just fall back to forward order
todos = await this.todos.orderBy('id').toArray();
}
// The reason we need to modify the done field on each todo is because in
// IndexedDB, integers can be indexed, but booleans cannot, so we represent
// "done" status as an integer. Only the database logic needs to know that
// detail, though, so for convenience when we return the todos, their "done"
// status is a boolean.
return todos.map((t) => {
t.done = !!t.done;
return t;
});
}
// setTodoDone sets whether or not the todo with the ID passed in is done.
// Returns a promise that resolves if the update is successful.
setTodoDone(id, done) {
return this.todos.update(id, { done: done ? 1 : 0 })
}
// addTodo adds a todo with the text passed in to the todos object store.
// Returns a promise that resolves if the addition is successful.
addTodo(text) {
// add a todo by passing in an object using Table.add.
return this.todos.add({ text: text, done: 0 })
}
// deleteTodo deletes a todo with the ID passed in from the todos object
// store. Returns a promise that resolves if the deletion is successful.
deleteTodo(todoID) {
// delete a todo by passing in the ID of that todo.
return this.todos.delete(todoID);
}
}
// forwardOrder is passed into getTodos to retrieve todos in chronological
// order.
export const forwardOrder = 'forward';
// reverseOrder is passed into getTodos to retrieve todos in reverse
// chronological order.
export const reverseOrder = 'reverse';
// unfinishedFirstOrder is passed into getTodos to retrieve todos such that
// unfinished todos come before finished todos in the returned array.
export const unfinishedFirstOrder = 'unfinished-first';
|
javascript
|
Sony may not have announced the PS4 Neo at E3 2016, but it could still be available this year.
According to Eurogamer's Richard Leadbetter, you can possibly expect the PS4 Neo before Microsoft's next souped up Xbox One - Project Scorpio.
"Several sources have indicated to me that PlayStation Neo launches this year, despite its E3 no-show," writes Leadbetter. "If that is the case, it'll be interesting to see how developers utilise its resources, and whether 4K really is the focus. And we can be equally as sure that Microsoft will be watching just as intently as it gears up for its own next-gen roll-out."
This strikes us as odd considering that E3 is usually the place where these kind of announcements are actually made. However with Gamescom in August and the Tokyo Game Show soon after Sony does still have a window to unveil it's iteration on the PS4.
If the PS4 Neo releasing this year is true, it corroborates Giantbomb's report that from October every PS4 game needs to have two separate operating modes.
Furthermore there are strict guidelines for developers to make sure there are no Neo-exclusive games, gameplay features or options exclusive to it. There will be parity in terms of peripherals such as PS VR as well. No price has been obtained but it should retail for around $399 (around Rs. 26,500), this should put it in the range of Rs. 40,000 for India which was the price of the PS4 at launch in the region.
In conversation with Financial Times that confirmed the PS4 Neo's absence at E3, Andrew House, President and Global Chief Executive of Sony Interactive Entertainment did not state how much the PS4 Neo will be sold for. He did hint that the "high-end PS4" would be more expensive than the current $350 version. Right now, the PS4 has an MRP of Rs. 32,990 in India.
"It is intended to sit alongside and complement the standard PS4," he said. "We will be selling both [versions] through the life cycle."
House claims it will target hardcore games and those looking with a 4K TV looking for more high-resolution content.
|
english
|
#pragma once
#include "Constants.hpp"
#include <stdlib.h>
#include <string>
#define NWNX_INTERNAL_EXPAND(s) #s
#define NWNX_INTERNAL_STRINGIFY(s) NWNX_INTERNAL_EXPAND(s)
#define NWNX_EXPECT_VERSION(version, revision) \
static_assert(NWNX_TARGET_NWN_BUILD == version && NWNX_TARGET_NWN_BUILD_REVISION == revision, \
"This build-specific code targets build " \
#version " revision " #revision \
" but is being compiled against build " \
NWNX_INTERNAL_STRINGIFY(NWNX_TARGET_NWN_BUILD) \
" revision " NWNX_INTERNAL_STRINGIFY(NWNX_TARGET_NWN_BUILD_REVISION))
#define NWN_API_PROLOGUE(...)
#define NWN_API_EPILOGUE(...)
struct CExoLinkedListNode;
typedef uint16_t RESTYPE;
typedef uint32_t ObjectID;
typedef uint32_t PlayerID;
namespace NWSync { struct CNWSync { void *m_pInternal; char *m_tmp1; uint32_t m_tmp2; }; }
struct DataBlock { char* m_data; size_t m_used; size_t m_allocated; bool m_owning;};
#define DataBlockRef std::shared_ptr<DataBlock>
struct CUUID { uint64_t ab = 0, cd = 0; };
struct json { uint8_t m_type = 0; void* m_value = nullptr; };
namespace Nui::JSON {
using WindowToken = int32_t; // nwscript compat type
using WindowIdentifier = std::string;
using ElementId = std::string;
using EventType = std::string;
using EventPayload = json;
using BindName = std::string;
using BindValue = json;
struct BindUpdate
{
ObjectID m_player = NWNXLib::API::Constants::OBJECT_INVALID;
WindowToken m_token = 0;
BindName m_bind;
BindValue m_value;
bool IsValid() const { return m_token > 0; }
};
//using BindUpdateQueue = std::queue<BindUpdate>;
struct Event
{
ObjectID m_player = NWNXLib::API::Constants::OBJECT_INVALID;
WindowToken m_token = 0;
EventType m_event;
ElementId m_element;
int32_t m_array_index = -1;
EventPayload m_payload;
bool IsValid() const { return m_token > 0; }
};
//using EventQueue = std::queue<Event>;
}
namespace NWSQLite {
using Database = void*;
}
#define NWN_CLASS_EXTENSION_CGameObject \
using CleanupFunc = std::function<void(void*)>; \
void nwnxSet(const std::string& key, int value, bool persist = false, const char *pn = PLUGIN_NAME); \
void nwnxSet(const std::string& key, float value, bool persist = false, const char *pn = PLUGIN_NAME); \
void nwnxSet(const std::string& key, std::string value, bool persist = false, const char *pn = PLUGIN_NAME); \
void nwnxSet(const std::string& key, void *value, std::optional<CleanupFunc> cleanup, const char *pn = PLUGIN_NAME); \
template <typename T> std::optional<T> nwnxGet(const std::string& key, const char *pn = PLUGIN_NAME); \
void nwnxRemove(const std::string& key, const char *pn = PLUGIN_NAME); \
void nwnxRemoveRegex(const std::string& regex, const char *pn = PLUGIN_NAME); \
|
cpp
|
Imagine a thrilling escape from the bustling streets of Bengaluru to the vibrant culture of Chennai in just two hours! Thanks to the upcoming Greenfield Expressway set to open in January 2024, this dreamy road trip is about to become a reality. Say goodbye to long hours on the road and hello to an exciting adventure that's all about the journey.
The Bengaluru-Chennai Expressway is a significant project among the 36 Greenfield Expressways currently under development in India.
Luxury Travel Redefined:
Once you hit the expressway, the possibilities are endless. Picture yourself onboard luxury buses and electric sleeper coaches, where every moment feels like a first-class experience. Glide through the picturesque landscapes of South India with the added benefit of electric power, which translates to a remarkable 30% reduction in ticket prices, making your trip both luxurious and budget-friendly.
A Road Less Travelled:
The 'New Alignment' project takes you from Hoskote in Bengaluru to Sriperumbudur in the Kanchipuram district, covering a total distance of 262 kilometres. For most of the journey, you'll cruise along eight-lane highways, ensuring a smooth and exhilarating ride. The final 22 kilometres feature an awe-inspiring elevated stretch, offering breathtaking views and a sense of soaring above the world. The first phase spans 62.6 kilometers from Hoskote to Bethamangala in Karnataka, followed by an 85-kilometer stretch from Bethamangala to Gudipala in Andhra Pradesh during the second phase. Finally, the third phase encompasses 106 kilometers, connecting Gudipala to Sriperumbuddur in Tamil Nadu.
A Grand Undertaking:
This ambitious project, initiated by Prime Minister Narendra Modi in May 2022, comes with a budget of over Rs17,930 crore. It's a testament to India's dedication to modernising its infrastructure, promising travellers a state-of-the-art experience. The construction unfolds in three phases, connecting Hoskote to Sriperumbudur, passing through Karnataka, Andhra Pradesh, and Tamil Nadu, and transforming 2,650 hectares of land into a highway of dreams.
More Expressway Adventures Await:
But that's not the end of the road! India has even more exciting expressway plans, including the Bengaluru-Mangalore Greenfield Expressway and the Mangaluru-Chennai Expressway via Bengaluru. The future of travel in India is fast, efficient, and eco-friendly, promising more scenic routes and unforgettable journeys.
A Greener Future Beckons:
As we look ahead, the call is out for innovative transportation solutions. Methanol trucks are on the horizon, offering an eco-friendly alternative to traditional diesel-powered vehicles. Join the movement to reduce pollution and dependence on imported fuels by embracing this green revolution.
So pack your bags, fuel your wanderlust, and get ready for an extraordinary adventure! Experience India's expressway extravaganza and discover the joy of seamless travel between Bengaluru and Chennai, all while embracing a greener, more sustainable future as per reports.
Think we missed out on something? Let us know in the comments section below. Or write about it here and earn Tripoto Credits!
Follow me on Instagram and explore this world through my eyes!
|
english
|
Yet another batsman, who made his fastest fifty at 22 deliveries is Virender Sehwag. Sehwag is one of those batsmen, often known for going after the bowlers from the get-go and not sparing them no matter where he bats. While he seldom plays at a spot other than the opening one, the Delhi batsman didn’t fail to bludgeon the Kenyan bowling at number three.
Skipper Sourav Ganguly and Sachin Tendulkar put on an opening stand of 258 before Sehwag applied the finishing touches. Having made fifty off 22 deliveries, he eventually finished with 55 not out off 23 balls. The whirlwind knock consisted of seven fours and three sixes that carried India to 351 and deliver a win by 186 runs.
|
english
|
package virtual_security
// ExchangeType - 市場種別
type ExchangeType string
const (
ExchangeTypeUnspecified ExchangeType = "" // 未指定
ExchangeTypeStock ExchangeType = "stock" // 株式現物
ExchangeTypeMargin ExchangeType = "margin" // 株式信用
ExchangeTypeFuture ExchangeType = "future" // 先物
)
// OrderStatus - 注文状態
type OrderStatus string
const (
OrderStatusUnspecified OrderStatus = "" // 未指定
OrderStatusNew OrderStatus = "new" // 新規
OrderStatusWait OrderStatus = "wait" // 待機
OrderStatusInOrder OrderStatus = "in_order" // 注文中
OrderStatusPart OrderStatus = "part" // 部分約定
OrderStatusDone OrderStatus = "done" // 全約定
OrderStatusInCancel OrderStatus = "in_cancel" // 取消中
OrderStatusCanceled OrderStatus = "canceled" // 取消済み
)
func (e OrderStatus) IsContractable() bool {
switch e {
case OrderStatusInOrder, OrderStatusPart:
return true
}
return false
}
func (e OrderStatus) IsFixed() bool {
switch e {
case OrderStatusDone, OrderStatusCanceled, OrderStatusUnspecified:
return true
}
return false
}
func (e OrderStatus) IsCancelable() bool {
switch e {
case OrderStatusNew, OrderStatusWait, OrderStatusInOrder, OrderStatusPart:
return true
}
return false
}
// StockExecutionCondition - 執行条件
type StockExecutionCondition string
const (
StockExecutionConditionUnspecified StockExecutionCondition = "" // 未指定
StockExecutionConditionMO StockExecutionCondition = "market_order" // 成行
StockExecutionConditionMOMO StockExecutionCondition = "market_order_on_morning_opening" // 寄成(前場)
StockExecutionConditionMOAO StockExecutionCondition = "market_order_on_afternoon_opening" // 寄成(後場)
StockExecutionConditionMOMC StockExecutionCondition = "market_order_on_morning_closing" // 引成(前場)
StockExecutionConditionMOAC StockExecutionCondition = "market_order_on_afternoon_closing" // 引成(後場)
StockExecutionConditionIOCMO StockExecutionCondition = "ioc_market_order" // IOC成行
StockExecutionConditionLO StockExecutionCondition = "limit_order" // 指値
StockExecutionConditionLOMO StockExecutionCondition = "limit_order_on_morning_opening" // 寄指(前場)
StockExecutionConditionLOAO StockExecutionCondition = "limit_order_on_afternoon_opening" // 寄指(後場)
StockExecutionConditionLOMC StockExecutionCondition = "limit_order_on_morning_closing" // 引指(前場)
StockExecutionConditionLOAC StockExecutionCondition = "limit_order_on_afternoon_closing" // 引指(後場)
StockExecutionConditionIOCLO StockExecutionCondition = "ioc_limit_order" // IOC指値
StockExecutionConditionFunariM StockExecutionCondition = "funari_on_morning" // 不成(前場)
StockExecutionConditionFunariA StockExecutionCondition = "funari_on_afternoon" // 不成(後場)
StockExecutionConditionStop StockExecutionCondition = "stop" // 逆指値
)
func (e StockExecutionCondition) IsMarketOrder() bool {
switch e {
case StockExecutionConditionMO, // 成行
StockExecutionConditionMOMO, // 寄成(前場)
StockExecutionConditionMOAO, // 寄成(後場)
StockExecutionConditionMOMC, // 引成(前場)
StockExecutionConditionMOAC, // 引成(後場)
StockExecutionConditionIOCMO: // IOC成行
return true
}
return false
}
func (e StockExecutionCondition) IsLimitOrder() bool {
switch e {
case StockExecutionConditionLO, // 指値
StockExecutionConditionLOMO, // 寄指(前場)
StockExecutionConditionLOAO, // 寄指(後場)
StockExecutionConditionLOMC, // 引指(前場)
StockExecutionConditionLOAC, // 引指(後場)
StockExecutionConditionIOCLO: // IOC指値
return true
}
return false
}
func (e StockExecutionCondition) IsFunari() bool {
switch e {
case StockExecutionConditionFunariM, // 不成(前場)
StockExecutionConditionFunariA: // 不成(後場)
return true
}
return false
}
func (e StockExecutionCondition) IsStop() bool {
switch e {
case StockExecutionConditionStop: // 逆指値
return true
}
return false
}
func (e StockExecutionCondition) IsContractableMorningSession() bool {
switch e {
case StockExecutionConditionMO,
StockExecutionConditionMOMO,
StockExecutionConditionIOCMO,
StockExecutionConditionLO,
StockExecutionConditionLOMO,
StockExecutionConditionIOCLO,
StockExecutionConditionFunariM,
StockExecutionConditionFunariA,
StockExecutionConditionStop:
return true
}
return false
}
func (e StockExecutionCondition) IsContractableMorningSessionClosing() bool {
switch e {
case StockExecutionConditionMO,
StockExecutionConditionMOMO,
StockExecutionConditionMOMC,
StockExecutionConditionIOCMO,
StockExecutionConditionLO,
StockExecutionConditionLOMO,
StockExecutionConditionLOMC,
StockExecutionConditionIOCLO,
StockExecutionConditionFunariM,
StockExecutionConditionFunariA,
StockExecutionConditionStop:
return true
}
return false
}
func (e StockExecutionCondition) IsContractableAfternoonSession() bool {
switch e {
case StockExecutionConditionMO,
StockExecutionConditionMOAO,
StockExecutionConditionIOCMO,
StockExecutionConditionLO,
StockExecutionConditionLOAO,
StockExecutionConditionIOCLO,
StockExecutionConditionFunariM,
StockExecutionConditionFunariA,
StockExecutionConditionStop:
return true
}
return false
}
func (e StockExecutionCondition) IsContractableAfternoonSessionClosing() bool {
switch e {
case StockExecutionConditionMO,
StockExecutionConditionMOAO,
StockExecutionConditionMOAC,
StockExecutionConditionIOCMO,
StockExecutionConditionLO,
StockExecutionConditionLOAO,
StockExecutionConditionLOAC,
StockExecutionConditionIOCLO,
StockExecutionConditionFunariM,
StockExecutionConditionFunariA,
StockExecutionConditionStop:
return true
}
return false
}
func (e StockExecutionCondition) isValid() bool {
switch e {
case StockExecutionConditionMO,
StockExecutionConditionMOMO,
StockExecutionConditionMOAO,
StockExecutionConditionMOMC,
StockExecutionConditionMOAC,
StockExecutionConditionIOCMO,
StockExecutionConditionLO,
StockExecutionConditionLOMO,
StockExecutionConditionLOAO,
StockExecutionConditionLOMC,
StockExecutionConditionLOAC,
StockExecutionConditionIOCLO,
StockExecutionConditionFunariM,
StockExecutionConditionFunariA,
StockExecutionConditionStop:
return true
}
return false
}
// Side - 売買方向
type Side string
const (
SideUnspecified Side = "" // 未指定
SideBuy Side = "buy" // 買い
SideSell Side = "sell" // 売り
)
func (e Side) isValid() bool {
switch e {
case SideBuy, SideSell:
return true
}
return false
}
// Session - セッション
type Session string
const (
SessionUnspecified Session = "" // 未指定
SessionMorning Session = "morning" // 前場
SessionAfternoon Session = "afternoon" // 後場
)
// PriceKind - 価格種別
type PriceKind string
const (
PriceKindUnspecified PriceKind = "" // 未指定
PriceKindOpening PriceKind = "opening" // 寄り
PriceKindRegular PriceKind = "regular" // ザラバ
PriceKindClosing PriceKind = "closing" // 引け
PriceKindOpeningAndClosing PriceKind = "opening_and_closing" // 寄りでかつ引け
)
// ComparisonOperator - 比較演算子
type ComparisonOperator string
const (
ComparisonOperatorUnspecified = "" // 未指定
ComparisonOperatorGT ComparisonOperator = "gt" // より大きい
ComparisonOperatorGE ComparisonOperator = "ge" // 以上
ComparisonOperatorEQ ComparisonOperator = "eq" // 等しい
ComparisonOperatorLE ComparisonOperator = "le" // 以下
ComparisonOperatorLT ComparisonOperator = "lt" // 未満
ComparisonOperatorNE ComparisonOperator = "ne" // 等しくない
)
func (e ComparisonOperator) CompareFloat64(a, b float64) bool {
switch e {
case ComparisonOperatorGT:
return a > b
case ComparisonOperatorGE:
return a >= b
case ComparisonOperatorEQ:
return a == b
case ComparisonOperatorLE:
return a <= b
case ComparisonOperatorLT:
return a < b
case ComparisonOperatorNE:
return a != b
}
return false
}
// TradeType - 取引区分
type TradeType string
const (
TradeTypeUnspecified TradeType = ""
TradeTypeEntry TradeType = "entry"
TradeTypeExit TradeType = "exit"
)
func (e TradeType) isValid() bool {
switch e {
case TradeTypeEntry, TradeTypeExit:
return true
}
return false
}
|
go
|
import { h } from 'vue'
export default {
name: "Heading",
vendor: "Fa",
type: "Solid",
tags: ["heading"],
render() {
return h(
"svg",
{"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 512 512","class":"v-icon","fill":"currentColor","data-name":"fa-heading","innerHTML":"<path d='M448 96v320h32a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16H320a16 16 0 0 1-16-16v-32a16 16 0 0 1 16-16h32V288H160v128h32a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16H32a16 16 0 0 1-16-16v-32a16 16 0 0 1 16-16h32V96H32a16 16 0 0 1-16-16V48a16 16 0 0 1 16-16h160a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16h-32v128h192V96h-32a16 16 0 0 1-16-16V48a16 16 0 0 1 16-16h160a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16z'/>"},
)
}
}
|
javascript
|
<gh_stars>0
import React from 'react';
import PropTypes from 'prop-types';
import MuiCheckbox from './examples-texts/mui/mui-checkbox.md';
import SuirCheckbox from './examples-texts/suir/suir-checkbox.md';
import GenericMuiComponent from '../helpers/generic-mui-component';
const Checkbox = ({ activeMapper }) => {
if (activeMapper === 'mui') {
return <MuiCheckbox />;
}
if (activeMapper === 'suir') {
return <SuirCheckbox />;
}
return <GenericMuiComponent activeMapper={activeMapper} component="checkbox" />;
};
Checkbox.propTypes = {
activeMapper: PropTypes.string.isRequired
};
export default Checkbox;
|
javascript
|
<filename>src/data/codigofacilito/CFinfo.json
{
"data": {
"email": "<EMAIL>",
"username": "Randy97",
"certificates": [
{
"score": 9,
"code": "e548f9ad-c579-47b5-aa3b-13028755af39",
"title": "Curso Profesional de Backend"
},
{
"score": 10,
"code": "5dc219cd-0fc4-4ff8-8801-40f0731fb345",
"title": "Curso Profesional de JavaScript"
},
{
"score": 9,
"code": "f49a5728-0f73-4804-9859-cd6c90acae5e",
"title": "Curso Profesional de React"
},
{
"score": 8,
"code": "",
"title": "SugarCRM Developer Specialist"
}
],
"articles": [],
"courses": [
{
"title": "Curso de AngularJS Gratis",
"progress": "100.0",
"url": "http://codigofacilito.com/courses/angularjs"
},
{
"title": "Curso Profesional de JavaScript",
"progress": "100.0",
"url": "http://codigofacilito.com/courses/javascript-profesional"
},
{
"title": "Curso Profesional de React",
"progress": "100.0",
"url": "http://codigofacilito.com/courses/react-profesional"
},
{
"title": "JavaScript y el DOM",
"progress": "100.0",
"url": "http://codigofacilito.com/courses/javascript-dom"
},
{
"title": "Curso Profesional de Backend",
"progress": "100.0",
"url": "http://codigofacilito.com/courses/backend-profesional"
},
{
"title": "Curso de TypeScript",
"progress": "30.0",
"url": "http://codigofacilito.com/courses/typescript"
},
{
"title": "Curso de Marca Personal",
"progress": "100.0",
"url": "http://platzi.com/clases/marca-personal/"
},
{
"title": "Master en PHP, SQL, POO, MVC, Laravel, Symfony, Wordpress +",
"progress": "90.0",
"url": "http://www.udemy.com/course/master-en-php-sql-poo-mvc-laravel-symfony-4-wordpress"
}
],
"finished_courses": [
{
"title": "Curso Profesional de JavaScript",
"url": "http://codigofacilito.com/courses/javascript-profesional"
},
{
"title": "Curso de AngularJS Gratis",
"url": "http://codigofacilito.com/courses/angularjs"
},
{
"title": "Curso Profesional de Backend",
"url": "http://codigofacilito.com/courses/backend-profesional"
},
{
"title": "Crea un sitio personal con Gatsby",
"url": "http://codigofacilito.com/courses/sitio-persional-gatsby"
},
{
"title": "Curso Profesional de React",
"url": "http://codigofacilito.com/courses/react-profesional"
},
{
"title": "JavaScript y el DOM",
"url": "http://codigofacilito.com/courses/javascript-dom"
}
]
},
"errors": []
}
|
json
|
{
"editor.formatOnSave": true,
"editor.tabSize": 2,
"typescript.preferences.quoteStyle": "single",
"typescript.tsdk": "node_modules/typescript/lib",
"search.exclude": {
"**/node_modules": true,
"dist": true,
"docs": true
},
"[svelte]": {
"editor.defaultFormatter": "svelte.svelte-vscode"
},
}
|
json
|
<filename>data/dndmaps/2020/07/t3_ht5fbr.json
{
"author": {
"id": "t2_46puf",
"name": "bbrd83"
},
"date": {
"day": 1594944000,
"full": 1595025060,
"month": 1593561600,
"week": 1594512000
},
"id": "t3_ht5fbr",
"misc": {
"postHint": "link"
},
"picture": {
"filesize": 120041,
"fullUrl": "https://external-preview.redd.it/2zgE3208_Ro19RzIGimvsEhz-Tybq3dySKzEzYj9nRE.jpg?auto=webp&s=8979008d301b6c2e5d1ef96d215aeaec8deaf8aa",
"hash": "ffecdfd291",
"height": 640,
"lqip": "data:image/jpg;base64,/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAQABADASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAgQF/8QAJRAAAgIBAgQHAAAAAAAAAAAAAQMCBBEAEiExUXEFExQiMkFi/8QAFQEBAQAAAAAAAAAAAAAAAAAABAX/xAAZEQACAwEAAAAAAAAAAAAAAAABMQADESH/2gAMAwEAAhEDEQA/AMFXidrYt1W1GTVZPkygAB+jLjntpLtOuk+vsKc8YMJLGAJdByGp6iHwBi9Ui2Z9wZ8eAx9DppJq2DFRk7AUzfGMQRt7Ac9QRZjUUaxj7P/Z",
"thumbnailUrl": "https://b.thumbs.redditmedia.com/2nnX9xQ2VnTG0YoYibRV2j1Wlazsw3m6h3TyvWLcjCI.jpg",
"url": "https://external-preview.redd.it/2zgE3208_Ro19RzIGimvsEhz-Tybq3dySKzEzYj9nRE.jpg?width=640&crop=smart&auto=webp&s=ef7481e9b8b7fd569d2e368fc8f70bec170c57ea",
"width": 640
},
"score": {
"comments": 1,
"downs": 0,
"isCurated": false,
"ratio": 1,
"ups": 25,
"value": 25
},
"subreddit": {
"id": "t5_3isai",
"name": "dndmaps"
},
"tags": ["Region"],
"title": "The Foothills of Mount Oscar—A wild territory where the party can encounter Orcish tribes, fey, old ruins, and giant monsters! (Description in Comments; Made for D&D levels 4-6)",
"url": "https://www.reddit.com/r/dndmaps/comments/ht5fbr/the_foothills_of_mount_oscara_wild_territory/"
}
|
json
|
SMS (Siva Manasulo Shruti) is a remake of Tamil movie Siva Manasula Sakthi. In which, Sudhir Babu playing a role Shiva, who is happy-go-lucky boy. Regina playing a role of Shruti.
The main story of the movie deals with Shiva and Shruti, who initially hates and despises each other and finally falls in love.
|
english
|
Apple iPhone OS 3.0 preview event - Live!
Android smartphone sales will outstrip iPhone sales by 2012, a report by industry watchers Informa Telecoms & Media has predicted.
NSW state corporation RailCorp has threatened a Sydney software developer with legal action if he fails to withdraw a train timetable application that is currently the second most popular application in its category in Apple's App Store.
Here are today’s notable headlines. You can get News To Know via email alert and RSS daily .
I have been using Spb Software's excellent applications on my Windows Mobile devices for years and was very pleased to see them branching out to support other mobile operating systems, including S60 and the iPhone. I posted a review of Spb Wallet for S60 devices and now that the iPhone version made an appearance on the iPhone App Store I can share my thoughts with you on this excellent application. With the large display and Safari integration, Spb Wallet is a real winner in my book. You can check out the full press release posted yesterday and my image gallery and video of the application in action.
T-Mobile G1 users are receiving notices that a new firmware update (version R33) is available to be pushed to their devices over-the-air. This is in contrast to Apple's approach which requires firmware updates be applied while physically cabled to a computer.
A common pastime at Macworld Expo was comparing iPhone apps with friends. You could see people everywhere huddled around their iPhones sharing tips on their latest and greatest app discoveries.
A guest post on ZDNet yesterday posed the question: Has Apple gotten lazy? It's not the first time I've heard it asked, considering Apple's headlines in recent months: a pullout from Macworld, the distractions of Steve Jobs' health and relatively low-key announcements out of Macworld.
Clearly, the jury is back on the Macworld keynote this morning. The "new and exciting" announced on stage this morning was, well, mostly new but hardly exciting.
I believe fring was the first to bring Skype calling capability to the iPhone back in October 2008. Today, Truphone announced the upgraded version of Truphone that will support Skype calling and instant messaging functions. With Truphone you can also place Skype calls without a WiFi connection and be billed just for your cellular plan minutes thanks to Truphone Anywhere.
|
english
|
<filename>src/days/day02.rs
use crate::intcode::{Computer, IndexedParameter};
use anyhow::{anyhow, Result};
use itertools::iproduct;
pub fn part1(source: &str) -> Result<String> {
let mut computer = Computer::new_from_str(source)?;
computer.set_value(IndexedParameter::Positional(1), 12);
computer.set_value(IndexedParameter::Positional(2), 2);
computer.run(vec![])?;
Ok(computer.get_memory_value(0).to_string())
}
pub fn part2(source: &str) -> Result<String> {
let target = 19690720;
for (noun, verb) in iproduct!(0..100, 0..100) {
let mut computer = Computer::new_from_str(source)?;
computer.set_value(IndexedParameter::Positional(1), noun);
computer.set_value(IndexedParameter::Positional(2), verb);
computer.run(vec![])?;
if computer.get_memory_value(0) == target {
return Ok((100 * noun + verb).to_string());
}
}
Err(anyhow!("Unable to find valid noun/verb combination"))
}
|
rust
|
NORTH Korea is preparing for more nuclear tests, chilling satellite images have revealed.
Extensive excavations are taking place at Kim Jong-un’s Punggye-ri nuclear site, with satellite images revealing tunnels are being built under Mount Mantap at the site, which previously provided support for underground nuclear tests.
Experts warn the new tunnels could support even more explosive tests.
The think tank, a programme of the US-Korea Institute in Washington DC, warns the tests have become more powerful since October 2009.
A security fence around the perimeter of the North Portal suggests it is “the primary test portal” with tunnels being dug at three other sites at Punggye-ri.
North Korea has conducted five declared and remotely detected underground nuclear tests at its dedicated nuclear test site at Punggye-ri in mountainous terrain in the northeast of the country over the last decade, 38 North said.
Analysts say new commercial satellite imagery suggest Pungyye-ri “is capable of handling a sixth nuclear test on short notice once a nuclear device and the associated monitoring equipment are emplaced”.
place at the North Portal with an “increase in a activity” at the command centre area.
But despite the flurry of activity it is unclear when the next test will take place as tensions escalate between the US and Pyongyang over the growing nuclear and missile threat.
Kim Jong-un has warned North Korea can test launch an intercontinental ballistic missile at any time from any location and threatened to unleash a “merciless” attack on the US if joint military exercises with South Korea continue.
Once fully developed, a North Korean ICBM could threaten the continental United States, which is around 5,500 miles from the North.
US and South Korean military chiefs have discussed operations if North Korea attacks large-scale joint drills between the allies.
Since last year Pyongyang has carried out two nuclear tests and a string of missile launches, including four in the last week.
US secretary of state Rex Tillerson said tough measures were needed to tackle North Korea, as 20 years of “failed” policies had done little more than see the US $1. 35bn worse off due to monster foreign aid payments.
Speaking on Thursday in Japan, Mr Tillerson said: "So we have 20 years of failed approach.
"That includes a period where the United States has provided $1. 35 billion in assistance to North Korea as an encouragement to take a different pathway. "
He added: "In the face of this ever-escalating threat, it is clear that a different approach is required.
"Part of the purpose of my visit to the region is to exchange views on a new approach. "
No Comments For This Post, Be first to write a Comment.
|
english
|
AIDS, the deadly acquired immune deficiency syndrome, is a taboo word in the Arab world. But the scary word has managed to crop up in many blog posts this week - from Jordan, Iraq, Palestine, Bahrain and Yemen.
Najma, from Mosul, Iraq, writes about how her cousin's graduation ceremony was called off because of threats on campus.
Mama, from Iraq, writes a touching post about why Iraqis are forced to move out of their homes. Some leave to escape bad memories, while others leave under threat. Many leave the country altogether.
Alive in Baghdad updates us about the oil refining facilities in Doura district in this video. Built in 1953 and partially destroyed from mortar attacks in December 2007, the refinery is located in the dangerous Doura District of Baghdad, where the lives of workers is under constant threat.
“The battle between criminal gangs and the state continues, yet the war is far from being over. Public statements keep coming from both sides and they don’t seem to promise a diplomatic resolution for the crisis,” reports Iraq the Model, on the latest situation in his country.
Iraqi Ladybird reports from a seminar about how there are 210 Israeli companies working in Iraq.
Turkey: What if Iraq is Split?
Iraq: A defining moment?
War in Basra. . . curfews in Baghdad. . . airstrikes on city centres. . . then a ceasefire. . . what on earth happened? As a BBC report said, the Basra operation is an empty vessel - it can be filled with any interpretation you choose. And fill it I will, with interpretations of Iraqi bloggers. Some polarised, some contradictory, but a selection that can fill the gaps that exist in current reports.
Hayder Kamal, at Alive in Baghdad, interviews an activist for women’s rights who discusses her work improving women’s knowledge of their rights.
Pranks were in the air across the Arab world this April Fool's Day. Ranging from an Israeli withdrawal from Palestine, to the sale of Mars to Dubai and the construction of a pipeline to supply the red planet with water from the Arabian Gulf, to the plight of a baby camel in Cairo, readers were left scratching their heads in disbelief.
Bahraini blogger Esra'a, at Mideast Youth, interviews a Kurdish student in this podcast which discusses the Kurdish situation and the hypocrisy of mainstream media towards their cause.
From Qatar, Mohamed Nanabhay stumbles upon a Downing Street Twitter message board, posts a question and gets a response too.
Saddavi at Qatar Living congratulates the Qatari football team for its first three points on the road to South Africa 2010 (Fifa World Cup), after beating Asian champions Iraq 2-0.
From Iraq, Layla Anwar comments on Muqtada Al Sadr's latest interview with Al Jazeera.
|
english
|
<filename>index/p/peaches-with-shortcake-topping-104839.json
{
"directions": [
"Preheat oven to 375\u00b0F. Combine peaches, sugar, lemon juice and cinnamon in large bowl; toss to blend well. Transfer filling to 8x8x2-inch glass baking dish.",
"Sift flour, 3 tablespoons sugar, baking powder and salt into large bowl. Whisk cream, egg and vanilla in small bowl to blend. Add cream mixture to flour mixture, stirring until very soft dough forms. Using 1/4-cup measure, drop dough atop filling in 9 mounds, spacing apart. Brush mounds with melted butter. Blend remaining 1 tablespoon sugar with cinnamon in small cup; sprinkle over mounds.",
"Bake dessert until filling bubbles and topping is golden brown, about 50 minutes. Cool 15 minutes. Serve warm with vanilla ice cream."
],
"ingredients": [
"4 cups frozen sliced peaches (about 13/4 pounds), thawed",
"1/4 cup sugar",
"1 tablespoon fresh lemon juice",
"1/2 teaspoon ground cinnamon",
"1 1/2 cups all purpose flour",
"4 tablespoons sugar",
"1 1/2 teaspoons baking powder",
"1/2 teaspoon salt",
"1 cup chilled whipping cream",
"1 large egg",
"1 teaspoon vanilla extract",
"1 tablespoon unsalted butter, melted",
"1/2 teaspoon ground cinnamon",
"Vanilla ice cream"
],
"language": "en-US",
"source": "www.epicurious.com",
"tags": [
"Fruit",
"Dessert",
"Bake",
"Peach",
"Summer",
"Kidney Friendly",
"Vegetarian",
"Pescatarian",
"Peanut Free",
"Tree Nut Free",
"Soy Free",
"Kosher"
],
"title": "Peaches with Shortcake Topping",
"url": "http://www.epicurious.com/recipes/food/views/peaches-with-shortcake-topping-104839"
}
|
json
|
import pprint
from app.models import Cepage
data = []
counter = 0
with open('static_data.tsv', 'r') as file:
for line in file:
if counter == 0:
headers = line.split('\t')
print(len(headers))
else:
print(len(line.split('\t')))
data.append(dict(zip(headers, line.replace('\u202f', '').split('\t'))))
counter += 1
pprint.pprint(data)
for wine in data:
try:
id_ = wine['id']
if len(id_) > 0:
id_ = int(id_)
name = wine[u'Nom du cépage']
regions = wine['Régions']
sous_regions = wine['Sous-régions']
superficie_france = wine['Superficie en France (ha)']
superficie_monde = wine['Superficie mondiale (ha)']
red = wine['Cépage'] == 'Noir'
vignobles = wine['Vignobles']
# changing types
superficie_france = int(superficie_france) if len(superficie_france) > 0 else None
superficie_monde = int(superficie_monde) if len(superficie_monde) > 0 else None
c = Cepage(
id=id_,
name=name,
regions=regions,
vignobles=vignobles,
sous_regions=sous_regions,
superficie_france=superficie_france,
superficie_monde=superficie_monde,
red=red
)
db.session.add(c)
db.session.commit()
except ValueError:
continue
|
python
|
<reponame>george-mcintyre/epics-core-java-backport-1.5
/*
*
*/
package org.epics.pvaccess.impl.remote.codec.impl;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.logging.Logger;
/**
* @author msekoranja
*/
public abstract class BlockingDatagramAbstractCodec extends BlockingAbstractCodec {
private final DatagramChannel channel;
private final InetSocketAddress socketAddress;
public BlockingDatagramAbstractCodec(
boolean serverFlag,
DatagramChannel channel,
ByteBuffer receiveBuffer,
ByteBuffer sendBuffer,
Logger logger) throws SocketException {
super(serverFlag, receiveBuffer, sendBuffer, channel.socket().getSendBufferSize(), logger);
this.channel = channel;
if (!channel.socket().isConnected())
throw new IllegalArgumentException("only connected datagram sockets are allowed");
this.socketAddress = (InetSocketAddress) channel.socket().getRemoteSocketAddress();
}
public int read(ByteBuffer dst) throws IOException {
return channel.read(dst);
}
public int write(ByteBuffer src) throws IOException {
return channel.write(src);
}
@Override
void internalDestroy() {
if (channel.isOpen()) {
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); // TODO
}
}
}
@Override
public InetSocketAddress getLastReadBufferSocketAddress() {
return socketAddress;
}
@Override
public void invalidDataStreamHandler() {
// reset, be ready for new packet
socketBuffer.clear();
readMode = ReadMode.NORMAL;
}
}
|
java
|
module.exports = 'It works from module2.js.'
|
javascript
|
<reponame>johnzupin/shaderc
// Copyright 2018 The Shaderc Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <spvc/spvc.hpp>
#include "spvc_log.h"
#include "spvc_private.h"
// MSVC 2013 doesn't define __func__
#ifndef __func__
#define __func__ __FUNCTION__
#endif
#define CHECK_CONTEXT(context) \
do { \
if (!context) { \
shaderc_spvc::ErrorLog(nullptr) \
<< "Invoked " << __func__ << " without an initialized context"; \
return shaderc_spvc_status_missing_context_error; \
} \
} while (0)
#define CHECK_CROSS_COMPILER(context, cross_compiler) \
do { \
if (!cross_compiler) { \
shaderc_spvc::ErrorLog(context) \
<< "Invoked " << __func__ \
<< " without an initialized cross compiler"; \
return shaderc_spvc_status_uninitialized_compiler_error; \
} \
} while (0)
#define CHECK_OPTIONS(context, options) \
do { \
if (!options) { \
shaderc_spvc::ErrorLog(context) \
<< "Invoked " << __func__ << " without an initialized options"; \
return shaderc_spvc_status_missing_options_error; \
} \
} while (0)
#define CHECK_RESULT(context, result) \
do { \
if (!result) { \
shaderc_spvc::ErrorLog(context) \
<< "Invoked " << __func__ << " without an initialized result"; \
return shaderc_spvc_status_missing_result_error; \
} \
} while (0)
#define CHECK_OUT_PARAM(context, param, param_str) \
do { \
if (!param) { \
shaderc_spvc::ErrorLog(context) \
<< "Invoked " << __func__ << " with invalid out param, " \
<< param_str; \
return shaderc_spvc_status_invalid_out_param; \
} \
} while (0)
#define CHECK_IN_PARAM(context, param, param_str) \
do { \
if (!param) { \
shaderc_spvc::ErrorLog(context) \
<< "Invoked " << __func__ << " with invalid in param, " \
<< param_str; \
return shaderc_spvc_status_invalid_in_param; \
} \
} while (0)
namespace {
spv::ExecutionModel spvc_model_to_spv_model(
shaderc_spvc_execution_model model) {
switch (model) {
case shaderc_spvc_execution_model_vertex:
return spv::ExecutionModel::ExecutionModelVertex;
case shaderc_spvc_execution_model_fragment:
return spv::ExecutionModel::ExecutionModelFragment;
case shaderc_spvc_execution_model_glcompute:
return spv::ExecutionModel::ExecutionModelGLCompute;
case shaderc_spvc_execution_model_invalid:
return spv::ExecutionModel::ExecutionModelMax;
}
// Older gcc doesn't recognize that all of the possible cases are covered
// above.
assert(false);
return spv::ExecutionModel::ExecutionModelMax;
}
shaderc_spvc_execution_model spv_model_to_spvc_model(
spv::ExecutionModel model) {
switch (model) {
case spv::ExecutionModel::ExecutionModelVertex:
return shaderc_spvc_execution_model_vertex;
case spv::ExecutionModel::ExecutionModelFragment:
return shaderc_spvc_execution_model_fragment;
case spv::ExecutionModel::ExecutionModelGLCompute:
return shaderc_spvc_execution_model_glcompute;
default:
return shaderc_spvc_execution_model_invalid;
}
}
const spirv_cross::SmallVector<spirv_cross::Resource>* get_shader_resources(
const spirv_cross::ShaderResources& resources,
shaderc_spvc_shader_resource resource) {
switch (resource) {
case shaderc_spvc_shader_resource_uniform_buffers:
return &(resources.uniform_buffers);
case shaderc_spvc_shader_resource_separate_images:
return &(resources.separate_images);
case shaderc_spvc_shader_resource_separate_samplers:
return &(resources.separate_samplers);
case shaderc_spvc_shader_resource_storage_buffers:
return &(resources.storage_buffers);
case shaderc_spvc_shader_resource_storage_images:
return &(resources.storage_images);
}
// Older gcc doesn't recognize that all of the possible cases are covered
// above.
assert(false);
return nullptr;
}
shaderc_spvc_texture_view_dimension spirv_dim_to_texture_view_dimension(
spv::Dim dim, bool arrayed) {
switch (dim) {
case spv::Dim::Dim1D:
return shaderc_spvc_texture_view_dimension_e1D;
case spv::Dim::Dim2D:
if (arrayed) {
return shaderc_spvc_texture_view_dimension_e2D_array;
} else {
return shaderc_spvc_texture_view_dimension_e2D;
}
case spv::Dim::Dim3D:
return shaderc_spvc_texture_view_dimension_e3D;
case spv::Dim::DimCube:
if (arrayed) {
return shaderc_spvc_texture_view_dimension_cube_array;
} else {
return shaderc_spvc_texture_view_dimension_cube;
}
default:
return shaderc_spvc_texture_view_dimension_undefined;
}
}
shaderc_spvc_texture_format_type spirv_cross_base_type_to_texture_format_type(
spirv_cross::SPIRType::BaseType type) {
switch (type) {
case spirv_cross::SPIRType::Float:
return shaderc_spvc_texture_format_type_float;
case spirv_cross::SPIRType::Int:
return shaderc_spvc_texture_format_type_sint;
case spirv_cross::SPIRType::UInt:
return shaderc_spvc_texture_format_type_uint;
default:
return shaderc_spvc_texture_format_type_other;
}
}
shaderc_spvc_storage_texture_format spv_image_format_to_storage_texture_format(
spv::ImageFormat format) {
switch (format) {
case spv::ImageFormatR8:
return shaderc_spvc_storage_texture_format_r8unorm;
case spv::ImageFormatR8Snorm:
return shaderc_spvc_storage_texture_format_r8snorm;
case spv::ImageFormatR8ui:
return shaderc_spvc_storage_texture_format_r8uint;
case spv::ImageFormatR8i:
return shaderc_spvc_storage_texture_format_r8sint;
case spv::ImageFormatR16ui:
return shaderc_spvc_storage_texture_format_r16uint;
case spv::ImageFormatR16i:
return shaderc_spvc_storage_texture_format_r16sint;
case spv::ImageFormatR16f:
return shaderc_spvc_storage_texture_format_r16float;
case spv::ImageFormatRg8:
return shaderc_spvc_storage_texture_format_rg8unorm;
case spv::ImageFormatRg8Snorm:
return shaderc_spvc_storage_texture_format_rg8snorm;
case spv::ImageFormatRg8ui:
return shaderc_spvc_storage_texture_format_rg8uint;
case spv::ImageFormatRg8i:
return shaderc_spvc_storage_texture_format_rg8sint;
case spv::ImageFormatR32f:
return shaderc_spvc_storage_texture_format_r32float;
case spv::ImageFormatR32ui:
return shaderc_spvc_storage_texture_format_r32uint;
case spv::ImageFormatR32i:
return shaderc_spvc_storage_texture_format_r32sint;
case spv::ImageFormatRg16ui:
return shaderc_spvc_storage_texture_format_rg16uint;
case spv::ImageFormatRg16i:
return shaderc_spvc_storage_texture_format_rg16sint;
case spv::ImageFormatRg16f:
return shaderc_spvc_storage_texture_format_rg16float;
case spv::ImageFormatRgba8:
return shaderc_spvc_storage_texture_format_rgba8unorm;
case spv::ImageFormatRgba8Snorm:
return shaderc_spvc_storage_texture_format_rgba8snorm;
case spv::ImageFormatRgba8ui:
return shaderc_spvc_storage_texture_format_rgba8uint;
case spv::ImageFormatRgba8i:
return shaderc_spvc_storage_texture_format_rgba8sint;
case spv::ImageFormatRgb10A2:
return shaderc_spvc_storage_texture_format_rgb10a2unorm;
case spv::ImageFormatR11fG11fB10f:
return shaderc_spvc_storage_texture_format_rg11b10float;
case spv::ImageFormatRg32f:
return shaderc_spvc_storage_texture_format_rg32float;
case spv::ImageFormatRg32ui:
return shaderc_spvc_storage_texture_format_rg32uint;
case spv::ImageFormatRg32i:
return shaderc_spvc_storage_texture_format_rg32sint;
case spv::ImageFormatRgba16ui:
return shaderc_spvc_storage_texture_format_rgba16uint;
case spv::ImageFormatRgba16i:
return shaderc_spvc_storage_texture_format_rgba16sint;
case spv::ImageFormatRgba16f:
return shaderc_spvc_storage_texture_format_rgba16float;
case spv::ImageFormatRgba32f:
return shaderc_spvc_storage_texture_format_rgba32float;
case spv::ImageFormatRgba32ui:
return shaderc_spvc_storage_texture_format_rgba32uint;
case spv::ImageFormatRgba32i:
return shaderc_spvc_storage_texture_format_rgba32sint;
default:
return shaderc_spvc_storage_texture_format_undefined;
}
}
spv_target_env shaderc_spvc_spv_env_to_spv_target_env(
shaderc_spvc_spv_env env) {
switch (env) {
case shaderc_spvc_spv_env_universal_1_0:
return SPV_ENV_UNIVERSAL_1_0;
case shaderc_spvc_spv_env_vulkan_1_0:
return SPV_ENV_VULKAN_1_0;
case shaderc_spvc_spv_env_universal_1_1:
return SPV_ENV_UNIVERSAL_1_1;
case shaderc_spvc_spv_env_opencl_2_1:
return SPV_ENV_OPENCL_2_1;
case shaderc_spvc_spv_env_opencl_2_2:
return SPV_ENV_OPENCL_2_2;
case shaderc_spvc_spv_env_opengl_4_0:
return SPV_ENV_OPENGL_4_0;
case shaderc_spvc_spv_env_opengl_4_1:
return SPV_ENV_OPENGL_4_1;
case shaderc_spvc_spv_env_opengl_4_2:
return SPV_ENV_OPENGL_4_2;
case shaderc_spvc_spv_env_opengl_4_3:
return SPV_ENV_OPENGL_4_3;
case shaderc_spvc_spv_env_opengl_4_5:
return SPV_ENV_OPENGL_4_5;
case shaderc_spvc_spv_env_universal_1_2:
return SPV_ENV_UNIVERSAL_1_2;
case shaderc_spvc_spv_env_opencl_1_2:
return SPV_ENV_OPENCL_1_2;
case shaderc_spvc_spv_env_opencl_embedded_1_2:
return SPV_ENV_OPENCL_EMBEDDED_1_2;
case shaderc_spvc_spv_env_opencl_2_0:
return SPV_ENV_OPENCL_2_0;
case shaderc_spvc_spv_env_opencl_embedded_2_0:
return SPV_ENV_OPENCL_EMBEDDED_2_0;
case shaderc_spvc_spv_env_opencl_embedded_2_1:
return SPV_ENV_OPENCL_EMBEDDED_2_1;
case shaderc_spvc_spv_env_opencl_embedded_2_2:
return SPV_ENV_OPENCL_EMBEDDED_2_2;
case shaderc_spvc_spv_env_universal_1_3:
return SPV_ENV_UNIVERSAL_1_3;
case shaderc_spvc_spv_env_vulkan_1_1:
return SPV_ENV_VULKAN_1_1;
case shaderc_spvc_spv_env_webgpu_0:
return SPV_ENV_WEBGPU_0;
case shaderc_spvc_spv_env_universal_1_4:
return SPV_ENV_UNIVERSAL_1_4;
case shaderc_spvc_spv_env_vulkan_1_1_spirv_1_4:
return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
case shaderc_spvc_spv_env_universal_1_5:
return SPV_ENV_UNIVERSAL_1_5;
case shaderc_spvc_spv_env_vulkan_1_2:
return SPV_ENV_VULKAN_1_2;
}
shaderc_spvc::ErrorLog(nullptr)
<< "Attempted to convert unknown shaderc_spvc_spv_env value, " << env;
assert(false);
return SPV_ENV_UNIVERSAL_1_0;
}
shaderc_spvc_status get_location_info_impl(
spirv_cross::Compiler* compiler,
const spirv_cross::SmallVector<spirv_cross::Resource>& resources,
shaderc_spvc_resource_location_info* locations, size_t* location_count) {
*location_count = resources.size();
if (!locations) return shaderc_spvc_status_success;
for (const auto& resource : resources) {
if (!compiler->get_decoration_bitset(resource.id)
.get(spv::DecorationLocation)) {
return shaderc_spvc_status_internal_error;
}
locations->id = resource.id;
if (compiler->get_decoration_bitset(resource.id)
.get(spv::DecorationLocation)) {
locations->location =
compiler->get_decoration(resource.id, spv::DecorationLocation);
locations->has_location = true;
} else {
locations->has_location = false;
}
locations++;
}
return shaderc_spvc_status_success;
}
} // namespace
shaderc_spvc_context_t shaderc_spvc_context_create() {
return new (std::nothrow) shaderc_spvc_context;
}
void shaderc_spvc_context_destroy(shaderc_spvc_context_t context) {
if (context) delete context;
}
const char* shaderc_spvc_context_get_messages(
const shaderc_spvc_context_t context) {
for (const auto& message : context->messages) {
context->messages_string += message;
}
context->messages.clear();
return context->messages_string.c_str();
}
shaderc_spvc_status shaderc_spvc_context_get_compiler(
const shaderc_spvc_context_t context, void** compiler) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, compiler, "compiler");
*compiler = context->cross_compiler.get();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_context_set_use_spvc_parser(
shaderc_spvc_context_t context, bool b) {
CHECK_CONTEXT(context);
context->use_spvc_parser = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_compile_options_t shaderc_spvc_compile_options_create(
shaderc_spvc_spv_env source_env, shaderc_spvc_spv_env target_env) {
shaderc_spvc_compile_options_t options =
new (std::nothrow) shaderc_spvc_compile_options;
if (options) {
options->glsl.version = 0;
options->source_env = shaderc_spvc_spv_env_to_spv_target_env(source_env);
options->target_env = shaderc_spvc_spv_env_to_spv_target_env(target_env);
}
return options;
}
shaderc_spvc_compile_options_t shaderc_spvc_compile_options_clone(
shaderc_spvc_compile_options_t options) {
if (options) return new (std::nothrow) shaderc_spvc_compile_options(*options);
return nullptr;
}
void shaderc_spvc_compile_options_destroy(
shaderc_spvc_compile_options_t options) {
if (options) delete options;
}
// DEPRECATED
shaderc_spvc_status shaderc_spvc_compile_options_set_source_env(
shaderc_spvc_compile_options_t options, shaderc_target_env env,
shaderc_env_version version) {
CHECK_OPTIONS(nullptr, options);
options->source_env = spvc_private::get_spv_target_env(env, version);
return shaderc_spvc_status_success;
}
// DEPRECATED
shaderc_spvc_status shaderc_spvc_compile_options_set_target_env(
shaderc_spvc_compile_options_t options, shaderc_target_env env,
shaderc_env_version version) {
CHECK_OPTIONS(nullptr, options);
options->target_env = spvc_private::get_spv_target_env(env, version);
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_entry_point(
shaderc_spvc_compile_options_t options, const char* entry_point) {
CHECK_OPTIONS(nullptr, options);
CHECK_IN_PARAM(nullptr, entry_point, "entry_point");
options->entry_point = entry_point;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_remove_unused_variables(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->remove_unused_variables = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_robust_buffer_access_pass(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->robust_buffer_access_pass = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_emit_line_directives(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.emit_line_directives = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_vulkan_semantics(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.vulkan_semantics = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_separate_shader_objects(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.separate_shader_objects = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_flatten_ubo(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->flatten_ubo = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_glsl_language_version(
shaderc_spvc_compile_options_t options, uint32_t version) {
CHECK_OPTIONS(nullptr, options);
options->glsl.version = version;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_flatten_multidimensional_arrays(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.flatten_multidimensional_arrays = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_force_zero_initialized_variables(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.force_zero_initialized_variables = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_es(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->forced_es_setting = b;
options->force_es = true;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_glsl_emit_push_constant_as_ubo(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.emit_push_constant_as_uniform_buffer = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_language_version(
shaderc_spvc_compile_options_t options, uint32_t version) {
CHECK_OPTIONS(nullptr, options);
options->msl.msl_version = version;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_msl_swizzle_texture_samples(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.swizzle_texture_samples = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_platform(
shaderc_spvc_compile_options_t options,
shaderc_spvc_msl_platform platform) {
CHECK_OPTIONS(nullptr, options);
switch (platform) {
case shaderc_spvc_msl_platform_ios:
options->msl.platform = spirv_cross::CompilerMSL::Options::iOS;
break;
case shaderc_spvc_msl_platform_macos:
options->msl.platform = spirv_cross::CompilerMSL::Options::macOS;
break;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_pad_fragment_output(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.pad_fragment_output_components = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_capture(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.capture_output_to_buffer = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_domain_lower_left(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.tess_domain_origin_lower_left = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_msl_argument_buffers(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.argument_buffers = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_msl_discrete_descriptor_sets(
shaderc_spvc_compile_options_t options, const uint32_t* descriptors,
size_t num_descriptors) {
CHECK_OPTIONS(nullptr, options);
options->msl_discrete_descriptor_sets.resize(num_descriptors);
std::copy_n(descriptors, num_descriptors,
options->msl_discrete_descriptor_sets.begin());
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_msl_enable_point_size_builtin(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->msl.enable_point_size_builtin = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_msl_buffer_size_buffer_index(
shaderc_spvc_compile_options_t options, uint32_t index) {
CHECK_OPTIONS(nullptr, options);
options->msl.buffer_size_buffer_index = index;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_hlsl_shader_model(
shaderc_spvc_compile_options_t options, uint32_t model) {
CHECK_OPTIONS(nullptr, options);
options->hlsl.shader_model = model;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_hlsl_point_size_compat(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->hlsl.point_size_compat = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_hlsl_point_coord_compat(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->hlsl.point_coord_compat = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status
shaderc_spvc_compile_options_set_hlsl_nonwritable_uav_texture_as_srv(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->hlsl.nonwritable_uav_texture_as_srv = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_set_hlsl_force_storage_buffer_as_uav(
const shaderc_spvc_context_t context, uint32_t desc_set, uint32_t binding) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
auto* hlsl_compiler = reinterpret_cast<spirv_cross::CompilerHLSL*>(
context->cross_compiler.get());
hlsl_compiler->set_hlsl_force_storage_buffer_as_uav(desc_set, binding);
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_fixup_clipspace(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.vertex.fixup_clipspace = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_flip_vert_y(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->glsl.vertex.flip_vert_y = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_validate(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->validate = b;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_compile_options_set_optimize(
shaderc_spvc_compile_options_t options, bool b) {
CHECK_OPTIONS(nullptr, options);
options->optimize = b;
return shaderc_spvc_status_success;
}
size_t shaderc_spvc_compile_options_set_for_fuzzing(
shaderc_spvc_compile_options_t options, const uint8_t* data, size_t size) {
if (!options || !data || size < sizeof(*options)) return 0;
memcpy(static_cast<void*>(options), data, sizeof(*options));
return sizeof(*options);
}
shaderc_spvc_status shaderc_spvc_initialize_impl(
const shaderc_spvc_context_t context, const uint32_t* source,
size_t source_len, shaderc_spvc_compile_options_t options,
shaderc_spvc_status (*generator)(const shaderc_spvc_context_t,
const uint32_t*, size_t,
shaderc_spvc_compile_options_t)) {
shaderc_spvc_status status = spvc_private::validate_and_translate_spirv(
context, source, source_len, options, &context->intermediate_shader);
if (status != shaderc_spvc_status_success) return status;
status = generator(context, context->intermediate_shader.data(),
context->intermediate_shader.size(), options);
if (status != shaderc_spvc_status_success) return status;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_initialize_for_glsl(
const shaderc_spvc_context_t context, const uint32_t* source,
size_t source_len, shaderc_spvc_compile_options_t options) {
CHECK_CONTEXT(context);
CHECK_OPTIONS(context, options);
CHECK_IN_PARAM(context, source, "source");
context->target_lang = SPVC_TARGET_LANG_GLSL;
return shaderc_spvc_initialize_impl(context, source, source_len, options,
spvc_private::generate_glsl_compiler);
}
shaderc_spvc_status shaderc_spvc_initialize_for_hlsl(
const shaderc_spvc_context_t context, const uint32_t* source,
size_t source_len, shaderc_spvc_compile_options_t options) {
CHECK_CONTEXT(context);
CHECK_OPTIONS(context, options);
CHECK_IN_PARAM(context, source, "source");
context->target_lang = SPVC_TARGET_LANG_HLSL;
return shaderc_spvc_initialize_impl(context, source, source_len, options,
spvc_private::generate_hlsl_compiler);
}
shaderc_spvc_status shaderc_spvc_initialize_for_msl(
const shaderc_spvc_context_t context, const uint32_t* source,
size_t source_len, shaderc_spvc_compile_options_t options) {
CHECK_CONTEXT(context);
CHECK_OPTIONS(context, options);
CHECK_IN_PARAM(context, source, "source");
context->target_lang = SPVC_TARGET_LANG_MSL;
return shaderc_spvc_initialize_impl(context, source, source_len, options,
spvc_private::generate_msl_compiler);
}
shaderc_spvc_status shaderc_spvc_initialize_for_vulkan(
const shaderc_spvc_context_t context, const uint32_t* source,
size_t source_len, shaderc_spvc_compile_options_t options) {
CHECK_CONTEXT(context);
CHECK_OPTIONS(context, options);
CHECK_IN_PARAM(context, source, "source");
context->target_lang = SPVC_TARGET_LANG_VULKAN;
return shaderc_spvc_initialize_impl(context, source, source_len, options,
spvc_private::generate_vulkan_compiler);
}
shaderc_spvc_status shaderc_spvc_compile_shader(
const shaderc_spvc_context_t context,
shaderc_spvc_compilation_result_t result) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
if (context->target_lang == SPVC_TARGET_LANG_UNKNOWN) {
shaderc_spvc::ErrorLog(context)
<< "Invoked compile_shader with unknown language";
return shaderc_spvc_status_configuration_error;
}
if (context->target_lang == SPVC_TARGET_LANG_VULKAN) {
// No actual cross compilation is needed, since the intermediate shader is
// already in Vulkan SPIR->V.
result->binary_output = context->intermediate_shader;
return shaderc_spvc_status_success;
} else {
shaderc_spvc_status status =
spvc_private::generate_shader(context->cross_compiler.get(), result);
if (status != shaderc_spvc_status_success) {
shaderc_spvc::ErrorLog(context) << "Compilation failed. Partial source:";
if (context->target_lang == SPVC_TARGET_LANG_GLSL) {
spirv_cross::CompilerGLSL* cast_compiler =
reinterpret_cast<spirv_cross::CompilerGLSL*>(
context->cross_compiler.get());
shaderc_spvc::ErrorLog(context) << cast_compiler->get_partial_source();
} else if (context->target_lang == SPVC_TARGET_LANG_HLSL) {
spirv_cross::CompilerHLSL* cast_compiler =
reinterpret_cast<spirv_cross::CompilerHLSL*>(
context->cross_compiler.get());
shaderc_spvc::ErrorLog(context) << cast_compiler->get_partial_source();
} else if (context->target_lang == SPVC_TARGET_LANG_MSL) {
spirv_cross::CompilerMSL* cast_compiler =
reinterpret_cast<spirv_cross::CompilerMSL*>(
context->cross_compiler.get());
shaderc_spvc::ErrorLog(context) << cast_compiler->get_partial_source();
} else {
shaderc_spvc::ErrorLog(context)
<< "Unexpected target language in context";
}
context->cross_compiler.reset();
}
return status;
}
}
shaderc_spvc_status shaderc_spvc_set_decoration(
const shaderc_spvc_context_t context, uint32_t id,
shaderc_spvc_decoration decoration, uint32_t argument) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
spv::Decoration spirv_cross_decoration;
shaderc_spvc_status status =
spvc_private::shaderc_spvc_decoration_to_spirv_cross_decoration(
decoration, &spirv_cross_decoration);
if (status == shaderc_spvc_status_success) {
context->cross_compiler->set_decoration(static_cast<spirv_cross::ID>(id),
spirv_cross_decoration, argument);
} else {
shaderc_spvc::ErrorLog(context) << "Decoration Conversion failed. "
"shaderc_spvc_decoration not supported.";
}
return status;
}
shaderc_spvc_status shaderc_spvc_get_decoration(
const shaderc_spvc_context_t context, uint32_t id,
shaderc_spvc_decoration decoration, uint32_t* value) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, value, "value");
spv::Decoration spirv_cross_decoration;
shaderc_spvc_status status =
spvc_private::shaderc_spvc_decoration_to_spirv_cross_decoration(
decoration, &spirv_cross_decoration);
if (status != shaderc_spvc_status_success) {
shaderc_spvc::ErrorLog(context) << "Decoration conversion failed. "
"shaderc_spvc_decoration not supported.";
return status;
}
*value = context->cross_compiler->get_decoration(
static_cast<spirv_cross::ID>(id), spirv_cross_decoration);
if (*value == 0) {
shaderc_spvc::ErrorLog(context)
<< "Getting decoration failed. id not found.";
return shaderc_spvc_status_compilation_error;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_unset_decoration(
const shaderc_spvc_context_t context, uint32_t id,
shaderc_spvc_decoration decoration) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
spv::Decoration spirv_cross_decoration;
shaderc_spvc_status status =
spvc_private::shaderc_spvc_decoration_to_spirv_cross_decoration(
decoration, &spirv_cross_decoration);
if (status == shaderc_spvc_status_success) {
context->cross_compiler->unset_decoration(static_cast<spirv_cross::ID>(id),
spirv_cross_decoration);
} else {
shaderc_spvc::ErrorLog(context) << "Decoration conversion failed. "
"shaderc_spvc_decoration not supported.";
}
return status;
}
shaderc_spvc_status shaderc_spvc_get_combined_image_samplers(
const shaderc_spvc_context_t context,
shaderc_spvc_combined_image_sampler* samplers, size_t* num_samplers) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, num_samplers, "num_samplers");
*num_samplers = context->cross_compiler->get_combined_image_samplers().size();
if (!samplers) return shaderc_spvc_status_success;
for (const auto& combined :
context->cross_compiler->get_combined_image_samplers()) {
samplers->combined_id = combined.combined_id;
samplers->image_id = combined.image_id;
samplers->sampler_id = combined.sampler_id;
samplers++;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_set_name(const shaderc_spvc_context_t context,
uint32_t id, const char* name) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_IN_PARAM(context, name, "name");
context->cross_compiler->set_name(id, name);
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_add_msl_resource_binding(
const shaderc_spvc_context_t context,
const shaderc_spvc_msl_resource_binding binding) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
if (context->target_lang != SPVC_TARGET_LANG_MSL) {
shaderc_spvc::ErrorLog(context)
<< "Invoked add_msl_resource_binding when target language was not MSL";
return shaderc_spvc_status_configuration_error;
}
spirv_cross::MSLResourceBinding cross_binding;
cross_binding.stage = spvc_model_to_spv_model(binding.stage);
cross_binding.binding = binding.binding;
cross_binding.desc_set = binding.desc_set;
cross_binding.msl_buffer = binding.msl_buffer;
cross_binding.msl_texture = binding.msl_texture;
cross_binding.msl_sampler = binding.msl_sampler;
reinterpret_cast<spirv_cross::CompilerMSL*>(context->cross_compiler.get())
->add_msl_resource_binding(cross_binding);
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_get_workgroup_size(
const shaderc_spvc_context_t context, const char* function_name,
shaderc_spvc_execution_model execution_model,
shaderc_spvc_workgroup_size* workgroup_size) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_IN_PARAM(context, function_name, "function_name");
CHECK_OUT_PARAM(context, workgroup_size, "workgroup_size");
const auto& cross_size =
context->cross_compiler
->get_entry_point(function_name,
spvc_model_to_spv_model(execution_model))
.workgroup_size;
workgroup_size->x = cross_size.x;
workgroup_size->y = cross_size.y;
workgroup_size->z = cross_size.z;
workgroup_size->constant = cross_size.constant;
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_needs_buffer_size_buffer(
const shaderc_spvc_context_t context, bool* b) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, b, "b");
if (context->target_lang != SPVC_TARGET_LANG_MSL) {
shaderc_spvc::ErrorLog(context)
<< "Invoked needs_buffer_size_buffer when target language was not MSL";
return shaderc_spvc_status_configuration_error;
}
*b =
reinterpret_cast<spirv_cross::CompilerMSL*>(context->cross_compiler.get())
->needs_buffer_size_buffer();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_build_combined_image_samplers(
const shaderc_spvc_context_t context) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
context->cross_compiler->build_combined_image_samplers();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_get_execution_model(
const shaderc_spvc_context_t context,
shaderc_spvc_execution_model* execution_model) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, execution_model, "execution_model");
auto spirv_model = context->cross_compiler->get_execution_model();
*execution_model = spv_model_to_spvc_model(spirv_model);
if (*execution_model == shaderc_spvc_execution_model_invalid) {
shaderc_spvc::ErrorLog(context)
<< "Shader execution model appears to be of an unsupported type";
return shaderc_spvc_status_internal_error;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_get_push_constant_buffer_count(
const shaderc_spvc_context_t context, size_t* count) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, count, "count");
*count = context->cross_compiler->get_shader_resources()
.push_constant_buffers.size();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_get_binding_info(
const shaderc_spvc_context_t context, shaderc_spvc_shader_resource resource,
shaderc_spvc_binding_type binding_type, shaderc_spvc_binding_info* bindings,
size_t* binding_count) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, binding_count, "binding_count");
auto* compiler = context->cross_compiler.get();
const auto& resources = compiler->get_shader_resources();
const auto* shader_resources = get_shader_resources(resources, resource);
*binding_count = shader_resources->size();
if (!bindings) return shaderc_spvc_status_success;
for (const auto& shader_resource : *shader_resources) {
bindings->texture_dimension = shaderc_spvc_texture_view_dimension_undefined;
bindings->texture_component_type = shaderc_spvc_texture_format_type_float;
if (!compiler->get_decoration_bitset(shader_resource.id)
.get(spv::DecorationBinding)) {
shaderc_spvc::ErrorLog(context)
<< "Unable to get binding decoration for shader resource";
return shaderc_spvc_status_internal_error;
}
uint32_t binding_decoration =
compiler->get_decoration(shader_resource.id, spv::DecorationBinding);
bindings->binding = binding_decoration;
if (!compiler->get_decoration_bitset(shader_resource.id)
.get(spv::DecorationDescriptorSet)) {
shaderc_spvc::ErrorLog(context)
<< "Unable to get descriptor set decoration for shader resource";
return shaderc_spvc_status_internal_error;
}
uint32_t descriptor_set_decoration = compiler->get_decoration(
shader_resource.id, spv::DecorationDescriptorSet);
bindings->set = descriptor_set_decoration;
bindings->id = shader_resource.id;
bindings->base_type_id = shader_resource.base_type_id;
switch (binding_type) {
case shaderc_spvc_binding_type_sampled_texture: {
spirv_cross::SPIRType::ImageType imageType =
compiler->get_type(bindings->base_type_id).image;
spirv_cross::SPIRType::BaseType textureComponentType =
compiler->get_type(imageType.type).basetype;
bindings->multisampled = imageType.ms;
bindings->texture_dimension = spirv_dim_to_texture_view_dimension(
imageType.dim, imageType.arrayed);
bindings->texture_component_type =
spirv_cross_base_type_to_texture_format_type(textureComponentType);
bindings->binding_type = binding_type;
} break;
case shaderc_spvc_binding_type_storage_buffer: {
// Differentiate between readonly storage bindings and writable ones
// based on the NonWritable decoration
spirv_cross::Bitset flags =
compiler->get_buffer_block_flags(shader_resource.id);
if (flags.get(spv::DecorationNonWritable)) {
bindings->binding_type =
shaderc_spvc_binding_type_readonly_storage_buffer;
} else {
bindings->binding_type = shaderc_spvc_binding_type_storage_buffer;
}
} break;
case shaderc_spvc_binding_type_storage_texture: {
spirv_cross::Bitset flags = compiler->get_decoration_bitset(shader_resource.id);
if (flags.get(spv::DecorationNonReadable)) {
bindings->binding_type = shaderc_spvc_binding_type_writeonly_storage_texture;
} else if (flags.get(spv::DecorationNonWritable)) {
bindings->binding_type = shaderc_spvc_binding_type_readonly_storage_texture;
} else {
bindings->binding_type = shaderc_spvc_binding_type_storage_texture;
}
spirv_cross::SPIRType::ImageType imageType =
compiler->get_type(bindings->base_type_id).image;
bindings->storage_texture_format =
spv_image_format_to_storage_texture_format(imageType.format);
bindings->texture_dimension = spirv_dim_to_texture_view_dimension(
imageType.dim, imageType.arrayed);
bindings->multisampled = imageType.ms;
} break;
case shaderc_spvc_binding_type_sampler: {
// The inheritance hierarchy here is odd, it goes
// Compiler->CompilerGLSL->CompilerHLSL/MSL/Reflection.
// CompilerGLSL is an intermediate super class for all of the other leaf
// classes. The method we need is defined on CompilerGLSL, not Compiler.
// This cast is safe, since we only should ever have a
// CompilerGLSL/HLSL/MSL/Reflection in |cross_compiler|.
auto* glsl_compiler = reinterpret_cast<spirv_cross::CompilerGLSL*>(
context->cross_compiler.get());
if (glsl_compiler->variable_is_depth_or_compare(shader_resource.id)) {
bindings->binding_type = shaderc_spvc_binding_type_comparison_sampler;
} else {
bindings->binding_type = shaderc_spvc_binding_type_sampler;
}
} break;
default:
bindings->binding_type = binding_type;
}
bindings++;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_get_input_stage_location_info(
const shaderc_spvc_context_t context,
shaderc_spvc_resource_location_info* locations, size_t* location_count) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, location_count, "location_count");
auto* compiler = context->cross_compiler.get();
shaderc_spvc_status status = get_location_info_impl(
compiler, compiler->get_shader_resources().stage_inputs, locations,
location_count);
if (status != shaderc_spvc_status_success) {
shaderc_spvc::ErrorLog(context)
<< "Unable to get location decoration for stage input";
}
return status;
}
shaderc_spvc_status shaderc_spvc_get_output_stage_location_info(
const shaderc_spvc_context_t context,
shaderc_spvc_resource_location_info* locations, size_t* location_count) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, location_count, "location_count");
auto* compiler = context->cross_compiler.get();
shaderc_spvc_status status = get_location_info_impl(
compiler, compiler->get_shader_resources().stage_outputs, locations,
location_count);
if (status != shaderc_spvc_status_success) {
shaderc_spvc::ErrorLog(context)
<< "Unable to get location decoration for stage output";
}
return status;
}
shaderc_spvc_status shaderc_spvc_get_output_stage_type_info(
const shaderc_spvc_context_t context,
shaderc_spvc_resource_type_info* types, size_t* type_count) {
CHECK_CONTEXT(context);
CHECK_CROSS_COMPILER(context, context->cross_compiler);
CHECK_OUT_PARAM(context, type_count, "type_count");
auto* compiler = context->cross_compiler.get();
const auto& resources = compiler->get_shader_resources().stage_outputs;
*type_count = resources.size();
if (!types) return shaderc_spvc_status_success;
for (const auto& resource : resources) {
if (!compiler->get_decoration_bitset(resource.id)
.get(spv::DecorationLocation)) {
shaderc_spvc::ErrorLog(context)
<< "Unable to get location decoration for stage output";
return shaderc_spvc_status_internal_error;
}
types->location =
compiler->get_decoration(resource.id, spv::DecorationLocation);
spirv_cross::SPIRType::BaseType base_type =
compiler->get_type(resource.base_type_id).basetype;
types->type = spirv_cross_base_type_to_texture_format_type(base_type);
types++;
}
return shaderc_spvc_status_success;
}
shaderc_spvc_compilation_result_t shaderc_spvc_result_create() {
return new (std::nothrow) shaderc_spvc_compilation_result;
}
void shaderc_spvc_result_destroy(shaderc_spvc_compilation_result_t result) {
if (result) delete result;
}
shaderc_spvc_status shaderc_spvc_result_get_string_output(
const shaderc_spvc_compilation_result_t result, const char** str) {
CHECK_RESULT(nullptr, result);
CHECK_OUT_PARAM(nullptr, str, "str");
*str = result->string_output.c_str();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_result_get_binary_output(
const shaderc_spvc_compilation_result_t result,
const uint32_t** binary_output) {
CHECK_RESULT(nullptr, result);
CHECK_OUT_PARAM(nullptr, binary_output, "binary_output");
*binary_output = result->binary_output.data();
return shaderc_spvc_status_success;
}
shaderc_spvc_status shaderc_spvc_result_get_binary_length(
const shaderc_spvc_compilation_result_t result, uint32_t* len) {
CHECK_RESULT(nullptr, result);
CHECK_OUT_PARAM(nullptr, len, "len");
*len = result->binary_output.size();
return shaderc_spvc_status_success;
}
|
cpp
|
<reponame>vaylor27/Thommas-Mod<filename>src/main/resources/assets/thommas/models/item/lithium_battery.json
{
"parent": "item/generated",
"textures": {
"layer0": "thommas:item/lithium_battery"
}
}
|
json
|
var exec = require('child_process').exec;
const Options = require('./options');
class Shell {
constructor() {
this._options = new Options();
}
async exec(command) {
let count = 0;
let results = {};
while (true) {
try {
results = await this._exec(command);
return results;
} catch(e) {
if (++count == this._options.retries) throw e;
console.log('retry count: ' + count);
await this._sleep(5000);
}
}
}
async _exec(command) {
const child = exec(command);
child.stdout.on('data', function (data) {
console.log(data);
});
child.stderr.on('data', function (data) {
console.log(data);
});
return new Promise(function (resolve, reject) {
child.addListener("error", reject);
child.addListener("exit", resolve);
});
}
_sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
}
module.exports = Shell;
|
javascript
|
<gh_stars>0
package com.diozero.devices;
/*
* #%L
* Organisation: mattjlewis
* Project: Device I/O Zero - Core
* Filename: ADXL345.java
*
* This file is part of the diozero project. More information about this project
* can be found at http://www.diozero.com/
* %%
* Copyright (C) 2016 - 2017 mattjlewis
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import com.diozero.api.I2CConstants;
import com.diozero.api.I2CDevice;
import com.diozero.api.imu.*;
import com.diozero.util.BitManipulation;
import com.diozero.util.RuntimeIOException;
/**
* http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.PDF
*/
public class ADXL345 implements ImuInterface {
// 13-bit
private static final int RESOLUTION = 13;
private static final int RANGE = (int)Math.pow(2, RESOLUTION);
// From -16 to 16
private static final double MAX_RANGE = 16*2;
private static final double SCALE_FACTOR = MAX_RANGE / RANGE;
private static final int ADXL345_ADDRESS = 0x53;
private static final int[] RANGE_LIST = { 2, 4, 8, 16 };
// Registers
private static final int THRESH_TAP = 0x1D; // Tap threshold
private static final int OFSX = 0x1E; // X-axis offset
private static final int OFSY = 0x1F; // Y-axis offset
private static final int OFSZ = 0x20; // Z-axis offset
private static final int TAP_DUR = 0x21; // Tap duration
private static final int TAP_LATENCY = 0x22; // Tap latency
private static final int TAP_WINDOW = 0x23; // Tap window
private static final int THRESH_ACT = 0x24; // Activity threshold
private static final int THRESH_INACT = 0x25; // Inactivity threshold
private static final int TIME_INACT = 0x26; // Inactivity time
private static final int ACT_INACT_CTL = 0x27; // Axis enable control for activity and inactivity detection
private static final int THRESH_FF = 0x28; // Free-fall threshold
private static final int TIME_FF = 0x29; // Free-fall time
private static final int TAP_AXES = 0x2A; // Axis control for single tap/double tap
private static final int ACT_TAP_STATUS = 0x2B; // Source of single tap/double tap
private static final int BW_RATE = 0x2C; // Data rate and power mode control
private static final int POWER_CTL = 0x2D; // Power-saving features control
private static final int INT_ENABLE = 0x2E; // Interrupt enable control
private static final int INT_MAP = 0x2F; // Interrupt mapping control
private static final int INT_SOURCE = 0x30; // Source of interrupts
private static final int DATA_FORMAT = 0x31; // Data format control
private static final int AXES_DATA = 0x32; // 3 sets of 2 byte axis data
private static final int FIFO_CTL = 0x38; // FIFO control
private static final int FIFO_STATUS = 0x39; // FIFO status
private static final byte POWER_CTL_LINK_BIT = 5;
private static final byte POWER_CTL_LINK = BitManipulation.getBitMask(POWER_CTL_LINK_BIT);
private static final byte POWER_CTL_AUTO_SLEEP_BIT = 4;
private static final byte POWER_CTL_AUTO_SLEEP = BitManipulation.getBitMask(POWER_CTL_AUTO_SLEEP_BIT);
private static final byte POWER_CTL_MEASURE_BIT = 3;
private static final byte POWER_CTL_MEASURE = BitManipulation.getBitMask(POWER_CTL_MEASURE_BIT);
private static final byte POWER_CTL_SLEEP_BIT = 2;
private static final byte POWER_CTL_SLEEP = BitManipulation.getBitMask(POWER_CTL_SLEEP_BIT);
private static final byte LOW_POWER_MODE_BIT = 4;
private static final byte LOW_POWER_MODE = BitManipulation.getBitMask(LOW_POWER_MODE_BIT);
private static final byte SUPPRESS_DOUBLE_TAP_BIT = 3;
private static final byte SUPPRESS_DOUBLE_TAP = BitManipulation.getBitMask(SUPPRESS_DOUBLE_TAP_BIT);
private static final byte FULL_RESOLUTION_MODE_BIT = 3;
private static final byte FULL_RESOLUTION_MODE = BitManipulation.getBitMask(FULL_RESOLUTION_MODE_BIT);
private static final byte SELF_TEST_MODE_BIT = 7;
private static final byte SELF_TEST_MODE = BitManipulation.getBitMask(SELF_TEST_MODE_BIT);
private static final float THRESH_TAP_RANGE = 16f;
private static final float THRESH_TAP_LSB = THRESH_TAP_RANGE / 0xFF;
private static final float OFFSET_RANGE = 2f;
private static final float OFFSET_LSB = OFFSET_RANGE / 0x7F;
private static final float TAP_DURATION_MS_RANGE = 160;
private static final float TAP_DURATION_MS_LSB = TAP_DURATION_MS_RANGE / 0xff;
private static final float TAP_LATENCY_MS_RANGE = 320;
private static final float TAP_LATENCY_MS_LSB = TAP_LATENCY_MS_RANGE / 0xff;
private static final float TAP_WINDOW_MS_RANGE = 320;
private static final float TAP_WINDOW_MS_LSB = TAP_WINDOW_MS_RANGE / 0xff;
private static final float ACTIVITY_THRESHOLD_RANGE = 16;
private static final float ACTIVITY_THRESHOLD_LSB = ACTIVITY_THRESHOLD_RANGE / 0xff;
private static final float INACTIVITY_THRESHOLD_RANGE = 16;
private static final float INACTIVITY_THRESHOLD_LSB = INACTIVITY_THRESHOLD_RANGE / 0xff;
private static final float INACTIVITY_TIME_RANGE = 256;
private static final float INACTIVITY_TIME_LSB = INACTIVITY_TIME_RANGE / 0xff;
private static final float FREEFALL_THRESHOLD_RANGE = 16;
private static final float FREEFALL_THRESHOLD_LSB = FREEFALL_THRESHOLD_RANGE / 0xff;
private static final float FREEFALL_TIME_RANGE = 1280;
private static final float FREEFALL_TIME_LSB = FREEFALL_TIME_RANGE / 0xff;
private I2CDevice device;
public ADXL345() {
device = new I2CDevice(I2CConstants.BUS_1, ADXL345_ADDRESS,
I2CConstants.ADDR_SIZE_7, I2CConstants.DEFAULT_CLOCK_FREQUENCY);
setNormalMeasurementMode();
}
/**
* Get the tap threshold in g
* @return Tap threshold (g)
*/
public float getTapThreshold() {
return device.readUByte(THRESH_TAP) * THRESH_TAP_LSB;
}
/**
* Set the tap threshold in g
* @param tapThreshold The threshold value in g for tap interrupts
*/
public void setTapThreshold(float tapThreshold) {
if (tapThreshold < 0 || tapThreshold > THRESH_TAP_RANGE) {
throw new IllegalArgumentException("Illegal tap threshold value (" +
tapThreshold + "), must be 0.." + THRESH_TAP_RANGE);
}
device.writeByte(THRESH_TAP, (byte)(Math.floor(tapThreshold / THRESH_TAP_LSB)));
}
private float getOffset(int register) {
// Signed 8-bit
return device.readByte(register) * OFFSET_LSB;
}
private void setOffset(int register, float offset) {
if (offset < 0 || offset > OFFSET_RANGE) {
throw new IllegalArgumentException("Illegal offset value (" +
offset + "), must be 0.." + OFFSET_RANGE);
}
device.writeByte(register, (byte)(Math.floor(offset / OFFSET_LSB)));
}
public float getOffsetX() {
return getOffset(OFSX);
}
/**
* Set the X-axis offset in g
* @param offset Offset value (g)
*/
public void setOffsetX(float offset) {
setOffset(OFSX, offset);
}
public float getOffsetY() {
return getOffset(OFSY);
}
/**
* Set the Y-axis offset in g
* @param offset Offset value (g)
*/
public void setOffsetY(float offset) {
setOffset(OFSY, offset);
}
public float getOffsetZ() {
return getOffset(OFSZ);
}
/**
* Set the Z-axis offset in g
* @param offset Offset value (g)
*/
public void setOffsetZ(float offset) {
setOffset(OFSZ, offset);
}
public float[] getOffsets() {
return new float[] { getOffset(OFSX), getOffset(OFSY), getOffset(OFSZ) };
}
public void setOffsets(float offsetX, float offsetY, float offsetZ) {
setOffset(OFSX, offsetX);
setOffset(OFSY, offsetY);
setOffset(OFSZ, offsetZ);
}
/**
* Get the tap duration in milliseconds
* @return Tap duration (milliseconds)
*/
public float getTapDuration() {
return device.readUByte(TAP_DUR) * TAP_DURATION_MS_LSB;
}
/**
* Set the tap duration in mS
* @param tapDuration The maximum time in ms that an event must be above to qualify as a tap event
*/
public void setTapDuration(float tapDuration) {
if (tapDuration < 0 || tapDuration > TAP_DURATION_MS_RANGE) {
throw new IllegalArgumentException("Illegal tap duration value (" +
tapDuration + "), must be 0.." + TAP_DURATION_MS_RANGE);
}
device.writeByte(TAP_DUR, (byte)(Math.floor(tapDuration / TAP_DURATION_MS_LSB)));
}
/**
* Get the tap latency in milliseconds
* @return The tap latency (milliseconds)
*/
public float getTapLatency() {
return device.readUByte(TAP_LATENCY) * TAP_LATENCY_MS_LSB;
}
/**
* Set the tap latency in mS
* @param tapLatency The wait time in mS from the detection of a tap event to the start of the
* time window during which a possible second tap event can be detected
*/
public void setTapLatency(float tapLatency) {
if (tapLatency < 0 || tapLatency > TAP_LATENCY_MS_RANGE) {
throw new IllegalArgumentException("Illegal tap latency value (" +
tapLatency + "), must be 0.." + TAP_LATENCY_MS_RANGE);
}
device.writeByte(TAP_LATENCY, (byte)(Math.floor(tapLatency / TAP_LATENCY_MS_LSB)));
}
/**
* Get the tap window in milliseconds
* @return Tap window (milliseconds)
*/
public float getTapWindow() {
return device.readUByte(TAP_WINDOW) * TAP_WINDOW_MS_LSB;
}
/**
* Set the tap window in mS
* @param tapWindow The amount of time in milliseconds after the expiration of the latency time
* during which a second valid tap can begin
*/
public void setTapWindow(float tapWindow) {
if (tapWindow < 0 || tapWindow > TAP_WINDOW_MS_RANGE) {
throw new IllegalArgumentException("Illegal tap window value (" +
tapWindow + "), must be 0.." + TAP_WINDOW_MS_RANGE);
}
device.writeByte(TAP_WINDOW, (byte)(Math.floor(tapWindow / TAP_WINDOW_MS_LSB)));
}
public float getActivityThreshold() {
return device.readUByte(THRESH_ACT) * ACTIVITY_THRESHOLD_LSB;
}
/**
* Set the activity threshold value in g
* @param activityThreshold The threshold value for detecting activity
*/
public void setActivityThreshold(float activityThreshold) {
if (activityThreshold < 0 || activityThreshold > ACTIVITY_THRESHOLD_RANGE) {
throw new IllegalArgumentException("Illegal activity threshold value (" +
activityThreshold + "), must be 0.." + ACTIVITY_THRESHOLD_RANGE);
}
device.writeByte(THRESH_ACT, (byte)(Math.floor(activityThreshold / ACTIVITY_THRESHOLD_LSB)));
}
public float getInactivityThreshold() {
return device.readUByte(THRESH_INACT) * INACTIVITY_THRESHOLD_LSB;
}
/**
* Set the inactivity threshold value in g
* @param inactivityThreshold The threshold value for detecting inactivity
*/
public void setInactivityThreshold(float inactivityThreshold) {
if (inactivityThreshold < 0 || inactivityThreshold > INACTIVITY_THRESHOLD_RANGE) {
throw new IllegalArgumentException("Illegal inactivity threshold value (" +
inactivityThreshold + "), must be 0.." + INACTIVITY_THRESHOLD_RANGE);
}
device.writeByte(THRESH_INACT, (byte)(Math.floor(inactivityThreshold / INACTIVITY_THRESHOLD_LSB)));
}
public float getInactivityTime() {
return device.readUByte(TIME_INACT) * INACTIVITY_TIME_LSB;
}
/**
* Set the inactivity time value in mS
* @param inactivityTime Value representing the amount of time that acceleration must
* be less than the value in the THRESH_INACT register for inactivity to be declared
*/
public void setInactivityTime(float inactivityTime) {
if (inactivityTime < 0 || inactivityTime > INACTIVITY_TIME_RANGE) {
throw new IllegalArgumentException("Illegal inactivity time value (" +
inactivityTime + "), must be 0.." + INACTIVITY_TIME_RANGE);
}
device.writeByte(TIME_INACT, (byte)(Math.floor(inactivityTime / INACTIVITY_TIME_LSB)));
}
/**
* D7 - Activity ac/dc
* D6 - ACT_X enable
* D5 - ACT_Y enable
* D4 - ACT_Z enable
* D3 - Inactivity ac/dc
* D2 - INACT_X enable
* D1 - INACT_Y enable
* D0 - INACT_Z enable
*
* A setting of 0 selects dc-coupled operation, and a setting of 1 enables ac-coupled operation.
* In dc-coupled operation, the current acceleration magnitude is compared directly with THRESH_ACT
* and THRESH_INACT to determine whether activity or inactivity is detected. In ac-coupled
* operation for activity detection, the acceleration value at the start of activity detection is
* taken as a reference value. New samples of acceleration are then compared to this reference value,
* and if the magnitude of the difference exceeds the THRESH_ACT value, the device triggers an
* activity interrupt. Similarly, in ac-coupled operation for inactivity detection, a reference
* value is used for comparison and is updated whenever the device exceeds the inactivity threshold.
* After the reference value is selected, the device compares the magnitude of the difference
* between the reference value and the current acceleration with THRESH_INACT. If the difference is
* less than the value in THRESH_INACT for the time in TIME_INACT, the device is considered
* inactive and the inactivity interrupt is triggered.
* @return Activity / inativity control flags
*/
public byte getActivityInactivityControlFlags() {
return device.readByte(ACT_INACT_CTL);
}
public void setActivityInactivityControlFlags(byte flags) {
device.writeByte(ACT_INACT_CTL, flags);
}
public float getFreefallThreshold() {
return device.readUByte(THRESH_FF) * FREEFALL_THRESHOLD_LSB;
}
/**
* Set the freefall threshold value in g
* @param freefallThreshold The threshold value for detecting inactivity
*/
public void setFreefallThreshold(float freefallThreshold) {
if (freefallThreshold < 0 || freefallThreshold > FREEFALL_THRESHOLD_RANGE) {
throw new IllegalArgumentException("Illegal freefall threshold value (" +
freefallThreshold + "), must be 0.." + FREEFALL_THRESHOLD_RANGE);
}
device.writeByte(THRESH_FF, (byte)(Math.floor(freefallThreshold / FREEFALL_THRESHOLD_LSB)));
}
public float getFreefallTime() {
return device.readUByte(TIME_FF) * FREEFALL_TIME_LSB;
}
/**
* Set the freefall time value in mS
* @param freefallTime Value representing minimum time that the value of all axes
* must be less than THRESH_FF to generate a freefall interrupt
*/
public void setFreefallTime(float freefallTime) {
if (freefallTime < 0 || freefallTime > FREEFALL_TIME_RANGE) {
throw new IllegalArgumentException("Illegal freefall time value (" +
freefallTime + "), must be 0.." + FREEFALL_TIME_RANGE);
}
device.writeByte(TIME_FF, (byte)(Math.floor(freefallTime / FREEFALL_TIME_LSB)));
}
public boolean isDoubleTapSuppressed() {
return (device.readByte(TAP_AXES) & SUPPRESS_DOUBLE_TAP) != 0;
}
public void setDoubleTapSuppressed(boolean doubleTapSuppressed) {
byte old_val = device.readByte(TAP_AXES);
if (doubleTapSuppressed != ((old_val & SUPPRESS_DOUBLE_TAP) != 0)) {
device.writeByte(TAP_AXES, doubleTapSuppressed ? old_val | SUPPRESS_DOUBLE_TAP : old_val & ~SUPPRESS_DOUBLE_TAP);
}
}
public byte getTapActivityStatusFlags() {
return device.readByte(ACT_TAP_STATUS);
}
public boolean isLowPowerMode() {
return (device.readByte(BW_RATE) & LOW_POWER_MODE) != 0;
}
public void setLowPowerMode(boolean lowPowerMode) {
byte old_val = device.readByte(BW_RATE);
if (lowPowerMode != ((old_val & LOW_POWER_MODE) != 0)) {
device.writeByte(BW_RATE, lowPowerMode ? old_val | LOW_POWER_MODE : old_val & ~LOW_POWER_MODE);
}
}
public OutputDataRateType getBandwidthDataRate() throws RuntimeIOException {
return OutputDataRateType.TYPES[device.readByte(BW_RATE) & 0x0f];
}
public void setBandwidthRate(OutputDataRateType dataRate) throws RuntimeIOException {
byte old_val = device.readByte(BW_RATE);
device.writeByte(BW_RATE, (old_val & 0xf0) | dataRate.code);
}
public void setNormalMeasurementMode() throws RuntimeIOException {
setPowerControlFlags(POWER_CTL_MEASURE);
}
public void setPowerControlFlags(byte powerControlValue) throws RuntimeIOException {
// Enable measure mode
device.writeByte(POWER_CTL, powerControlValue);
}
public byte getInterruptEnableFlags() {
return device.readByte(INT_ENABLE);
}
public void setInterruptEnableFlags(byte flags) {
device.writeByte(INT_ENABLE, flags);
}
public byte getInterruptMapFlags() {
return device.readByte(INT_MAP);
}
public void setInterruptMapFlagS(byte flags) {
device.writeByte(INT_MAP, flags);
}
public byte getInterruptSourceFlags() {
return device.readByte(INT_SOURCE);
}
public boolean isFullResolutionMode() {
return (device.readByte(DATA_FORMAT) & FULL_RESOLUTION_MODE) != 0;
}
public void setFullResolutionMode(boolean fullResolution) {
byte old_val = device.readByte(DATA_FORMAT);
if (fullResolution != ((old_val & FULL_RESOLUTION_MODE) != 0)) {
device.writeByte(DATA_FORMAT, fullResolution ? old_val | FULL_RESOLUTION_MODE : old_val & ~SELF_TEST_MODE);
}
}
public boolean isSelfTestMode() {
return (device.readByte(DATA_FORMAT) & SELF_TEST_MODE) != 0;
}
public void setSelfTestMode(boolean selfTest) {
byte old_val = device.readByte(DATA_FORMAT);
if (selfTest != ((old_val & SELF_TEST_MODE) != 0)) {
device.writeByte(DATA_FORMAT, selfTest ? old_val | SELF_TEST_MODE : old_val & ~SELF_TEST_MODE);
}
}
public int getAccelFsr() {
return RANGE_LIST[device.readByte(DATA_FORMAT) & 0x3];
}
public void setAccelFsr(int range) {
for (int i : RANGE_LIST) {
if (RANGE_LIST[i] == range) {
device.writeByte(DATA_FORMAT, i);
return;
}
}
throw new IllegalArgumentException("Invalid range value (" + range +
"), must be one of " + Arrays.toString(RANGE_LIST));
}
/**
* D7 D6 | D5 | D4 D3 D2 D1 D0
* FIFO_MODE | Trigger | Samples
* FIFO modes:
* 0 Bypass - FIFO is bypassed
* 1 FIFO - FIFO collects up to 32 values and then stops collecting data, collecting new data only when FIFO is not full
* 2 Stream - FIFO holds the last 32 data values. When FIFO is full, the oldest data is overwritten with newer data
* 3 Trigger - When triggered by the trigger bit, FIFO holds the last data samples before the trigger event and then
* continues to collect data until full. New data is collected only when FIFO is not full
* Trigger bit: A value of 0 in the trigger bit links the trigger event of trigger mode to INT1,
* and a value of 1 links the trigger event to INT2
* Samples: The function of these bits depends on the FIFO mode selected (see below).
* Entering a value of 0 in the samples bits immediately sets the watermark status bit in the INT_SOURCE
* register, regardless of which FIFO mode is selected. Undesirable operation may occur if a value of 0
* is used for the samples bits when trigger mode is used
* FIFO Mode | Samples Bits Function
* Bypass | None.
* FIFO | Specifies how many FIFO entries are needed to trigger a watermark interrupt.
* Stream | Specifies how many FIFO entries are needed to trigger a watermark interrupt.
* Trigger | Specifies how many FIFO samples are retained in the FIFO buffer before a trigger event.
* @return FIFO Control flags
*/
public byte getFifoControlFlags() {
return device.readByte(FIFO_CTL);
}
public void setFifoControlFlags(byte flags) {
device.writeByte(FIFO_CTL, flags);
}
/**
* D7 | D6 | D5 D4 D3 D2 D1 D0
* FIFO Trig | 0 | Entries
* FIFO Trig: A 1 in the FIFO_TRIG bit corresponds to a trigger event occurring,
* and a 0 means that a FIFO trigger event has not occurred
* Entries: These bits report how many data values are stored in FIFO. Access to collect the data
* from FIFO is provided through the DATAX, DATAY, and DATAZ registers. FIFO reads must be done
* in burst or multiple-byte mode because each FIFO level is cleared after any read (single-or
* multiple-byte) of FIFO. FIFO stores a maximum of 32 entries, which equates to a maximum of 33
* entries available at any given time because an additional entry is available at the output
* filter of the device.
* @return FIFO status
*/
public byte getFifoStatus() {
return device.readByte(FIFO_STATUS);
}
@Override
public ImuData getImuData() throws RuntimeIOException {
// TODO Auto-generated method stub
return null;
}
@Override
public Vector3D getGyroData() throws RuntimeIOException {
throw new UnsupportedOperationException("ADXL345 doesn't hava a gyro");
}
@Override
public Vector3D getAccelerometerData() throws RuntimeIOException {
ByteBuffer data = ByteBuffer.wrap(device.readBytes(AXES_DATA, 6));
short x = data.getShort();
short y = data.getShort();
short z = data.getShort();
return ImuDataFactory.createVector(new short[] {x, y, z}, SCALE_FACTOR);
}
@Override
public Vector3D getCompassData() throws RuntimeIOException {
throw new UnsupportedOperationException("ADXL345 doesn't hava a compass");
}
@Override
public boolean hasGyro() {
return false;
}
@Override
public boolean hasAccelerometer() {
return true;
}
@Override
public boolean hasCompass() {
return false;
}
@Override
public void addTapListener(TapListener listener) {
// TODO Auto-generated method stub
}
@Override
public void addOrientationListener(OrientationListener listener) {
// TODO Auto-generated method stub
}
@Override
public String getImuName() {
return "ADXL345";
}
@Override
public int getPollInterval() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void startRead() {
setNormalMeasurementMode();
}
@Override
public void stopRead() {
setPowerControlFlags((byte)(POWER_CTL_AUTO_SLEEP | POWER_CTL_SLEEP));
}
public static class OutputDataRateType {
public static final OutputDataRateType[] TYPES = {
new OutputDataRateType(0B0000, 0.1f),
new OutputDataRateType(0B0001, 0.2f),
new OutputDataRateType(0B0010, 0.39f),
new OutputDataRateType(0B0011, 0.78f),
new OutputDataRateType(0B0100, 1.56f),
new OutputDataRateType(0B0101, 3.13f),
new OutputDataRateType(0B0110, 6.25f),
new OutputDataRateType(0B0111, 12.5f),
new OutputDataRateType(0B1000, 25f),
new OutputDataRateType(0B1001, 50f),
new OutputDataRateType(0B1010, 100f),
new OutputDataRateType(0B1011, 200f),
new OutputDataRateType(0B1100, 400f),
new OutputDataRateType(0B1101, 800f),
new OutputDataRateType(0B1110, 1600f),
new OutputDataRateType(0B1111, 3200f)
};
private int code;
private float outputDataRate;
private float bandwidth;
private OutputDataRateType(int code, float outputDataRate) {
this.code = code;
this.outputDataRate = outputDataRate;
bandwidth = outputDataRate / 2;
}
public int getCode() {
return code;
}
public float getOutputDataRate() {
return outputDataRate;
}
public float getBandwidth() {
return bandwidth;
}
}
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.