content
stringlengths 7
2.61M
|
---|
Anatomic-Radiologic Comparison of the Effects of Liposculpture on the Lymphatic System of the Lower Extremities A study of the lymphatic anatomy of the leg was performed using lymphography. Methods of visualization of the lymphatic anatomy are discussed and include radiographic visualization during surgery and direct examination of tissues after injection of vital dyes. Using these methods, the effect of liposuction on the lymphatics of the leg was studied in a single patient. Results of this preliminary study indicate that liposuction of the lower extremity does not cause disruption of the lymphatic system of the leg. |
Vertical P-MOSFETs with heterojunction between source/drain and channel The growth of high quality strained SiGe-Si and SiGeC-Si heterostructures allows incorporation of band gap engineering into Si technology, which can be used to improve device characteristics. A heterojunction MOSFET (HJMOSFET) structure has been proposed in which the large valence band offset at SiGe-Si heterojunctions reduces the punchthrough and DIBL for P-MOSFETs (Hareland et al, 1993). Vertical MOSFETs allow more freedom in terms of band gap engineering, and the channel length is not limited by the lithography (Liu et al, 1998). In this paper, we show experimentally that the heterojunction at the source can be used to suppress the floating body effect and short channel effect. Vertical P-MOSFETs with strained SiGe and SiGeC sources have been fabricated with 60-75 nm effective channel lengths. The electrical characteristics of the devices are compared with those of control Si devices and with simulation results. |
Optimal prediction model using improved differential evolution algorithm A Taguchi-based the differential evolution (TDE) is applied as an improved the differential evolution to solve the global optimization. The differential evolution (DE) is an easy and valid evolutionary algorithm for fitness function optimization. For grey forecasting model (GM) which is a time series forecasting model, the parameters are calculated by the TDE. The academic research of Wang and Hsu is a base of this paper. Finally, the forecasted result of TDEGM is superior to other evolutionary algorithms. |
Metal halide high-pressure discharge lamps of this type are used particularly for fiber-optic illuminating systems in medicine (endoscopy) and technology (boroscopy), where light at color temperatures between 4500 and 7000 K. and good to very good color rendition in all color temperature ranges, along with high lighting intensities, are needed.
Low-loss coupling of the light into the fiber-optic bunch necessitates good focusing, or in other words a focusing diameter that is less than or at most equal to the usable diameter of the fiber-optic bunch. To produce a corresponding light spot, the arc core is essentially projected by a reflector or other optical system. If the light emitted by the arc core does not include all the spectral components of the total light emitted by the lamp, then the color rendition property of the focused light can worsen compared with that of the unfocused light. It is therefore highly important, with a view to use in the aforementioned focusing systems, to purposefully find fill ingredients that emit at the hot arc core and not only at the cooler arc edge. Moreover, for good focusing and high light intensities at the entry to the fiber-optic bunch, especially compact lamp dimensions and a very short light arc (only a few millimeters) with maximum light densities (on average, several tens of kcd/cm.sup.2) must be sought.
From European Patent Disclosure EP 0 193 086, to which U.S. Pat. No. 9,686,419, Blook et al. corresponds, assigned to the assignee of this application, metal halide high-pressure discharge lamps with similar short light arcs and correspondingly high light densities are known that produce light with good color rendition properties.
However, their disadvantage is that the fills of these lamps contain cadmium. For the sake of environmental protection, at the end of the lamp life the toxic heavy metal, cadmium, must be returned to the raw material cycle or be properly disposed of, which in both cases involves attendant costs. Moreover, the lamps with a Cd filling have an irritating greenish tinge, and the color location is located above Planckian locus.
It is an object of The Invention to create a metal halide high-pressure discharge lamp that has a very short light arc with a very high light density as well as a color temperature between 4500 and 7000 K. at a color location near the Planckian locus, good color rendition, and especially in combination with a strongly focusing reflector or other optical system, and that attains this object with a cadmium-free fill.
Briefly, the fill of the lamp according to the invention comprises mercury, at least one noble gas and at least one halogen, and metals that form halides, namely dysprosium (Dy), hafnium (Hf), lithium (Li) and indium (In). The fill quantities, in micromoles per milliliter (.mu.mol/ml) of vessel volume, are advantageously between 0.3 and 3 each for Dy, Hf and Li, and between 0.2 and 2 for In.
The metal halide high-pressure discharge lamp is operated at specific arc powers between 100 and 180 W per millimeter of arc length. Given the compact geometrical dimensions of the lamp--very short electrode spacing (a few millimeters) and small vessel volume (a few tenths of a millimeter)--this is equivalent to wall loads of 70 to 120 W/cm.sup.2 of wall area of the discharge vessel. By means of the fill components, according to the invention, of the discharge vessel, mean light densities of 25 to 75 kcd per cm.sup.2 of arc area are attained, which can be focused with the aid of a reflector or other optical system onto a light spot whose diameter is less than 10 mm. The particular value of the invention is that the good to very good color rendition (Ra.gtoreq.75) is preserved even after focusing, and the color location is near Planckian locus, and this is achieved with a fill that does without the toxic cadmium used until now.
Dysprosium, with its multiple-line spectrum, assures a high radiation flux in the visible range of the electromagnetic spectrum and additionally contributes to the continuous spectrum. Hafnium also produces a multiple-line spectrum and moreover reduces the tendency to devitrification, by building up a reinforced halogen jacket on the bulb wall. Because of the high vapor pressure of hafnium halides, the tendency to bulb blackening is also reduced, and consequently the usable light flux during the lamp life is increased.
By means of lithium and indium, the radiation flux especially in the red and blue portions of the optical spectral region is reinforced. Overall, the light emitted has a spectral composition that is quite close to that of Planckian radiation, or in other words has good to very good color rendition properties. Depending on the proportion of fill quantities of the various components, light can be generated with a color temperature between 4500 and 7000 K.
The lamp according to the invention is preferably used in dichroitic special reflectors, which essentially project the inner arc core. By the purposeful selection of the two atomic radiators, lithium and indium, which radiate preferentially in the hot arc core, it is achieved that the good color rendition properties are preserved even at the focal point of this reflector. Moreover, by the use of lithium in combination with hafnium, high color stability is attained; that is, the color temperature varies only slightly over the lifetime of the lamp.
For arc stabilization, the discharge vessel can contain in addition up to 3 .mu.mol of cesium per cm.sup.3 of vessel volume. To maintain the halogen cycle process, iodine and bromine are preferably used in a molar ratio between 0.3 and 1.5. The lamp also contains mercury, in an amount of typically a few tens to a few hundreds of .mu.mol per cm.sup.3 of vessel volume and a noble gas, such as argon, as the basic gas. The fill pressure of the noble gas in the cold lamp is less than atmospheric pressure--typically a few tens of kPa--so that in this case risk-free manipulation is possible. On the other hand, the pressure range is high enough that upon ignition an undesired evaporation of the tungsten electrodes with an attendant blackening of the discharge vessel is largely prevented.
The metal halide high-pressure discharge lamp according to the invention, while preferably used in a reflector securely joined to the lamp, can nevertheless also be used without an integrated joined reflector. |
Alterations in cell number and cell morphology in copper deficient endothelial cells In postimplantation embryo culture, copper (Cu) deficiency impairs yolk sac vessel development. We used human umbilical vein endothelial cells (HUVEC) to test the hypothesis that the yolk sac vessel anomalies observed in Cu deficiency result from abnormal EC morphology and motility. HUVEC were cultured in low serum (2%) medium for 72 h in chamber slides. The addition of the Cu chelator triethylenepentamine (TEPA) to the culture media resulted in a dosedependent decrease in cell number. The addition of 50 uM Cu prevented the reduction in cell viability observed in 10 uM TEPA but not in 50 uM TEPA treated cells. To test the effects of Cu on EC cytoskeleton, HUVEC were grown for 72 h in culture media containing 10 or 50 uM TEPA, with and without 50 uM Cu and processed for fluorescence microscopy. In control medium, actin was organized into stress fibers; tubulin filaments extended from the perinuclear organizing center to the periphery. HUVEC grown in medium containing 10 uM TEPA showed marked reductions in actin filaments; the cells appeared round and hollow. Tubulin extensions were reduced in the Cu deficient cells. These effects we exacerbated at 50 uM TEPA. The addition of 50 uM Cu to 10 uM TEPA treated cells restored the expression patterns of actin and tubulin similar to control; but not at 50 uM TEPA. These data suggest that Cu deficiency disturbs the organization of the cytoskeleton. We are investigating the functional implications of this pattern of expression in endothelial cells. |
<reponame>SeanSobey/ts-std-lib<gh_stars>0
import { InspectOptions } from 'util';
import { v4 as uuidv4 } from 'uuid';
import { IValue } from './IValue';
import { IEquatable, equals } from './Equality';
import { IInspectable, inspect } from './IInspectable';
import { JsonSerializable, jsonProperty } from './Serialization/Json/JsonSerializable';
/**
* A globally unique user identifer implementation
* @see https://www.npmjs.com/package/uuid
*/
export class Guid extends JsonSerializable implements IValue<string>, IEquatable<Guid>, IInspectable {
@jsonProperty('guid')
private readonly _guid: string;
public constructor(guid?: string) {
super();
if (guid && !this.isValid(guid)) {
throw new Error('Invalid guid');
}
this._guid = guid || uuidv4();
}
public valueOf(): string {
return this._guid;
}
public [equals](other: Guid): boolean {
return this._guid === other._guid;
}
public [inspect](_options?: InspectOptions): string {
return `<${Guid.name}> ${this._guid}`;
}
private isValid(guid: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(guid);
}
}
|
It has been almost 30 years since the Chernobyl nuclear disaster sprayed radioactive fallout across parts of Europe. Nevertheless, Norwegian officials have measured much higher levels of radioactive contamination than usual in grazing animals this autumn.
“This year is extreme,” says Lavrans Skuterud, a researcher at The Norwegian Radiation Protection Authority.
In September, a sample of reindeer from Vågå Reinlag AS in Jotunheimen contained 8,200 becquerels per kilogram of the radioactive substance cesium-137.
In September 2012, the maximum value at that location was 1,500 becquerels.
Measurements in sheep also showed high levels of radioactivity. In Valdres and Gudbrandsdal, both in central southern Norway, samples of mutton contained 4,500 becquerels per kilogram.
Lots of mushrooms
Skuterud is confident that he knows the reason.
“There have been quite a lot of mushrooms this year. The mushroom season has also been quite long. And the mushrooms have grown high in the mountains.”
The gypsy mushroom poses a particular problem. It is edible, and both humans and animals find it very tasty, but it can take up a lot of radioactivity.
Back to pasture
Reindeer herders in Vågå have sent between 800 and 900 animals back out to pasture after the measurements of radioactivity.
“The animals can probably be slaughtered this winter, when the levels of radioactivity tend to fall,” according to Skuterud. That does, however, mean lost revenue and extra costs.
In Valdres and Gudbrandsdal, many sheep are now being given special feed. They are fenced in and are being fed less contaminated feed before being slaughtered. In sheep and reindeer, the radioactive substance has a half-life of two to three weeks.
In Norway, the regulatory limit for sheep meat is 600 becquerels per kilogram.
A surprise
The researchers know why there is more radioactivity in the animals this year.
Yet they are somewhat surprised by the very high levels.
“The Chernobyl accident happened in 1986. That is almost 30 years ago,” Skuterud says.
The reactor at Chernobyl was designed to be inexpensive and efficient. Unfortunately, it was also inherently unstable, and one spring day in 1986, things went horribly wrong.
A half-life of 30 years
Cesium-137 has a half-life of 30 years. In about two years, half of the radioactive dust that blew in over Norway after the dramatic spring night in 1986 should be gone.
“The level in the environment has fallen even faster. Some was washed out, and some was bound in the soil. Only a small portion is in circulation in the food chain. When we look at the values in grazing animals, they rise in autumn, and it looks as if this will last forever. But when it comes to winter, values are in steady decline, at least in reindeer,” says Skuterud.
Measurements from the 1960s
The Norwegian Radiation Protection Authority began to measure radioactive cesium in reindeer herders as early as 1965. The measurements began in Kautokeino Sami, in very northern Norway as a result of the testing of nuclear weapons in the 1950s and 1960s.
Since Chernobyl, measurements have been carried out on herders in the areas that were hardest hit, namely Central and South Norway.
“Before Chernobyl, we never saw the levels we see today, even when the nuclear tests were at the most intense in the 1960s,” Skuterud says.
The tests were conducted at high altitudes. That spread the radioactivity instead of allowing it to concentrate in specific areas, which is what happened after Chernobyl.
Southern Sami hit hard
The Sami people in southern Norway are probably among the most radioactive in the world, according to Skuterud. However, the health effects of this situation are unknown.
“We would like to do health studies of this group. But it is a very small population, so the results are uncertain. But from what we know about the consequences of these radiation doses, we do not expect health effects,” Skuterud said.
Less cancer among the Sami
There have been studies of cancer incidence in the northern Sami population after the fallout in the 1950s and 1960s.
The Sami population turned out to have significantly lower cancer rates than the general population. This is probably due to a healthier lifestyle, according to Skuterud.
“They are more physically active and eat a lot of reindeer meat, which is lean and healthy. They also eat a lot of fish and berries.”
Still, this does not give us any answers when it comes to the long-term effects of the fallout, the researcher says.
Since Chernobyl, there have been strong advisories about the amount of reindeer meat that can safely be eaten per day. The Sami have been very conscious of the dangers of radioactivity.
Large differences
Officials in different countries have imposed regulatory thresholds on cesium-137 in food as a way to keep track of the annual consumption of food containing the substance. However, these limits vary greatly from country to country.
There is consensus that people should not be exposed to more than 800,000 becquerels per year. The disagreement centres on differences in diet and the number of foods that are contaminated.
“Following the nuclear accident in Fukushima in Japan in 2011, the issue has re-emerged. Today, there is a considerable amount of research on it,” Skuterud explains.
Norway has very liberal thresholds compared to those in Japan.
The threshold for common foodstuffs is 600 becquerels per kilogram, but only 100 becquerels in Japan.
For foods that are eaten more rarely, such as game and freshwater fish, the Japanese threshold is 500 and the Norwegian 3000.
A question of politics
In Norway, the high threshold was discussed after the Chernobyl accident, and ultimately the decision was political, says Skuterud.
“The threshold for this category was kept high because indigenous people lived by herding. They were in danger of losing their livelihood. That could lead to more serious health problems than the radioactivity,” he said.
------------
Read the Norwegian version of this article at forskning.no |
1. Field of the Invention
The present invention relates to a cell phone, and more particularly, a solar cell phone.
Cell phones are very convenient, as they allow people to stay connected to friends and loved ones on the go, as well as enable people to conduct business when not in the same room. Certain activities, however, such as conference calls, long business calls, and playing games and videos, can drain the cell phone's battery. In order to recharge the battery, individuals must be near an electrical outlet and must plug the phone into the outlet via a cord for extended lengths of time. If not around an outlet, the phone can die and the person can be stranded. An effective solution is necessary.
The present invention is a solar cell phone with a plurality of small solar panels that can be used to charge the rechargeable battery of the cell phone, rather than using an electrical power source. The present invention can be especially useful for businesspeople who are constantly checking their email or talking to clients, as well as people who use their cell phones to watch TV, watch movies, play games, play music, and surf the Web. Individuals looking to reduce their electric use will appreciate the convenience and practicality afforded by the solar cell phone.
2. Description of the Prior Art
Numerous innovations for solar powered cell phones have been provided in the prior art that will be described. Even though these innovations may be suitable for the specific individual purposes to which they address, however, they differ from the present invention.
A FIRST EXAMPLE, U.S. Patent Office Publication No. 2002/0088486, Published on Jul. 11, 2002, to Chenx teaches a solar-powered device that is adapted to be disposed on a battery unit of a mobile telephone handset so as to charge the battery unit. The solar-powered device includes a light sensor, a photoelectric converting circuit coupled operably to the light sensor so as to convert light that is sensed by the light sensor into a corresponding current signal, and a current processing circuit, coupled electrically to the photoelectric converting circuit, for receiving and processing the current signal so as to result in a charging current that is adapted to charge the battery unit of the mobile telephone handset.
A SECOND EXAMPLE, U.S. Patent Office Publication No.2005/0282591, Published on Dec. 22, 2005, to Shaff teaches a mobile telephone apparatus in which a solar power source is used to supplement battery power. A solar cell array is positioned on the surface of the telephone and supplies electric current to the telephone. A preferred embodiment of the present invention is equipped with speech recognition software that allows the user to issue commands (such as dialing the telephone) verbally to the telephone. In addition, this speech recognition may be used to operate an integrated AM/FM broadcast radio to allow the telephone to double as a radio. In an alternative embodiment, the solar mobile telephone is integrated into a headset to allow for convenient hands-free operation.
A THIRD EXAMPLE, U.S. Patent Office Publication No.2006/0238163, Published on Oct. 26, 2006, to Chen teaches a mobile phone which includes a main body. The main body further includes a solar power module, a display module, and an input module (i.e., a keypad). The solar power module is adapted for providing electrical power to the mobile phone. The solar power module includes a solar cell panel configured for converting light energy to electrical power. The input module includes a control switch for setting the solar power module in one of the following states: “on”, “off”, or “storage”. Advantageously, the mobile phone can also be supplied with at least one heating pad disposed on the surface thereof, selectively controlled (e.g., on/off and/or a temperature chosen), to provide heat to a hand and/or other body part of a user.
A FOURTH EXAMPLE, U.S. Patent Office Publication No. 2008/0143291, Published on Jun. 19, 2008, to Lin et al. teaches a communication apparatus with a solar energy charging function that includes a host and a display panel movably and pivotally coupled to the host to define a foldable mobile phone, and a solar panel is coaxially and pivotally coupled to a shaft of the host, such that the solar panel can be folded and covered onto an upper surface of the display panel. If the battery power of the mobile phone is low, users can individually lift the solar panel open from the display panel to charge the battery that is electrically coupled to the mobile phone, so as to enhance the power capacity, using time limit and battery charging requirements of the communication apparatus.
A FIFTH EXAMPLE, U.S. Patent Office Publication No.2010/0167797, Published on Jul. 1, 2010, to Morichi teaches a cellular phone according to the present invention comprises a plurality of solar cell modules arranged on different surfaces of a casing, a plurality of electric power control parts connected to each of the plurality of solar cell modules, a mechanical form detection sensor as a state detection part for detecting a state of said cellular phone, and an electric power selection part.
It is apparent now that numerous innovations for solar powered cell phones have been provided in the prior art that are adequate for various purposes. Furthermore, even though these innovations may be suitable for the specific individual purposes to which they address, accordingly, they would not be suitable for the purposes of the present invention as heretofore described. |
package parser;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import repository.Comment;
import repository.Task;
import repository.TaskList;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
class ListParserTest {
private ListParser parser;
private String json;
@BeforeEach
void setUp() {
this.parser = new ListParser();
this.json = "{\"name\":\"The name\",\"created\":\"1610240405874\",\"tasks\": [{\"title\":\"The title\",\"description\":\"The description\",\"created\":\"1610240405874\",\"comments\": [{\"content\":\"The Comment\",\"created\":\"1610240405874\"},{\"content\":\"The Comment\",\"created\":\"1610240405874\"}]}]}";
}
@Test
void getObject() {
TaskList l = this.parser.getObject(this.json);
System.out.println("Object => " + l);
}
@Test
void parse() {
Comment comment = new Comment("The Comment", new Date(Long.parseLong("1610240405874")));
ArrayList<Comment> comments = new ArrayList<>();
comments.add(comment);
comments.add(comment);
Task task = new Task("The title", "The description", new Date(Long.parseLong("1610240405874")), comments, false);
HashMap<String,Task> tasks = new HashMap<>();
tasks.put("The title", task);
TaskList list = new TaskList("The name", new Date(Long.parseLong("1610240405874")), tasks);
System.out.println(this.parser.parse(list));
}
} |
/// Returns the output size of a digest.
pub const fn digest_size(mode: Algorithm) -> usize {
match mode {
Algorithm::Sha1 => 20,
Algorithm::Sha224 => 28,
Algorithm::Sha256 => 32,
Algorithm::Sha384 => 48,
Algorithm::Sha512 => 64,
Algorithm::Blake2s => 32,
Algorithm::Blake2b => 64,
Algorithm::Sha3_224 => 28,
Algorithm::Sha3_256 => 32,
Algorithm::Sha3_384 => 48,
Algorithm::Sha3_512 => 64,
}
} |
/**
* @author loser
* @ClassName DesignerVO
* @Description
* @Date 2016/07/03 2:20
*/
@Data
public class PersonStatistics {
public PersonStatistics(Integer accountId,String name){
this.accountId = accountId;
this.name = name;
}
private Integer accountId;
private String name;
private Integer total = 0;
private Integer totalFinish = 0;
private Integer month = 0;
private Integer monthFinish = 0;
private Integer monthCancel = 0;
private String totalRate = "";
private String monthRate = "";
} |
A federal judge in Texas is set to hear arguments on whether he should end the Deferred Action for Childhood Arrivals program, a case that could tee up a fast track for the issue to hit the Supreme Court this fall.
District Judge Andrew Hanen, a George W. Bush appointee, will hear arguments from seven states that sued over DACA, a program that protects from deportation young undocumented immigrants who came to the US as children. The states, led by Texas, argue the DACA program is unconstitutional -- relying heavily on a previous court ruling from Hanen that blocked an expansion of the program and the creation of a similar program for immigrant parents from going into effect.
At issue Wednesday will be whether Hanen should immediately order a halt to the program, setting the stage for him to make a final ruling on its constitutionality.
The administration has decided to not defend DACA in Hanen's court, so pro-immigrant groups will step in to defend the program instead. The administration has argued to Hanen that if he decides to issue an immediate stoppage of the program, he should limit any ruling to recipients in the states that have sued, and that he should delay his order's effectiveness to give the administration time to appeal.
Wednesday's hearing comes as the Trump administration is already preparing to appeal a different order, from a DC district judge, which would require it to reopen the program to new applications and restore it in full. Previous courts have merely ordered the government to continue renewing permits. That judge has postponed the implementation of his decision 20 days to allow for the appeal. The other cases are pending before appellate courts in California and New York.
Hanen is widely seen as unfriendly to DACA, given his previous ruling on its sister program.
If he were to rule the program should be ended, it would conflict with the other court rulings that the program should be reopened -- likely setting the stage for a fast track to the Supreme Court by this fall.
"I think what you see here is the government hiding behind a legal rationale because it's unwilling to embrace the reality that it is abandoning DACA for reasons of policy, not reasons of law," Verilli said, calling it a "misuse of the judicial process to achieve policy objectives."
"It's, as I said, quite striking that this administration is using these kinds of legal maneuvers to try to achieve an outcome that it's unwilling to actually embrace and defend on the merits," he added.
"The last administration violated its duty to enforce our immigration laws by directing and implementing a categorical, multipronged non-enforcement immigration policy for a massive group of illegal aliens," Sessions said. "This wrongful action left DACA open to the same legal challenges that effectively invalidated another program they established -- Deferred Action for Parents of Americans and Lawful Permanent Residents (DAPA). ... The Trump administration and this Department of Justice will continue to aggressively defend the executive branch's lawful authority and duty to ensure a lawful system of immigration for our country." |
Anti-war campaigners from the US and Europe slammed NATO’s buildup near Russian borders as they hosted their own conference in the Polish capital, Warsaw, where a summit of the leaders of the NATO military bloc began on Friday.
The counter-forum will discuss a range of topics, including the growth of military spending, the expansion of nuclear arsenals, relations between NATO and the EU, the European refugee crisis and the deployment of US missile defense components on European territory.
An anti-war rally to protest the opening of new NATO bases around the globe is also scheduled to take place on Saturday as part of the event.
The leader of the Polish Stop the War Initiative, which was one of the organizers of the anti-war summit, stressed that Warsaw has been arming itself in every way possible – increasing the number of troops and military spending – since joining NATO in 1999.
“On top of that, we have plans of deploying NATO bases” in Poland, Philip Ilkovsky told Russian media.
“Neither the Russians nor the Poles need the current arms race because in case of war, ordinary people will suffer, not the people who are making the decisions behind a tall fence at the NATO summit,” the activist said, as cited by TASS.
A two-day summit of the leaders of the 28-member NATO alliance, including Barack Obama, Angela Merkel and others, kicked off in the Polish capital on Friday, focusing on boosting security in the eastern part of the bloc.
Among the decisions expected to be finalized in Warsaw is the deployment of four 4,000-strong NATO battalions in Poland and the Baltic States and the creation of a multinational brigade in Romania.
Petr Ikonovich from Social Justice Movement Poland told TASS that Russia “shouldn’t be excluded” from the global security system.
“It’s a vicious circle. If we aim our missiles at Russia, it will, obviously, respond in the same manner,” he said.
The participants of the anti-war summit in Warsaw consider NATO "an aggressive alliance, which bears responsibility for thousands of victims in various conflicts, as well as for the increasing flow of refugees to Europe that causes the growing hysteria nationalism. This NATO policy will eventually lead to the collapse of the European Union," Ikonovich warned.
“We oppose the deployment of the US and NATO bases in Poland as it will lead to an increased threat to our country,” the activist said, adding that the social sector in Poland will also suffer due to the transfer of funds to military needs.
Protests were reported in Paris, Athens, Naples and elsewhere across Europe ahead of the NATO summit in Warsaw, while New York and Lisbon are among the cities where demonstrations are planned for Saturday.
“If the course on militarization remains, protests in Poland and around the globe will only increase,” Ilkovsky said.
Despite the main topic of the Warsaw Summit being to counter what NATO claims to be a Russian threat, polls reveal that an increased number of Europeans disagree with the bloc’s approach towards dealing with Moscow.
Only 9 percent of Germans currently support NATO’s buildup in Eastern Europe, a fresh survey by YouGov revealed.
Two-thirds of respondents also agreed with Germany’s foreign minister, who earlier said the military alliance should abandon its “saber-rattling” on Russia’s doorstep.
In June, the Pew Research Center’s Spring 2016 Global Attitudes Survey showed that most Europeans do not view Russia as a threat, instead naming Islamic State (IS, formerly ISIS/ISIL) terror group, climate change, economic instability, cyber-attacks and the refugee influx as the main security challenges.
The only two countries that spoke in favor of boosting defense spending turned out to be Poland and the Netherlands.
Earlier this week, polls in Sweden showed a sharp drop in support for the country’s possible NATO membership, with numbers going down from 41 to 33 percent in less than a year. |
Error Analysis of a Stochastic Collocation Method for Parabolic Partial Differential Equations with Random Input Data A stochastic collocation method for solving linear parabolic partial differential equations with random coefficients, forcing terms, and initial conditions is analyzed. The input data are assumed to depend on a finite number of random variables. Unlike previous analyses, a wider range of situations are considered, including input data that depend nonlinearly on the random variables and random variables that are correlated or even unbounded. We provide a rigorous convergence analysis and demonstrate the exponential decay of the interpolation error in the probability space for both finite element semidiscrete spatial discretizations and for finite element, Crank--Nicolson fully discrete space-time discretizations. Ingredients in the convergence analysis include the proof of the analyticity, with respect to the probabilistic parameters, of the semidiscrete and fully discrete approximate solutions. A numerical example is provided to illustrate the analyses. |
# 作用就是向网易云信发送请求,帮助后台发送短信息给客户
import hashlib
import json
import os
import uuid
from time import time
import requests
from django.core.mail import send_mail
from qiniu import Auth, put_file, put_data
from djangoday4.settings import EMAIL_HOST_USER, MEDIA_ROOT
from user.models import UserProfile
# 发送短信息
def util_sendmsg(mobile):
url = 'https://api.netease.im/sms/sendcode.action'
data = {'mobile': mobile}
# 4部分组成 headers: AppKey Nonce CurTime CheckSum
AppKey = '1bdcdeda105c1d91e802a191d8f5ed94'
Nonce = '843hjfd87fdfshdjfhs5433'
CurTime = str(time())
AppSecret = '05bf2ece7293'
content = AppSecret + Nonce + CurTime
CheckSum = hashlib.sha1(content.encode('utf-8')).hexdigest()
headers = {'AppKey': AppKey, 'Nonce': Nonce, 'CurTime': CurTime, 'CheckSum': CheckSum}
response = requests.post(url, data, headers=headers)
# json
str_result = response.text # 获取响应体
json_result = json.loads(str_result) # 转成json
return json_result
# 发送邮件
def send_email(email, request):
subject = '个人博客找回密码'
user = UserProfile.objects.filter(email=email).first()
ran_code = uuid.uuid4()
print(ran_code)
print(type(ran_code))
ran_code = str(ran_code)
print(type(ran_code))
ran_code = ran_code.replace('-', '')
request.session[ran_code] = user.id
message = '''
可爱的用户:
<br>
您好!此链接用户找回密码,请点击链接: <a href='http://127.0.0.1:8000/user/update_pwd?c=%s'>更新密码</a>,
<br>
如果链接不能点击,请复制:<br>
http://127.0.0.1:8000/user/update_pwd?c=%s
个人博客团队
''' % (ran_code, ran_code)
# 发送邮件send_mail
result = send_mail(subject, "", EMAIL_HOST_USER, [email, ], html_message=message)
return result
# 上传图片到七牛云
def upload_image(storeobj):
access_key = '<KEY>'
secret_key = '<KEY>'
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 要上传的空间
bucket_name = 'myblog'
# 上传后保存的文件名
key = storeobj.name
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
# 要上传文件的本地路径
# localfile = os.path.join(MEDIA_ROOT, imagepath) # 本地图片
ret, info = put_data(token, key, storeobj.read())
print(ret, info)
filename = ret.get('key')
save_path = 'http://pr67kkhq9.bkt.clouddn.com/'+filename
return save_path
|
import tkinter as tk
janela = tk.Tk()
mensagem_para_usuario = "mensagem que pode ser util para um user"
msg = tk.Message(janela, text= mensagem_para_usuario)
msg.config(bg='#f5fffa',font=('times',24,'italic'))
msg.pack()
janela.mainloop() |
# Generated by Django 3.2.7 on 2021-09-30 17:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0007_store_review'),
]
operations = [
migrations.DeleteModel(
name='CustomClass',
),
migrations.DeleteModel(
name='CustomFonts',
),
migrations.DeleteModel(
name='Settings',
),
migrations.DeleteModel(
name='Store',
),
]
|
<filename>config/packager/utils/source-file-parsers/ssr/sources/pages/pokemon-page/_api/requests/get-pokemon-list/index.ts
import { IResponse, PureRestRequest } from '@mihanizm56/fetch-api';
import { makeRequestConfig } from './make-request-config';
export const getPokemonListRequest = (): Promise<IResponse> =>
new PureRestRequest().getRequest(makeRequestConfig());
|
Canadian developers Nvizzio Creations and Meridian 4 have announced that their new game, Eden Rising: Supremacy will launch on Steam in early access on May 17th, 2018. This multiplayer open world-tower defense hybrid delivers a unique co-op experience with a refreshing blend of exploration, crafting, action, combat and tower defense.
The game will launch with a slew of features already available including a 4 square mile world with four distinct biomes to explore. Those biomes will increase in size and scope during early access development. The early access version will have over 30 hours of gameplay including some end game content which will let players to team up and test themselves.
Nvizzio has also launched a video series, The Ascendants’ Vault, which takes an in-depth look at Eden Rising’s world and core features. So if you’re looking for more information on the game, thats a good place to start.
Eden Rising: Supremacy will be hitting Steam Early Access on May 17th, 2018. As of today, players can wishlist the game now on Steam and head over to the official site for more information.
You can watch the latest gameplay trailer below. |
<gh_stars>0
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "Arduino.h"
#include <Adafruit_NeoPixel.h>
class Controller : public Adafruit_NeoPixel
{
public:
Controller(uint16_t n, uint8_t p, neoPixelType t) : Adafruit_NeoPixel(n, p, t) {}
void init();
void service();
void setColor(int8_t r, int8_t g, int8_t b);
void setColor(int16_t led, int8_t r, int8_t g, int8_t b);
};
#endif |
<gh_stars>0
package com.iph.directly.domain;
import android.app.PendingIntent;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.maps.model.LatLng;
import com.iph.directly.domain.model.Location;
import com.iph.directly.domain.model.Toilet;
import rx.Observable;
/**
* Created by vanya on 10/8/2016.
*/
public interface LocationRepository {
Observable<Location> getCurrentLocation();
Observable<Location> getLocationFromLatLng(double latitude, double longitude);
Observable<Toilet> initPlaceId(Location currentLocation, Toilet toilet);
Observable<String> getCurrentLocationText();
class LocationNotEnabledException extends RuntimeException {
private Status status;
public LocationNotEnabledException(Status status) {
this.status = status;
}
public Status getStatus() {
return status;
}
}
}
|
In many cases, products are subjected to a quality control after their production to be able to detect possible flaws. Various methods and devices are known here in the prior art precisely for checking surfaces and connections between components, which usually use multiple cameras for the examination. For example, soldered joints are checked in that a camera records a soldered object and makes a decision in regard to the quality of the soldered joint via a corresponding analysis program on a computer. A corresponding method and a device are described in DE 10 2004 004 278 A1. In addition to the camera, a handling device is provided therein to move the soldered object in relation to the stationary camera. The handling device grips the circuit board to be evaluated and rotates it appropriately in front of the camera.
The use of a recording unit for three-dimensional images for executing line scanning in an equipping device for electronic components for automatically equipping circuit boards with electronic components is known from DE 697 10 714 T2. Displacement of the recording unit in the x and y directions over the circuit board to be equipped is provided for this purpose.
A device and a method for automatically inspecting moving surfaces is known from DE 697 03 487 T2. Three different illumination/observation channels are used for this purpose.
Furthermore, methods and devices for checking bottles having a threaded section are known from DE 696 10 925 T2, for example. In these methods, the bottles move along a high-speed line, video images being recorded of each bottle, the pixels of the particular video image being processed, and the pixels being examined in interesting areas of interest, which were previously selected, to detect thread defects in general over the circumference of the bottle.
DE 203 17 095 U1 discloses a device for recognizing flaws of an object surface in cast parts in particular, a light source for illuminating the object, a light detector for recording a beam reflected from the object surface toward the illumination beam, and an analysis unit for analyzing the image data thus received for error recognition being provided. In the analysis, the number of pixels to be examined and the size of the pixel regions to be considered are to be kept as small as possible. Among all recorded pixels, those whose brightness values deviate from a mean pixel brightness by more than a predefinable tolerance value are ascertained.
The use of a laser beam for scanning a circuit board for its examination is also known, e.g., from DE 198 83 004 T1, in which the scanning device comprises two galvanic mirrors having rotating shafts orthogonal to one another and a scanning lens.
The use of six cameras for quality checking in wafers is disclosed in DE 103 52 936 A1, two camera systems being oriented vertically from above on the upper edge zone of the wafer, two camera systems being oriented from below on the lower edge zone, and two camera systems being oriented horizontally on the lateral edge of the wafer. Defects are detected using automatic classification.
DE 101 04 355 A1 discloses a device and a method for image scanning of the surface of an object, for use in a lacquering line for determining contaminants and/or flaws of the surfaces of an object. The device comprises a recording system and a controllable transport medium, the transport medium being able to be moved linearly along a horizontal axis in relation to the recording system and the recording system being able to be moved along a second vertical axis using a travel medium. The recording system comprises a camera and a light.
The devices and methods of the prior art described above each have the disadvantage that the achievable precision of the recorded information is not especially high and the speed of the image recording is also quite low. Critical image recording in particular, as when reading out codes on circuit boards which are positioned at different points, is not possible using these devices of the prior art. |
import unittest
import numpy as np
from math import log
from functools import reduce
from hmm.distributions import Multinomial, Gaussian, GaussianMixtureModel
from hmm.logprob import LogProb, ZERO
class GaussianMixtureModelTest(unittest.TestCase):
def test_mixture(self):
gaussians = [Gaussian(np.zeros(3), np.ones(3)), Gaussian(np.ones(3) * 10, np.ones(3) * 20)]
probs = [0.5, 0.5]
mixture = GaussianMixtureModel(probs, gaussians)
x = np.ones(3) * 10
self.assertAlmostEqual(
mixture[x].prob,
log(0.5 * GaussianTest.normal(x) + 0.5 * GaussianTest.normal(x, 10, 20)),
delta=1e-8
)
def test_at(self):
gaussians = [Gaussian(np.zeros(3), np.ones(3)), Gaussian(np.ones(3) * 10, np.ones(3) * 20)]
probs = [0.5, 0.5]
mixture = GaussianMixtureModel(probs, gaussians)
x = np.ones(3) * 10
scaler = 0.5 * GaussianTest.normal(x) + 0.5 * GaussianTest.normal(x, 10, 20)
self.assertAlmostEqual(mixture.at(0, x).prob, log((0.5 * GaussianTest.normal(x)) / scaler ) , delta=1e-8)
class MultinomialTest(unittest.TestCase):
def test_multinomial(self):
multinomial = Multinomial({0:0.2, 1:0.8})
self.assertEqual(multinomial.domain, set([0, 1]))
def test_loglikelihood(self):
multinomial = Multinomial({0:0.2, 1:0.8})
self.assertAlmostEqual(multinomial[0].prob, log(0.2), delta=1e-8)
self.assertAlmostEqual(multinomial[1].prob, log(0.8), delta=1e-8)
class GaussianTest(unittest.TestCase):
@classmethod
def normal(cls, x, mu = 0, sigma = 1):
scaler = 1.0 / np.sqrt(2.0 * np.pi * sigma)
error = np.exp(-0.5 * np.square((x - mu)) / sigma)
return reduce(lambda x, y: x * y, scaler * error)
def test_gaussian(self):
gaussian = Gaussian(np.zeros(3), np.ones(3))
ll_gaussian = gaussian[np.zeros(3)]
ll_expected = LogProb.from_float(GaussianTest.normal(np.zeros(3)))
self.assertAlmostEqual(ll_gaussian.prob, ll_expected.prob, delta=1e-8)
gaussian = Gaussian(np.ones(3) * 4, np.ones(3) * 15)
ll_gaussian = gaussian[np.ones(3) * 2]
ll_expected = LogProb.from_float(GaussianTest.normal(np.ones(3) * 2, 4, 15))
self.assertAlmostEqual(ll_gaussian.prob, ll_expected.prob, delta=1e-8)
|
/**
* Sends message to the client if problems occured during compilation process.
*/
private void sendExceptionMessage(Session session, ErrorConvertibleException e) {
try {
messageTransmitter.transmitException(session, e);
} catch (IOException e1) {
logger.warn(e.toString());
}
} |
MMsINC: a large-scale chemoinformatics database MMsINC (http://mms.dsfarm.unipd.it/MMsINC/search) is a database of non-redundant, richly annotated and biomedically relevant chemical structures. A primary goal of MMsINC is to guarantee the highest quality and the uniqueness of each entry. MMsINC then adds value to these entries by including the analysis of crucial chemical properties, such as ionization and tautomerization processes, and the in silico prediction of 24 important molecular properties in the biochemical profile of each structure. MMsINC is consequently a natural input for different chemoinformatics and virtual screening applications. In addition, MMsINC supports various types of queries, including substructure queries and the novel molecular scissoring query. MMsINC is interfaced with other primary data collectors, such as PubChem, Protein Data Bank (PDB), the Food and Drug Administration database of approved drugs and ZINC. INTRODUCTION One of the most important issues in the post-proteomic era is relating protein pharmacology by ligand chemistry. In fact, there is intriguing pharmacological evidence that related drugs can recognize molecular targets that appear unrelated by many bioinformatics metrics. Drug side effects and related toxicity profiles can be considered the obvious consequence of this polypharmacology. The capability of chemically related drugs to bind proteins without sequence or structure similarity can limit attempts in bioinformatics to understand and categorize their pharmacological action. On the other hand, a chemo-centric approach to this problem compares not only the biological targets themselves, but also the chemistry involving their ligands. We have planned MMsINC with this chemo-centric approach in mind, integrating chemical structures, their chemical behaviour annotations and purpose-specific search functions, with the aim of creating a valuable tool for the interpretation of protein pharmacology (including toxicology) by ligand chemistry. (If you refer to MMsINC database and web interface for your published research, we ask that you please cite this article.) Like others, from a chemoinformatics point of view MMsINC is a chemical structure database, where chemicals are appropriately stored and annotated. However, MMsINC has as its main priorities to eliminate redundancy in its data, and to guarantee the accuracy of all chemical annotations derived from a chemical structure to avoid chemical misleading. An accurate chemical annotation is also crucial for the significance of any qualitative or quantitative chemical similarity metrics, which are a key principle in ligand/drug design and a good guide to the biological comparison of chemicals. Indeed, structure-and property-based similarities are useful tools implemented by MMsINC with the goal to establish chemical connections among all MMsINC entries and other publicly available databases (PDB, PubChem, DrugBank, ZINC and ChemDB, among others). We also apply MMsINC's structure-based annotation and similarity to classify all MMsINC entries into sets of several biologically relevant targets based on their fragment-driven similarity score. MMsINC is consequently a natural input for different chemoinformatics and virtual screening applications, and its integration with well-consolidated virtual screening tools, such as pharmacophore screening and molecular docking is in progress ( Table 1). All of MMsINC's data and functions are accessible through a user-friendly web interface that we describe later in this text. DATABASE CREATION MMsINC is a public, web-based informatics platform derived from the aggregation and multi-step treatment of 46 data sources: primarily commercial vendor catalogues, but also of publicly available repositories (e.g. NCI, http:// cactus.nci.nih.gov). For sources that periodically update their data and make them available on the Internet, we automatically download the data and synchronize MMsINC with the latest version. Complete information about all the vendors is available in the Supplementary Materials. In total, the current database contains about 4 million unique compounds, resulting from the distillation of the original set of 7.5 million entries ( Table 2). The objective of our treatment process is to generate a data set that is free of redundancy and with a chemical orthography that is as accurate as possible. In addition, we calculate the most probable tautomeric and ionic states at physiological conditions, and we produce one possible stable conformer for each molecular entry. These are the steps we follow to assemble the MMsINC data set. Step 1: first redundancy washing. Using the Molecular Operating Environment software suite (MOE, version 2007.09, http://www.chemcomp.com), we remove all originally redundant entries based on their SMILES representation, reducing the number of entries from 7.5 M to 4 M. Step 2: generation of tautomers. We apply the LigPrep 2.1 tool by Schro¨dinger LLC (http://www.schrodinger.com/) to generate the tautomers for each molecule resulting from Step 1. Many of the tautomers we generate at this stage are unstable molecules, and therefore unlikely to be encountered in practice. These will be eliminated later in our process. In the meantime, we add all the generated tautomers to our data set. Step 3: generation of ionic states. By ionic states, we refer to the most energetically favourable electrically charged states that a molecule can assume at a pH of 7.4. We calculate the most favourable ionic states for each molecular entry resulting from Step 2 by using the 'Protonate' tool in the MOE suite. The calculations add a further 250 000 MMsINC entries. Step 4: conformer selection. The three-dimensional (3D) structure of each MMsINC entry (including all tautomers and ionic states) is calculated by using Corina 3.4 (http:// www.mol-net.de). For each input structure, Corina generates possible conformers, which are variations of the molecule where the existing bonds are the same, but parts of the molecule are rotated differently along these bonds. The software then selects one of the lowest energy conformers generated. We use Corina with its default configuration. Step 5: second redundancy washing. The SMILES encoding used for the first redundancy washing is ambiguous, making it possible for some molecular redundancy to slip through Step 1. In addition, it is possible for Steps 2 and 3 to generate identical structures. We therefore perform a second, InChI-based, redundancy washing that eliminates any such duplicates and achieves our goal of structural uniqueness in the database. Step 6: unstable tautomer elimination. To eliminate the unstable tautomers generated in Step 2, we determine their energy stability with a force field-based criterion using the 3D structural data calculated in Step 4. For each 'parent' neutral molecule, we then keep in our data set only the most stable tautomers, up to a maximum of five. Instead, the less stable tautomers are discarded. The calculations leave us with $1.1 M tautomers that become part of the MMsINC data set. The result of these steps is a non-redundant data set of neutral molecular structures, as well as their stable tautomers and ionic states. Molecular descriptors For the molecules resulting from the data set building process, we calculate 24 molecular properties useful for quantitative structure-activity relationship (QSAR), diversity analysis or combinatorial library design. We assign the corresponding partial charges to all atoms of each unique conformer by using the MMFF94 force field algorithm implemented by MOE. All other descriptors summarized in Table 3 are calculated using the MOE tool 'QSAR-Descriptor'. For a detailed explanation of the descriptors, please refer to the MMsINC help pages accessible via Internet. By assays Y Y a Only for registered users. QUERYING THE DATABASE The MMsINC database is accessible to the public via our web application. It allows users to search the database by structural criteria, either by specifying a structure by one of the standard notations (SMILES, InChI, standard molecular formula), by drawing it with the Java Molecular Editor (JME, by Peter Ertl, http://www.molinspiration. com/jme/) or by identifying a structure in the MMsINC database by its MMsCode-our database's unique molecular identifier. The application also allows users to find MMsINC molecules by similarity to PDB Ligands, which in turn are selected by similarity to a query structure. In the following sections, we describe these different structure and similarity search methods supported by MMsINC. Identical structure search The identical structure search allows the user to search for molecules that match the structure specified by the query. MMsCode and InChI queries will result in at most one result, since they are unambiguous. On the other hand, SMILES and molecular formulas are ambiguous, so the search will return all molecules represented by the query found in MMsINC. Substructure search The substructure search is a query that allows the user to find molecules that contain a substructure of interest. The user specifies the substructure as a SMILES string or as an MMsCode which identifies a structure known to MMsINC. The query is executed using structural keys, which are bit vectors that indicate with a '1' the presence of a particular structural feature, and with a '0' its absence. MMsINC uses 643-bit structural keys that identify a subset of the structures in the PubChem fingerprints. If the query is specified as a SMILES string, MMsINC generates a query structural key dynamically. On the other hand, if the query is an MMsCode the system fetches the precalculated structural key associated with the identified molecule. The query key is then compared with the structural keys of the molecules in MMsINC, and the molecules that contain all the structural bits of the query are retrieved. This method provides a rapid and effective screening of the database, but its results can include false positives, since the key may not completely describe the query structure. Therefore, these preliminary results are filtered by an exact subgraph containment check using the Chemistry Development Kit (CDK) library. In some cases the preliminary key search results in too many molecules to perform the subgraph containment check on all the molecules in a reasonable amount of time. In these cases, MMsINC only performs the subgraph isomorphism check on the molecules as they are displayed to the user, indicating whether they are false positives. Currently this behaviour is applied only if the structural key search results in more than 30 000 results ( Figure 1). Molecular scissoring search The molecular scissoring search is a novel type of query based on chemically relevant molecular fragments known as scaffolds. The user provides a query structure, as in the substructure search described in the previous section. The system identifies the scaffolds present in the query structure, and asks the user to specify which ones to use for the search, and whether to perform an 'and' query searching for the molecules that contain all the selected scaffolds, or an 'or' query searching for the molecules that contain any of the selected scaffolds. The query is then sent to the database where it is evaluated with the help of appropriate indices over the scaffold data. Our current implementation of the scissoring search can in some rare cases allow the user to select scaffolds that do not exist in the query molecule. We know about this issue and are already working to resolve it. However, we do not believe it is serious enough to justify disabling the scissoring query in MMsINC. This query type is important because it allows chemists to easily and quickly search for molecules that contain particular chemical substructures that are known to be chemically and/or pharmacologically relevant (Figure 2). Similarity search The similarity search is a query type that retrieves all molecules in MMsINC that are structurally similar to query molecule. We measure the similarity between structures using the Tanimoto similarity score on the structural keys describing them. The Tanimoto similarity is defined as the ratio of the number of bits set to '1' in both keys to the number of bits set to '1' in either of the two keys. For two structural keys A, B we have: To perform a similarity search, the user enters a query structure and specifies a minimum acceptable similarity score. MMsINC compares the precalculated structural keys of its molecules with the structural key of the query and returns all the molecules with a Tanimoto similarity greater than or equal to the threshold. To accelerate Tanimoto similarity searches, we have implemented the technique by Swamidass and Baldi. Their result allows us to bound the number of ones in the target structural key required to achieve a similarity score that meets the threshold, considerably reducing the number of molecules for which we actually need to calculate the Tanimoto similarity. The fraction of the database that is pruned from the search by using this technique varies from 30% to 100%. Filtering by descriptors As a supplement to the more sophisticated structural query methods just described, MMsINC users can further filter their search results (except when performing the identical structure search) by the molecular descriptors that MMsINC provides for each molecule in the database. Displaying structural query results Results from a structural query are displayed in pages of up to 20 molecules. For each result, the system displays the structural diagram of the molecule and its MMsCode. Users can select results that interest them and place them in the MMsINC 'cart' as they browse through the search results. The cart can then be saved locally to a standard SDF file. Clicking on a molecule from the results list takes the user to the molecule report for the specific selection ( Figure 3). The report shows the user basic information about the molecule like the compound type (neutral, tautomer or ionic state), the molecular formula and its InChI and SMILES representations. The report also contains a 2D image of the molecule, and a 3D-movable rendering of molecule shown using Chemis3D (http://chemis.free.fr/ mol3d/) Java applet. In addition, the precalculated descriptors for the molecule are listed at the bottom of the report. Finally, for neutral molecules the system lists all its tautomers and ions, while for tautomers and ions the neutral state of the molecule is indicated. From the molecule's report page the user can download the structural and descriptor data to his or her own computer in several standardized formats, including SDF, PDB, XYZ, as well as 2D and 3D MOLFILE. The user can also retrieve the list of the PDB ligands that are similar to the molecule, as well as retrieving a list of structurally similar FDA-approved drugs. Finally, the report has links to the PubChem and ZINC entries for the molecule. Query by similarity to PDB ligands An alternative method to query MMsINC is via similarity to PDB ligands that have been inserted into our database. This search type has two modes of operation: SMILES and PDB. In the first mode, the user provides a molecular structure as a query, and a minimum threshold for the Tanimoto similarity measure. MMsINC finds PDB ligands with a Tanimoto similarity to the query structure greater than or equal to the specified threshold. In the second mode, the user specifies a list of up to five PDB protein identifiers. MMsINC finds all the ligands for the identified PDB proteins. In either case, MMsINC presents to the user the identified PDB ligands, with their structural diagram and the ligand code. Selecting a specific ligand takes the user to the ligand report page. The ligand report page summarizes all the MMsINC neutral molecules, tautomers, ionic states and FDAapproved drugs that are similar to the ligand, with a Tanimoto similarity score threshold specified by the user but !0.70 (Figure 4). Clicking on any of these molecules takes the user to the molecule's report page. The ligand report page also contains basic information about the ligand, such as its 2D structural diagram, its three-letter code and its name, and a table showing all the PDB proteins that interact with this ligand is displayed with a click. The PDB ligand search is based on the complete set of ligands from the PDB Chemical Component Dictionary (CCD). The MMsINC database integrates the version of the PDB CCD retrieved on January 31, 2008. However, it should be noted that not all of these PDB ligands used by the query mechanism are included in the main MMsINC data. Implementation The MMsINC system uses the PostgreSQL RDBMS (http://www.postgresql.org) to manage its data. The database is installed on a server running Linux. The system's web application has been developed in PHP, with some components written in Java. MMsINC uses the CDK to perform some of its molecular analyses. CONCLUSION The MMsINC database has been created to support a chemo-centric approach to relate protein pharmacology by ligand chemistry. The primary aims of this growing database are the accuracy of all chemical information and the elimination of redundant data. In addition, MMsINC is naturally predisposed to integrate chemical, biological and pharmacological information coming from other publicly available databases. Finally, its useful and novel molecule query functions make it a new tool for chemoinformaticians. The integration with consolidated virtual screening tools, such as pharmacophore screening and molecular docking, will be available in the next release of MMsINC. SUPPLEMENTARY DATA Supplementary Data are available at NAR Online. |
<reponame>benhunter/ctf
/* */ package org.springframework.util.xml;
/* */
/* */ import java.util.ArrayList;
/* */ import java.util.Arrays;
/* */ import java.util.Collection;
/* */ import java.util.List;
/* */ import org.springframework.lang.Nullable;
/* */ import org.springframework.util.Assert;
/* */ import org.w3c.dom.Element;
/* */ import org.w3c.dom.Node;
/* */ import org.w3c.dom.NodeList;
/* */ import org.xml.sax.ContentHandler;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract class DomUtils
/* */ {
/* */ public static List<Element> getChildElementsByTagName(Element ele, String... childEleNames) {
/* 61 */ Assert.notNull(ele, "Element must not be null");
/* 62 */ Assert.notNull(childEleNames, "Element names collection must not be null");
/* 63 */ List<String> childEleNameList = Arrays.asList(childEleNames);
/* 64 */ NodeList nl = ele.getChildNodes();
/* 65 */ List<Element> childEles = new ArrayList<>();
/* 66 */ for (int i = 0; i < nl.getLength(); i++) {
/* 67 */ Node node = nl.item(i);
/* 68 */ if (node instanceof Element && nodeNameMatch(node, childEleNameList)) {
/* 69 */ childEles.add((Element)node);
/* */ }
/* */ }
/* 72 */ return childEles;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static List<Element> getChildElementsByTagName(Element ele, String childEleName) {
/* 86 */ return getChildElementsByTagName(ele, new String[] { childEleName });
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Nullable
/* */ public static Element getChildElementByTagName(Element ele, String childEleName) {
/* 97 */ Assert.notNull(ele, "Element must not be null");
/* 98 */ Assert.notNull(childEleName, "Element name must not be null");
/* 99 */ NodeList nl = ele.getChildNodes();
/* 100 */ for (int i = 0; i < nl.getLength(); i++) {
/* 101 */ Node node = nl.item(i);
/* 102 */ if (node instanceof Element && nodeNameMatch(node, childEleName)) {
/* 103 */ return (Element)node;
/* */ }
/* */ }
/* 106 */ return null;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Nullable
/* */ public static String getChildElementValueByTagName(Element ele, String childEleName) {
/* 117 */ Element child = getChildElementByTagName(ele, childEleName);
/* 118 */ return (child != null) ? getTextValue(child) : null;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static List<Element> getChildElements(Element ele) {
/* 127 */ Assert.notNull(ele, "Element must not be null");
/* 128 */ NodeList nl = ele.getChildNodes();
/* 129 */ List<Element> childEles = new ArrayList<>();
/* 130 */ for (int i = 0; i < nl.getLength(); i++) {
/* 131 */ Node node = nl.item(i);
/* 132 */ if (node instanceof Element) {
/* 133 */ childEles.add((Element)node);
/* */ }
/* */ }
/* 136 */ return childEles;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static String getTextValue(Element valueEle) {
/* 149 */ Assert.notNull(valueEle, "Element must not be null");
/* 150 */ StringBuilder sb = new StringBuilder();
/* 151 */ NodeList nl = valueEle.getChildNodes();
/* 152 */ for (int i = 0; i < nl.getLength(); i++) {
/* 153 */ Node item = nl.item(i);
/* 154 */ if ((item instanceof org.w3c.dom.CharacterData && !(item instanceof org.w3c.dom.Comment)) || item instanceof org.w3c.dom.EntityReference) {
/* 155 */ sb.append(item.getNodeValue());
/* */ }
/* */ }
/* 158 */ return sb.toString();
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static boolean nodeNameEquals(Node node, String desiredName) {
/* 167 */ Assert.notNull(node, "Node must not be null");
/* 168 */ Assert.notNull(desiredName, "Desired name must not be null");
/* 169 */ return nodeNameMatch(node, desiredName);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static ContentHandler createContentHandler(Node node) {
/* 178 */ return new DomContentHandler(node);
/* */ }
/* */
/* */
/* */
/* */
/* */ private static boolean nodeNameMatch(Node node, String desiredName) {
/* 185 */ return (desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName()));
/* */ }
/* */
/* */
/* */
/* */
/* */ private static boolean nodeNameMatch(Node node, Collection<?> desiredNames) {
/* 192 */ return (desiredNames.contains(node.getNodeName()) || desiredNames.contains(node.getLocalName()));
/* */ }
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/util/xml/DomUtils.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
<reponame>AlexYaruki/nigiri
#include <nigiri.h>
#include <cassert>
int main() {
bool jvmAvailable = nigiri::ForeignRuntimeManager::isCategoryAvailable("jvm");
assert(jvmAvailable);
auto jvm = nigiri::ForeignRuntimeManager::createRuntime("jvm");
bool jvmStarted = jvm->start({});
assert(jvmStarted);
}
|
FANTASY FOOTBALL TIPS: Which defenders are worth signing in Gameweek 6?
It has already been a thrilling start to the new Premier League season.
And the excitement will hopefully continue this weekend, with Fulham and Watford kicking off the action in tomorrow’s lunchtime fixture.
Other match-ups include Cardiff vs Manchester City, Liverpool vs Southampton and West Ham vs Chelsea.
But which defenders should you add to your ranks in Gameweek 6?
Jurgen Klopp’s men are flying at the minute, winning five out of five in the league, and their £6m centre-back has been largely to thank.
The towering Dutchman is a true defensive presence for the Reds and will be expected to tame Southampton at Anfield on Saturday.
Up against lower-level opposition at home, the Foxes rarely ship in many at the back when playing at the King Power.
Their £5.1m right-back - who has scored 22 points so far - is a good option ahead of their home clash with struggling Huddersfield, then.
The £5.1m man seems to be Jose Mourinho’s first-choice at left-back and has recovered from a nasty injury picked up on international duty for England.
Would be a smart addition to your side with Wolves in store at Old Trafford on Saturday.
A slight gamble amid Burnley’s poor form, yet Sean Dyche’s men are typically solid at home and their opponents on Saturday, Bournemouth, tend to struggle when on the road.
The Clarets’ £5m centre-back could very well keep a clean sheet in that fixture, and could get on the scoresheet after netting two in their first five games.
Another Liverpool centre-half worth signing this week is £5.1m Gomez, who has been outstanding for the Reds so far.
He has already recorded 24 points in the campaign and is likely to add to that tally at home to Southampton on Saturday. |
#include <bits/stdc++.h>
using namespace std;
int max(int a,int b)
{
return a>b ?a:b;
}
int main()
{
int a,b,c;
printf("enter values for a,b and c\n");
scanf("%d%d%d",&a,&b,&c);
printf("%d\n",max(a,max(b,c)));
return 0;
} |
<filename>fycli/skeleton/cli.py
#!/usr/bin/env python
import sys
from dataclasses import dataclass, field
from textwrap import dedent
from ..argparser import ExtendedHelpArgumentParser, subcommand_exists
from ..environment.environment import Environment
from .skeleton import Skeleton
@dataclass
class SkeletonCLI:
trace: bool
command: str
environment: Environment = field(init=False)
def __post_init__(self):
parser = ExtendedHelpArgumentParser(
usage=dedent(
"""
fy deploy <command> [-h|--help]
commands:
apply apply skeleton to current directory
clean remove skeleton from current directory
refresh run clean then apply
"""
),
)
parser.add_argument("command", help="subcommand to run")
args = parser.parse_args(sys.argv[2:3])
subcommand = args.command
subcommand_exists(self, parser, subcommand)
self.environment = Environment()
self.skeleton = Skeleton(environment=self.environment)
getattr(self, subcommand)()
def apply(self):
parser = ExtendedHelpArgumentParser(usage="\n fy skeleton plan [-h|--help]")
parser.parse_args(sys.argv[3:4])
print("\n==> skeleton apply\n")
self.skeleton.apply()
def clean(self):
parser = ExtendedHelpArgumentParser(usage="\n fy skeleton clean [-h|--help]")
parser.parse_args(sys.argv[3:4])
print("\n==> skeleton clean\n")
self.skeleton.clean()
def refresh(self):
parser = ExtendedHelpArgumentParser(usage="\n fy skeleton refresh [-h|--help]")
parser.parse_args(sys.argv[3:4])
self.clean()
self.apply()
|
#!/usr/bin/env python
# -*- coding: latin-1 -*-
# TestVectors.py
# Written by Andr Carrington
#
# Copyright 2022 University of Ottawa
#
# 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.
# Uses test vectors from Fawcett[1], Hilden[2], Carrington et al[3]
#
# References:
# 1. Fawcett T. An Introduction to ROC Analysis, Pattern
# Recognition Letters, 2005.
# 2. Hilden J. The Area under the ROC Curve and Its Competitors,
# Medical Decision Making, 1991.
# 3. Carrington AM, Fieguth P, Qazi H, Holzinger A, Chen H, Mayr F
# Manuel D. A new concordant partial AUC and partial c statistic
# for imbalanced data in the evaluation of machine learning
# algorithms. BMC Medical Informatics and Decision Making, 2020.
#
import numpy as np
def getNumberOfTestVectors():
testNum = 1
while True:
scores, labels, pAUCranges, groupAxis, descr = getTestVector(testNum, noError=True)
if len(scores) == 0:
break
#endif
testNum = testNum + 1
#endwhile
return testNum-1
#enddef
def getTestVector(testNum, noError=False):
# all test groups are defined along FPR as the groupAxis, unless otherwise specified
groupAxis = 'FPR'
if testNum == 1: # old testNum 1
descr = 'Test 1. Fawcett Figure 3 data (balanced classes) with partial curve boundaries ' + \
'aligned with instances on step verticals'
scores = np.array([ 0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38,
0.37, 0.36, 0.35, 0.34, 0.33, 0.30, 0.1])
labels = np.array([ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1,
0, 0, 0, 1, 0, 1, 0])
groups = [[0.0, 0.3], [0.3, 0.5], [0.5, 1.0]]
elif testNum == 2: # old testNum 2 (scores made proper for reference, no effect on measurement)
descr = 'Test 2. Carrington Figure 7 data (with a 1:3 P:N class imbalance) with partial curve ' + \
'boundaries aligned with instances.'
# This has the same scores as Carrington Figure 8, and scores similar to Fawcett Figure 3,
# but the labels are altered for class imbalance
scores = [ 0.95, 0.9, 0.8, 0.7, 0.65, 0.64, 0.63, 0.62, 0.61, 0.60, 0.5, 0.49, 0.48, 0.47,
0.46, 0.45, 0.44, 0.43, 0.40, 0.2]
labels = [ 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0]
groups = [[0.0, 0.2], [0.2, 0.4], [0.4, 1.0]]
elif testNum == 3: # no old testNum equivalent
descr = 'Test 3. Hilden Figure 2a data with scores reversed to follow the normal convention'
# scores (0, 1, 2, 3) high for negative were changed to (3, 2, 1, 0) respectively, high for positive
scores = [ 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
labels = [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 4: # no old testNum equivalent
descr = 'Test 4. Hilden Figure 2b data with scores reversed to follow the normal convention'
# scores (0, 1, 2, 3) high for negative were changed to (3, 2, 1, 0) respectively, high for positive
scores = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0]
labels = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 5: # old testNum 5 (scores made proper for reference, no effect on measurement)
descr = 'Test 5. Hilden Figure 2c data with scores reversed to follow the normal convention'
# scores (0, 1, 2, 3) high for negative were changed to (3, 2, 1, 0) respectively, high for positive
# histogram counts were divided by 5, so that (50, 35, 15) became (10, 7, 3)
scores = [ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3]
labels = [ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 6: # old testNum 6
descr = 'Test 6. Fawcett Figure 3 data with partial curve boundaries aligned with instances ' + \
'on step horizontals'
scores = [ 0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38, 0.37,
0.36, 0.35, 0.34, 0.33, 0.30, 0.1 ]
labels = [ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0,
0, 0, 1, 0, 1, 0 ]
groups = [[0.0, 0.2], [0.2, 0.6], [0.6, 1.0]]
elif testNum == 7: # old testNum 7
descr = 'Test 7. Fawcett Figure 3 data with partial curve boundaries not aligned with '\
'instances, requiring interpolation'
scores = [ 0.9, 0.8, 0.7, 0.6, 0.55, 0.54, 0.53, 0.52, 0.51, 0.505, 0.4, 0.39, 0.38, 0.37,
0.36, 0.35, 0.34, 0.33, 0.30, 0.1 ]
labels = [ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0,
0, 0, 1, 0, 1, 0]
groups = [[0.0, 0.17], [0.17, 0.52], [0.52, 1.0]]
elif testNum == 8: # old testNum 8
descr = 'Test 8. Carrington Figure 4 data with the same shape and measure as Fawcett Figure 3 ' + \
'but with different scores'
scores = [ 0.95, 0.9, 0.8, 0.7, 0.65, 0.64, 0.63, 0.62, 0.61, 0.60, 0.5, 0.49, 0.48, 0.47,
0.46, 0.45, 0.44, 0.43, 0.40, 0.2]
labels = [ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0,
0, 0, 1, 0, 1, 0]
groups = [[0.0, 0.17], [0.17, 0.52], [0.52, 1.0]]
#groups = [[0.0, 0.3], [0.3, 0.5], [0.5, 1.0]]
#groups = [[0.8, 1.0]]
#groups = [[0.4, 0.6]]
#endif
elif testNum == 9: # old testNum 9
descr = 'Test 9. Carrington Figure 7 data: same instances as Carrington Figure 4, but different ' + \
'labels'
scores = [ 0.95, 0.9, 0.8, 0.7, 0.65, 0.64, 0.63, 0.62, 0.61, 0.60, 0.5, 0.49, 0.48, 0.47,
0.46, 0.45, 0.44, 0.43, 0.40, 0.2]
labels = [ 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0]
groups = [[0.0, 0.17], [0.17, 0.52], [0.52, 1.0]]
elif testNum == 10: # old testNum 3
descr = 'Test 10. Carrington Figure 8 data'
scores = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
labels = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 11: # old testNum 4
descr = 'Test 11. A classifier that does worse than "continuous" chance'
scores = [0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6]
labels = [ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 12:
descr = 'Test 12. Simplest test'
scores = [0.8, 0.7, 0.7, 0.6]
labels = [ 1, 1, 0, 0]
groups = [[0.0, 0.25], [0.25, 0.5], [0.5, 1.0]]
elif testNum == 13:
descr = 'Test 13. A simple test'
scores = [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.7, 0.7, 0.7]
labels = [ 1, 1, 0, 1, 1, 0, 1, 1, 0]
groups = [[0.0, 0.25], [0.25, 0.5], [0.5, 1.0]]
elif testNum == 14: # previously 3b
descr = 'Test 14.(3b) A variation of Test 3: Hilden Figure 2a data with scores reversed to follow the normal convention'
# scores (0, 1, 2, 3) high for negative were changed to (3, 2, 1, 0) respectively, high for positive
scores = [ 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # 3b
labels = [ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 3b
# groups = [[0.0, 0.5], [0.5, 1.0]]
groups = [[0.0, 0.2], [0.2, 0.4], [0.4, 1.0]]
elif testNum == 15: # previously 3c
descr = 'Test 15.(3c) A variation of Test 3: Hilden Figure 2a data with scores reversed to follow the normal convention'
# scores (0, 1, 2, 3) high for negative were changed to (3, 2, 1, 0) respectively, high for positive
scores = [ 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] # 3c
labels = [ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 3c
#groups = [[0.0, 0.5], [0.5, 1.0]]
groups = [[0.0, 0.2], [0.2, 0.4], [0.4, 1.0]]
elif testNum == 16: # previously 3d
descr = 'Test 16.(3d) A variation of Test 3: Hilden Figure 2a data with scores reversed to follow the normal convention'
scores = [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1] # 3d
labels = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 3d
groups = [[0.0, 0.2], [0.2, 0.5], [0.5, 1.0]]
elif testNum == 17:
descr = 'Test 17. Hypothesis test re smaller group AUCnn_i'
# creating ROC: (0,0), (0.33,0.6), (0.66,0.9), (1,1)
# x ascends by thirds - do 9 actual negatives
# y ascends by 0.6, 0.3, 0.1 - do 10 actual positives
# 3 sets of ties with scores: h=0.8, m=0.5, l=0.2
h=0.8; m=0.5; l=0.2
scores = [h, h, h, h, h, h, h, h, h, m, m, m, m, m, m, l, l, l, l].copy()
labels = [1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0]
groups = [[0.0, 1.0/3.0], [1.0/3.0, 2.0/3.0], [2.0/3.0, 1.0]]
elif testNum == 18:
descr = 'Test 18. Hypothesis test flipped re smaller group AUCnn_i'
# similar to test 17 except labels and scores flipped
# creating ROC: (0,0), (0.33,0.1), (0.66,0.4), (1,1)
h=0.8; m=0.5; l=0.2
scores = [l, l, l, l, l, l, l, l, l, m, m, m, m, m, m, h, h, h, h].copy()
labels = [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1]
groups = [[0.0, 1.0/3.0], [1.0/3.0, 2.0/3.0], [2.0/3.0, 1.0]]
elif testNum == 19:
descr = 'Test 19. Testing'
h = 0.8; m = 0.5; l = 0.2
scores = [h, h, h, h, h, m, m, m, m, m, m, m, m, l, l, l ].copy()
labels = [0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1 ]
groups = [[0.0, 1.0 / 3.0], [1.0 / 3.0, 2.0 / 3.0], [2.0 / 3.0, 1.0]]
elif testNum == 20:
descr = 'Test 20. Example output from a decision tree'
h = 1; l = 0
scores = [h, h, h, h, h, l, l, l, l, l, l, l, l, l, l, l].copy()
labels = [0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1]
groups = [[0.0, 1.0 / 3.0], [1.0 / 3.0, 2.0 / 3.0], [2.0 / 3.0, 1.0]]
else:
if noError:
scores, labels, groups, groupAxis, descr = [[], [], [], '', '']
else:
raise ValueError('Not a valid built-in test number.')
#endif
#endif
return scores, labels, groups, groupAxis, descr
#enddef |
def send_email(subject, text, to_addrs, quiet=True):
e = EMail(subject, text, to_addrs)
if e.app.cfg['log_email_only']:
return e.log()
if quiet:
return e.send_quiet()
return e.send() |
Lnc-RNA UCA1 Promotes TGF--Mediated Epithelial-Mesenchymal Transition via Inhibiting miR-204 in Gastric Cancer Cells (lncRNA) Two gastric cancer cell lines are chosen, MNK45 and SGC-7901. Transforming growth factor- (TGF-) is used to promote epithelial-mesenchymal transition (EMT) by using cancer cell invasion assay. The transmembrane cell quantities are counted and ZEB1, slug, vimentine and E-Cadherin gene expression levels are measured by quantitative PCR assay. siRNA of UCA1 and miR-204 are used to conrm crosstalk among TGF-, UCA1 and miR-204. Introduction Cancer is basically a genetic modi cation disease resulting in aberrant cellular homeostasis and successive growth. The discovery of protein-coding genetic mutations established our principles of understanding how these exome aberrances drove pathogenesis of tumor. However, only protein-coding sequence mutations cannot solely explain why and how cancer is generated and developed. Since the coding sequences account for only 2% of the whole genome, it is reasonable to assume that the noncoding sequences play major roles on the cancer phenotypes. All genes in human are transcribed into RNA, which dominantly are noncoding RNAs. Long noncoding RNAs (lncRNA) are transcripts > 200 nucleotides with no protein translation potentials. It is recognized that lncRNAs are delicately regulated and restricted to certain cell types. The biological functions of majority of the lncRNAs remain un-discovered. MicroRNAs (miRNAs) bind to 3'-untranslated region (3'UTR) of mRNAs of target genes, resulting in the degradation of mRNAs or the suppression of translation process. The involvement of miRNAs in regulating tumors malignancies had been reported by plenty of researchers. Gastric cancer is the most common subtype of gastrointestinal cancer worldwide. It is the fth most common type of cancer and the third in mortality comparing with all other cancer types. According to report in 2015 of National Central Cancer Registry of China (NCCRC), gastric cancer is the second both in incidence rate and mortality in China. The ve-years survival rate of gastric cancer is below 30%. Patients with gastric cancer are often diagnosed at the intermediate or even terminal stages of the disease with liver, lymph nodes or lung metastasis, which hinders e ciency of the treatment and contributes to the low ve-years survival rates. The transforming growth factor- (TGF-) is the key factor in the gastric tumor micro-environment. By stimulating vascular endothelial growth factor C (VEGF-c), TGF- signaling pathway stimulates lymph-angiogenesis, increases invasion ability of the tumor cells and promotes epithelial-mesenchymal transition (EMT). Slug, ZEB1, Vimentine, and E-cadherin are proved to be related with the EMT process. To understand how the TGF- signaling pathway delicately regulates metastasis of gastric cancer would de nitely provide strong evidence to support excise therapy in clinic. LncRNA urothelial cancer associated 1 (UCA1) is highly expressed in variant tumor cells, such as bladder cancer and oral squamous cell carcinoma, and associated with bad prognosis of the diseases. But its impact on gastric cancer is unclear. As a possible target of UCA1, recent studies have shown that miR-204 expressed signi cantly low in several tumors including colorectal cancer. However, the potential role of miR-204 in gastric cancer is largely unknown. The purpose of this study is to investigate whether and how lncRNA UCA1 and miR-204 participate in the TGF- stimulated EMT in two gastric cancer cell lines. Cell Culture Gastric cancer cell lines, MNK-45 and SGC-7901 were purchased from ATCC. Cells are cultured in DMEM medium with 10% fetal bovine serum, 100U/ml penicillin, 100g/ml streptomycin, at 37°C incubator with 5% carbon dioxide. Cell expansion and splitting process is restrictedly performed according to the manufacture's protocol. Tumor Cell Invasion Assay When the culture ask is 70-80% con uent, the gastric cancer cells are cultured with DMEM medium without fetal bovine serum overnight. Recombinant human TGF-1 is purchased from PeproTech (Cat:100-21c). 10ng/ml TGF-1 is added into the cell culture medium and incubated for 48 hours. After being digested with trypsin, the gastric cells are calculated and put in ice for further usage. 600l DMEM medium with 15% fetal bovine serum is added into the bottome of the transwells, subsequently cell suspension is added into the membrane at 2x10 5 concentration. Incubate at 37°C incubator overnight. After getting rid of the oating cells at the bottom of the transwells, the cells adherent to the bottom of transwells are xed with 50% methanol for 15 minutes, and washed with PBS solution for three times. Then stained with crystal violet solution for 30 minutes. After being air-dryed, the transwells are observed and six zones are chosen randomly under microscope. Quantitative RT-PCR Trizol is used to extract total RNA from the gastric cancer cells according to standard protocol. cDNA is synthesized by using PrimeScript RT kit from Takara Statistics Analysis Average and standard deviation data were analyzed in Excel. T test is used for signi cance study. P < 0.05 considered as signi cance. Univariate analysis of variance is used by using SPSS 10.0. TGF- enhances gastric tumor cell invasion After being incubated with 10ng/ml TGF-, Transwell-Matrigeal trans-membrane assay is performed, and subsequently cells stayed at the bottom of the transwells are stained with crystal violet. Multiple negative controls are used. Six random visions under microscope are took into account, and the numbers of stained cells are calculated and compared. As shown in Fig. 1, for the MNK-45 and SGC-7901 cell lines, there are both signi cant more cells went through membrane once treated with TGF- than non-treated cells (p < 0.05). TGF- treatment promotes EMT We use the MNK-45 cell line to study how the EMT related genes change their expression levels due to its signi cant enhanced transmission ability by TGF- treatment. After being treated with TGF- for 24 hours, in the MNK-45 cells, the slug, ZEB1, vimentine, and E-Cadeherin gene expression levels are 3.93±0.35, 5.10±0.17, 3.67±0.21, 0.50±0.10 times comparing with the negative control cells (P < 0.05) (Fig. 2). By using quantitative PCR assay, we demonstrate that TGF- treatment can increase slug, ZEB1 and vimentine gene levels and decrease E-Cadherin expression levels signi cantly (P < 0.05). Blockage of UCA1 inhibits TGF- induced activation of EMT To analyze whether lncRNA UCA1 interferes with the TGF- signaling pathway, several siRNAs of UCA1 (si-UCA1) and negative control siRNAs of UCA1 (NC-si-UCA1) are tested upon MNK-45 cells. The si-UCA1 chosen to use in the subsequent experiments can block 70% of UCA1 expression (0.30±0.05). The NC-si-UCA1 does not interfere with UCA1 expression at all (data not shown). Discussion In this study, we demonstrated that TGF- can signi cantly increase gastric cancer cell transmission ability and remarkably enhance EMT related gene expression levels. This result is correlated with previous Recent studies demonstrated aberrant lncRNA UCA1 expression existed in variant carcinomas including bladder cancer, gastrointestinal tumor, neural blastoma and breast cancer. UCA1 attracts miRNA in a competitive way, so called "sponge", in order to free target genes of the miRNA to perform their functions. Interestingly, UCA1 plays through variant pathways. In renal cancer, UCA1 plays a critical regulatory role in proliferation and progression of renal cancer cells by interacting with miR-182-5p/DLL4 axis. In gastric cancer, UCA1 works with miR-7, 495, 498 to promote tumor-genesis. In MNK45 gastric cancer cell line, we demonstrated that UCA1 sponges miR-204 to free its target gene ZEB1 (Fig. 6). It is still early to assume that UCA1 works in a tissue speci c way to promote metastasis and thoroughly studies are required to nd out its fundamental mechanisms. Interconversion between epithelial and mesenchymal is highly conserved process during embryogenesis. Epithelial-mesenchymal transition (EMT) is regulated by environmental signals, such as Wnt, TGF-, FGF family members and intracellular signaling pathways. EMT related transcription factors (EMT-TF) include zinc nger proteins (e.g., SNAI1, SNAI2), helix-loop-helix transcription factors (e.g., E47), zinc nger and homeodomain protein ZEB1 (also called TCF8 or DeltaEF1) and ZEB2 (also called SIP1). ZEB1/2 may trigger the repression of epithelial genes, such as E-Cadherin, to damage adhesion and tight junctions and the stimulation of mesenchymal factors, such as vimentine, to facilitate transdifferentiation process. In this study, ZEB1 gene expression level is signi cantly enhanced and E-Cadherin expression level is nearly at the half level after TGF- treatment in gastric cancer cells. This suggests that TGF- de nitely promotes EMT process. Besides ZEB1, vimentine, slug and E-Cadherin, other EMT related genes will be tested in the subsequent studies. Page 7/9 In this study, we demonstrated the cross-talk among TGF-, lnc-UCA1 and miR-204 in gastric cancer cells as shown in Fig. 6. miR-204 inhibits TGF- function, and UCA1 sponges miR-204 to stop its functions. We reasonably suspect that miR-204 expression level could be measured and used to predict prognosis of the gastric cancer. Meanwhile, UCA1 inhibitors might be considered as potential genetic medical drugs, although further and wider explorations are required in the future. Declarations Ethics approval and consent to participate Authors' contributions Dr. Ding-Fu Zhong did most of the lab works. Dr. Dan Chen and Dr. Ying Nie analyzed the data and did the microscope job. Dr. Hong-Ying Zhang and Dr. Yi Yang discussed with Dr. Ding-Fu Zhong and provided very useful suggestions. Dr. Li-Yu Hu wrote the manuscript and the mastermind behind all the lab works. |
A Prospective Study of the Headache Phase in 32 Migraine with Aura Patients For an accurate description of the clinical features of the headache phase in migraine with aura (MA) attacks, we thought it useful to conduct a prospective study of consecutively referred MA patients seeking treatment at the Headache Centre of the University of Parma Institute of Neurology. The case series included 32 patients (22 women and 10 men). At the time of the first visit, each patient was given a questionnaire to be filled in at the next MA attack. Six patients (four women and two men) had attacks of migraine aura without headache. Among the remaining 26 patients (18 women and eight men), the duration of the headache phase was < 24 h in 23 (88.5%); pain location was bilateral in 14 (53.8%) and unilateral in 12, but occurring on the opposite side to aura only in one patient; pain intensity was mild or moderate in 13 (50.0%). The headache phase of MA appeared to have clinical features that differed widely from patient to patient and was consistent with the International Headache Society diagnostic criteria for migraine without aura in 26.9% of patients and for tension-type headache (TTH) in 23.1%. |
Burns and injuries resulting from the use of gel candles. Scented gel candles are common decorative household items composed of gelled mineral oil, fragrances, and dye. Like traditional wax candles, they have an open flame. Because of defective design, there have been several burns and injuries caused by these products. Here we report our experience with a scald burn from a gel candle and describe 34 additional injuries attributed to gel candles previously unreported in the medical literature. |
If you're a regular Silicon Valley-area commuter or coffee shop patron, chances are you've seen more iPads than the rest of the country. The Nielsen Company's profile of the typical iPad user--aged 25 to 36 and making upwards of $75,000 a year--reads like the average Bay Area tech player's rap sheet. As the holiday season approaches and wallets start to open wider than usual, this affluent demographic won't have to look hard to find upscale cases for their toys.
From now until the end of the year, a slew of the big labels in designer fashion and accessories are rolling out their offerings for iPad cases. Burberry's signature plaid Haymarket check cover shipped Oct. 1. Orbino's offering, currently available for pre-order, comes in Cognac Ostrich, Deep Red and yes, even a Brown Crocodile. Tod's touts the counterpart to Orbino's crocodile with a $4,900 alligator skin case that comes in tan, dark brown and an ostentatious blue.
"Think of it as the perfect blank canvas with which a flashy and overly expensive case can be designed for," says Lauren Pazzaneze, owner of the fashion and design blog JunkyardArts.com.
A blank canvas, perhaps. But one that's winning awards. For the past 10 years Apple has dominated the IDEA design awards, receiving recognition for its work on the iPod, iMac and iPhone, among many others. Jonathan Ive, the principle designer of numerous Apple devices, including the iPad, was awarded an honorary Ph.D. from the Rhode Island School of Design, and was named the "world's smartest designer" in 2010 by Fortune.
During Fashion Week in late September, Burberry hosted a tie-in to its runway show, inviting customers to watch the event in one of the company's 25 flagship stores. After watching the show, customers were given iPads to shop for the items they just saw on the live stream, marrying the haute couture runway experience with the use of tech-forward items. Burberry--as well as Gucci and Tod's--offers an iPad app.
"When you see all these designers coming out with tech products at the same time," says Pazzaneze, "it's a matter of everyone realizing that techies have money."
Luxury retailers in the hospitality industry seem to want in on the tech money too. The upscale InterContinental Hotels Group recently equipped its concierge teams in New York, London, Atlanta and Hong Kong with iPads, wearing tech-forwardness on its multinational sleeve. It's a move to attract the consumer who wants to feel like they're e-savvy (whether they actually are or not), while engaging those that wouldn't otherwise be familiar with tablet culture (i.e., those outside Silicon Valley).
"We put menu pages from different restaurants in front of our client's faces," says Dominic Alfonzetti, chief concierge at InterContinental New York Barclay hotel. "Everybody loves a new toy, and they all love this."
Of course the market has yet to see whether venturing into unknown territory, like luxury iPad cases, will pan out. In this respect, popular designer philosophy seems to resemble Karl Lagerfeld's recent tweet: "I only go to places if I have a professional reason. I'm not a tourist." |
Food Fortification Using Spray-Dried Emulsions of Fish Oil Produced with Maltodextrin, Plant and Whey ProteinsEffect on Sensory Perception, Volatiles and Storage Stability Fortification of foods with fish oil rich in n3 fatty acids improves the nutritional value, but creates challenges with flavor and oxidative stability, especially during storage. Pea, soy, and sunflower proteins were used in combination with whey protein or maltodextrin to encapsulate fish oil by spray-drying. The use of whey protein compared with maltodextrin as wall material improved oxidative stability of spray-dried emulsions, although the use of whey protein increased the number of observed cracks in outer shell of the particles. Non- and encapsulated oil were used in cookies and chocolates to examine flavor characteristics by generic descriptive analysis and volatile products by solid-phase microextraction with gas chromatography-mass spectrometry. A long-term storage test at room temperature was conducted to evaluate the oxidative stability of the food models. Fortification changed the texture, odor, and flavor of the food models with fishy flavor being the most impactful attribute. For both food models, use of pea protein with maltodextrin resembled attributes of control the best. Fortification and encapsulation material also affected volatile profiles of food models. Both non-encapsulated oil and whey protein formulations performed well in regard to oxidative stability for both food models. Generally, the cookie model showed more potential for fortification than the chocolate one. Introduction Fish oil in the form of either fatty fish or oil supplement is the main source of n-3 long chain polyunsaturated fatty acids (PUFAs), most importantly eicosapentaenoic acid (20:5n-3, EPA) and docosahexaenoic acid (22:6n-3, DHA), in the human diet. These n-3 PUFAs play an important role in the cardiovascular system and inflammatory balance and are essential for normal brain and eye development. Although the health benefits of n-3 PUFAs are well established, their dietary intake is not at the recommended level. The low intake of long chain PUFAs relates to the fishy smell and flavor of most supplements. n-3-enriched foods are an alternative to fish and fish oil supplements. In Europe, foods with 0.3 g alpha-linolenic acid per 100 g and per 100 kcal, or at least 40 mg of the sum of EPA or DHA per 100 g and per 100 kcal can be claimed as a source of n-3 fatty acids. According to the same regulation, a claim that a food is high in n-3 fatty acids can be made when the product contains at least 0.6 g alpha-linolenic acid per 100 g and per 100 kcal, or at least 80 mg of the sum of EPA or DHA per 100 g and per 100 kcal. However, fortification with fish oil is challenging as EPA and DHA are prone to lipid oxidation. Lipid oxidation decreases the nutritional and sensory quality, and can even result in the formation of potentially toxic compounds. Further, the natural flavor and polarity of fish oil may place limits on the potential product types that can be fortified. Microencapsulation of oil could address these challenges. The most common microencapsulation technique used for fish oil is spray drying. In the resulting powder, the encapsulated core is protected from oxygen and pro-oxidants by a wall material commonly consisting of carbohydrates and/or proteins, and thus improved oxidative stability is achieved. Microencapsulation can mask fishy flavor, and dry powder is more convenient in industrial processes than liquid oil, allowing a wider selection of foods for fortification. The challenges and opportunities for n-3 food fortification have been previously reviewed, in general by Ganesh and Hettiarachchy and focusing on fortification by fish oil by Jamshidi et al.. Although previous studies exist on microencapsulation of fish oils, incorporation of the capsules into foods has been scarcely studied. Biopolymers used as wall materials may dissolve in liquid and semi-liquid foods, turning them into fish oil emulsion, which no longer provides the oil protection from pro-oxidants. Thus, the main target foods for encapsulated fish oil are solid foods like bars, infant powder formulas, and baked products. For example, Jeyakumari et al. incorporated fish oil or fish oil microencapsulates in cookies. While microencapsulation improved the oxidative stability of fish oil in the cookies determined by the thiobarbituric acid (TBA) value, sensory evaluations showed a negative impact on the texture and taste of several formulations. However, plant proteins were not used in this study as part of wall material formulation. Finding the encapsulation formulation and food matrix combination that provides both sensory quality as well as oxidative stability is likely to be the main challenge in fortification. The hypothesis of this study was that by using plant proteins (pea, soy, and sunflower proteins) in combination with other proteins or carbohydrates in encapsulation by spray drying, the fish oil flavor could be masked and oxidative stability of fish oil improved in fortified foods. Therefore, the main objectives were to develop fortified food models (shortbread cookies and dark chocolate) containing encapsulated fish oil using different protein/carbohydrate or protein/protein combinations as wall material and to investigate the sensory perception and volatile profiles of the developed food concepts. Shortbread cookies and dark chocolate were chosen as food models based on their low water activity and long shelf-life. Prior to addition to the food models, the surface and total oil content of the spray-dried emulsions (SDEMs) were determined gravimetrically and fatty acid composition was analyzed using gas chromatography (GC) with a flame ionization detector (FID). Further, oxidative stability index (OSI) and volatile secondary oxidation products (VSOPs) using headspace solid-phase microextraction (HS-SPME) coupled GC with mass spectrometer (MS) were analyzed to characterize oxidative stability of SDEMs. Only the most promising formulations were used in both food models in different concentrations, analyzed by HS-SPME-GC-MS and evaluated by a trained sensory panel. Finally, a longterm storage test at room temperature was conducted to evaluate the oxidative stability based on VSOPs of the food models. Characterization of SDEMs All plant protein containing SDEMs with whey protein concentrate (W) had a higher total oil content than corresponding emulsions containing maltodextrin (M). The total oil content, ranging from 38.62% to 44.18%, was lower than predicted based on the composition for the emulsions, suggesting small losses of oil during processing and incomplete water evaporation during spray-drying, especially in samples containing M (Table 1). M can absorb more water than W because it forms an outer layer on the droplet, which alters the surface stickiness of particles due to the transition into a glassy state. W, combined with sunflower protein (SF) and pea protein (P), had lower content of surface oil (SFW 13.39% and PW 15.90%) compared with samples with M (SFM 15.87% and PM 17.35%). In the soy protein (S)-containing sample the surface oil content was comparable. Wang et al. reported that the whey protein isolate content in the emulsion increased the oil retention principally by reducing the time to form a semi-permeable crust at the droplet-air interface during spray-drying, making it difficult for the oil to diffuse to the particle surface during drying. Encapsulation efficiency (EE) values were relatively high for powders with such high oil content (57.27% (PM) to 69.64% (SFW)). High oil-loading microcapsules (1:1) have generally low EE, affecting the higher surface oil content of the particles. The findings are in agreement with those of Di Giorgio et al., where EE ranged from 57.73% (1:1 = protein:oil mass ratio) to 88.74% (4:1 = protein:oil mass ratio). The fatty acid composition of SDEMs was comparable with that of non-encapsulated fish oil (FO) ( Table 2). The DHA content ranged from 14.29% to 14.57% while the EPA content ranged from 9.77% to 10.22% in SDEMs, respectively. The content in the native oil was slightly higher with 14.69% and 10.34% of DHA and EPA, respectively. However, these differences were not significant. Castejn et al. confirmed that encapsulation by spray drying did not affect omega-3 fatty acid profile of lipids extracted from oilseeds and microalgae. Table 2. Fatty acid composition (% of total fatty acids) of non-encapsulated and encapsulated fish oil, including sums of saturated fatty acids ( SFA), monounsaturated fatty acids ( MUFA), polyunsaturated fatty acids ( PUFA), and n-3 and n-6 fatty acids. Generally, scanning electron microscopy (SEM) images showed typical well-separated particles similar to irregular-shaped beads ( Figure 1). However, agglomerates were visible in the PW sample. The samples were not uniform in size, which can be explained by the high oil:coating material ratio. Rodea-Gonzlez et al. reported that as the core to wall material ratio decreased, more uniformly sized microcapsules were formed. Pea protein containing powders consisted of a large number of small particles ( Figure 1) with the greatest resemblance to the MW sample. Gharsallaoui et al. presented SEM images of powders of oil obtained by using 0.25% pea protein isolate and 11% starch hydrolysates with various dextrose equivalents (DE) as wall materials. In their study, microcapsules obtained from DE-6 were dented and partially disrupted, while powders obtained from DE-19 and DE-28 were slightly circular and uniform, showing minimum cracks and dents on the surface. The particles of the powders containing M were smoother and more spherical than those containing W. The highest number of cracks was found in the SFW, SW, and PW samples. All SDEMs were more stable than FO (OSI 1.36 h) ( Table 1) of which PW was the most stable (OSI 15.7 h). Although amino acids with the highest antioxidant capacity, i.e., the sulfur-containing amino acids (cysteine, methionine, and tryptophan) are not abundant in pea proteins, they contain comparably high amounts of hydrophobic and aromatic amino acids, such as proline, valine, leucine, isoleucine, and phenylalanine, which also All SDEMs were more stable than FO (OSI 1.36 h) ( Table 1) of which PW was the most stable (OSI 15.7 h). Although amino acids with the highest antioxidant capacity, i.e., the sulfur-containing amino acids (cysteine, methionine, and tryptophan) are not abundant in pea proteins, they contain comparably high amounts of hydrophobic and aromatic amino acids, such as proline, valine, leucine, isoleucine, and phenylalanine, which also possess antioxidant activity. Generally, the majority of antioxidative amino acids are inaccessible in unmodified pea protein due to association and molecular tertiary structure. However, enzymatic hydrolysis may expose these amino acids. There was no correlation between OSI and surface lipid content. Volatile profiles of SDEMs were analyzed, and VSOPs were selected based on abundance and origin. Selected VSOPs were propanal, 2-ethylfuran, hexanal, 2-hexenal (E), 2-pentylfuran, 3,5-octadien-2-one (E,Z/E,E), and nonanal, which are known oxidation products of fish oil. The total peak area of selected VSOPs was in line with OSI (Table 1) with PW having the lowest formation of selected VSOPs and the highest OSI, and SFM having the highest formation of selected VSOPs and the lowest OSI. It can be concluded that the use of W compared with M as wall material improved oxidative stability of SDEMs, although the use of W increased the number of observed cracks in SDEMs. SDEMs with OSI over 10 h and a total peak area of selected VSOPs under 30 10 5 counts per s ( Table 1) were regarded as stable enough for food processing. Although, failing the quality parameters set, SM was included in order to study the effect of the use of M vs W in wall material composition during fortification. Therefore, for the fortification, MW, SW, PW, SM, and PM and FO were used. Further, a control (C) without any addition of fish oil was studied to determine the matrix effects of the food models. Performance of the Assessors and the Panel The panel agreed on fishy flavor in both food models. A high agreement was also attained on crumbliness and melting texture in chocolates, and on fishy odor and flavor intensity in cookies. The odor intensity and bitter taste were the most difficult for the panel. The panel also had some disagreement on sweetness and oily taste in shortbread cookies and on aftertaste in chocolates. Some assessors had difficulties in differentiating chocolates based on fishy odor, while for others the difference was clear. However, none of the participants performed systematically poorly, due to which the results of all assessors were included in subsequent statistical analyses. The Effect of SDEMs on Perceived Sensory Differences The most notable differences between samples appeared in fishy odor and flavor in both chocolates and cookies (Appendix A; Tables A1 and A2). Additionally, differences were found in melting sensation and crumbliness in chocolate (Appendix A; Table A1), and in odor and flavor intensity, softness, and moistness in cookies (Appendix A; Table A2). There were no differences between SW and SM cookies in fish flavor in lower (1.5%) or higher (3.0%) oil content, whereas PW was estimated to have a fishier flavor than PM at both oil contents. In the study by Hughes et al., increased fish oil content decreased the aroma, flavor, and texture acceptability scores of fortified nutrition bars. Additionally, whole wheat bread enriched with higher content of microencapsulated n-3 fatty acids correlated with more intense fishy flavor and lower acceptability scores. Increasing the amount of encapsulated oil in cookies from 1.5% to 3.0% increased the fishy flavor for SM, SW, and PW, however not for PM. Differences between soy and pea proteins became more prominent in the higher oil content. Cookies containing SM were generally evaluated as fishier than PM. However, PW produced a fishier flavor than SW. In chocolate, the use of S and W increased the perceived fishy flavor. The fishy flavor-enhancing effect of W may result from higher total oil levels than M-containing SDEMs. Additionally, smoother powders containing M are potentially better at hiding the fishiness than cracked ones containing W. In chocolate, SW had a stronger fishy odor than PW. The same was also observed in cookies with SM being fishier than PM. Soy protein itself may have an off-flavor, which may raise fishy odor when interacting with matrix. Overall, the fishy-enhancing effect of S in cookies was most pronounced at the higher oil content. Additionally, compared with M, W increased fishy odor when combined with P (in shortbread cookies) and S (in chocolate). The addition of fish oil in all forms reduced the sensation of chocolate melting and increased crumbliness. However, M added less crumbliness than W. In cookies, M decreased the perceived softness compared with C and the cookies containing FO. Additionally, Gonzlez et al. reported bread enriched with microencapsulated chia oil was harder than bread with non-encapsulated oil. However, there was no statistically significant difference between control and microencapsulated bread. This indicates that in addition to wall materials, the food matrix plays a key role in the effect of microcapsules on the texture. Sensory Profiles In the consensus principal component analysis (PCA) (Figure 2A), PC-1 explained 69% and PC-2 19% of the variance among cookies. The fishy flavor and fishy odor had a positive loading on PC-1. Softness, crumbliness, and moisture had negative loadings on PC-2 in which the cookies were evenly distributed. FOs were the softest and MWs were the hardest. SDEM cookies with a higher oil content had a positive load on PC-1, indicating them to be fishier, while cookies with less oil had not as clear fishiness. However, pea protein cookies made an exception: PW1 and PW2 had distinct fishiness while PM1 and PM2 showed minor fishiness. The PCA pea protein and maltodextrin combination resembled the most C and was the best choice for cookies enriched with SDEMs. FO cookies were not perceived as fishy, even though the oil was not protected by encapsulation, as was also noticed in the study of Hughes et al. in which a small amount of fish oil in the product remained undetected and did not affect the acceptability. PM2 showed minor fishiness. The PCA pea protein and maltodextrin combination resembled the most C and was the best choice for cookies enriched with SDEMs. FO cookies were not perceived as fishy, even though the oil was not protected by encapsulation, as was also noticed in the study of Hughes et al. in which a small amount of fish oil in the product remained undetected and did not affect the acceptability. For the chocolates, PC-1 explained 76% and PC-2 18% ( Figure 2B). Fishy flavor and crumbliness had positive loadings on PC-1, while fishy odor, aftertaste, and oily mouthfeel had an average loading on PC-2. W addition on chocolate increased crumbliness and fishy flavor. Especially SW had strong fishiness as was also noted in general linear model analysis of variance (ANOVA) calculations (Appendix A; Table A2). Although maltodex- For the chocolates, PC-1 explained 76% and PC-2 18% ( Figure 2B). Fishy flavor and crumbliness had positive loadings on PC-1, while fishy odor, aftertaste, and oily mouthfeel had an average loading on PC-2. W addition on chocolate increased crumbliness and fishy flavor. Especially SW had strong fishiness as was also noted in general linear model analysis of variance (ANOVA) calculations (Appendix A; Table A2). Although maltodextrin/plant protein combinations and FO chocolates formed a separate group from W samples, all enriched chocolates differed from C. However, maltodextrin seems to be the most promising alternative to for enriched chocolates, especially combined with pea protein. Volatile Composition of Food Models From the fresh cookie model, 37 volatile compounds were identified (Table 3), of which 2-heptanone was the most abundant followed by 2-nonanone, 2,4-dimethylheptane, and acetic acid. The only volatiles not also found in C were propanal and maltol. Propanol is a typical volatile oxidation product formed from n-3 PUFAs and maltol is a product of the early stages of the Maillard reaction. Additionally, other Maillard reaction products were detected in the cookie model due to the baking process such as furfural, 2-furanmethanol, and 3-dihydro-3,5-dihydroxy-6-methyl-4H-pyran-4-one. Similar compounds have been detected in corresponding models previously. Typical volatiles originating from butter were, e.g., 2,3-butanedione, butanoic acid, hexanoic acid, nonanal, and -hexalactone, as also found previously. Table 3. Retention times, match with NIST library, and main ions in the mass spectra of 53 identified volatile compounds analyzed by headspace solid-phase microextraction with gas chromatography with mass spectrometer detection from non-stored shortbread cookie and dark chocolate models fortified with fish oil. * Volatile compounds not identified in controls (not containing fish oil). ** x = minor compound (peak area < 5 10 6 ), xx = main compound (peak area > 5 10 6 ), xxx = major compound (peak area > 5 10 7 ). In the PCA model of the volatile profile of the fortified cookies ( Figure 3A,B), PC-1 accounted for 35% and PC-2 for 17% of the variation. Replicates of samples grouped together are shown in Figure 3A,C, positioned on the left side, was separated from the fortified samples only associated with 1,2-butanediol, which may be related to better extractability as no volatiles from fish oil were present. 1,2-Butanediol was also present in other samples, but the contribution of other volatiles was greater if samples contained fish oil. FO grouped in the center of PCA related to nonanal and -hexalactone ( Figure 3B) regardless of concentration, while samples with encapsulated fish oil separated based on concentration. All encapsulated fish oil cookie samples were found further on the right if a higher concentration was added. The samples containing M showed the tendency to be found in the lower half of PCA and the ones only containing proteins as encapsulation material were located on the upper half of PCA, except for SM1, which grouped with SW1 and PW1 in the upper half ( Figure 3A). SW2 and PW2 grouped together in the right upper corner and were mainly associated with hydrocarbons (like 4-methyldecane, 4methylocyane, and 2,4-dimethylheptane), and propanal. PM1, MW1, MW2, PM2, and SM2 were all found in the lower half of the PCA related to maltol, ethanol, 2,3-butanedione, 2,3butanediol, and Maillard reaction products. MW showed a lower impact of concentration compared with samples with other encapsulation material combinations ( Figure 3A). If the PCA model of volatile profiles is compared to PCA models and the descriptive sensory profiles (Figures 2A and 3A), some correlation can be found. In both cases, PM1 and SM1 resembled the C most closely. Both volatiles profiles and descriptive sensory profiles showed high fish oil concentration dependency. The PCA model for the chocolate samples ( Figure 3E,F), PC-1, accounted for 33% while PC-2 accounted for 18% of the variation. All replicates grouped together and C and FO were located by themselves ( Figure 3E). C, FO, and MW were all found on the right side of PC-1. C was related to acetic acid, D-limonene, and nonanoic acid, FO to -pinene, 3-carene, 2-methylpropanal, and 3-methylbutanoic acid, and MW to propanoic acid and lactic acid. SW, PW, SM, and PM were located on the left side of PC-1 with the ones containing M closer to the center of PCA. SW and PW grouped together and were associated with 2-methylheptane, 2,4-methylheptane, hexanal, hexanoic acid, and 2,3-butanedione ( Figure 3F). SM was found on the left upper quadrant and is more related to 2-ethyl-3,5-dimethylpyrazine, linalool, and 2,5-dimethylpyrazine. Compared to SM, PM was located in the left lower quadrant associated with 2-butanone, 4-methyloctane, 2methylheptane, 2,4-methylheptane, and 2,3-butanedione. Less correlation between volatile profiles and descriptive sensory profiles could be found for the chocolate model than for the cookie one. However, both profiles ( Figures 2B and 3E) showed that the control was significant different from any of fortified samples. Therefore, fortification had a significant impact on both profiles for the chocolate model. Although, in case of cookies most and in case of chocolate all identified volatiles were found in all samples, and an effect of fortification and encapsulation material was seen on the ratio of volatiles in the volatile profiles. In cookies, an effect of concentration of encapsulated fish oil was also demonstrated. However, the differences could not only be associated with the addition of FO and encapsulated fish oil as mostly volatiles from the food matrix were affected. This points to differences in the release most likely caused by compositional and textural changes of the food model matrix through fortification, also noted in the sensory analysis. Storage Test of Food Models Volatile profiles of stored food models (6 months, RT) were compared to volatile profiles of fresh ones, and in the case of cookies and chocolate 15 and 11 oxidation indicators were determined, respectively. Oxidation indicators only detected in samples containing fish oil were propanal, 2-ethylfuran, 1-penten-3-ol, 2-hexenal (E), 3,5-octadien-2-one (E,E), 5-ethyl-2(5H)-furanone, and 2-nonenal (E), of which 2-hexenal (E) and 2-nonenal (E) were only detected in the cookie model. All compounds are common volatile oxidation products for n-3-rich fish oil. Other selected oxidation indicators were acetic acid, pentanal, propanoic acid, hexanal, butanoic acid, heptanal, hexanoic acid, and nonanal, which were also present in C and could also be formed from other lipids present. Pentanal and butanoic acid were not detected from chocolate. In the PCA models of oxidation indicators in fresh and stored samples, PC-1 explained 84% and 80% of total variance for the cookies and chocolates, respectively (Appendix B; Figure A1). For both food models, all fresh samples were grouped together on the left side of PCAs with only the stored C being close to fresh samples. The models were heavily influenced by the fact that oxidation indicators originating from fish oil were only detected in stored and not in fresh samples, except propanal in the cookie model. This clearly indicated that all models oxidized during storage. For determination of the effect of encapsulation material on lipid oxidation during storage, PCAs only taking the stored samples into account were conducted ( Figure 3). The loadings of oxidation indicators in the PCAs of the oxidized samples for both cookies and chocolate were all on positive site of PC-1 ( Figure 3D,H), which means the further right a sample is located on PC-1, the more oxidized it is. In the case of cookies, all replicates of C, FO, SW, and PW were located on the negative side of PC-1 ( Figure 3C) with C being, as expected, the furthest left and least oxidized. MW and PM displayed a clear concentration dependency. All cookies with higher concentrations were further right on PC-1 compared with lower concentrations using the same encapsulation material. A similar effect of concentration was also seen for oxidative stability of bread fortified with microencapsulated n-3 PUFAs powder as higher concentration promoted oxidation. The effect was lowest for PW. In the case of SM, both concentrations were found on the positive side of PC-1, and it was clearly the most oxidized of all cookie models. PC-2 displayed some differences in the formation of lipid oxidation indicators ( Figure 3D), which can be related to the extent of oxidation as certain compounds are formed earlier than others. In the case of chocolate, C was also located the farthest on the left side of PC-1 ( Figure 3G). Further, FO, SW, PW, and PM were found on the negative side of PC-1, while MW and SM were found on the positive side of PC-1. FO, SW, PW, and SM correlated more to acetic acid, 3,5-octadien-2-one (E,Z), heptanal, nonanal, and hexanoic acid ( Figure 3H), as they were located on the positive side of PC-2 ( Figure 3G). However, PM and MW, located on the negative side of PC-2, were more correlated to propanal and 1-penten-3-ol ( Figure 3H). As expected, for both food models, C was the least oxidized. In the case of cookies, the oxidation order from least to most oxidized was FO, SW, PW, PM, MW, and SM for the lower and FO, PW, SW, PM, MW, and SM for the higher concentration. In the case of chocolate oxidation order from least to most oxidized was FO, SW/PW, PW/SW, PM, MW, and SM. The order was similar in both food models. The oxidative stability of food models containing encapsulated material was similar to the oxidative stability of SDEMs used. In both cases, the samples containing W were more oxidative stable than samples containing M. However, it cannot be concluded that oxidative stability is fully dependent on oxidative stability of the SDEMs as PM performed better in food models as expected based on oxidative stability of the SDEMs and MW performed worse than expected. Surprisingly, the highest oxidative stability in both fortified food models was seen if they contained FO. High oxidative stability was also seen for fish oil-fortified nutrition bars compared with the control based on hexanal and propanal levels, and peroxide value after 10 weeks of storage. The effect was mainly attributed to the addition of tocopherols in the fish oil and the use of soy products containing isoflavones with antioxidant activity. However, compared with this study, no encapsulated fish oil was studied. Encapsulation clearly improved the oxidative stability of the fish oil, as seen in Section 2.1. Yet, it could be that the SDEMs contain more prooxidants, e.g., already formed hydroperoxides from processing or metals introduced during processing than the FO. Spray-drying could also have a negative effect on antioxidants content as spray-drying has been shown to decrease the tocopherol content in oil. Further, the non-polar fish oil might be better incorporated in high fat food models than the more polar encapsulated oil. The fish oil-fortified nutrition bars with high oxidative stability studied by Hughes et al. also contained significantly high fat content emulsifying properties based on the ingredient list reported. This raises the question of whether encapsulation is always necessary in terms of storage stability if fish oil is incorporated in high fat food models. (Table 4). Aqueous emulsions of the core (FO; 10%) and wall material solution (10% of wall material combination (MW, SFW, SW, PW, SFM, SM, PM)) were formed using Thermomix (Vorwerk, Wuppertal, Germany) operated at 9000 rpm for 120 s at 40 C. The emulsions were homogenized at 240 bar (I step) and 40 bar (II step) using a high-pressure laboratory valve homogenizer (Panda 2K, GEA Niro Soavi, Parma, Italy). The emulsions were pumped into a pilot plant spray dryer (A/S Niro Atomizer, Copenhagen, Denmark; spraying mechanism-disc with a 110 mm diameter, 6400 rpm number of revolutions) chamber at a constant feeding speed of 77 mL/min. The airflow rate was approx. 400 kg/h, and the temperatures of inlet and outlet were 130 C and 90 C, respectively. Food Models: Shortbread Cookie and Dark Chocolate The formula of shortbread (w/w) was 34.5% of butter (Valio Ltd., Helsinki, Finland), 50.4% of wheat flour (Myllyn Paras Finland Oy, Hyvinkaa, Finland), and 15.2% of sugar (granulated sugar, Rainbow, Sucros Oy, Skyl, Finland), purchased locally from the grocery store. Oil or powder was added so that it replaced flour. Butter (of room temperature) and sugar were mixed followed by gradual addition of wheat flour. Two concentrations of fish oil (as such or encapsulated MW, SW, PW, SM, or PM) were added to the shortbread cookies to reach 40 mg of the sum of EPA or DHA per 100 g and per 100 kcal (claim: source of n-3 fatty acids;, or 80 mg of the sum of EPA or DHA per 100 g and per 100 kcal (claim: high in n-3 fatty acids;. Additions were calculated based on the total oil content of encapsulated oil and the fatty acid composition of FO (see Section 2.1). Additionally, for sensory training, cookies were made with 0.5, 1.5, 2.5, and 5 times the health claim of 40 mg of the sum of EPA or DHA per 100 g and per 100 kcal using fish oil. A fish oil-free control sample was also included. The dough was rolled into balls and then shaped into cookies (approx. 4 cm in diameter) and baked at 175 C for 14 min. After the baking the average weight of one cookie was 12.9 g (standard deviation 0.56 g). The dark chocolate couverture (70% Arriba cacao, Ecuador; Lidl Stiftung & Co. KG, Neckarsulm Germany) was cut and heated to 45 C and kept at this temperature for 15 min to ensure complete melting. FO or encapsulated fish oil (MW, SW, PW, SM, or PM) was mixed with the chocolate mass at 35 C for 2 min. A three-stage tempering was applied: 40 to 45 C for 10 min, 26 to 28 C for 5 min, and 30 to 32 C for 10 min. The tempered mass was immediately filled into silicone molds (115 mm 77 mm 9 mm, length width height) and kept for 12 h at 4 ± 1 C. The FO and encapsulated fish oil were added to chocolate concentrations to reach 60 mg of the sum of EPA or DHA per 100 g and per 100 kcal (claim: source of n-3 fatty acids). Additions were calculated based on the total oil content of encapsulated oil and the fatty acid composition of FO (see Section 2.1). As a control, chocolate without fish oil was prepared. SEM The powder was attached to the microscope state using two-sided adhesive tape, mounted on SEM tubs, and coated with palladium in a sputter coater. Samples were analyzed using SEM Quanta 200 (FEI Company, Hillsboro, OR, USA) operating an accelerating voltage of 30 kV and 400 magnifications. Total and Surface Oil Content and EE Lipids were extracted with n-hexane or a chloroform/methanol mixture (2:1, v/v) for surface and total oil, respectively, and weighted according to the method by Takeungwongtrakul et al., also previously described in Damerau et al.. EE was calculated by using the following equation: Fatty Acid Profiles Fatty acid methyl esters by GC-FID were analyzed as previously described (). Encapsulated lipids were extracted with n-hexane/2-propanal mixture (3:1, v/v) after re-suspending the sample in 0.8% potassium chloride in MQ-water. Methanolic hydrogen chloride was used in methylation. A Shimadzu GC-2030 with an AOC-20i auto injector and an FID (Shimadzu corporation, Kyoto, Japan) equipped with a DB-23 (60 m 0.25 mm i.d., liquid film 0.25 m, Agilent Technologies, J.W. Scientific, Santa Clara, CA, USA) column were used. GC conditions: helium flow 1.4 mL/min; 130 C held 1 min, 6.5 C/min to 170 C, 2.75 C/min to 205 C, held for 18 min, 30 C/min to 230 C and held for 2 min. The peaks were identified by using the external standards, and FAs quantified using the internal standard and correction factors determined with the external standard mixtures. OSI A 743 Rancimat (Metrom, Zofingen, Switzerland) eight-channel oxidative stability instrument was used. Samples (2.5 g each) were placed in a reaction vessel in a thermostatic electric heating block. The temperature was set at 110 C and an airflow rate at 20 L/h. The OSI was expressed as hours. Sensory Evaluation The panelists, 10 women and 2 men, were recruited among the staff and the students of the University of Turku. As an inclusion criterion, all panelists had prior experience in sensory evaluation. They were familiarized with the samples and sensory attributes during two 1 h training sessions. The generic descriptive method was used to determine the effects of SDEMs and oil concentrations. Two odor attributes, five flavor attributes, and six texture attributes were selected (Table 5). Panelists were tested between and after all sessions for producing reliable and reproducible results. The sensory evaluations were performed by ISO 8589 standard. The samples, 6.5 g of cookie or 4.0 g piece of chocolate, were served in glass bowls at room temperature and labelled with three-digit random codes in an order that followed a Latin Squared design. Samples were evaluated in duplicate; cookies in four and chocolates in two sessions. The assessors were instructed to take a sample in the mouth, chew and rotate it in the mouth, and give their first impression. With mouthfeel and texture attributes, continued chewing of the sample to evaluate an after-effect was instructed. The intensities of the attributes (Table 5) were evaluated on a scale of 0-10 (0; no attribute observed, 10; strong attribute observed) with the help of reference samples. The assessors were instructed to clean their mouths by drinking activated carbon-filtered water and chewing an unsalted water biscuit (Carr's Table Water Storage Test The cookie and chocolate models were stored at room temperature for 6 months and packaged in food-grade plastic containers. Fresh and stored samples were kept under nitrogen at −80 C until analysis. Analysis of Volatiles VSOPs of SDEMs were analyzed using HS-SPME-GC-MS as described by Damerau et al.. 0.5 g ± 0.005 g of SDEM, 1 g ± 0.01 g of the crushed cookie models, and 1 g ± 0.01 g of finely chopped chocolate models were weighed in triplicate in 20 mL headspace vials and flushed with nitrogen. Volatiles were extracted using HS-SPME using TriPlus RSH autosampler (Thermo Scientific, Reinach, Switzerland) equipped with a DVB/CAR/PDMS-fiber (50/30 m film thickness; Supelco, Bellefonte, PA, USA). Extraction conditions: agitation speed 250 rpm, incubation 50 C for 20 min, extraction 50 C for 30 min, and desorption 240 C for 6 min. Extracted volatiles were analyzed with TRACE 1310 GC (Thermo Scientific, Reinach, Switzerland) equipped with a SPB ® -624 capillary column (60 m 0.25 mm 1.4 m, Supelco, Bellefonte, PA, USA) and coupled with an ISQ 7000 MS detector (Thermo Scientific, Reinach, Switzerland). GC-MS conditions: helium flow 1.4 mL/min; oven at 40 C held 6 min, 5 C/min to 220 C and held for 10 min; EI mode 70 eV and scan range 40 to 300 amu. Compounds were identified by the NIST MS Search library (version 2.3. National Institute of Standards and Technology, Gaithersburg, MD, USA) and by comparing retention times and MS spectra of standards. Statistical Analysis PanelCheck (version 1.4.2, Nofima, Troms, Norway) was used to evaluate the performance of the panel and assessors. Reproducibility and discriminability of assessors and agreement of the panel were analyzed using univariate (p-MSE, F&p, MSE, correlation, and eggshell plot) and multivariate methods (Tucker-1 and Manhattan plots) as described by Tomic et al.. An overview of the sensory profile of cookies and chocolates was formed with PCA using averaged data over assessors and replicates by Unscrambler ® X version 11.0 (Camo Analytics AS., Oslo, Norway). The data were autoscaled, and full cross-validation and singular value decomposition were used. PCA was also applied to averaged peak area data to determine the correlation of volatiles and samples at different time points. Data were mean-centered and weighed (1/sdev). The data of the descriptive analysis were analyzed by ANOVA for each attribute. Between subject factors used for chocolate were plant proteins (S and P) and wall materials (M and W) and for cookies the two above-mentioned as well as the oil concentration (1.5% and 3.0%). Pairwise comparisons were calculated with either Bonferroni adjustment or Tukey's HSD post hoc test. Statistical tests were performed with IBM SPSS Statistics 27 (IBM Corporation, Armonk, NY, USA). The criterion of statistical significance was p < 0.05. Conclusions Encapsulation by spray-drying using pea, soy, and sunflower protein in combination with either whey protein concentrate or maltodextrin increased oxidative stability of fish oil. The best protection was achieved with a combination of pea or soy protein with whey protein concentrate. The fatty acid composition of the oil was not affected by the encapsulation process. The most promising formulations were successfully used for the fortification of shortbread cookie and dark chocolate food models, which were studied as such and during storage. The sensory panel detected differences between fortified food models and controls regardless of formulation. The main attributes for the distinction were fishy flavor and odor. Increasing the oil content in cookies had a negative impact on sensory perception. For both food models, fortification using fish oil encapsulated with pea protein and maltodextrin showed the closest resemblance to control. Based on sensory perception, mainly textural changes, the cookies were a more promising model than chocolate for fortification. Volatiles profiles could be differentiated based on fortification and encapsulation material for both tested food models. This was mainly due to compositional and textural changes affecting the release of volatiles. Six months storage at room temperature revealed high oxidative stability for food models fortified with fish oil encapsulated with pea or soy protein with whey protein concentrate, similar as for spray-dried emulsion themselves based on volatile oxidation products. Increasing oil content had a negative impact on the oxidative stability. While as hypothesized some of the plant protein containing formulations showed good potential, fortification using non-encapsulated fish oil was surprisingly promising as well based on sensory perception, volatile profiles, and oxidative stability for the high-fat food models used in this study. Therefore, the most ability for fortification was seen for pea protein formulations and direct addition of fish oil using the cookie model. However, further research studying sensory perception during storage and effect on fortification in less fatty food matrices is needed to evaluate the full potential of encapsulation with pea protein. Further, analysis by gas chromatography-olfactometry would be useful to study odor activity and to allow better correlation of sensory and volatile data. Funding: The work was carried out with financial support from the Academy of Finland project "Omics of oxidation-Solutions for a better quality of docosahexaenoic and eicosapentaenoic acids" (Decision No. 315274, PI Kaisa Linderborg). Personal grant to S.A.M. from Turku University Foun-dation is also acknowledged. Additionally, the project was financially supported by Minister of Education and Science (Poland) in the range of the program entitled "Regional Initiative of Excellence" for the years 2019-2022, Project No. 010/RID/2018/19, amount of funding 12.000.000 PLN. Institutional Review Board Statement: The study was conducted according to the guidelines of the Declaration of Helsinki. Ethical guidelines in organizing sensory evaluations and handling personal data were followed although the study was not pre-approved by any Institutional Review Board or Ethics Committee as no invasive protocols were applied. The study consisted of sensory evaluation, i.e., looking, smelling and tasting of products made of food grade raw materials. Informed Consent Statement: Informed consent was obtained from all subjects involved in the study. Prior to the tests, panelists were informed about the procedures, samples, and treatments, and informed consent was obtained from all participants. The volunteers had the choice to expectorate the samples if they wished not to swallow them. Data Availability Statement: Data of the chemical and physical analyses is available from the corresponding authors upon reasonable request. Sensory data of the individual panelists is not available to protect the privacy of the panelists. Acknowledgments: The authors would like to thank Enni Mannila and Annalisa Seubert for technical assistance with part of fatty acid and volatile analysis, respectively. Finally, the authors thank all the participants of the sensory evaluation. Conflicts of Interest: The authors declare no conflict of interest. The funders had no role in the design of the study; in the collection, analyses, or interpretation of data; in the writing of the manuscript, or in the decision to publish the results. * Fishy odor and flavor, melting texture, and crumbliness were statistically significant (p < 0.05), while other attributes had not significant differences (p > 0.05) according to ANOVA. ** FO = non-encapsulated fish oil and spry-dried emulsions formulated M = maltodextrin, W = WPC = whey protein concentrate, S = soy protein or P = pea protein as wall material. Scale from 0 (no attribute) to 10 (strong attribute). * Sweetness, bitterness, aftertaste, moist and oily mouthfeel were not statistically significant (p > 0.05), while other attributes had p < 0.05. ** FO = non-encapsulated fish oil and spry-dried emulsions formulated M = maltodextrin, W = WPC = whey protein concentrate, S = soy protein or P = pea protein as wall material, 1 = 1.5% oil, and 2 = 3.0% oil. |
About 240 barrels of crude oil—roughly 10,000 gallons—leaked from a Sunoco pipeline this week, contaminating a large area in the Oak Glen Nature Preserve, near Cincinnati, OH.
Local, state and federal officials reported to the scene Monday evening and contained the leak by about 5 a.m. Tuesday, Cincinnati's WCPO reported. The cause remains under investigation and cleanup could take two weeks.
Crude oil is pictured in a stream near the site of a pipeline leak in Southern Ohio. Photo credit: U.S. Environmental Protection Agency/via RT America
Sunoco Logistics Partners owns most of the Mid-Valley Pipeline Co. pipeline, which extends 1,000 miles from Michigan to Texas. No injuries were reported after the leak, according to the Cincinnati Enquirer.
U.S. Environmental Protection Agency (EPA) spokeswoman Heather Lauer said the crude oil was pooled in a marshland area about the size of a football field, as of Wednesday morning. There are natural barriers that the agency hopes will prevent it from seeping into the Great Miami River, which is just 150 meters away.
While some authorities say the leak is unlikely to affect drinking water in the area, the EPA is investigating and trying to ensure that the underground pipe's oil has not leaked into the ground water supply. In addition to the Great Miami River, water treatment plants are nearby, upstream in Fairfield, OH and upstream on the Ohio River.
"We do have a drinking well used for drinking on this side of the road that will be sampled in the near future, in addition, the health department has identified up to 70 more locations that will be looking into," the EPA's Steve Renninger told WCPO.
Crude oil flows from a stream to a lake near the oil spill. Photo credit: U.S. Environmental Protection Agency/via RT America
The first cleanup phase will take about a week or so, officials estimated. That includes recovering crude oil and contaminated land using powerful vacuum cleaners and large machinery.
The oil spill began Monday evening. Photo credit: U.S. Environmental Agency/via RT America
"[An oil spill] could definitely have been worse later in the spring when all of our wildlife is coming out of hibernation," Bob Mason, stewardship manager with Great Parks, said. "Plus now the ground is still hard, still somewhat frozen, so that helps."
The pipeline carries crude oil to refineries in Ohio and Oregon. Inspectors last checked it in 2011. A system-wide inspection of the 1,119-mile-long pipeline five years ago resulted in a $48,700 fine for Sunoco, which did not address corrosion problems in the pipeline.
According to the Enquirer, Gary M. Broughton placed the initial 911 call after taking in a "fuel, oily smell." He got out of his car and saw oil spreading across a pond.
"It's absolutely terrible," Broughton told the 911 dispatcher.
"It made me sick when I saw it."
Visit EcoWatch’s PIPELINES page for more related news on this topic. |
<reponame>arjunlal99/arctic-sea<gh_stars>0
/*
* Copyright 2015-2019 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* 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 org.n52.iceland.i18n.metadata;
import java.util.Locale;
import java.util.Set;
import org.n52.janmayen.i18n.MultilingualString;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Objects;
import com.google.common.collect.Sets;
public abstract class AbstractI18NMetadata {
private final String identifier;
private final MultilingualString name;
private final MultilingualString description;
/**
* constructor
*
* @param id The identifier of this object
* @param name The multilingual name of this object
* @param description the multilingual description of this object
*/
public AbstractI18NMetadata(String id,
MultilingualString name,
MultilingualString description) {
this.identifier = id;
this.name = newIfNull(name);
this.description = newIfNull(description);
}
/**
* constructor
*
* @param id The identifier of this object
*/
public AbstractI18NMetadata(String id) {
this(id, null, null);
}
/**
* The the identifier of this object
*
* @return The object identifier
*/
public String getIdentifier() {
return identifier;
}
/**
* @return the multilingual name of this object
*/
public MultilingualString getName() {
return this.name;
}
/**
* @return the multilingual description of this object
*/
public MultilingualString getDescription() {
return this.description;
}
/**
* @return a {@link ToStringHelper} filled with the state of this class
*/
protected ToStringHelper toStringHelper() {
return MoreObjects.toStringHelper(this)
.add("identifier", getIdentifier())
.add("name", getName())
.add("description", getDescription());
}
@Override
public String toString() {
return toStringHelper().toString();
}
@Override
public int hashCode() {
return Objects.hashCode(getIdentifier(), getName(), getDescription());
}
@Override
public boolean equals(Object o) {
if (o instanceof AbstractI18NMetadata) {
AbstractI18NMetadata that = (AbstractI18NMetadata) o;
return Objects.equal(this.getIdentifier(), that.getIdentifier()) &&
Objects.equal(this.getName(), that.getName()) &&
Objects.equal(this.getDescription(), that.getDescription());
}
return false;
}
/**
* @return a unmodifiable set of all {@link Locale}s present in this object.
*/
public Set<Locale> getLocales() {
return Sets.union(getName().getLocales(),
getDescription().getLocales());
}
/**
* Creates a new {@link MultilingualString} if the supplied string is
* {@code null}.
*
* @param string the string
*
* @return either {@code string} or a new {@code MultilingualString}
*/
protected static MultilingualString newIfNull(MultilingualString string) {
return string == null ? new MultilingualString() : string;
}
}
|
#!/usr/bin/env python
"""
The kploy main UX.
@author: <NAME>, http://mhausenblas.info/#i
@since: 2015-11-29
@status: beta
"""
import argparse
import logging
import os
import sys
import pprint
import base64
import kploycommon
from tabulate import tabulate
from pyk import toolkit
from pyk import util
DEBUG = False # you can change that to enable debug messages ...
VERBOSE = False # ... but leave this one in peace
DEPLOYMENT_DESCRIPTOR = "Kployfile"
EXPORT_ARCHIVE_FILENAME = "app.kploy"
SECRETS_FILE_EXT = ".secret"
RC_DIR = "rcs/"
SVC_DIR = "services/"
ENV_DIR = "env/"
KAR_BASE_URL = "http://registry.kploy.net/api/v1"
VALID_WORKSPACE_PREFIXES = (
"http://github.com/",
"https://github.com/"
)
if DEBUG:
FORMAT = "%(asctime)-0s %(levelname)s %(message)s [at line %(lineno)d]"
logging.basicConfig(level=logging.DEBUG, format=FORMAT, datefmt="%Y-%m-%dT%I:%M:%S")
else:
FORMAT = "%(asctime)-0s %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT, datefmt="%Y-%m-%dT%I:%M:%S")
logging.getLogger("requests").setLevel(logging.WARNING)
class InvalidWorkspaceError(Exception):
"""
Error when executing the `push` command: The `source` field in the `Kployfile` file is neither a GitHub username or repo URL.
"""
pass
class NoSuchAppError(Exception):
"""
Error when executing the `pull` command: The supplied app ID is invalid, that is, the app does not exist (at least not in this workspace).
"""
pass
def cmd_dryrun(param):
"""
Looks for a `Kployfile` file in the current directory and tries
to validate its content, incl. syntax validation and mock execution.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Trying to execute a dry run on %s " %(kployfile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
print("Validating application `%s/%s` ..." %(kploy["namespace"], kploy["name"]))
print("\n CHECK: Is the Kubernetes cluster up & running and accessible via `%s`?" %(kploy["apiserver"]))
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
nodes = pyk_client.execute_operation(method="GET", ops_path="/api/v1/nodes")
if VERBOSE: logging.info("Got node list %s " %(util.serialize_tojson(nodes.json())))
print(" \o/ ... I found %d node(s) to deploy your wonderful app onto." %(len(nodes.json()["items"])))
print("\n CHECK: Are there RC and service manifests available around here?")
try:
rcs = os.path.join(here, RC_DIR)
logging.debug("Asserting %s exists" %(os.path.dirname(rcs)))
assert os.path.exists(rcs)
rc_manifests_confirmed = kploycommon._visit(rcs, "RC", cache_remotes=kploy["cache_remotes"])
print(" I found %s RC manifest(s) in %s" %(int(len(rc_manifests_confirmed)), os.path.dirname(rcs)))
if VERBOSE: kploycommon._dump(rc_manifests_confirmed)
services = os.path.join(here, SVC_DIR)
logging.debug("Asserting %s exists" %(os.path.dirname(services)))
assert os.path.exists(services)
svc_manifests_confirmed = kploycommon._visit(services, "service", cache_remotes=kploy["cache_remotes"])
print(" I found %s service manifest(s) in %s" %(int(len(svc_manifests_confirmed)), os.path.dirname(services)))
if VERBOSE: kploycommon._dump(svc_manifests_confirmed)
print(" \o/ ... I found both RC and service manifests to deploy your wonderful app!")
except:
print("No RC and/or service manifests found to deploy your app. You can use `kploy init` to create missing artefacts.")
sys.exit(1)
except (IOError, IndexError, KeyError) as e:
print("Something went wrong:\n%s" %(e))
sys.exit(1)
print(80*"=")
print("\nOK, we're looking good! You're ready to deploy your app with `kploy run` now :)\n")
def cmd_run(param):
"""
Looks for a `Kployfile` file in the current directory and tries to run it.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Trying to run %s " %(kployfile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
# set up a Namespace for this app:
kploycommon._create_ns(pyk_client, kploy["namespace"], VERBOSE)
# set up a Secrets for this app:
env = os.path.join(here, ENV_DIR)
secrets = {}
logging.debug("Visiting %s" %env)
for _, _, file_names in os.walk(env):
for afile in file_names:
if afile.endswith(SECRETS_FILE_EXT):
logging.debug("Got a secret input: %s" %(afile))
key = os.path.splitext(afile)[0]
logging.debug("Secret key: %s" %(key))
with open(os.path.join(env, afile), "r") as sec_file:
raw_data = sec_file.read().strip()
logging.debug("Secret data: %s" %(raw_data))
val = base64.b64encode(raw_data)
logging.debug("Secret base64 encoded data: %s" %(val))
secrets[key] = val
kploycommon._create_secrets(pyk_client, kploy["name"], kploy["namespace"], secrets, VERBOSE)
# collect Services and RCs ...
rc_manifests_confirmed, svc_manifests_confirmed = [], []
services = os.path.join(here, SVC_DIR)
rcs = os.path.join(here, RC_DIR)
svc_manifests_confirmed = kploycommon._visit(services, 'service', cache_remotes=kploy["cache_remotes"])
rc_manifests_confirmed = kploycommon._visit(rcs, 'RC', cache_remotes=kploy["cache_remotes"])
# ... and deploy them:
kploycommon._deploy(pyk_client, kploy["namespace"], here, SVC_DIR, svc_manifests_confirmed, 'service', VERBOSE)
kploycommon._deploy(pyk_client, kploy["namespace"], here, RC_DIR, rc_manifests_confirmed, 'RC', VERBOSE)
except (Exception) as e:
print("Something went wrong deploying your app:\n%s" %(e))
print("Consider validating your deployment with `kploy dryrun` first!")
sys.exit(1)
print(80*"=")
print("\nOK, I've deployed `%s/%s`.\nUse `kploy list` and `kploy stats` to check how it's doing." %(kploy["namespace"], kploy["name"]))
def cmd_list(param):
"""
Lists app resources and their status.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Listing resource status of app based on %s " %(kployfile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
print("Resources of app `%s/%s`:\n" %(kploy["namespace"], kploy["name"]))
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
rc_manifests_confirmed, svc_manifests_confirmed = [], []
services = os.path.join(here, SVC_DIR)
rcs = os.path.join(here, RC_DIR)
svc_list = kploycommon._visit(services, 'service', cache_remotes=True)
rc_list = kploycommon._visit(rcs, 'RC', cache_remotes=True)
res_list = []
# gather Services status:
print("[Services and RCs]\n")
for svc in svc_list:
svc_manifest, _ = util.load_yaml(filename=os.path.join(here, SVC_DIR, svc))
svc_name = svc_manifest["metadata"]["name"]
svc_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/services/", svc_name])
svc_URL = "".join([kploy["apiserver"], svc_path])
svc_status = kploycommon._check_status(pyk_client, svc_path)
res_list.append([svc_name, os.path.join(SVC_DIR, svc), "service", svc_status, svc_URL])
# gather RC status:
for rc in rc_list:
rc_manifest, _ = util.load_yaml(filename=os.path.join(here, RC_DIR, rc))
rc_name = rc_manifest["metadata"]["name"]
rc_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/replicationcontrollers/", rc_name])
rc_URL = "".join([kploy["apiserver"], rc_path])
rc_status = kploycommon._check_status(pyk_client, rc_path)
res_list.append([rc_name, os.path.join(RC_DIR, rc), "RC", rc_status, rc_URL])
print(tabulate(res_list, ["NAME", "MANIFEST", "TYPE", "STATUS", "URL"], tablefmt="plain"))
# gather Secrets status:
print("\n" + 80*"=")
print("[Secrets]")
sec_list = []
secret_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/secrets/kploy-secrets"])
sec_URL = "".join([kploy["apiserver"], secret_path])
secret = pyk_client.describe_resource(secret_path)
if secret.status_code == 200:
print("URL: %s" %(sec_URL))
secret_data = secret.json()["data"]
for k, v in secret_data.iteritems():
sec_list.append([k, base64.b64decode(v)])
print(tabulate(sec_list, ["KEY", "VALUE"], tablefmt="plain"))
else:
print("No env data deployed.")
print("\n" + 80*"=")
except (Exception) as e:
print("Something went wrong:\n%s" %(e))
print("Consider validating your deployment with `kploy dryrun` first!")
sys.exit(1)
def cmd_init(param):
"""
Creates a dummy `Kployfile` file in the current directory sets up the directories.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if not param:
param = EXPORT_ARCHIVE_FILENAME
if os.path.exists(kployfile):
print("Hey! %s already exists.\nI'm not going to destroy existing work. #kthxbye" %(kployfile))
sys.exit(1)
archivefile = os.path.join(here, param)
if not os.path.exists(SVC_DIR):
os.makedirs(SVC_DIR)
if not os.path.exists(RC_DIR):
os.makedirs(RC_DIR)
if os.path.exists(archivefile): # set up via archive
if VERBOSE: logging.info("Detected archive %s" %(archivefile))
kploycommon._init_from_archive(archivefile)
print(80*"=")
print("\nOK, I've set up the app from archive.\nYou can now validate it with `kploy dryrun`\n")
else: # create from scratch
if VERBOSE: logging.info("Setting up app %s " %(kployfile))
ikploy = {}
ikploy["apiserver"] = "http://localhost:8080"
ikploy["author"] = "CHANGE_ME"
ikploy["cache_remotes"] = False
ikploy["name"] = "CHANGE_ME"
ikploy["namespace"] = "default"
ikploy["source"] = "CHANGE_ME"
if VERBOSE: logging.info("%s" %(ikploy))
util.serialize_yaml_tofile(kployfile, ikploy)
print(80*"=")
print("\nOK, I've set up the `%s`, the app deployment descriptor from scratch and created necessary directories." %(DEPLOYMENT_DESCRIPTOR))
print("Now edit the app deployment descriptor and copy manifests into the respective directories.\n")
def cmd_destroy(param):
"""
Destroys the app, removing all resources.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Trying to destroy app based on %s " %(kployfile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
# delete all services and RCs:
rc_manifests_confirmed, svc_manifests_confirmed = [], []
services = os.path.join(here, SVC_DIR)
rcs = os.path.join(here, RC_DIR)
svc_manifests_confirmed = kploycommon._visit(services, 'service', cache_remotes=True)
rc_manifests_confirmed = kploycommon._visit(rcs, 'RC', cache_remotes=True)
kploycommon._destroy(pyk_client, kploy["namespace"], here, SVC_DIR, svc_manifests_confirmed, 'service', VERBOSE)
kploycommon._destroy(pyk_client, kploy["namespace"], here, RC_DIR, rc_manifests_confirmed, 'RC', VERBOSE)
# delete secrets:
secret_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/secrets/kploy-secrets"])
pyk_client.delete_resource(resource_path=secret_path)
# delete the namespace:
ns_path = "".join(["/api/v1/namespaces/", kploy["namespace"]])
pyk_client.delete_resource(resource_path=ns_path)
except (Exception) as e:
print("Something went wrong destroying your app:\n%s" %(e))
print("Consider validating your deployment with `kploy dryrun` first!")
sys.exit(1)
print(80*"=")
print("\nOK, I've destroyed `%s/%s`\n" %(kploy["namespace"], kploy["name"]))
def cmd_stats(param):
"""
Shows cluster utilization and provides summary of the pods' state, from the point of view of your app.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Providing stats for your app based on %s " %(kployfile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
print("Runtime stats for app `%s/%s`:" %(kploy["namespace"], kploy["name"]))
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
# provide container summary:
print("\n[Your app's pods]\n")
guarded_pods_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/pods?labelSelector=guard%3Dpyk"])
pods = pyk_client.execute_operation(method="GET", ops_path=guarded_pods_path)
pods_list = pods.json()["items"]
if not pods_list:
print "No pods are online. "
return
pod_details = []
used_nodes = []
for pod in pods_list:
if pod["status"]["hostIP"] not in used_nodes:
used_nodes.append(pod["status"]["hostIP"])
pod_details.append([
pod["metadata"]["name"],
pod["status"]["hostIP"],
pod["status"]["phase"],
"".join([kploy["apiserver"], pod["metadata"]["selfLink"]])
])
print(tabulate(pod_details, ["NAME", "HOST", "STATUS", "URL"], tablefmt="plain"))
print("\n" + 80*"=")
# provide utilization info:
print("[Nodes used by your app]\n")
nodes = pyk_client.execute_operation(method="GET", ops_path="/api/v1/nodes")
nodes_list = nodes.json()["items"]
node_ips = []
for node in nodes_list:
if node["metadata"]["name"] in used_nodes:
node_ips.append([
node["metadata"]["name"],
node["status"]["nodeInfo"]["osImage"],
node["status"]["nodeInfo"]["containerRuntimeVersion"],
node["status"]["capacity"]["pods"] + ", " + node["status"]["capacity"]["cpu"] + ", " + node["status"]["capacity"]["memory"],
"".join([kploy["apiserver"], node["metadata"]["selfLink"]])
])
print(tabulate(node_ips, ["IP", "HOST OS", "CONTAINER RUNTIME", "CAPACITY (PODS, CPU, MEM)", "URL"], tablefmt="plain"))
print("\n" + 80*"=")
except (Exception) as e:
print("Something went wrong:\n%s" %(e))
print("Consider validating your deployment with `kploy dryrun` first!")
sys.exit(1)
def cmd_export(param):
"""
Creates an archive of all relevant app files, incl. Kployfile and manifest directories.
You can use the resulting archive then with `kploy init` to bootstrap you app in a different location.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
if VERBOSE: logging.info("Exporting app based on content from %s " %(here))
try:
kploy, _ = util.load_yaml(filename=kployfile)
if not param:
param = EXPORT_ARCHIVE_FILENAME
archive_filename, archive_file = kploycommon._export_init(here, DEPLOYMENT_DESCRIPTOR, param)
print("Adding content of app `%s/%s` to %s" %(kploy["namespace"], kploy["name"], archive_filename))
rc_manifests_confirmed, svc_manifests_confirmed = [], []
services = os.path.join(here, SVC_DIR)
rcs = os.path.join(here, RC_DIR)
svc_list = kploycommon._visit(services, 'service', cache_remotes=True)
rc_list = kploycommon._visit(rcs, 'RC', cache_remotes=True)
res_list = []
for svc in svc_list:
svc_file_name = os.path.join(SVC_DIR, svc)
kploycommon._export_add(archive_file, svc_file_name)
for rc in rc_list:
rc_file_name = os.path.join(RC_DIR, rc)
kploycommon._export_add(archive_file, rc_file_name)
kploycommon._export_done(archive_file)
except (Exception) as e:
print("Something went wrong:\n%s" %(e))
print("Consider validating your deployment with `kploy dryrun` first!")
sys.exit(1)
def cmd_debug(pod_name):
"""
Enables you to debug a Pod by taking it offline through removing the `guard=pyk` label.
Usage: `debug pod`, for example, `debug webserver-42abc`.
"""
if not pod_name:
print("Sorry, I need a Pod name in order to do my work. Do a `kploy stats` first to glean the Pod name you want to debug, e.g. `webserver-42abc`.")
print("With the Pod name you can then run `kploy debug webserver-42abc` to take the Pod offline and subsequently for example use `kubectl exec` to enter the Pod.")
sys.exit(1)
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
print("Trying to take Pod %s offline for debugging ..." %(pod_name))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
pod_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/pods/", pod_name])
pod = pyk_client.describe_resource(pod_path)
resource = pod.json()
resource["metadata"]["labels"] = {}
logging.debug("Removed guard label from Pod, now labeled with: %s" %(resource["metadata"]["labels"]))
pyk_client.execute_operation(method='PUT', ops_path=pod_path, payload=util.serialize_tojson(resource))
# now we just need to make sure that the newly created Pod is again owned by kploy:
rc_name = pod_name[0:pod_name.rfind("-")] # NOTE: this is a hack, it assumes a certain generator pattern; need to figure a better way to find a Pod's RC
logging.debug("Generating RC name from Pod: %s" %(rc_name))
rc_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/replicationcontrollers/", rc_name])
rc = pyk_client.describe_resource(rc_path)
kploycommon._own_pods_of_rc(pyk_client, rc, kploy["namespace"], rc_path, VERBOSE)
except (Exception) as e:
print("Something went wrong when taking the Pod offline:\n%s" %(e))
sys.exit(1)
print(80*"=")
print("\nOK, the Pod %s is offline. Now you can, for example, use `kubectl exec` now to debug it." %(pod_name))
def cmd_scale(scale_def):
"""
Enables you to scale an RC up or down by setting the number of replicas.
Usage: `scale rc=replica_count`, for example, `scale webserver-rc=10`.
"""
if not scale_def:
print("Sorry, I need a scale definition in order to do my work. Do a `kploy list` first to glean the RC name you want to scale, e.g. `webserver-rc`.")
print("With the RC name you can then run `kploy scale webserver-rc=5` to scale the respective RC to 5 replicas.")
sys.exit(1)
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
try:
rc_name = scale_def.split("=")[0]
replica_count = int(scale_def.split("=")[1])
except (Exception) as e:
print("Can't parse scale definition `%s` due to: %s" %(scale_def, e))
print("The scale definition should look as follows: `rc=replica_count`, for example, `scale webserver-rc=10`.")
sys.exit(1)
print("Trying to scale RC %s to %d replicas" %(rc_name, replica_count))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
pyk_client = kploycommon._connect(api_server=kploy["apiserver"], debug=DEBUG)
rc_path = "".join(["/api/v1/namespaces/", kploy["namespace"], "/replicationcontrollers/", rc_name])
rc = pyk_client.describe_resource(rc_path)
resource = rc.json()
old_replica_count = resource["spec"]["replicas"]
if VERBOSE: logging.info("Scaling RC from %d to %d replicas" %(old_replica_count, replica_count))
logging.debug("RC about to be scaled: %s" %(resource))
resource["spec"]["replicas"] = replica_count
pyk_client.execute_operation(method='PUT', ops_path=rc_path, payload=util.serialize_tojson(resource))
# and make sure that the newly created Pods are owned by kploy (on scale up)
if replica_count > old_replica_count:
logging.debug("Scaling up, trying to own new Pods")
rc = pyk_client.describe_resource(rc_path)
kploycommon._own_pods_of_rc(pyk_client, rc, kploy["namespace"], rc_path, VERBOSE)
except (Exception) as e:
print("Something went wrong when scaling RC:\n%s" %(e))
sys.exit(1)
print(80*"=")
print("OK, I've scaled RC %s to %d replicas. You can do a `kploy stats` now to verify it." %(rc_name, replica_count))
def cmd_push(param):
"""
Exports the app and uploads it to KAR, the kploy app registry (https://github.com/kubernauts/kploy.net).
Note that you MUST set the `source` field in the `Kployfile` file to a GitHub username or repo URL,
otherwise the push operation will fail. For example, you can use `source : https://github.com/mhausenblas`
if you don't have a project repo for the app (yet) or `source : https://github.com/mhausenblas/abc`
if you want to explicitly set the app's project repo.
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
archivefile = os.path.join(here, "".join([".", EXPORT_ARCHIVE_FILENAME]))
app_link = KAR_BASE_URL
if VERBOSE: logging.info("Creating temporary app archive %s" %(archivefile))
cmd_export(archivefile)
if VERBOSE: logging.info("Trying to upload %s" %(archivefile))
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
if kploy["source"].startswith(VALID_WORKSPACE_PREFIXES):
print("Using %s as the app's workspace" %(kploy["source"]))
res = kploycommon._push_app_archive(kploy["source"], archivefile, KAR_BASE_URL, VERBOSE)
app_link = "".join([res.json()["selfLink"], "?workspace=", kploy["source"]])
else:
raise InvalidWorkspaceError
except (InvalidWorkspaceError) as iwe:
print(iwe.__doc__)
print("To learn how to fix this, run `kploy explain push`")
sys.exit(1)
except (Exception) as e:
print("Something went wrong pushing your app to the registry:\n%s" %(e))
sys.exit(1)
finally:
if os.path.exists(archivefile):
os.remove(archivefile)
print(80*"=")
print("\nOK, I've successfully pushed the app archive to the registry:")
print("%s" %(app_link))
print("\nTo list the available app(s), use the `kploy pull` command.\n")
def cmd_pull(param):
"""
Lists apps or downloads + imports app from KAR, the kploy app registry (https://github.com/kubernauts/kploy.net).
Note that you MUST set the `source` field in the `Kployfile` file to a GitHub username or repo URL,
otherwise the pull operation will fail. For example, you can use `source : https://github.com/mhausenblas`
if you don't have a project repo for the app (yet) or `source : https://github.com/mhausenblas/abc`
if you want to explicitly set the app's project repo.
Without argument all available apps are listed, with an argument the respective app is first
downloaded and then imported (as with `kploy init`):
kploy pull
kploy pull $ID
"""
here = os.path.realpath(".")
kployfile = os.path.join(here, DEPLOYMENT_DESCRIPTOR)
archivefile = os.path.join(here, "".join([".", EXPORT_ARCHIVE_FILENAME]))
app_link = KAR_BASE_URL
try:
kploy, _ = util.load_yaml(filename=kployfile)
logging.debug(kploy)
if kploy["source"].startswith(VALID_WORKSPACE_PREFIXES):
print("Using %s as the app's workspace" %(kploy["source"]))
if not param:
if VERBOSE: logging.info("Trying to list apps in the workspace ...")
res = kploycommon._list_apps(kploy["source"], KAR_BASE_URL, VERBOSE)
apps = res.json()
app_list = []
for app in apps:
app_list.append([
app["timeCreated"],
app["name"].split("/")[-1].split(".")[0],
app["size"]
])
print(tabulate(sorted(app_list, reverse=True), ["TIMESTAMP", "ID", "SIZE"], tablefmt="plain"))
else:
app_id = param
if VERBOSE: logging.info("Trying to download app %s from the workspace ..." %(app_id))
if not kploycommon._download_app(kploy["source"], app_id, archivefile, KAR_BASE_URL, VERBOSE):
raise NoSuchAppError
else:
cmd_init(archivefile)
else:
raise InvalidWorkspaceError
except (InvalidWorkspaceError) as iwe:
print(iwe.__doc__)
print("To learn how to fix this, run `kploy explain push`")
sys.exit(1)
except (NoSuchAppError) as nsae:
print(nsae.__doc__)
print("To learn how to fix this, run `kploy explain pull`")
sys.exit(1)
except (Exception) as e:
print("Something went wrong pulling from the registry:\n%s" %(e))
sys.exit(1)
finally:
if os.path.exists(archivefile):
os.remove(archivefile)
if not param:
print(80*"=")
print("\nOK, I've successfully pulled from the registry.")
print("\nYou can now `kploy pull $ID` to download and init an app.")
print("\nWARNING: a `kploy pull $ID` will overwrite whatever you had locally.\n")
def main():
try:
cmds = {
"dryrun" : cmd_dryrun,
"run" : cmd_run,
"list": cmd_list,
"init": cmd_init,
"destroy": cmd_destroy,
"stats": cmd_stats,
"export": cmd_export,
"debug": cmd_debug,
"scale": cmd_scale,
"push" : cmd_push,
"pull" : cmd_pull
}
parser = argparse.ArgumentParser(
description="kploy is an opinionated Kubernetes deployment system for appops",
epilog="Examples: `kploy init`, `kploy run`, `kploy list`, or to learn its usage: `kploy explain run`, `kploy explain list`, etc.")
parser.add_argument("command", nargs="*", help="Currently supported commands are: %s and if you want to learn about a command, prepend `explain`, like: explain list " %(kploycommon._fmt_cmds(cmds)))
parser.add_argument("-v", "--verbose", help="let me tell you every little dirty secret", action="store_true")
args = parser.parse_args()
if len(args.command) == 0:
parser.print_help()
sys.exit(0)
if args.verbose:
VERBOSE = True
logging.debug("Got command %s" %(args))
if args.command[0] == "explain":
cmd = args.command[1]
print(cmd + ":" + cmds[cmd].__doc__)
else:
cmd = args.command[0]
param = None
if len(args.command) == 2: # we have an additional parameter for the command
param = args.command[1]
logging.debug("Executing command %s with param %s" %(cmd, param))
if cmd in cmds.keys():
cmds[cmd](param)
except (Exception) as e:
print("Something went wrong:\n%s" %(e))
sys.exit(1)
if __name__ == "__main__":
main()
|
<filename>updater/src/main.rs<gh_stars>100-1000
// 关闭window子系统
#![windows_subsystem = "windows"]
use druid::debug_state::DebugState;
use druid::widget::prelude::*;
use druid::widget::Flex;
use druid::Application;
use druid::{
theme, AppLauncher, Color, Data, Lens, LinearGradient, Point, Rect, UnitPoint, WidgetExt,
WindowDesc,
};
use std::env;
use std::ffi::OsString;
use std::fs;
use std::path::Path;
use std::process;
use std::thread;
#[macro_use]
extern crate serde_derive;
use std::time::Duration;
// #[cfg(any(windows))]
// use std::os::windows::prelude::FileExt;
// #[cfg(any(windows))]
// fn read_at(file: &mut File, buffer: &mut [u8], offset: u64) -> Result<usize, std::io::Error> {
// file.seek_read(buffer, offset)
// }
use sysinfo::{ProcessExt, Signal, System, SystemExt};
// #[cfg(any(unix))]
// use std::os::unix::prelude::FileExt;
// #[cfg(any(unix))]
// fn read_at(file: &mut File, buffer: &mut [u8], offset: u64) -> Result<usize, std::io::Error> {
// file.read_at(buffer, offset)
// }
#[derive(Serialize, Deserialize, Debug)]
struct FileHashAndPath {
file_path: String,
hash: String,
}
extern crate serde;
extern crate serde_json;
#[derive(Serialize, Deserialize, Debug)]
struct UpdateConfigJson {
added: Vec<FileHashAndPath>,
changed: Vec<FileHashAndPath>,
}
#[derive(Clone, Data, Lens, Default)]
struct UpdateState {
progressbar: f64,
}
pub fn main() {
// describe the main window
let main_window = WindowDesc::new(build_root_widget())
.title("更新程序")
.window_size((400.0, 40.0))
.resizable(false)
.show_titlebar(false);
// create the initial app state
// 进度条显示
let initial_state: UpdateState = UpdateState { progressbar: 0.0 };
// start the application. Here we pass in the application state.
let launcher = AppLauncher::with_window(main_window);
// 给进度条的回调
let event_sink = launcher.get_external_handle();
thread::spawn(move || set_progressbar(event_sink));
launcher
.log_to_console()
.launch(initial_state)
.expect("Failed to launch application");
}
// todo 出错后版本后退问题, 中断继续问题
fn copy_file(
event_sink: &druid::ExtEventSink,
config: &UpdateConfigJson,
path: &OsString,
update_temp_path: &OsString,
) {
let mut hand_file_num = 0.0;
let total_file = (config.added.len() + config.changed.len()) as f64;
// 结束进程后迁移文件
for item in config.added.iter().chain(config.changed.iter()) {
hand_file_num += 1.0;
let file_path = Path::new(&path).join(&item.file_path);
println!("{:?} {}", &file_path, hand_file_num);
let from_path = Path::new(&update_temp_path).join(&item.hash);
event_sink.add_idle_callback(move |data: &mut UpdateState| {
println!("{}", data.progressbar);
data.progressbar = (hand_file_num / total_file) as f64;
});
// ui绘制时间
thread::sleep(Duration::from_millis(10));
if !from_path.is_file() {
// 缺少依赖处理 todo
continue;
}
if file_path.is_file() {
if let Err(_) = fs::remove_file(&file_path) {
// 删除对应文件产生错误处理 todo
};
}
if let Err(_) = fs::create_dir_all(file_path.parent().unwrap()) {
// 创建父文件夹失败处理 todo
}
if let Err(_) = fs::copy(from_path, file_path) {
// 复制文件到对应路径错误处理 todo
}
}
}
fn set_progressbar(event_sink: druid::ExtEventSink) {
// 当前执行exe的 没传过来直接结束进程
std::thread::sleep(Duration::from_millis(100));
let exe_path = match env::var("exe_path") {
Ok(path) if Path::new(&path).is_absolute() => Path::new(&path).as_os_str().to_owned(),
_ => {
event_sink.add_idle_callback(move |_: &mut UpdateState| {
Application::global().quit();
});
return;
}
};
let path = Path::new(&exe_path)
.parent()
.unwrap()
.as_os_str()
.to_owned();
// 更新temp目录
let update_temp_path = match env::var("update_temp_path") {
Ok(path) if Path::new(&path).is_absolute() => Path::new(&path).as_os_str().to_owned(),
_ => Path::new(&path).join("update_temp").as_os_str().to_owned(),
};
let update_config_file_name = match env::var("update_config_file_name") {
Ok(name) => name,
_ => "update-config.json".to_string(),
};
// todo 处理读取更新配置出错
let config: UpdateConfigJson = serde_json::from_slice(
&fs::read(Path::new(&update_temp_path).join(update_config_file_name)).unwrap_or_default(),
)
.unwrap();
// 如果读取到需要更新的配置时才更新 结束进程
if config.added.len() > 0 || config.changed.len() > 0 {
// 系统的所有信息,包括进程信息
let sys = System::new_all();
let current_exe_path = env::current_exe().unwrap();
//注意 如果有其他进程的执行exe的路径是直接kill掉处理
for (_pid, process) in sys.processes() {
match process.exe() {
v if v.starts_with(&path) && v != current_exe_path => {
process.kill(Signal::Kill);
}
_ => continue,
};
}
}
copy_file(&event_sink, &config, &path, &update_temp_path);
// 更新结束 退出ui
println!("done");
// 重启exe
process::Command::new(exe_path)
.spawn()
.unwrap();
event_sink.add_idle_callback(move |_: &mut UpdateState| {
Application::global().quit();
});
}
fn build_root_widget() -> impl Widget<UpdateState> {
Flex::column()
.with_spacer(10.0)
.with_child(
ProgressBarWidget::new()
.on_added(|_, _, _, _| {
println!("on_added");
})
.lens(UpdateState::progressbar),
)
.must_fill_main_axis(true)
.background(Color::rgb8(0xBA, 0xBA, 0xBA))
}
#[derive(Debug, Clone, Default)]
struct ProgressBarWidget {}
impl ProgressBarWidget {
pub fn new() -> ProgressBarWidget {
Self::default()
}
}
impl Widget<f64> for ProgressBarWidget {
fn event(&mut self, _ctx: &mut EventCtx, _event: &Event, _data: &mut f64, _env: &Env) {}
fn lifecycle(&mut self, _ctx: &mut LifeCycleCtx, _event: &LifeCycle, _data: &f64, _env: &Env) {}
fn update(&mut self, ctx: &mut UpdateCtx, _old_data: &f64, _data: &f64, _env: &Env) {
ctx.request_paint();
}
fn layout(
&mut self,
_layout_ctx: &mut LayoutCtx,
bc: &BoxConstraints,
_data: &f64,
_env: &Env,
) -> Size {
// width height 宽高
bc.constrain((360.0, 40.0))
}
fn paint(&mut self, ctx: &mut PaintCtx, data: &f64, env: &Env) {
let height = env.get(theme::BASIC_WIDGET_HEIGHT);
let corner_radius = env.get(theme::PROGRESS_BAR_RADIUS);
let clamped = data.max(0.0).min(1.0);
let stroke_width = 2.0;
let inset = -stroke_width / 2.0;
let size = ctx.size();
// let str = format!("{:.2}%", clamped * 100.0);
let rounded_rect = Size::new(size.width, height)
.to_rect()
.inset(inset)
.to_rounded_rect(corner_radius);
// Paint the border
ctx.stroke(rounded_rect, &env.get(theme::BORDER_DARK), stroke_width);
// Paint the background
let background_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(
env.get(theme::BACKGROUND_LIGHT),
env.get(theme::BACKGROUND_DARK),
),
);
ctx.fill(rounded_rect, &background_gradient);
// Paint the bar
let calculated_bar_width = clamped * rounded_rect.width();
let rounded_rect = Rect::from_origin_size(
Point::new(-inset, 0.),
Size::new(calculated_bar_width, height),
)
.inset((0.0, inset))
.to_rounded_rect(corner_radius);
let bar_gradient = LinearGradient::new(
UnitPoint::TOP,
UnitPoint::BOTTOM,
(env.get(theme::PRIMARY_LIGHT), env.get(theme::PRIMARY_DARK)),
);
ctx.fill(rounded_rect, &bar_gradient);
}
fn debug_state(&self, data: &f64) -> DebugState {
DebugState {
display_name: self.short_type_name().to_string(),
main_value: data.to_string(),
..Default::default()
}
}
}
|
/**
* Writes dynamic property information for {@link ShapedElement} or
* {@link State} pathway element. In GPML2013a, cellular component shapeTypes
* and double lineStyle information are written to dynamic properties because
* they were not yet defined in the GPML2013a schema/enum classes.
*
* @param dynamicProperties the list of dynamic properties.
* @param shapedElement the shaped pathway element.
* @param se the jdom shaped pathway element element.
* @throws ConverterException
*/
protected void writeShapedOrStateDynamicProperties(Map<String, String> dynamicProperties,
ShapedElement shapedElement, Element se) throws ConverterException {
for (String key : dynamicProperties.keySet()) {
Element dp = new Element("Attribute", se.getNamespace());
setAttr("Attribute", "Key", dp, key);
setAttr("Attribute", "Value", dp, dynamicProperties.get(key));
if (dp != null) {
se.addContent(dp);
}
}
ShapeType shapeType = shapedElement.getShapeType();
if (CELL_CMPNT_MAP.containsKey(shapeType)) {
Element dp = new Element("Attribute", se.getNamespace());
setAttr("Attribute", "Key", dp, CELL_CMPNT_KEY);
String shapeTypeStr = shapeType.getName();
shapeTypeStr = fromCamelCase(shapeTypeStr);
setAttr("Attribute", "Value", dp, shapeTypeStr);
if (dp != null) {
se.addContent(dp);
}
}
LineStyleType borderStyle = shapedElement.getBorderStyle();
if (borderStyle.getName().equalsIgnoreCase("Double")) {
Element dp = new Element("Attribute", se.getNamespace());
setAttr("Attribute", "Key", dp, DOUBLE_LINE_KEY);
setAttr("Attribute", "Value", dp, "Double");
if (dp != null) {
se.addContent(dp);
}
}
if (shapedElement.getClass() == State.class) {
Double rotation = shapedElement.getRotation();
if (rotation != 0) {
String rotationStr = String.valueOf(rotation);
Element dp = new Element("Attribute", se.getNamespace());
setAttr("Attribute", "Key", dp, STATE_ROTATION);
setAttr("Attribute", "Value", dp, rotationStr);
if (dp != null) {
se.addContent(dp);
}
}
}
} |
<filename>sdk/go/pulumi/urnset.go
// Copyright 2016-2021, Pulumi Corporation.
//
// 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 pulumi
import (
"sort"
)
type urnSet map[URN]struct{}
func (s urnSet) add(v URN) {
s[v] = struct{}{}
}
func (s urnSet) has(v URN) bool {
_, ok := s[v]
return ok
}
func (s urnSet) contains(other urnSet) bool {
for v := range other {
if !s.has(v) {
return false
}
}
return true
}
func (s urnSet) union(other urnSet) {
for v := range other {
s.add(v)
}
}
func (s urnSet) values() []URN {
values := make([]URN, 0, len(s))
for v := range s {
values = append(values, v)
}
return values
}
func (s urnSet) sortedValues() []URN {
v := s.values()
sort.Slice(v, func(i, j int) bool { return v[i] < v[j] })
return v
}
|
In known wall-protecting handrails, rail members are mounted on brackets in a manner such they can deflect and deform under impacts from objects to prevent damage to the underlying wall. The rail members protect the underlying walls and provide support for persons walking through the building. These handrails are widely used in hospitals and nursing homes, where carts, wheelchairs and the like are moved through hallways and are likely to strike the walls.
Known handrails are supported in spaced-apart relation to the walls to allow space between the handrail and the user's fingers. The supports are individual brackets that are strongly attached to the walls and to the handrails. In some cases a single bolt is used that passes through a hole in a portion of the handrail, a corresponding hole in the bracket, and through the wall. Such a system is disclosed in U.S. Pat. No. 5,288,048.
Also known is a handrail installation in which single bolts are used at each support point for the rail and in which the rail need not be drilled to fasten it to the support. The rail and supports permit covers and/or other components to be pre-assembled to the rail before the rail is attached to the supports. All of the supports for the rail can be installed onto the wall or post system (or other supporting structure) before the rail is installed. The rail is then installed onto the supports using a tool. Such a system is disclosed in U.S. Pat. No. 6,508,458.
The present inventors have recognized the need for a handrail assembly that allows the handrail supports to be first installed onto the wall and then the handrail installed onto the supports. The present inventors have recognized the need for supports that eliminate the requirement for using a tool to install the handrail to the supports and that constituted an easily installed and cost effective assembly. |
<gh_stars>1-10
/// <reference types="node" />
import { WriteStream } from 'fs';
import { ServerResponse } from 'http';
import PokeResult, { PokeError, PokeSuccess } from '../interfaces/PokeResult';
/**
* Defines protocol js.Poke supports
*/
declare type Protocol = 'http' | 'https';
/**
* Callback event name
*/
export declare type CallbackEvent = 'data' | 'error' | 'response' | 'end';
/**
* Defines types of stream
*/
declare type Stream = WriteStream | ServerResponse;
/**
* Defines container for different callbacks
*/
declare type EventCallbacksContainer = {
data?: (chunk: string | Buffer) => void;
error?: (result: PokeError) => void;
response?: (param?: PokeSuccess) => void;
end?: () => void;
};
export declare type EventCallbackFunctions = EventCallbacksContainer[keyof EventCallbacksContainer];
export declare class EventManagerClass {
protected callbacks: EventCallbacksContainer;
protected isPokeError: (input: PokeError) => void;
constructor();
protected isProtocol: (input: string) => input is Protocol;
protected isCallbackEvent(input: string): input is CallbackEvent;
protected set(eventName: CallbackEvent, callback: any): void;
protected response(result: PokeResult): void;
protected end(): void;
protected error(result: PokeError): void;
protected data(chunk: string): void;
protected stream(writableStream: Stream): void;
}
export {};
|
export let USERS_API_URL: string
export let POSTS_API_URL: string
export let FEED_API_URL: string
export let USERS_SEARCH_API_URL: string
export const setConfigVariables = (name?: string) => {
USERS_API_URL = name ? `https://users.${name}/api/v2` : 'https://users.api.feeds.dev/api/v2'
POSTS_API_URL = name ? `https://posts.${name}/api/v3` : 'https://posts.api.feeds.dev/api/v3'
FEED_API_URL = name ? `https://posts.${name}/api/v3` : 'https://posts.api.feeds.dev/api/v3'
USERS_SEARCH_API_URL = name ? `https://users.${name}/api/v3` : 'https://users.api.feeds.dev/api/v3'
} |
/*
* OpenBOR - http://www.LavaLit.com
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE in OpenBOR root for details.
*
* Copyright (c) 2004 - 2011 OpenBOR Team
*/
#ifndef KERNEL_PRX_H
#define KERNEL_PRX_H
#include <psploadexec_kernel.h>
int loadexec(const char *file, struct SceKernelLoadExecVSHParam *param);
int getDevkitVersion();
int getHardwareModel();
#endif
|
An image shows the areas where the state's rain debt has been most dramatic, the larger the precipitation deficit, the redder the map. Photo by NASA/Goddard Scientific Visualization Studio
LOS ANGELES, July 30 (UPI) -- It would take a whole year's worth of precipitation to replenish the drought-ridden soils of California and erase the state's so-called "rain debt."
That's the takeaway from a new study by researchers at NASA's Goddard Space Flight Center. The scientists used decades of satellite data and ground-based precipitation measurements to analyze average rain and snow totals.
The data was used to calculate how far recent precipitation totals have fallen short of expected averages.
Averages aren't necessarily the norm, but the middle point between fluctuations. In non-drought periods, wet and dry years balance each other out. But according to the new study -- published in the Journal of Geophysical Research -- California has experienced a string of dry years between 2012 and 2014, building up a rain deficit of 13 inches.
Another seven inches have been added in recent months, bringing the total debt to 20. That's the equivalent of an average year's precipitation in the Golden State.
The team of researchers, led by Andrey Savtchenko, say the state's rain debt and ongoing drought is mostly the result of a stationary high-pressure system off the coast that's continually blocked the formation of what scientists call "atmospheric rivers."
Atmospheric rivers are narrow bands of water vapor that travel between differing bodies of moving air, sometime propelled by and along with jet streams. They exist all over the world and generally travel west to east. When they arrive on the coast of California from the Pacific, these condense bands of water-rich air are pushed up by the mountains, squeezing the water out in intense rainfall events.
California, the new research suggests, relies on these rivers to supply anywhere from a quarter to a half of their average precipitation total.
"When they say that an atmospheric river makes landfall, it's almost like a hurricane, without the winds. They cause extreme precipitation," Savtchenko explained in a press release.
Some forecasters have suggested the strengthening El Nino system off the Southern California coast could encourage a more active rainy season during the fall and winter, alleviating the state's drought. But while the system is more likely to encourage rain than not, Savtchenko says El Nino patterns are a small factor in governing California's long term precipitation trends.
The new research suggests dramatic precipitation variability and long droughts are simply a fact of life in California. Some suggest it will only get worse as the planet warms. It's a conundrum that's a reality for more and more people as the state's population continues to grow.
"Drought has happened here before. It will happen again, and some research groups have presented evidence it will happen more frequently as the planet warms," Savtchenko said. "But, even if the climate doesn't change, are our demands for fresh water sustainable?" |
Roost of Gray Flying Foxes (Pteropus griseus) in Indonesia and Records of a New Hunting Threat Pteropus griseus (gray flying fox) is a species of Old World fruit bat that is listed by the International Union for Conservation of Nature (IUCN) as Data Deficient. The species is found on small islands in the Lesser Sundas and Sulawesi, and is endemic to Indonesia, but no contemporary roosts are known, and the last study of the species was in Timor in the Lesser Sundas. In this study, we describe the first known day roost in Sulawesi for Pteropus griseus and collected anecdotal evidence regarding conservation threats to the colony. We compared data from flying foxes collected from this roost to other P. griseus specimens and those of closely related co-occurring species to confirm its identity. We confirmed that this roost is likely of Pteropus griseus, though the subspecies identity remains to be determined. However, it is newly threatened by middlemen traders of bat meat from North Sulawesi arriving to encourage local villagers near the roost to hunt the bats. Elevated levels of hunting may deplete the entire colony in a single season should no conservation action be taken to safeguard the roost. |
export default 'https://avb-contacts-api.herokuapp.com';
|
<reponame>mjd507/ZSYY
package com.rainwii.zsyy.activity.online;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.rainwii.zsyy.R;
import com.rainwii.zsyy.activity.base.BaseActivity;
/**
* 描述:
* 作者 mjd
* 日期:2015/10/29 10:23
*/
public class OnlineQuestionTalkActivity extends BaseActivity {
private ImageView tvDoctorPhoto;
private TextView tvName;
private TextView tvPosition;
private RatingBar ratingBar;
private Button btnAsk;
private ListView lv;
private RelativeLayout layoutMedia;
private void assignViews() {
tvDoctorPhoto = (ImageView) findViewById(R.id.tv_doctor_photo);
tvName = (TextView) findViewById(R.id.tv_name);
tvPosition = (TextView) findViewById(R.id.tv_position);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
btnAsk = (Button) findViewById(R.id.btn_ask);
lv = (ListView) findViewById(R.id.lv);
layoutMedia = (RelativeLayout) findViewById(R.id.layout_media);
}
@Override
protected void initViews() {
setContentView(R.layout.activity_online_question_talk);
setTitleBack("图文咨询");
assignViews();
}
@Override
protected void initData() {
tvDoctorPhoto.setImageResource(R.drawable.ic_doctor_logo);
tvName.setText("范小芬");
tvPosition.setText("副主任医师");
ratingBar.setRating(5);
btnAsk.setVisibility(View.VISIBLE);
}
@Override
protected void initListeners() {
btnAsk.setOnClickListener(this);
}
@Override
protected void handleClick(View view) {
switch (view.getId()) {
case R.id.btn_ask:
enterActivity(OnlineAskQuestionActivity.class);
break;
}
}
}
|
<filename>src/main/java/com/github/dockerjava/core/util/ServiceFiltersBuilder.java<gh_stars>0
package com.github.dockerjava.core.util;
import org.apache.commons.lang.builder.EqualsBuilder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Representation of filters to service lists.
*/
public class ServiceFiltersBuilder {
private Map<String, List<String>> filters = new HashMap<>();
public ServiceFiltersBuilder() {
}
public ServiceFiltersBuilder withFilter(String key, String... value) {
filters.put(key, Arrays.asList(value));
return this;
}
public ServiceFiltersBuilder withFilter(String key, List<String> value) {
filters.put(key, value);
return this;
}
public List<String> getFilter(String key) {
return filters.get(key);
}
public ServiceFiltersBuilder withIds(List<String> ids) {
withFilter("id", ids);
return this;
}
public List<String> getIds() {
return getFilter("id");
}
public ServiceFiltersBuilder withNames(List<String> names) {
withFilter("name", names);
return this;
}
public List<String> getNames() {
return getFilter("names");
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
@Override
public int hashCode() {
return filters.hashCode();
}
public Map<String, List<String>> build() {
return filters;
}
}
|
package org.jessenpan.leetcode.bit;
/**
* @author jessenpan
* tag:bit
*/
public class S393Utf8Validation {
public boolean validUtf8(int[] data) {
if (data == null || data.length == 0) {
return false;
}
int len = data.length;
int i = 0;
while (i < len) {
if (((data[i] >> 3) & 30) == 30 && ((data[i] >> 3) & 1) == 0) {
//4-byte
if (len - i - 1 < 3) {
return false;
}
if (isValidLeft(data, i + 1, 3)) {
i += 4;
continue;
} else {
return false;
}
} else if (((data[i] >> 4) & 14) == 14 && ((data[i] >> 4) & 1) == 0) {
//3-byte
if (len - i - 1 < 2) {
return false;
}
if (isValidLeft(data, i + 1, 2)) {
i += 3;
continue;
} else {
return false;
}
} else if (((data[i] >> 5) & 6) == 6 && ((data[i] >> 5) & 1) == 0) {
//2-byte
if (len - i - 1 < 1) {
return false;
}
if (isValidLeft(data, i + 1, 1)) {
i += 2;
continue;
} else {
return false;
}
} else if (((data[i] >> 7) & 1) == 0) {
i++;
continue;
}
return false;
}
return true;
}
private boolean isValidLeft(int[] data, int index, int size) {
int len = index + size;
for (int i = index; i < len; i++) {
if (!isValidOther(data[i])) {
return false;
}
}
return true;
}
private boolean isValidOther(int data) {
return ((data >> 6) & 2) == 2;
}
}
|
<reponame>Team-Black/JavaAutoTest
package jbse.algo;
import java.util.function.Supplier;
import jbse.common.exc.ClasspathException;
import jbse.mem.State;
import jbse.mem.exc.FrozenStateException;
import jbse.val.Calculator;
/**
* One implicit (boolean, is offset far?),
* one immediate (offset).
*
* @author <NAME>
*
*/
public final class BytecodeData_1ZOF extends BytecodeData {
final boolean far;
@Override
public void readImmediates(State state, Calculator calc)
throws InterruptException, ClasspathException, FrozenStateException {
if (this.far) {
readImmediateSignedDword(state, calc, 1);
readJump(state, immediateSignedDword());
} else {
readImmediateSignedWord(state, calc, 1);
readJump(state, immediateSignedWord());
}
}
/**
* Do not instantiate!
*/
private BytecodeData_1ZOF(boolean far) {
this.far = far;
}
/**
* Factory (with fluent interface).
*
* @param far a {@code boolean}, whether the jump is a far jump.
* It is the value of the implicit of the created object.
* @return a {@link Supplier}{@code <}{@link BytecodeData_1ZOF}{@code >},
* the actual factory for {@link BytecodeData_1ZOF} objects.
*/
public static Supplier<BytecodeData_1ZOF> withFarOffset(boolean far) {
return () -> new BytecodeData_1ZOF(far);
}
}
|
Effects of alfentanil and esmolol on hemodynamic and catecholamine response to tracheal intubation. OBJECTIVE To compare the effects of alfentanil and esmolol on hemodynamic and catecholamine response to tracheal intubation. METHODS Thirty-five adult patients were randomly allocated to one of three groups, Group A (control group). Group B (esmolol group) and Group C (alfentanil group). The patients received either 2 mg/kg esmolol (in Group B) or 30 microg/kg alfentanil (in Group C) before intubation. Tracheal intubation was performed with 4 mg/kg thiopental and 0.1 mg/kg vecuronium and 3% isoflurane. Systolic blood pressure (SBP), diastolic blood pressure (DBP), mean blood pressure (MBP), heart rate (HR), norepinephrine (NE), epinephrine (E) and dopamine (DA) were measured before and after intubation. RESULTS The control group had a baseline SBP of 149 +/- 23 mmHg while Groups B, C had a baseline SBP of 148 +/- 23, and 150 +/- 21 mmHg, respectively (P>0.05). Three min after tracheal intubation, the control group SBP increased to 160 +/- 30 mmHg and Group B remained at the baseline level, 147 +/- 5 mmHg, and Group C significantly decreased to 91 +/- 22 mmHg (P<0.01). Two min after intubation HR in Group B increased significantly but 3 min after intubation HR in Groups B and C were significantly lower than that of control group (P<0.05). NE in Groups A and B increased significantly to 5.75 +/- 3.51 and 6.75 +/- 3.30 nmol/L 3 min after intubation (P<0.01). In Group C, 3 min after intubation NE was not significantly different from the baseline but E decreased significantly (P<0.01). CONCLUSION 2 mg/kg esmolol can moderate the hemodynamic response to tracheal intubation to a certain extent and 30 microg/kg alfentanil can completely attenuate the hemodynamic and catecholamine responses. |
Production of Chinese hamster monoclonal antibody to a human cell-surface antigen using a hamster-human somatic cell hybrid as antigen. Hybridomas producing monoclonal antibody (MAb) of predefined specificity were isolated from a Chinese hamster that had received injections of a Chinese hamster-human somatic cell hybrid. A standard method for the production of murine hybridomas was used to produce Chinese spleen lymphocyte X murine plasmacytoma hybridomas, and they were screened for complement-mediated cytotoxicity against a panel of Chinese hamster-human somatic cell hybrids and agglutination of human erythrocytes. Two hybridomas were established in tissue culture following limiting dilution cloning, and their reactivity with a panel of Chinese hamster-human somatic cell hybrids indicates that they are specific for the previously identified human cell-surface antigen a1. The Chinese hamster appears to respond preferentially to human antigens of Chinese hamster-human somatic cell hybrids, and it will serve as a useful tool for the production of MAb specific for human cell-surface antigens expressed in the many well-characterized Chinese hamster-human somatic cell hybrids available. |
Veterans History Project
The Veterans History Project of the Library of Congress American Folklife Center (commonly known as the Veterans History Project) was created by the United States Congress in 2000 to collect and preserve the firsthand remembrances of U.S. wartime veterans. Its mandate ensures future generations may hear directly from those who served to better understand the realities of war.
The program is conducted through Congressional offices and relies on a national network of veteran service organizations, universities, secondary schools, community groups and the general public to record interviews according to program guidelines. These and original letters, diaries, photos, memoirs and historic documents related to a veteran's wartime service are then preserved at the Library of Congress. Through 2010 the project held more than 65,000 collections and was considered the largest oral history program of its kind in the nation. It serves as an important resource for scholars, historians, students and the general public.
The Veterans History Project authorizing legislation (Public Law 106-380) was sponsored by Representatives Ron Kind, Amo Houghton, and Steny Hoyer in the U.S. House of Representatives and Senators Max Cleland and Chuck Hagel in the U.S. Senate. It received unanimous support and was signed into law by President Bill Clinton on October 27, 2000. |
use std::error::Error;
use domain::organization::team::{Repository, Service, Team, ValidationError};
use uuid::Uuid;
pub struct TeamService<R: Repository> {
pub repository: R,
}
impl<R: Repository> Service for TeamService<R> {
fn create(&self, team: Team) -> Result<Team, Box<dyn Error>> {
fn validate(team: Team) -> Result<Team, Box<dyn Error>> {
if team.id.is_some() {
Err(ValidationError::IdIsPresent.into())
} else {
Ok(team)
}
}
self.repository.add(validate(team)?)
}
fn read(&self, id: Uuid) -> Result<Option<Team>, Box<dyn Error>> {
fn validate(id: Uuid) -> Result<Uuid, Box<dyn Error>> {
if id.is_nil() {
Err(ValidationError::InvalidId.into())
} else {
Ok(id)
}
}
self.repository.find_by_id(validate(id)?)
}
fn list(&self, organization_id: Uuid) -> Result<Vec<Team>, Box<dyn Error>> {
fn validate(organization_id: Uuid) -> Result<Uuid, Box<dyn Error>> {
if organization_id.is_nil() {
Err(ValidationError::InvalidOrganizationId.into())
} else {
Ok(organization_id)
}
}
self.repository
.find_all_by_organization_id(validate(organization_id)?)
}
fn update(&self, team: Team) -> Result<Team, Box<dyn Error>> {
fn validate(team: Team) -> Result<Team, Box<dyn Error>> {
if team.id.is_none() {
Err(ValidationError::IdIsNone.into())
} else if team.id.ok_or("expected ID")?.is_nil() {
Err(ValidationError::InvalidId.into())
} else {
Ok(team)
}
}
self.repository.add(validate(team)?)
}
fn delete(&self, id: Uuid) -> Result<Option<Team>, Box<dyn Error>> {
fn validate(id: Uuid) -> Result<Uuid, Box<dyn Error>> {
if id.is_nil() {
Err(ValidationError::InvalidId.into())
} else {
Ok(id)
}
}
self.repository.remove(validate(id)?)
}
}
|
Perceived burdensomeness and thwarted belongingness influence the childhood polyvictimization and suicide ideation association among Hispanic undergraduates Abstract The present study examined the mediating effect of perceived burdensomeness (PB) and thwarted belongingness (TB) in the association between childhood polyvictimization and suicide ideation (past week) among 528 Hispanic college students. Nearly 10% reported polyvictimization, 19.8% had suicide ideation, and polyvictimization was a risk factor of suicide ideation through PB and TB. The indirect effect through PB was stronger than the indirect effect through TB. Interventions should focus on PB and TB to alleviate suicide ideation among Hispanic undergraduate students. |
Perspectives in the treatment of renal anaemia new concepts and new drugs. There are several new erythropoiesis stimulating agents that may potentially improve in the near future the management of anaemia in patients with chronic kidney disease. Some of the new erythropoiesis stimulating agents were synthesised by modification of the aminoacide sequence of the erythropoietin (EPO) molecule and hyperglycosylation and therefore they have improved pharmacokinetics (darbopoietin or CERA) by prolongation of the serum elimination half-life compared to epoietins. These agents may be administered less frequently with better stabilisation of blood haemoglobin concentration. There are a promising attempts to overcome the parenteral way of drug administration. Such non-peptide drugs acts as inhibitors of prolyl hydroxylase and GATA-2 transcription factor enhancing the endogenous EPO synthesis. |
Reconstruction of monthly NAO and EU indices back to AD 1675 Instrumental station pressure, temperature and precipitation measurements and proxy data were used to statistically reconstruct monthly time series of the North Atlantic Oscillation (NAO) and the Eurasian (EU) circulation indices back to 1675. Systematic testing of the reconstruction procedure indicated generally reliable reconstructions throughout the entire period, except for summertime before about 1750. Predictive skill varied for different subperiods depending on data availability. It was highest for autumn and winter and was generally better for the EU than for the NAO index. Wavelet analysis suggested significant lowfrequency variability, especially for the spring, summer and annual averaged indices. The covariability between the NAO and EU indices was found to exhibit large decadal to century timescale variations, indicating that climate variability over the continent is temporarily decoupled from the NAO. |
YANGON (Reuters) - A top United Nations envoy held talks with Myanmar pro-democracy leader Aung San Suu Kyi on Saturday but there was no indication the country’s reclusive military rulers were willing to meet him.
Vijay Nambiar met with Nobel laureate Suu Kyi, who was released from seven years of house arrest on November 13, for nearly two hours in Yangon but his itinerary did not include the capital Naypyitaw, home to government ministers and the junta top brass.
Diplomats said Nambiar’s failure to meet the regime on his first visit, just a few weeks after Myanmar’s first election in two decades and ahead of the formation of a new civilian-led government, suggests there could be many hurdles ahead in the West’s efforts to engage the generals.
Nambiar, who was appointed special envoy to Myanmar by U.N. Secretary-General Ban Ki-moon earlier this year, was scheduled to meet diplomats and recently elected lawmakers over the weekend. He is due to leave Myanmar on Monday.
Suu Kyi, who has spent 15 of the past 21 years in some form of detention because of her fight against military dictatorship, has been given a free reign by the generals since her release, which has raised some suspicion about their motives.
She welcomed the Indian diplomat’s visit and called for more engagement with the U.N.
“We were able to tell him what we wanted to do, while we got a chance to know the secretary general’s feelings,” Suu Kyi told reporters.
A retired Burmese academic, who asked not to be identified, said the regime’s snub was a sign the generals were not yet willing to cooperate with the U.N. after years of strained ties.
“We can say it is the beginning of a new scenario: a new U.N envoy, Aung San Suu Kyi free from house arrest, newly elected parties and candidates and so on, but the key player is missing,” he said.
Nambiar is a former Indian ambassador to China and is believed to have a good relationship with Beijing, a key ally of the Myanmar junta. He recently visited India, China and Singapore to discuss issues related to Myanmar and its political process.
He is Ban’s chief of staff and has replaced Ibrahim Gambari, who served as the U.N.’s envoy to Myanmar for four years but was widely criticised as being ineffective. |
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.ioc;
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import edu.wpi.first.wpilibj.RobotBase;
import edu.wpi.first.wpilibj.XboxController;
import frc.robot.commands.navcommands.GoToPosition;
import frc.robot.commands.navcommands.mocks.MockGotoPosition;
import frc.robot.common.*;
import frc.robot.subsystems.*;
import frc.robot.subsystems.mocks.MatchSimDrivetrain;
import frc.robot.subsystems.mocks.MockCommandDrivetrain;
import frc.robot.subsystems.mocks.MockDrivetrain;
import frc.robot.subsystems.mocks.MockIntake;
import frc.robot.subsystems.mocks.MockLedSubsystem;
import frc.robot.subsystems.mocks.MockShooter;
/**
* Add your docs here.
*/
public class DependenciesModule extends AbstractModule {
protected void configure() {
// create logger for injecting
this.bind(ILogger.class).toProvider(LoggerProvider.class);
this.bind(Location.class).asEagerSingleton();
// Due to some subsystems not being compatible with the HAL Sims we need to use
// mocks instead
if (RobotBase.isReal()) {
this.bind(IShooterSubsystem.class).to(ShooterSubsystem.class).in(Singleton.class);
this.bind(IDrivetrainSubsystem.class).to(SwerveDrivetrain.class).in(Singleton.class);
this.bind(IClimbSubsystem.class).to(ClimbSubsystem.class).in(Singleton.class);
this.bind(IIntakeSubsystem.class).to(Intake.class).in(Singleton.class);
this.bind(ILedSubsystem.class).to(LedSubsystem.class).in(Singleton.class);
} else {
this.bind(IShooterSubsystem.class).to(MockShooter.class).in(Singleton.class);
this.bind(IDrivetrainSubsystem.class).to(MockDrivetrain.class).in(Singleton.class);
this.bind(IIntakeSubsystem.class).to(MockIntake.class).in(Singleton.class);
this.bind(MockCommandDrivetrain.class).to(MatchSimDrivetrain.class);
// Mock out the Navigation Commands
this.bind(GoToPosition.class).to(MockGotoPosition.class);
this.bind(ILedSubsystem.class).to(MockLedSubsystem.class).in(Singleton.class);
}
}
}
|
<filename>sources/ippcp/pcparcfourencrypt.c
/*******************************************************************************
* Copyright 2005-2020 Intel Corporation
*
* 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.
*******************************************************************************/
/*
//
// Purpose:
// Cryptography Primitive.
// RC4 implementation
//
*/
#include "owndefs.h"
#include "owncp.h"
#include "pcparcfour.h"
#include "pcptool.h"
/*F*
// Name: ippsARCFourEncrypt
//
// Purpose: Encrypt data stream.
//
// Returns: Reason:
// ippStsNullPtrErr pCtx == NULL
// pSrc == NULL
// pDst == NULL
// ippStsContextMatchErr pCtx->idCtx != idCtxARCFOUR
// ippStsLengthErr length<1
// ippStsNoErr no errors
//
// Parameters:
// pSrc pointer to the source byte data block stream
// pDst pointer to the destination byte data block stream
// length stream length (bytes)
// pCtx ponter to the ARCFOUR context
//
// Note:
// Convenience function only
*F*/
IPPFUN(IppStatus, ippsARCFourEncrypt, (const Ipp8u *pSrc, Ipp8u *pDst, int length,
IppsARCFourState *pCtx))
{
/* test context */
IPP_BAD_PTR1_RET(pCtx);
/* use aligned context */
pCtx = (IppsARCFourState*)( IPP_ALIGNED_PTR(pCtx, RC4_ALIGNMENT) );
IPP_BADARG_RET(!RC4_VALID_ID(pCtx), ippStsContextMatchErr);
/* test source and destination pointers */
IPP_BAD_PTR2_RET(pSrc, pDst);
/* test stream length */
IPP_BADARG_RET((length<1), ippStsLengthErr);
/* process data */
ARCFourProcessData(pSrc, pDst, length, pCtx);
return ippStsNoErr;
}
|
<gh_stars>0
import React from 'react';
import styled from 'styled-components';
import { BsArrowClockwise } from 'react-icons/bs';
export const ButtonHolder = function(props: any) {
return (<>
<ButtonHolderWrapper>
<TextHolder>Iteration count: {props.i}</TextHolder>
<RefreshBtn onClick={props.onRefresh}><BsArrowClockwise></BsArrowClockwise></RefreshBtn>
<TextHolder><small>Made by <A target="_blank" href="https://github.com/capure" >Capure</A></small></TextHolder>
</ButtonHolderWrapper>
</>);
}
const A = styled.a`
text-decoration: none;
color: white;
outline: none;
transition: 1s ease;
&:hover {
color: #f57a54;
}
`;
const RefreshBtn = styled.div`
color: white;
font-size: 50px;
width: 350px;
display: flex;
justify-content: center;
align-items: center;
transition: 1s ease;
&:hover {
color: #427afd;
cursor: pointer;
}
`;
const TextHolder = styled.div`
color: white;
font-size: 30px;
height: 100%;
width: 320px;
margin-left: 30px;
display: flex;
align-items: center;
justify-content: flex-start;
`;
const ButtonHolderWrapper = styled.div`
width: 100%;
height: 150px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
background-color: #1c1b1d;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
`; |
Inspection Camera Guide: What are are the Best Models to consider?
When it comes to choosing the best model of inspection camera, unfortunately there is no one best model to suit all applications. The model that you choose will be very much dependent on your need. Inspection cameras are used for so many purposes and it would be best to consider your own need prior to even looking at the models that are available. Inspection cameras are used to view inaccessible spaces which cannot be seen by the human eye, in drains, under floors, in roof spaces, behind walls and even in the human body, there are so many applications. The cameras come with a flexible or rigid tube of varying lengths, attached to a camera at one end and a monitor at the other end. Technology is such now that the camera can be attached to a mobile phone or tablet and is capable of not only displaying the picture of what is behind the structure but it can also photograph and record the images with high resolution allowing the user to have a clear and accurate picture of what is going on. The applications are endless and the time, effort and money that they can save a company is quite considerable. Consider a surgeon working to save someone’s life, the examinations that can take place can provide a quick diagnosis and it takes a lot of the ‘guesswork’ out of the equation for the surgeon.
What about the engineer who is working on large pieces of machinery, maybe on an aircraft or HGV. Without the camera, diagnostics would involve dismantling large pieces of equipment to attempt to get to the route of the problem whereas the camera can be used in very small spaces and between structures to save the time and effort involved in taking the machinery to pieces. The cameras have various features, some of which are listed below and it is up to the purchaser to decide on the features that they would need. Costs vary with some of the very sophisticated machines costing quite a bit to some of the less involved cameras being within easy reach of most homeowners, meaning that they can be used for applications in and around the home too.
You can read more about inspection cameras through other sources. Read the following guide after you’ve been through this full review: Top 10 Best Inspection Camera (Reviews).
What size does the camera need to be?
What length of tubing do you require and how strong does it have to be?
Do you require it to be waterproof?
How much illumination do you require?
What size of flash memory would you require?
Would you need a zoom feature?
Do you need to be able to rotate the image on the screen?
Would you require that the camera switches itself off after a period of inactivity?
Do you require the ability to be able to record your voice to describe what is seen by the camera as the images emerge?
With so many different options, the best model will be the one to suit your application, read the reviews to hear from those who have bought the camera. You do want your camera to be of a good, robust quality, capable of clear and meaningful images. |
Numerical study of conjugate heat transfer within a bottom heated cylindrical enclosure The conjugate heat transfer within a bottom-heated non-conventional cylindrical enclosure is important with respect to the processes in chemical and nuclear industries. In this research work numerical analysis of the enclosure with respect to the centrifuge machines used in the process industry is presented. Various CFD simulations of the experimental work of are performed to study the effects of materials of the disc and inner cylinder and geometries of outer cylinder on the enclosure. Generally, a uniform temperature is required in such enclosures. A more uniform temperature is observed in the enclosure by using aluminum inner cylinder at a temperature of 433K of the bottom disc and using two different diameter outer cylinders as compared to the mild steel and stainless steel. |
<reponame>lxliuxuankb/skywalking<gh_stars>1-10
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.skywalking.oap.server.core.analysis.metrics;
import org.apache.skywalking.oap.server.core.remote.grpc.proto.RemoteData;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class ApdexMetricsTest {
@Before
public void setUp() {
ApdexMetrics.setDICT(name -> name.equals("foo") ? 500 : 1000);
}
@Test
public void testEntrance() {
ApdexMetrics apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.calculate();
assertThat(apdex.getValue(), is(10000));
apdex = new ApdexMetricsImpl();
apdex.combine(1000, "foo", true);
apdex.calculate();
assertThat(apdex.getValue(), is(5000));
apdex = new ApdexMetricsImpl();
apdex.combine(2000, "foo", true);
apdex.calculate();
assertThat(apdex.getValue(), is(0));
apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.combine(300, "bar", true);
apdex.calculate();
assertThat(apdex.getValue(), is(10000));
apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.combine(1500, "bar", true);
apdex.calculate();
assertThat(apdex.getValue(), is(7500));
apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.combine(300, "bar", false);
apdex.calculate();
assertThat(apdex.getValue(), is(5000));
apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.combine(1500, "bar", false);
apdex.calculate();
assertThat(apdex.getValue(), is(5000));
apdex = new ApdexMetricsImpl();
apdex.combine(200, "foo", true);
apdex.combine(5000, "bar", true);
apdex.calculate();
assertThat(apdex.getValue(), is(5000));
}
@Test
public void testCombine() {
ApdexMetrics apdex1 = new ApdexMetricsImpl();
apdex1.combine(200, "foo", true);
apdex1.combine(300, "bar", true);
apdex1.combine(200, "foo", true);
apdex1.combine(1500, "bar", true);
ApdexMetrics apdex2 = new ApdexMetricsImpl();
apdex2.combine(200, "foo", true);
apdex2.combine(300, "bar", false);
apdex2.combine(200, "foo", true);
apdex2.combine(1500, "bar", false);
apdex2.combine(200, "foo", true);
apdex2.combine(5000, "bar", true);
apdex1.combine(apdex2);
apdex1.calculate();
assertThat(apdex1.getValue(), is(6500));
}
public class ApdexMetricsImpl extends ApdexMetrics {
@Override
public String id() {
return null;
}
@Override
public Metrics toHour() {
return null;
}
@Override
public Metrics toDay() {
return null;
}
@Override
public Metrics toMonth() {
return null;
}
@Override
public int remoteHashCode() {
return 0;
}
@Override
public void deserialize(RemoteData remoteData) {
}
@Override
public RemoteData.Builder serialize() {
return null;
}
}
}
|
Data on expectations, perceived quality, satisfaction with hospital care and financial ability of patients who suffer from acute and chronic respiratory diseases, in Central Greece. The research article presents the data collected from a questionnaire based survey that aimed to evaluate patients expectations, perceived quality, satisfaction with hospital care and financial ability of 202 hospitalized patients suffering from acute or chronic respiratory diseases. The anonymous and self-completed questionnaire was divided in two parts. The first part included questions to elicit information on social and demographic characteristics (gender, age group, education level, categorization of respiratory disease, evaluation of the current hospitalization, nationality and way of living with). The second part included the 26-items Elderly Patient Satisfaction Scale and the 12-items Financial Ability Scale, which are validated in the Greek language with a high internal consistency. Data were collected from February 2016 to December 2018. Specifications table Raw, analyzed, descriptive Parameters for data collection Permission to carry out the research in the hospitals was provided by the Scientific Councils of the Public Hospitals in which the participants were hospitalized. A written consent was obtained from all the patients. The anonymity of the patients was guaranteed. They were given an introductory and information sheet for the purpose of the research and were informed that their participation was voluntary and that they were free to withdraw at any time without any consequence. Description of data collection An anonymous and self-completed questionnaire has been distributed to a sample of 202 hospitalized patients suffering from acute or chronic respiratory diseases. Data source location Larissa, Greece Data accessibility Data are hosted with the article Value of the data The data can be used for the evaluation of the expectations, perceived quality, satisfaction with care, and financial ability of patients who suffer from acute and chronic respiratory diseases in Central Greece. The data can be used from other researchers for comparison in different countries. These data add value to patient care especially in countries in which harsh austerity measures were enacted. The questionnaire and the validated scales can be used in other studies for the validation and cultural adaptation in their language and for benchmarking reasons . The data can be used for the improvement of the quality of care provided to patients with acute and chronic respiratory disease. Furthermore, the data are valuable for the development of a national policy for quality assurance of care provided to patients who suffer from respiratory diseases and for the improvement of their financial ability. Data description The dataset in this research article describes the data from 202 (57.4% men) hospitalized patients suffering from acute or chronic respiratory diseases. Raw data of the questionnaire include patients' responses (Supplementary Excel file format) to its items. The questionnaire used in the survey is included in a separated file (Supplementary Word file "Questionnaire"). The labels in the raw data file (Supplementary Excel file format) are in accordance with the items of the questionnaire. The labeling of the variable in the Excel file corresponds to the variable at the "questionnaire". Mean scores have been calculated and the relevant labels are in the Excel file. The "questionnaire" included 3 sections: Section 1 includes 7 social and demographic characteristics (gender, age group, education level, categorization of respiratory disease, evaluation of the current hospitalization, nationality and way of living with) that are presented in Table 1, showing the frequencies and the percentages of their answers. The section 2 includes the 12-items Financial Ability Scale (FAS) and the section 3 the 26-items Elderly Patient Satisfaction Scale (EPSS). The patients were called to reply three times at the same items: one for rating their expectations, one for evaluating perceived quality of care and one for assessing their level of satisfaction with hospital care. The mean scores of the patients at the 26 statements of the expectations, perceived quality and satisfaction with care scales as well as the mean financial ability of the participants are presented in Table 2. High scores indicate high expectations, perceived quality, satisfaction with care and financial ability. Separated comparisons of the differences between the two genders ( Table 3 ), between age groups ( Table 4 ), between persons with different education level ( Table 5 ), between persons with chronic and acute respiratory diseases ( Table 6 ) and between patients' rating of the current hospitalization compared with others in the past ( Table 7 ) regarding their mean expectations, perceived quality and satisfaction with care scores and financial ability have been performed. Table 8 shows the spearman correlation coefficients of the expectations, perceived quality, satisfaction with care and financial ability scores. Experimental design, materials, and methods An anonymous and especially designed questionnaire was used to explore patients' expectancies, perceived quality of care provided and satisfaction with hospital care, as well as their fi- Table 3 Differences between men and women regarding mean expectations, perceived quality and satisfaction with care scores. nancial ability. The patients were recruited on the basis of their availability and their willingness to participate. A written informed consent was obtained from all the patients. The anonymity of the patients was guaranteed. They were given an introductory and information sheet about the purpose and the aim of the research and were informed that their participation was voluntary and that they were free to withdraw at any time without any consequence. The data collection Table 7 Differences between patients' rating of the current hospitalization compared with others in the past and mean expectations, perceived quality, satisfaction with care and financial ability scores. The questionnaire was administered in the Greek language. The first part included questions to elicit information on social and demographics. The second part included the FAS and the EPSS which are validated in the Greek language with a high internal consistency . The EPSS contains 26 statements that evaluate: the patients' expectations in terms of what patients expect from their hospital care (they were called to answer to a 6-likert scale ranging from 0: indifferent to 5: strongly agree), the patients' perceived quality of hospital care that assessed what they consider as quality of care components (they were called to answer to a 8-likert scale ranging from 0: indifferent to 7: very important) the patients' satisfaction with hospital care that consisted of the same 26 statements asking from the patients to answer how they feel with the care provided (they were called to answer to a 8-likert scale ranging from 0: indifferent to 7: very satisfied). In this research, patients' expectations, perceived quality and satisfaction with hospital care were measured within the context of at least three days of hospitalization. The FAS contains 12 items that assess the financial ability of the patients as an indirect measure of the impact of economic crisis on their financial status. The participants were called to answer to each question (how do you rate your ability to) by using a 5-point Likert scale (very good, good, moderate, little, no ability). All the items were coded and scored, and the completed questionnaires were included in the data analysis set. IBM-SPSS-25 was used to analyze the data. Supplementary data associated with this article can be found in the online version at |
BRAF testing in metastatic colorectal carcinoma and novel, chemotherapy-free therapeutic options In the past 25 years, treatment of metastatic colorectal cancer (mCRC) has undergone profound changes. The approval of newer chemotherapeutics such as irinotecan and oxaliplatin was followed in 2005 by the first targeted therapies, for example, monoclonal antibodies directed against the epidermal growth factor receptor (EGFR), as cetuximab and panitumumab, or the angiogenesis inhibitors bevacizumab, ramucirumab, and aflibercept. With the rapidly progressing molecular characterization of mCRC in the last 10 years and the classification of the disease in four consensus subtypes, further changes are emerging, which will promote, among other things, the introduction of protein-kinase inhibitors developed for specific molecular aberrations as well as immune checkpoint inhibitors into the treatment algorithm. Thorough molecular pathologic testing is indispensable today for guideline-compliant treatment of mCRC patients. In addition to RAS testing as a precondition for the therapy decision with regard to cetuximab and panitumumab, BRAF testing is of considerable relevance to allow decision making with regard to the newly approved chemotherapy-free combination of the BRAF inhibitor encorafenib and cetuximab in cases where a BRAF-V600E mutation is detected. Additional diagnostic tests should also include genome instability (microsatellite instability). Overall, more and more molecular alterations need to be investigated simultaneously, so that the use of focused next-generation sequencing is increasingly recommended. This overview describes the prognostic relevance of BRAF testing in the context of molecular pathologic diagnostics of mCRC, presents new treatment options for BRAF-mutated mCRC patients, and explains which modern DNA analytical and immunohistochemical methods are available to detect BRAF mutations in mCRC patients. Despite significant advances in treatment, CRC continues to be one of the cancer entities with an unfavorable prognosis in Europe with about 250,000 deaths per year and an annual incidence of more than 500,000 new cases. As the molecular characterization of metastatic CRC (mCRC) and the classification of CRC into molecular subtypes progresses, the number of options for the use of targeted therapies is also increasing, with molecular diagnostics becoming ever more important. The German version of this article can be found under https://doi.org/10.1007/s00292-021-00942-9 More than 95% of all BRAF mutations are BRAF-V600 mutations, where valine (V) is mostly substituted by glutamic acid (E) at position 1799 in codon 600 (in exon 15) of the BRAF gene. Apart from this most frequent mutation, BRAF V600E, there are also less common mutations in codon 600, in which valine at position 1799 is substituted by lysine (BRAF V600K ), aspartic acid (BRAF V600D ), methionine (BRAF V600M ), or arginine (BRAF V600R ). Clinically, a comparison of the BRAF-V600 mutation with the significantly less common BRAF mutations in codons 594 and 596 shows that the former is more often found in right-sided and mucinous primary tumors with peritoneal metastasis, whereas BRAF 594/596 tumors have a better prognosis. Unless expressly described otherwise, all the statements made in the following sections of this paper refer to BRAF V600E mutations in mCRC. B-Raf is a key kinase in the Ras/RAF/ MEK-mitogen-activated protein kinase (MAPK) signaling pathway, which is involved in the regulation of cell growth. The alteration of the BRAF gene due to mutation leads to the constitutive activation of this protein kinase, thus causing uncontrolled cell division and consecutively leading to (neo-)angiogenesis and metastasis. Resulting from studies on the CRC transcriptome, mCRC has been classified into four consensus subtypes (consensus molecular subtypes, CMS). KRAS mutations predominantly occur in the epithelial, "metabolic" subtype CMS3, which is characterized by metabolic dysregulation and partly also by chromosomal and microsatellite instability (MSI). BRAF mutations, however, are often seen in the "MSI-immune" subtype CMS1, which is dominated by somatic hypermutation and MSI. It is extremely rare that BRAF mutations occur together with a mutation of the RAS gene. According to the current German S3 guideline, molecular testing for the presence of both mutations should be carried out before initiating first-line therapy, wherever possible. In this context, BRAF testing should best be done simultaneously with the RAS test or sequentially after exclusion of the RAS mutation. epidemiological characteristics that differ from those of adenomas and which develop during a "classic adenoma-carcinoma sequence" based on mutations of the APC gene. The BRAF-driven form of sessile serrated adenomas (SSA) leads to impaired apoptosis of crypt epithelia followed by senescence with epigenetic promoter (CpG) methylation and decreased expression of various genes (e.g., hMLH1, MGMT, p16). SSAs as a tumor pre-stage and precursor lesion are flat polyps that barely protrude from the mucosa, predominantly occur in the right-sided colon, and are difficult to detect even endoscopically. Patients with large SSA have a higher risk of developing colorectal cancer; women with SSA have a five-fold higher risk than men. BRAF mutation: a clearly negative prognostic factor in CRC In mCRC, advanced age is a negative prognostic marker, as is tumor location proximal to the left flexure. As part of an investigation on further potential prognostic markers in this indication, the influence of BRAF mutations and MSI on metastatic spread and prognosis was analyzed within a large retrospective case series: BRAF-mutant tumors, particularly those harboring a V600E mutation, are associated with a significantly poorer overall survival (OS) than BRAF wild-type tumors (median 10.4 versus 34.7 months; hazard ratio = 10.66, p < 0.001), as well as with a higher rate of peritoneal and distant lymph node metastasis. The prognostically highly unfavorable impact of BRAF V600 was also repeatedly reported in randomized controlled trials ; a detailed discussion of the prognostic impact of BRAF mutations and their connection with microsatellite stability and instability as a further biomarker can be found in two recent reviews. Apart from hereditary non-polyposisassociated colorectal carcinoma (HN-PCC), MSI occurs in mCRC patients with an estimated frequency of only 4-8%. If BRAF mutations and MSI occur simultaneously-the frequency is reciprocally about one third each-these alterations constitute sporadic defects of mismatch repair (dMMR). MSI patients appear to have a better prognosis than patients with microsatellite stability (MSS) ; although the number of published cases is still limited, the available clinical evidence suggests that patients with a BRAF V600E mutation and MSS have a poorer outcome than those with BRAF V600E and high MSI status. In the metastatic setting, the combination of BRAF V600E and MSS seems to predominate, with the BRAF mutation determining the poor outcome. BRAF mutation: unclear predictive value with regard to former conventional therapies The predictive relevance of BRAF mutations for the use of anti-epidermal growth factor receptor (EGFR) therapy, i.e., the two monoclonal antibodies cetuximab and panitumumab, is currently under debate due to the fact that BRAF and RAS mutations are almost mutually exclusive and that RAS mutations are known negative predictive factors for the use of anti-EGFR therapy. In CRC, cetuximab and panitumumab are approved for use in RAS wild-type patients only: for their use in patients with a BRAF mutation, only limited data are available from subgroup analyses of larger confirmatory studies (. Table 1), as well as from retrospective case series derived from clinical routine data. Two partly overlapping meta-analyses confirmed a clinical benefit for anti-EGFR antibody therapy in patients with wild-type RAS and wild-type BRAF; in RAS wild-type patients harboring a BRAF mutation, however, data showed only a limited, non-significant clinical benefit in terms of progression-free survival (PFS) as well as OS. The current body of evidence, on the other hand, does not justify the exclusion of anti-EGFR antibodies from the therapeutic repertoire for BRAF V600E -mutant patients either. Data from the German randomized phase-II study VOLFI comparing panitumumab plus chemotherapy vs. mono-chemotherapy in first-line treatment showed that the addition of panitumumab to chemotherapy tended to increase the overall response rate (ORR) in the 14 patients with BRAF-mutated tumors (odds ratio = 14.93, 95% confidence interval 1.03-200.00). Anti-VEGF therapy, which-as with anti-EGFR therapy-is given in combination with oxaliplatin-containing (mostly in first-line) or irinotecan-containing chemotherapy (mostly in second-line), is a clinically relevant routine treatment of mCRC and can be used independent of RAS status. However, since no or only indirect comparisons are available to date, the predictive value of BRAF testing with regard to this treatment regimen is still unclear. Results of a small phase-II study and subgroup analyses of two large phase-III studies also do not allow a clear overall assessment of the intensified chemotherapy backbone (FOLFOXIRI) in BRAF-mutant patients. A metaanalysis of five randomized studies of quite differing case numbers recently found that in BRAFmutated patients-with the total case numbers still being small-intensified combination therapy does not provide an additional benefit in the first-line setting. A meta-analysis performed by the ARCAD study group, published in autumn 2020 and pooling data from two studies comparing chemotherapy plusanti-EGFR with chemotherapy plus-anti-VEGFR therapy as first-line options for mCRC, could not demonstrate a significant difference in OS for the subgroup of BRAF-mutated patients (n = 138) that received either bevacizumab-based or cetuximab-based therapy (HR = 1.01 ). The benefit of anti-VEGF therapy with bevacizumab per se and the predictive role of BRAF for initiating bevacizumab-based therapy still requires further investigation (. Table 1). Although targeted tyrosine kinase inhibitors have been used in clinical routine since 2011 with very good outcomes in BRAF V600 -mutated melanoma, BRAFmutated mCRC proved to be less sensitive to monotherapy. The reason behind this may be CRC-specific resistance mechanisms in the MAPK signaling cascade. In-vitro studies demonstrated suppression of the negative feed- Abstract In the past 25 years, treatment of metastatic colorectal cancer (mCRC) has undergone profound changes. The approval of newer chemotherapeutics such as irinotecan and oxaliplatin was followed in 2005 by the first targeted therapies, for example, monoclonal antibodies directed against the epidermal growth factor receptor (EGFR), as cetuximab and panitumumab, or the angiogenesis inhibitors bevacizumab, ramucirumab, and aflibercept. With the rapidly progressing molecular characterization of mCRC in the last 10 years and the classification of the disease in four consensus subtypes, further changes are emerging, which will promote, among other things, the introduction of protein-kinase inhibitors developed for specific molecular aberrations as well as immune checkpoint inhibitors into the treatment algorithm. Thorough molecular pathologic testing is indispensable today for guideline-compliant treatment of mCRC patients. In addition to RAS testing as a precondition for the therapy decision with regard to cetuximab and panitumumab, BRAF testing is of considerable relevance to allow decision making with regard to the newly approved chemotherapyfree combination of the BRAF inhibitor encorafenib and cetuximab in cases where a BRAF-V600E mutation is detected. Additional diagnostic tests should also include genome instability (microsatellite instability). Overall, more and more molecular alterations need to be investigated simultaneously, so that the use of focused next-generation sequencing is increasingly recommended. This overview describes the prognostic relevance of BRAF testing in the context of molecular pathologic diagnostics of mCRC, presents new treatment options for BRAF-mutated mCRC patients, and explains which modern DNA analytical and immunohistochemical methods are available to detect BRAF mutations in mCRC patients. Schlsselwrter Cetuximab Encorafenib BRAF-Inhibitoren Proteinkinaseinhibitoren Protoonkogene B-Raf-Proteine back loop between extracellular signalregulated kinase (ERK)and the EGFRunder BRAF monotherapy with overall high EGFR expression in CRC and possibly even stronger activation of the receptor by its ligands (. Fig. 1; ). This results in a reactivation of the EGFR pathway, e.g., by-passing the mutated BRAF protein via CRAF. Thus, it seems important to inhibit the EGFR pathway by simultaneously administering a therapy directed against EGFR in addition to BRAF block-ade in order to block the multi-track resistance mechanisms within the MAPK signaling pathway. Therapeutic options in BRAFmutant mCRC Until recently, first-and second-line treatment of mCRC has generally been based on the use of combination chemotherapies, mostly including-in the case of left-sided RAS wild-type tu-mors-EGFR antibody therapy, as described in the previous section ), but also the Pan-Asian Adapted ESMO Consensus Guidelines published in early 2018. Although this article refers to the somewhat older ESMO guideline, the reference always applies to both guidelines and the current study evidence shown therein. Table 1 Studies and retrospective analyses on the significance of BRAF as a predictive marker in the use of anti-epidermal growth factor receptor therapies (A) and anti-vascular endothelial growth factor therapies (B) for BRAF-mutated metastatic colorectal cancer Study/phase (or type) of study Current treatment recommendations for mCRC are drawing much attention to the general condition of the patients, which are typically of older age. Regarding patients fit enough for systemic treatment, a distinction is made between the therapeutic objectives of "cytoreduction, " i.e., reduction of the tumor mass, and "disease control, " i.e., delaying further progression. First-line therapy in BRAF-mutant mCRC: a controversial treatment standard The combination of an antimetabolite (5-fluorouracil, plus leucovorin as a folinic acid derivative) and a platinum compound interfering with DNA replication (oxaliplatin) together with a topoisomerase I inhibitor (irinotecan) and the angiogenesis inhibitor (anti-VEGF) bevacizumab represents the current European guideline standard for BRAF-mutant mCRC patients in good general health. However, considering the evidence level in the BRAFmutated subgroup, it has to be noted that this recommendation is based on a very small number of patients (N = 28) from the TRIBE study and is therefore associated with uncertainties. In the BRAF subgroup of this phase-III study, the OS under FOLFOXIRI plus bevacizumab was 19 months with an ORR of 56%; however, there was no significant difference to the comparator group consisting of FOLFIRI plus bevacizumab (. Table 1; ). This first-line standard. Due to their poor prognosis, the concept of an 'aggressive' first-line treatment in BRAF V600E -mutated mCRC, using almost the entire arsenal of therapy modalities, is currently of clinical relevance with regard to the current recommendations for this mCRC patient collective-especially when cytoreduction is the therapeutic objective. On the other hand, it is unclear to what extent patients in Germany are treated with this intensi-fied first-line therapy, which is associated with relevant adverse events (AE). As mentioned above, the issue of using anti-EGFR-based therapy in BRAFmutant tumors is currently the subject of controversial debates due to the inconclusive results of two meta-analyses. New chemotherapy-free, targeted option after systemic therapy Due to the limited therapeutic options after completion of first-line treatment, no clear recommendations could be drawn to date for second-and third-line therapy of BRAF-mutant mCRC patients. The German S3 guideline stated in 2019 that "Individual (presently) not approved therapeutic approaches, e.g. with a BRAF inhibitor, MEK inhibitor and anti-EGFR antibody or, if possible, treatment within a clinical study (are) to be taken into consideration"; until recently, none of the therapeutic options mentioned here was approved for this indication. In June 2020, however, the combination of the BRAF inhibitor encorafenib and the anti-EGFR antibody cetuximab was granted European Union (EU) approval, making such a chemotherapyfree, purely targeted dual blockade available for routine care. This combination is indicated for the treatment of adult patients with mCRC and a BRAF V600E mutation who have received prior systemic treatment. The phase-III BEACON CRC trial, on which the approval was based, investigated the triple blockade with en- The tolerability of the dual blockade was slightly more favorable than that of the triple blockade and of the control group (. Fig. 2). The safety profile of the combination of encorafenib and cetuximab was well manageable and showed, in terms of AE, the expected class effects. The most common AEs included: elevated creatinine level (50%), nausea (34%), diarrhea (33%), low hemoglobin level (32%), fatigue (30%), acneiform dermatitis (29%), and decreased appetite (27%). Due to the comparable efficacy results of triple versus dual blockade and the slightly more favorable tolerability of encorafenib plus cetuximab, the European Medicines Agency (EMA) approved the dual combination regimen in June 2020. A new update analysis after a median follow-up of 12.8 months confirmed the above-described results with a consistent tolerability profile Fig. 3). BRAF diagnostics As a consequence of the above-described clinical situation, diagnostic testing for the presence of RAS and BRAF mutations in mCRC is essential: for BRAF-mutated patients, encorafenib plus cetuximab can be taken into consideration as a newly available therapeutic option. The guidelines recommend performing these tests either before initiating first-line therapy in mCRC, or already at the time of initial diagnosis of CRC, in order to exclude the presence of Lynch syndrome via additional dMMR testing. In the same way as BRAFmutated tumors, such hereditary CRCs without polyposis (HNPCC) also constitute a biologically distinct subtype of CRC. If a BRAF mutation is present in a dMMR/MSI tumor, Lynch syndrome can be mostly excluded. Thus, the determination of BRAF mutation status is of diagnostic and therapeutic relevance and helps to differentiate somatic from genetic "mismatch" repair defects. The diagnosis of a sporadic tumor, thus excluding HNPCC/ Lynch syndrome, can be supported by analyzing MLH1 promoter methylation, since the presence of such methylation additionally corroborates the diagnosis of a sporadic, high MSI (. Fig. 4). BRAF testing can be performed either simultaneously with RAS testing or stepwise after excluding a RAS mutation. Nowadays, however, the simultaneous approach is recommended applying gene panel diagnostics based on focused nextgeneration sequencing (NGS). Sample preparation In the course of the diagnostic workup, specimens are mostly obtained during colonoscopy or surgical removal of the primary tumor. After fixation via 10% neutral buffered formalin (4% formaldehyde) for 24-48 h and embedding in paraffin, the specimens are well suited for the tests indicated in. Fig. 4. For molecular determination of MSI status, healthy tissue samples distant from the tumor should also be stored and analyzed. If tissue samples contain a low percentage of tumor cells, a macrodissection prior to DNA extraction is highly recommended for cancer cell enrichment. In recent years, NGS methods have been increasingly used in molecular diagnostics, allowing the detection of selected genes/genomic regions relevant for diagnosis and therapy (targeted NGS) simultaneously with high sensitivity and specificity. Therefore, BRAF mutation testing in CRC is often no longer carried out as an isolated individual test but integrated into the parallel detection of other molecular alterations such as KRAS and NRAS. The sensitivity of NGS-based methods is generally very high (approximately 1% detection limit), but hampered by artifacts occurring during formalin fixation. In many laboratories, a threshold of 5% variant allele frequency (VAF) is therefore requested, which can however be undercut in specific situations. Today, ThermoFisher Scientific and Illumina are the most prominent NGS platforms available. Both platforms enable analysis of numerous commer-cial or in-house gene panels, based on either amplicon-based (multiplex polymerase chain reaction, PCR) or hybridcapture methods for enriching the selected target regions. Numerous bioinformatic programs are available for the evaluation of NGS data. However, these should be used by scientists/physicians that have profound experience in molecular diagnostics. In the BEACON CRC study, which was conducted in a total of 221 centers in 28 countries (111 of which were centers in Europe), evaluation of the procedures used for BRAF status determination from 510 samples revealed the following picture: in 48.8% of the analyses, single gene detection was still used for BRAF testing; protein-based methods (immunohistology) were used in 0.7% of the analyses. However, the majority of BRAF tests were performed together with the detection of other gene alterations (e.g., as focused, amplicon-based NGS) (50.5%). Discrepancies observed betweenlocal and central testing showthe relevance of standardization of diagnostic procedures, especially in view of the increasing importance of targeted therapeutic approaches: clear confirmation of the locally detected BRAF V600E mutation was found in just 90.7% of central testing. Of note, this discrepancy was largely due to insufficient neoplastic tissue in the sample, most likely resulting from the fact that BRAF-mutant tumors are generally associated with mucinous adenocarcinoma that contain fewer tumor cells. In 1.6% of the central repeat tests, the local result was clearly negated. Taking into account this possibility of a discrepancy between local and central testing, the study protocol allowed the inclusion of patients based on local BRAF V600E detection in molecular prescreening, but additionally required central confirmation, as part of the inclusion criteria, within 30 days of initial receipt of study medication. Once the study had reached the pre-specified number of discrepant test results, the assay, which was developed and then approved in the USA as a "companion diagnostic, " became a prerequisite for the inclusion of all further patients. The EU and US regulations on invitro diagnostics (IVD) are fundamentally different: in the US, such tests are subject to central approval (Premarket Approval) by the Food and Drug Administration (FDA), while in the EU manufacturers can chose an accredited "notified body" that evaluates the conformity of their test; once confirmed, the manufacturer is allowed to label its product with the so-called CE label (CE: Confor- mit Europene) 2. Furthermore, the FDA usually grants approval for targeted therapies only in conjunction with a defined and simultaneously approved companion diagnostic, which, at the time of drug approval, has an exclusivity of use: the usage of the respective companion diagnostic is therefore a prerequisite in the USA for the prescription of the drug by the physician. The US legislation distinguishes such standardized, mostly commercially available tests from so-called laboratory-developed tests (LDT), which-like the classical test methods such as Sanger sequencing-are designed, validated, and applied by institutes for their own use. The German Accreditation Body (DAkkS) refers to such LDTs as "in-house tests." They are normally not subject to formal approval or labeling requirements; however, a few years ago, the DAkkS issued a guideline for the validation of molecular pathological examination methods. In the US, a discussion paper was presented by the FDA in January 2017, advocating stronger prospective regulation of LDTs due to their increasing prognostic and predictive importance-this applies in particular to the role and growing importance of NGS. With the FoundationOne ® CDx (F1CDx) test, an 2 With the "CE label, " the manufacturer, distributor, or EU authorized representative declares under EU Regulation 765/2008 "that the product meets the applicable requirements stipulated in the harmonization legislation of the Community on its affixing. " NGS method was approved as a companion diagnostic for the first time in the USA in late 2017 (. Table 3; ). Review Against this background, the diversity of competing classical and modern DNA analytical methods for BRAF mutation determination is easier to understand. Of the various commercial procedures using allele-specific PCR techniques, only the Qiagen therascreen ® test is currently recommended for BRAF-mutated mCRC in the US; in Europe, this test is CE-labeled. It is to be expected that for the tests currently approved for melanoma only, appropriate adjustments will soon be made in the US with regard to CRC. In the BEACON CRC approval study, the only methods allowed by the study protocol were PCR and NGS based on local assays. A comparison between commercially available (i.e., FDA-approved) tests and LDTs for EGFR, KRAS, and BRAF mutations showed that there was no overall difference between the methods and the three tested genes in assay performance; the average analysis accuracy was 97%. Since testing for KRAS, BRAF, MSI/dMMR, MLH1, and possibly other genes constitutes a prerequisite of CRC diagnostics, panel-based assays are understandably more prominent in current pathological practice-in Germany, all major university and non-university institutions are now using focused NGS for this purpose. Frequently used platforms include Illumina (MiSeq™ or NextSeq™) and Thermo Fisher (Ion Gene Studio S5™) : in a multicenter validation study across Germany, a high level of consistency between different NGS platforms and gene panels was shown; apart from CRC, samples of lung and breast cancers were also tested. Immunohistochemical methods Besides DNA analytical methods, protein-based analyses using the VE1 antibody may provide an alternative to molecular pathological testing for BRAF V600E ; the latter is widely regarded as the gold standard in BRAF mutation testing. At the same time, protein-based immunohistological detection is the only reasonably practicable method for determining the expression level of mutant BRAF protein. This method is also applicable for MSI testing. It is characterized by a specificity of 98-100%, a sensitivity of 85-100%, and an in-lab turnaround time of 1 day. Thus, the method is generally reliable, but some challenges remain, such as establishing a standardized scoring of protein expression, which is needed to avoid a substantial number of misclassifications. Immunostaining is in principle a fast and cost-effective method for the determination of BRAF-mutant protein; however, as CRC meanwhile requires the determination of multiple alterations, DNA analytical methods should certainly be preferred nowadays. Chu et al. investigated outcomes of immunohistochemical (IHC) and NGS testing in a cohort of almost 1900 CRC patients. The rate of false-positive IHC tests was 17%; however, confirmatory re-testing by NGS was performed in only 43% of the IHC-tested patients. NGS-tested patients had a favorable median OS, at younger age, and a lower rate of synchronous metastases and a higher rate of therapy. The authors concluded that NGS should be considered as standard testing but that IHC might serve as an optional screening test if NGS testing is not available in a timely manner. This is underlined by the rapid availability of results via IHC and the finding that reflexive IHC testing made it possible to identify 57% more BRAF-mutated mCRC than standard NGS methods. For this article no studies with human participants or animals were performed by any of the authors. All studies performed were in accordance with the ethical standards indicated in each case. The supplement containing this article is not sponsored by industry. Open Access. This article is licensed under a Creative Commons Attribution 4.0 International License, which permits use, sharing, adaptation, distribution and reproduction in any medium or format, as long as you give appropriate credit to the original author(s) and the source, provide a link to the Creative Commons licence, and indicate if changes were made. The images or other third party material in this article are included in the article's Creative Commons licence, unless indicated otherwise in a credit line to the material. If material is not included in the article's Creative Commons licence and your intended use is not permitted by statutory regulation or exceeds the permitted use, you will need to obtain permission directly from the copyright holder. To view a copy of this licence, visit http://creativecommons.org/licenses/by/4.0/. |
<filename>packages/augur-core/source/libraries/ContractInterfaces.ts<gh_stars>0
import { BigNumber } from "bignumber.js";
import * as c from "./GenericContractInterfaces";
export * from "./GenericContractInterfaces";
export class Contract extends c.Contract<BigNumber> {
}
export class Augur extends c.Augur<BigNumber> {
}
export class Cash extends c.Cash<BigNumber> {
}
export class ERC820Registry extends c.ERC820Registry<BigNumber> {
}
export class LegacyReputationToken extends c.LegacyReputationToken<BigNumber> {
}
export class TestNetReputationToken extends c.TestNetReputationToken<BigNumber> {
}
export class TestOrders extends c.TestOrders<BigNumber> {
}
export class Time extends c.Time<BigNumber> {
}
export class TimeControlled extends c.TimeControlled<BigNumber> {
}
export class AuctionFactory extends c.AuctionFactory<BigNumber> {
}
export class AuctionTokenFactory extends c.AuctionTokenFactory<BigNumber> {
}
export class DisputeCrowdsourcerFactory extends c.DisputeCrowdsourcerFactory<BigNumber> {
}
export class DisputeWindowFactory extends c.DisputeWindowFactory<BigNumber> {
}
export class InitialReporterFactory extends c.InitialReporterFactory<BigNumber> {
}
export class MapFactory extends c.MapFactory<BigNumber> {
}
export class MarketFactory extends c.MarketFactory<BigNumber> {
}
export class ReputationTokenFactory extends c.ReputationTokenFactory<BigNumber> {
}
export class ShareTokenFactory extends c.ShareTokenFactory<BigNumber> {
}
export class TestNetReputationTokenFactory extends c.TestNetReputationTokenFactory<BigNumber> {
}
export class UniverseFactory extends c.UniverseFactory<BigNumber> {
}
export class DelegationTarget extends c.DelegationTarget<BigNumber> {
}
export class Map extends c.Map<BigNumber> {
}
export class Auction extends c.Auction<BigNumber> {
}
export class AuctionToken extends c.AuctionToken<BigNumber> {
}
export class DisputeCrowdsourcer extends c.DisputeCrowdsourcer<BigNumber> {
}
export class DisputeOverloadToken extends c.DisputeOverloadToken<BigNumber> {
}
export class DisputeWindow extends c.DisputeWindow<BigNumber> {
}
export class InitialReporter extends c.InitialReporter<BigNumber> {
}
export class Market extends c.Market<BigNumber> {
}
export class ReputationToken extends c.ReputationToken<BigNumber> {
}
export class Universe extends c.Universe<BigNumber> {
}
export class CancelOrder extends c.CancelOrder<BigNumber> {
}
export class ClaimTradingProceeds extends c.ClaimTradingProceeds<BigNumber> {
}
export class CompleteSets extends c.CompleteSets<BigNumber> {
}
export class CreateOrder extends c.CreateOrder<BigNumber> {
}
export class FillOrder extends c.FillOrder<BigNumber> {
}
export class Orders extends c.Orders<BigNumber> {
}
export class ProfitLoss extends c.ProfitLoss<BigNumber> {
}
export class ShareToken extends c.ShareToken<BigNumber> {
}
export class SimulateTrade extends c.SimulateTrade<BigNumber> {
}
export class Trade extends c.Trade<BigNumber> {
}
|
Testosterone-binding globulin in stump-tailed macaque monkeys (Macaca speciosa). A specific androgen-binding macromolecule has been demonstrated in the serum of Macaca speciosa monkeys (M-TeBG). This receptor is a protein, -globulin, which was studied by polyacrylamide gel electrophoresis (PAGE) and equilibrium dialysis. PAGE enabled us to point out that this M-TeBG had a specificity towards androgens, estrogens and progesterone but not for cortisol, corticosterone, DOC and aldosterone; by use of the Ferguson Plot a radius of 3.04 ± 0.48 (SD) nm was computed and a molecular weight estimated at 105,000; by isoelectrofocusing this protein showed a mean pHi of 5.41 ± 0.10 (SD). By equilibrium dialysis the affinity constant (KA) and binding capacity (BAPT) of this M-TeBG for testosterone and estrogen were studied for males, females, prepuberal males and females, and males under estrogen treatment. For testosterone, the KAs found were 1.82 109 1/mole for males and 1.99 109 1/mole for females. BAPT values were similar to those found for normal men, women, boys and girls before puber... |
Police in riot gear break up shoe melee at Florida Mall
The wild scene erupted about 9:45 p.m. as hundreds of people packed the mall's parking lot, hoping to buy the new shoe at midnight. As the crowd grew, a large contingent of Orange County deputy sheriffs arrived, braced for problems.
The launch of an expensive new basketball shoe — timed to Orlando's hosting of the NBA All-Star Game — triggered a melee Thursday night at Florida Mall that was quelled by deputies in riot gear.
Similar shoe releases have caused violence at shoe stores across the country.
Two people were arrested on trespassing charges Thursday at Florida Mall. A third person — a woman — was arrested this morning for fighting outside Foot Locker.
Witnesses told the Orlando Sentinel that the crowd was asked to wait across the street when the mall closed at 9 p.m., but one person made a mad dash toward the Foot Locker where the shoes were to go on sale, and hundreds followed.
"I saw hundreds of people running toward me. I thought I was going to get trampled," said Amanda Charles, 20, who was among a group of a half-dozen friends who drove from Jacksonville to try to buy the glow-in-the-dark Nikes.
Witnesses said more deputies quickly arrived, decked out in riot gear and fortified by still more deputies on horseback, on motorcycles and in patrol cars. A helicopter with a spotlight hovered overhead.
"We were afraid of the cops and the horses," said Mario Torres, 22, of Orlando.
The deputies formed a line and used shields to push back the estimated 600 to 800 people, witnesses said. They said the deputies threatened to use pepper spray but did not.
"It was pandemonium," said Rico Gomez, 23, who flew to Orlando to New Haven with friends just to buy the new Nikes.
More than 100 law-enforcement officers from the Sheriff's Office, the Orlando Police Department and Florida Highway Patrol responded to the mall and were continuing to disperse the crowd as of midnight. People continued to mill about, and some cars remained in the lot after the free-for-all as many people were hoping the sale would go on as planned.
"All I know is I paid a couple of hundred dollars for a flight," said Sky Smith, 26, also of New Haven. "I'm not leaving without my shoes."
As people lingered, law officers ramped up efforts to eject them from mall property, parking lots and a smaller shopping center and restaurants along Sand Lake Road. |
/*----------------------------------------------------------------------------*/
/* Hobbit message daemon. */
/* */
/* This Hobbit worker module saves the client messages that arrive on the */
/* CLICHG channel, for use when looking at problems with a host. */
/* */
/* Copyright (C) 2004-2006 <NAME> <<EMAIL>> */
/* */
/* This program is released under the GNU General Public License (GPL), */
/* version 2. See the file "COPYING" for details. */
/* */
/*----------------------------------------------------------------------------*/
static char rcsid[] = "$Id: hobbitd_hostdata.c,v 1.2 2006-05-27 07:03:45 henrik Exp $";
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <signal.h>
#include <limits.h>
#include <errno.h>
#include "libbbgen.h"
#include "hobbitd_worker.h"
#define MAX_META 20 /* The maximum number of meta-data items in a message */
int main(int argc, char *argv[])
{
char *msg;
int running;
int argi, seq;
char *clientlogdir;
/* Handle program options. */
for (argi = 1; (argi < argc); argi++) {
if (argnmatch(argv[argi], "--logdir=")) {
clientlogdir = strchr(argv[argi], '=')+1;
}
else if (strcmp(argv[argi], "--debug") == 0) {
/*
* A global "debug" variable is available. If
* it is set, then "dprintf()" outputs debug messages.
*/
debug = 1;
}
}
if (clientlogdir == NULL) clientlogdir = xgetenv("CLIENTLOGS");
if (clientlogdir == NULL) {
clientlogdir = (char *)malloc(strlen(xgetenv("BBVAR")) + 10);
sprintf(clientlogdir, "%s/hostdata", xgetenv("BBVAR"));
}
save_errbuf = 0;
signal(SIGCHLD, SIG_IGN);
running = 1;
while (running) {
char *eoln, *restofmsg, *p;
char *metadata[MAX_META+1];
int metacount;
msg = get_hobbitd_message(C_CLICHG, "hobbitd_hostdata", &seq, NULL);
if (msg == NULL) {
/*
* get_hobbitd_message will return NULL if hobbitd_channel closes
* the input pipe. We should shutdown when that happens.
*/
running = 0;
continue;
}
/* Split the message in the first line (with meta-data), and the rest */
eoln = strchr(msg, '\n');
if (eoln) {
*eoln = '\0';
restofmsg = eoln+1;
}
else {
restofmsg = "";
}
metacount = 0;
p = gettok(msg, "|");
while (p && (metacount < MAX_META)) {
metadata[metacount++] = p;
p = gettok(NULL, "|");
}
metadata[metacount] = NULL;
if (strncmp(metadata[0], "@@clichg", 8) == 0) {
char hostdir[PATH_MAX];
char fn[PATH_MAX];
FILE *fd;
sprintf(hostdir, "%s/%s", clientlogdir, metadata[3]);
mkdir(hostdir, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
sprintf(fn, "%s/%s", hostdir, metadata[4]);
fd = fopen(fn, "w");
if (fd == NULL) {
errprintf("Cannot create file %s: %s\n", fn, strerror(errno));
continue;
}
fwrite(restofmsg, strlen(restofmsg), 1, fd);
fclose(fd);
}
/*
* A "shutdown" message is sent when the master daemon
* terminates. The child workers should shutdown also.
*/
else if (strncmp(metadata[0], "@@shutdown", 10) == 0) {
running = 0;
continue;
}
/*
* A "logrotate" message is sent when the Hobbit logs are
* rotated. The child workers must re-open their logfiles,
* typically stdin and stderr - the filename is always
* provided in the HOBBITCHANNEL_LOGFILENAME environment.
*/
else if (strncmp(metadata[0], "@@logrotate", 11) == 0) {
char *fn = xgetenv("HOBBITCHANNEL_LOGFILENAME");
if (fn && strlen(fn)) {
freopen(fn, "a", stdout);
freopen(fn, "a", stderr);
}
continue;
}
else if ((metacount > 3) && (strncmp(metadata[0], "@@drophost", 10) == 0)) {
/* @@drophost|timestamp|sender|hostname */
char hostdir[PATH_MAX];
sprintf(hostdir, "%s/%s", clientlogdir, metadata[3]);
dropdirectory(hostdir, 1);
}
else if ((metacount > 4) && (strncmp(metadata[0], "@@renamehost", 12) == 0)) {
/* @@renamehost|timestamp|sender|hostname|newhostname */
char oldhostdir[PATH_MAX], newhostdir[PATH_MAX];
sprintf(oldhostdir, "%s/%s", clientlogdir, metadata[3]);
sprintf(newhostdir, "%s/%s", clientlogdir, metadata[4]);
rename(oldhostdir, newhostdir);
}
}
return 0;
}
|
public class Main {
public static void main(String[] args) {
IBoard board = new Board(7, 7,
new int[][] {
{},
{ 2 },
{ 1, 1 },
{ 1, 1 },
{ 1, 1 },
{ 2 },
{}
},
new int[][] {
{},
{ 1, 1 },
{ 1, 1, 1 },
{ 1, 1 },
{ 1, 1 },
{ 1 },
{},
});
IBoardSolver solver = new BoardSolver();
IBoard solved = solver.solve(board);
showBoard(solved);
}
static void showBoard(IBoard board) {
if (board == null) { System.out.println("No answer!"); return; }
for (int r = 0; r < board.getHeight(); r++) {
for (int c = 0; c < board.getWidth(); c++) {
if (board.getCellState(r, c) == CellState.FILLED) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
}
}
|
<gh_stars>1-10
package common.interceptor;
import java.lang.invoke.MethodHandles;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* @author <NAME>( <EMAIL> )
* @since 2018.12.05
*/
public class PermissionCheckInterceptor extends HandlerInterceptorAdapter {
private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
public String[] excludeURLs;
public String[] getExcludeURLs() {
return excludeURLs;
}
public void setExcludeURLs(String[] excludeURLs) {
this.excludeURLs = excludeURLs;
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (excludeURLs != null) {
for (int i = 0; i < getExcludeURLs().length; i++) {
AntPathMatcher m = new AntPathMatcher();
if (m.match(getExcludeURLs()[i], request.getRequestURI())) {
return true;
}
}
}
// JSON 요청일때 RequestBody의 값을 얻어오기 위해 request.getInputStream()하여 JSON 문자열을 Map으로 변환하면
// Controller에서 Map으로 받을 수 없음. 스트림을 이미 소비 했기 때문에 Stream closed 에러가 발생 함.
// JSON이나 일반 웹 요청에서 권한 체크를 처리하기 위한 파라미터는 HTTP GET 메서드로 전달하고 받기 바람.
logger.debug("TODO 세션 및 권한체크 구현 바람");
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
super.postHandle(request, response, handler, modelAndView);
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
} |
# Copyright (c) 2014 Rackspace, 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.
import ConfigParser
import os
import re
import time
import pyrax
# read the config file
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.expanduser('~/.poppy/poppy.conf')
configParser.read(configFilePath)
# get the config parameters
project_id = configParser.get('drivers:dns:rackspace', 'project_id')
api_key = configParser.get('drivers:dns:rackspace', 'api_key')
# replace any single or double quotes from parameters
api_key = re.sub(r'^"|"$', '', api_key)
api_key = re.sub(r"^'|'$", '', api_key)
project_id = re.sub(r'^"|"$', '', project_id)
project_id = re.sub(r"^'|'$", '', project_id)
# Connect to Rackspace DNS using API key.
pyrax.set_setting("identity_type", "rackspace")
pyrax.set_credentials(project_id, api_key)
dns = pyrax.cloud_dns
for domain in dns.get_domain_iterator():
print('Deleting {0}'.format(domain.name))
try:
dns.delete(domain)
except pyrax.exceptions.NotFound:
pass
time.sleep(2)
|
<filename>src/main/java/nablarch/fw/results/TransactionAbnormalEnd.java
package nablarch.fw.results;
import nablarch.core.log.basic.LogLevel;
import nablarch.core.util.annotation.Published;
/**
* 業務処理が異常終了したことを示す例外クラス。
*
* @author <NAME>
*/
@Published(tag = "architect")
public class TransactionAbnormalEnd extends nablarch.fw.results.InternalError {
/** 終了コード */
private final int exitCode;
/**
* 終了コードとメッセージ(障害コードとオプション)を元に例外を構築する。
*
* @param exitCode 終了コード(プロセスを終了({@link System#exit(int)})する際に設定する値)
* @param failureCode 障害コード
* @param messageOptions 障害コードからメッセージを取得する際に使用するオプション情報
*/
@Published
public TransactionAbnormalEnd(int exitCode, String failureCode,
Object... messageOptions) {
super(LogLevel.FATAL, failureCode, messageOptions);
validateExitCode(exitCode);
this.exitCode = exitCode;
}
/**
* 終了コードとメッセージ(障害コードとオプション)、元例外{@link Throwable}を元に例外を構築する。
* <p/>
* 元例外が存在しない場合は、{@link #TransactionAbnormalEnd(int, String, Object...)} を使用する。
*
* @param exitCode 終了コード(プロセスを終了({@link System#exit(int)})する際に設定する値)
* @param error 元例外
* @param failureCode 障害コード
* @param messageOptions 障害コードからメッセージを取得する際に使用するオプション情報
*/
@Published
public TransactionAbnormalEnd(int exitCode,
Throwable error,
String failureCode,
Object... messageOptions) {
super(LogLevel.FATAL, error, failureCode, messageOptions);
validateExitCode(exitCode);
this.exitCode = exitCode;
}
/**
* 設定された終了コードの値のバリデーションを行う。
*
* @param exitCode 終了コード
*/
private static void validateExitCode(int exitCode) {
if (exitCode < 100 || exitCode > 199) {
throw new IllegalArgumentException(
"Exit code was invalid range. "
+ "Please set it in the range of 199 from 100. "
+ "specified value was:" + exitCode
);
}
}
/**
* {@inheritDoc}
*
* @return インスタンス生成時に指定された終了コードを返却する。
*/
@Published(tag = "architect")
public int getStatusCode() {
return exitCode;
}
}
|
from hashlib import sha512
from string import ascii_lowercase, ascii_uppercase, digits
from getpass import getpass
from math import log
from argparse import ArgumentParser
from time import sleep
from contextlib import suppress
SYMBOLS = "!@#$%^&*"
CHARACTERS = ascii_lowercase + ascii_uppercase + digits + SYMBOLS
NOUNS1 = ['fire', 'queen', 'blog', 'tax', 'concrete', 'glove']
NOUNS2 = ['army', 'color', 'duck', 'morning', 'fear', 'train']
NOUNS3 = ['town', 'library', 'existence', 'pipe', 'instrument', 'army']
DEFAULT_LENGTH = 16
CODE_EXPOSURE = len(NOUNS1) * len(NOUNS2) * len(NOUNS3)
def escape(text):
text = text.replace("\\", "\\\\")
text = text.replace("|", "\\|")
return text
def hash_components(password, username, domain):
# hashes the password, salted with the username and domain
# its not "safe", its intended to uniqify a master password
components = []
components.append(escape(password))
components.append(escape(username))
components.append(escape(domain.lower()))
text = "|".join(components)
return sha512(text.encode("utf-8")).digest()
def hash_to_pass(hash, size=DEFAULT_LENGTH):
# takes a hash, and forms a `size`-char long password
# there will be at least one lowercase, uppercase, digit, and symbol
assert size <= log(2 ** (8 * len(hash)) // CODE_EXPOSURE, len(CHARACTERS)) # roughly 82
value = int.from_bytes(hash, byteorder="little")
value //= CODE_EXPOSURE
result = []
for _ in range(size):
value, residue = divmod(value, len(CHARACTERS))
result.append(CHARACTERS[residue])
indices = list(range(size))
for alphabet in (ascii_lowercase, ascii_uppercase, digits, SYMBOLS):
value, index = divmod(value, len(indices))
value, residue = divmod(value, len(alphabet))
result[indices.pop(index)] = alphabet[residue]
return "".join(result)
def hash_viz(password):
# Emits 6**3 = 216 = ~7.75 bits of info, in
# the most distinguishable form possible, for typo recognition
hash = sha512(password.encode("utf-8")).digest()
value = int.from_bytes(hash, byteorder="little")
words = []
for alphabet in (NOUNS1, NOUNS2, NOUNS3):
value, residue = divmod(value, len(alphabet))
words.append(alphabet[residue])
return " ".join(words).upper()
def print_banner():
banner = r"""\
_ _ _ _____
| | | | | | | __ \
| |__| | __ _ ___| |__ | |__) |_ _ ___ ___
| __ |/ _` / __| '_ \| ___/ _` / __/ __|
| | | | (_| \__ \ | | | | | (_| \__ \__ \
|_| |_|\__,_|___/_| |_|_| \__,_|___/___/
"""
print(banner)
def copy_to_clip(text):
try:
import pyperclip
pyperclip.copy(text)
except:
return False
return True
def prompt_interactive():
print_banner()
domain = input("Domain:\n> ")
username = input("Username:\n> ")
password = getpass("Password:\n> ")
code_words = hash_viz(password)
print("\nCode words: \"" + code_words + "\"")
hash = hash_components(password, username, domain)
hashpass = hash_to_pass(hash)
print("HashPass: " + hashpass + "\n")
if copy_to_clip(hashpass):
print("HashPass copied to clipboard.")
print("Exiting in 10 seconds.")
sleep(10)
def prompt_silent():
domain = input()
username = input()
password = <PASSWORD>pass("")
hash = hash_components(password, username, domain)
hashpass = hash_to_pass(hash)
print(hashpass)
def main():
parser = ArgumentParser()
parser.add_argument('-s', '--silent', action='store_true')
args = parser.parse_args()
try:
if args.silent:
prompt_silent()
else:
prompt_interactive()
except KeyboardInterrupt:
print("")
if __name__ == "__main__":
main()
|
Role of thermal and mechanical effects on drug release from thermosensitive nanocarriers The combination of focused ultrasound (FUS) with thermosensitive liposomes (TSL) is a promising method for drug delivery since it allows a localized release upon moderate heating with ultrasound. Besides thermal effects, FUS also induces mechanical stresses on drug nanocarriers. We propose in this study to examine the influence of both effects (thermal and mechanical) on drug release. For this, an in-vitro setup allowing liposomal drug delivery using FUS was first evaluated. Calcein was used as a model drug. FUS experiments were performed in water at 37°C using a 1 MHz transducer focused at 48 mm, at 1 kHz PRF and 40% duty cycle. The driving pressure and the insonation duration were varied from 1 to 2 MPa and from 0 to 30 min, respectively. Thermal heating using a water-bath was also performed with temperatures from 37 to 49°C. For TSL, the release reaches a plateau above 42°C (45%) after 10 min heating while no release is observed for non-thermosensitive liposomes (NTSL). Using FUS, a rapid calcein release is observed for pressures from 1 to 1.5 MPa (from 0% to 49%) for TSL. Above 1.5 MPa, the release increases slightly (59% at 2 MPa). For NTSL, a weak calcein release is measured for acoustic pressures higher than 1.5 MPa. This release is attributed to the mechanical stress generated by FUS which is sufficient to destabilize the liposomal membrane. Mechanical stress alone can enhance the calcein release by up to 17% for pressures higher than 1.75 MPa. |
/*
* Copyright (c) 2020-2021. helpberkeley.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.helpberkeley.memberdata;
import org.helpberkeley.memberdata.v200.ControlBlockV200;
import org.helpberkeley.memberdata.v300.ControlBlockV300;
import java.text.MessageFormat;
import java.util.*;
public abstract class ControlBlock {
public static final String INTRA_FIELD_SEPARATOR = "|";
static final String ERROR_MISSING_OPS_MANAGER =
"Control block missing a " + Constants.CONTROL_BLOCK_OPS_MANAGER + " entry.\n";
static final String BAD_HEADER_ROW = "Line 1, column names missing.\n";
static final String MISSING_OR_INVALID_HEADER_ROW
= "Line 1, header row missing or has a duplicate column name ({0})\n";
static final String ERROR_WRONG_NUMBER_OF_VERSION_KEYS =
"Control block Version key must appear once and only once";
static final String ERROR_WRONG_NUMBER_OF_VERSION_VALUES =
"Too many non-empty columns. Control block Version value must appear once and only once";
static final String ERROR_UNKNOWN_DIRECTIVE = "Unexpected control block directive \"{0}\" in "
+ Constants.WORKFLOW_NAME_COLUMN + " column at line {1}.\n";
static final String UNKNOWN_BACKUP_DRIVER =
Constants.CONTROL_BLOCK_BACKUP_DRIVER + " {0} is not a member. Misspelling?\n";
static final String BACKUP_IS_NOT_A_DRIVER =
Constants.CONTROL_BLOCK_BACKUP_DRIVER + " {0} is not a driver.\n";
static final String UNKNOWN_OPS_MANAGER =
Constants.CONTROL_BLOCK_OPS_MANAGER + " {0} is not a member. Misspelling?\n";
static final String OPS_MANAGER_PHONE_MISMATCH =
Constants.CONTROL_BLOCK_OPS_MANAGER + " {0} phone {1} does not match the member data\n";
static final String UNKNOWN_SPLIT_RESTAURANT =
Constants.CONTROL_BLOCK_SPLIT_RESTAURANT + " contains unknown restaurant {0}. Misspelling?\n";
public static final String UNKNOWN_CLEANUP_DRIVER =
Constants.CONTROL_BLOCK_SPLIT_RESTAURANT + " {0} for {1} is not a member. Misspelling?\n";
public static final String WRONG_CLEANUP_DRIVER =
Constants.CONTROL_BLOCK_SPLIT_RESTAURANT + " {0} is not going to {1}.\n";
public static final String MISSING_SPLIT_RESTAURANT =
"Control block does not contain a "
+ Constants.CONTROL_BLOCK_SPLIT_RESTAURANT + " entry for {0}\n";
public boolean isDisableLateArrivalAudit() {
return disableLateArrivalAudit;
}
public static final String UNSUPPORTED =
"{0} (line {1}) is not supported in control block version {2}\n";
private final Set<String> columnNames;
private final List<OpsManager> opsManagers = new ArrayList<>();
private final Map<String, SplitRestaurant> splitRestaurantMap = new HashMap<>();
private final List<String> backupDrivers = new ArrayList<>();
private boolean disableLateArrivalAudit = false;
private boolean disableSplitRestaurantAudits = false;
private boolean disableRestaurantsAudit = false;
protected final StringBuilder warnings = new StringBuilder();
protected ControlBlock(String header) {
try {
columnNames = Set.of(header.split(Constants.CSV_SEPARATOR));
} catch (IllegalArgumentException ex) {
throw new MemberDataException(MessageFormat.format(MISSING_OR_INVALID_HEADER_ROW, ex.getMessage()));
}
auditColumnNames();
}
protected void unsupported(long lineNumber, String feature) {
warnings.append(MessageFormat.format(UNSUPPORTED, feature, lineNumber, getVersion()));
}
private void auditColumnNames() {
if ((! columnNames.contains(Constants.WORKFLOW_CONSUMER_COLUMN))
&& (! columnNames.contains(Constants.WORKFLOW_DRIVER_COLUMN))
&& (! columnNames.contains(Constants.WORKFLOW_USER_NAME_COLUMN))
&& (! columnNames.contains(Constants.WORKFLOW_NAME_COLUMN))
&& (! columnNames.contains(Constants.WORKFLOW_CITY_COLUMN))) {
throw new MemberDataException(BAD_HEADER_ROW);
}
}
public static ControlBlock create(String csvData) {
// Normalize lines
String normalized = csvData.replaceAll("\\r\\n?", "\n");
// Break into lines
String[] lines = normalized.split("\n");
String header = lines[0];
if (! header.contains(Constants.CSV_SEPARATOR)) {
throw new MemberDataException(BAD_HEADER_ROW);
}
String version = new VersionParser(lines).version();
switch (version) {
case Constants.CONTROL_BLOCK_VERSION_UNKNOWN:
return new ControlBlockV0(header);
case Constants.CONTROL_BLOCK_VERSION_1:
return new ControlBlockV1(header);
case Constants.CONTROL_BLOCK_VERSION_200:
return new ControlBlockV200(header);
case Constants.CONTROL_BLOCK_VERSION_300:
return new ControlBlockV300(header);
default:
throw new MemberDataException(
"Control block version " + version + " is not supported.\n");
}
}
boolean lateArrivalAuditDisabled() {
return disableLateArrivalAudit;
}
public boolean splitRestaurantAuditsDisabled() {
return disableSplitRestaurantAudits;
}
public boolean restaurantsAuditDisabled() {
return disableRestaurantsAudit;
}
protected void auditOpsManager(StringBuilder errors, Map<String, User> users) {
if (opsManagers.isEmpty()) {
errors.append(ERROR_MISSING_OPS_MANAGER);
}
for (OpsManager opsManager : opsManagers) {
User user = users.get(opsManager.userName);
if (user == null) {
errors.append(MessageFormat.format(UNKNOWN_OPS_MANAGER, opsManager.userName));
} else {
String phone = opsManager.phone.replaceAll("\\D", "");
boolean match = phone.equals(user.getPhoneNumber().replaceAll("\\D", ""));
if (! match) {
match = phone.equals(user.getAltPhoneNumber().replaceAll("\\D", ""));
}
if (! match) {
warnings.append(MessageFormat.format(OPS_MANAGER_PHONE_MISMATCH,
opsManager.userName, opsManager.phone));
}
}
}
}
//
// Split Restaurant audits:
// - valid restaurant name
// - all split restaurants have control block entries
// - cleanup driver is a valid user name
// - cleanup driver is picking up at that restaurant
//
protected void auditSplitRestaurants(StringBuilder errors, Map<String, User> users,
Map<String, Restaurant> allRestaurants, List<Restaurant> splitRestaurants) {
if (disableSplitRestaurantAudits) {
return;
}
for (SplitRestaurant splitRestaurant : splitRestaurantMap.values()) {
if (!allRestaurants.containsKey(splitRestaurant.name)) {
errors.append(MessageFormat.format(UNKNOWN_SPLIT_RESTAURANT, splitRestaurant.name));
}
}
for (Restaurant restaurant : splitRestaurants) {
String name = restaurant.getName();
SplitRestaurant splitRestaurant = splitRestaurantMap.get(name);
if (splitRestaurant == null) {
errors.append(MessageFormat.format(MISSING_SPLIT_RESTAURANT, name));
continue;
}
if (! users.containsKey(splitRestaurant.cleanupDriverUserName)) {
errors.append(MessageFormat.format(UNKNOWN_CLEANUP_DRIVER,
splitRestaurant.cleanupDriverUserName, name));
continue;
}
Map<String, Driver> drivers = restaurant.getDrivers();
assert drivers != null : name;
if (! drivers.containsKey(splitRestaurant.cleanupDriverUserName)) {
errors.append(MessageFormat.format(
WRONG_CLEANUP_DRIVER, splitRestaurant.cleanupDriverUserName, name));
}
}
}
protected void auditBackupDrivers(StringBuilder errors, Map<String, User> users) {
if (backupDrivers.isEmpty()) {
warnings.append("No " + Constants.CONTROL_BLOCK_BACKUP_DRIVER + " set in the control block.\n");
}
for (String backupDriver : backupDrivers) {
User user = users.get(backupDriver);
if (user == null) {
errors.append(MessageFormat.format(UNKNOWN_BACKUP_DRIVER, backupDriver));
} else if (! user.isDriver()) {
warnings.append(MessageFormat.format(BACKUP_IS_NOT_A_DRIVER, backupDriver));
}
}
}
public abstract String getVersion();
List<OpsManager> getOpsManagers() {
return opsManagers;
}
public OpsManager getFirstOpsManager() {
if (opsManagers.size() == 0) {
throw new MemberDataException("No OpsManager found");
}
return opsManagers.get(0);
}
List<SplitRestaurant> getSplitRestaurants() {
return new ArrayList<>(splitRestaurantMap.values());
}
public SplitRestaurant getSplitRestaurant(String restaurantName) {
SplitRestaurant splitRestaurant = splitRestaurantMap.get(restaurantName);
if (splitRestaurant == null) {
throw new MemberDataException
("Split restaurant \"" + restaurantName + "\" not found in the control block");
}
return splitRestaurant;
}
public List<String> getBackupDrivers() {
return backupDrivers;
}
void processRow(WorkflowBean bean, long lineNumber) {
String variable = bean.getControlBlockKey().replaceAll(" ", "");
String value = bean.getControlBlockValue().replaceAll("\\s*\\|\\s*", "|");
switch (variable) {
case Constants.CONTROL_BLOCK_VERSION:
processVersion(value);
break;
case Constants.CONTROL_BLOCK_OPS_MANAGER:
processOpsManager(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_SPLIT_RESTAURANT:
processSplitRestaurant(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_BACKUP_DRIVER:
processBackupDriver(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_LATE_ARRIVAL_AUDIT:
case Constants.CONTROL_BLOCK_UNVISITED_RESTAURANTS_AUDIT:
case Constants.CONTROL_BLOCK_SPLIT_RESTAURANT_AUDITS:
processAuditControl(variable, value, lineNumber);
break;
case Constants.CONTROL_BLOCK_ALT_MEAL_OPTIONS:
processAltMealOptions(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_ALT_GROCERY_OPTIONS:
processAltGroceryOptions(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_START_TIMES:
processStartTimes(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_PICKUP_MANAGER:
processPickupManager(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_FOOD_SOURCES:
processFoodSources(value, lineNumber);
break;
case Constants.CONTROL_BLOCK_MESSAGE_FORMAT:
processMessageFormat(value, lineNumber);
break;
default:
warnings.append("Unknown key \"")
.append(variable)
.append("\" in the ")
.append(Constants.WORKFLOW_USER_NAME_COLUMN)
.append(" column at line ")
.append(lineNumber)
.append(".\n");
}
}
// FIX THIS, DS: refactor the two beans
void processRow(RestaurantBean bean, long lineNumber) {
String variable = bean.getControlBlockKey().replaceAll(" ", "");
String value = bean.getControlBlockValue().replaceAll("\\s*\\|\\s*", "|");
switch (variable) {
case Constants.CONTROL_BLOCK_VERSION:
processVersion(value);
break;
case Constants.CONTROL_BLOCK_OPS_MANAGER:
case Constants.CONTROL_BLOCK_SPLIT_RESTAURANT:
case Constants.CONTROL_BLOCK_BACKUP_DRIVER:
case Constants.CONTROL_BLOCK_LATE_ARRIVAL_AUDIT:
// Skip. Not relevant to restaurant template
break;
default:
warnings.append("Unknown key \"")
.append(variable)
.append("\" in the ")
.append(Constants.WORKFLOW_USER_NAME_COLUMN)
.append(" column at line ")
.append(lineNumber)
.append(".\n");
}
}
public String getWarnings() {
return warnings.toString();
}
private void processVersion(String value) {
if (! value.equals(getVersion())) {
throw new MemberDataException("Control block version mismatch: " + value + " and " + getVersion());
}
}
private void processAuditControl(String variable, String value, long lineNumber) {
boolean disableAudit;
if (value.equalsIgnoreCase("enable")) {
disableAudit = false;
} else if (value.equalsIgnoreCase("disable")) {
disableAudit = true;
} else {
throw new MemberDataException("Invalid setting \"" + value + "\" for " + variable
+ " at line " + lineNumber + ". Must be Enable or Disable.\n");
}
switch (variable) {
case Constants.CONTROL_BLOCK_LATE_ARRIVAL_AUDIT:
disableLateArrivalAudit = disableAudit;
break;
case Constants.CONTROL_BLOCK_SPLIT_RESTAURANT_AUDITS:
disableSplitRestaurantAudits = disableAudit;
break;
default:
assert variable.equals(Constants.CONTROL_BLOCK_UNVISITED_RESTAURANTS_AUDIT) : variable;
disableRestaurantsAudit = disableAudit;
break;
}
}
//
// An OpManager data field should look like "userName | phone number"
//
private void processOpsManager(final String value, long lineNumber) {
String[] fields = value.split("\\" + INTRA_FIELD_SEPARATOR, -42);
if (fields.length != 2) {
throw new MemberDataException("OpsManager value \"" + value
+ "\" at line " + lineNumber + " does not match \"username | phone\".\n");
}
String userName = fields[0].trim();
String phone = fields[1].trim();
StringBuilder errors = new StringBuilder();
if (! opsManagers.isEmpty()) {
errors.append("Line ").append(lineNumber).append(", multiple OpsManager entries not yet supported.\n");
}
if (userName.isEmpty()) {
errors.append("Empty OpsManager user name at line ").append(lineNumber).append(".\n");
}
if (userName.startsWith("@")) {
errors.append("OpsManager user name \"")
.append(userName).append("\" at line ").append(lineNumber)
.append(" cannot start with @\n");
}
if (userName.indexOf(' ') != -1) {
errors.append("OpsManager user name \"")
.append(userName).append("\" at line ").append(lineNumber)
.append(" cannot contain spaces.\n");
}
if (userName.contains(Constants.CONTROL_BLOCK_VALUE_DEFAULT_PREFIX)) {
errors.append("Set OpsManager user name \"")
.append(userName).append("\" at line ").append(lineNumber)
.append(" to a valid OpsManager user name.\n");
}
if (phone.isEmpty()) {
errors.append("Empty OpsManager phone number at line ").append(lineNumber).append(".\n");
}
if (phone.contains(Constants.CONTROL_BLOCK_VALUE_DEFAULT_PREFIX)) {
errors.append("Set OpsManager phone \"")
.append(phone).append("\" at line ").append(lineNumber)
.append(" to a valid phone number.\n");
}
if (errors.length() != 0) {
throw new MemberDataException(errors.toString());
}
opsManagers.add(new OpsManager(userName, phone));
}
//
// A SplitRestaurant data field should look like "restaurant name | cleanup driver username"
//
private void processSplitRestaurant(final String value, long lineNumber) {
String[] fields = value.split("\\" + INTRA_FIELD_SEPARATOR, -42);
if (fields.length != 2) {
throw new MemberDataException(Constants.CONTROL_BLOCK_SPLIT_RESTAURANT + " value \"" + value
+ "\" at line " + lineNumber
+ " does not match \"restaurant name | cleanup driver user name\"");
}
String restaurantName = fields[0].trim();
String cleanupDriver = fields[1].trim();
StringBuilder errors = new StringBuilder();
if (restaurantName.isEmpty()) {
errors.append("Empty SplitRestaurant restaurant name at line ").append(lineNumber).append(".\n");
}
if (restaurantName.contains(Constants.CONTROL_BLOCK_VALUE_DEFAULT_PREFIX)) {
errors.append("Set SplitRestaurant name \"")
.append(restaurantName).append("\" at line ").append(lineNumber)
.append(" to a valid restaurant name.\n");
}
if (cleanupDriver.isEmpty()) {
errors.append("Empty SplitRestaurant cleanup driver user name at line ").append(lineNumber).append(".\n");
}
if (cleanupDriver.startsWith("@")) {
errors.append("SplitRestaurant cleanup driver user name \"")
.append(cleanupDriver).append("\" at line ").append(lineNumber)
.append(" cannot start with @\n");
}
if (cleanupDriver.indexOf(' ') != -1) {
errors.append("SplitRestaurant cleanup driver user name \"")
.append(cleanupDriver).append("\" at line ").append(lineNumber)
.append(" cannot contain spaces.\n");
}
if (cleanupDriver.contains(Constants.CONTROL_BLOCK_VALUE_DEFAULT_PREFIX)) {
errors.append("Set SplitRestaurant cleanup driver user name \"")
.append(restaurantName).append("\" at line ").append(lineNumber)
.append(" to a valid user name.\n");
}
if (splitRestaurantMap.containsKey(restaurantName)) {
errors.append("Control block contains SplitRestaurant ")
.append(restaurantName)
.append(" more than once\n");
}
if (errors.length() != 0) {
throw new MemberDataException(errors.toString());
}
splitRestaurantMap.put(restaurantName, new SplitRestaurant(restaurantName, cleanupDriver));
}
private void processBackupDriver(final String backupDriver, long lineNumber) {
if (backupDriver.contains(INTRA_FIELD_SEPARATOR)) {
throw new MemberDataException(Constants.CONTROL_BLOCK_BACKUP_DRIVER + " value \"" + backupDriver
+ "\" at line " + lineNumber
+ " does not match \"backupDriverUserName\"");
}
StringBuilder errors = new StringBuilder();
if (backupDriver.isEmpty()) {
errors.append("Empty BackupDriver user name at line ").append(lineNumber).append(".\n");
}
if (backupDriver.startsWith(Constants.CONTROL_BLOCK_VALUE_DEFAULT_PREFIX)) {
errors.append("Set BackupDriverUserName \"")
.append(backupDriver).append("\" at line ").append(lineNumber)
.append(" to a valid user name.\n");
}
if (backupDriver.startsWith("@")) {
errors.append("BackupDriver user name \"")
.append(backupDriver).append("\" at line ").append(lineNumber)
.append(" cannot start with a @\n");
}
if (backupDriver.indexOf(' ') != -1) {
errors.append("BackupDriver user name \"")
.append(backupDriver).append("\" at line ").append(lineNumber)
.append(" cannot contain spaces.\n");
}
if (errors.length() != 0) {
throw new MemberDataException(errors.toString());
}
backupDrivers.add(backupDriver);
}
public void processAltMealOptions(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_ALT_MEAL_OPTIONS);
}
public void processAltGroceryOptions(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_ALT_GROCERY_OPTIONS);
}
public void processStartTimes(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_START_TIMES);
}
public void processFoodSources(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_FOOD_SOURCES);
}
public void processPickupManager(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_PICKUP_MANAGER);
}
public void processMessageFormat(String value, long lineNumber) {
unsupported(lineNumber, Constants.CONTROL_BLOCK_MESSAGE_FORMAT);
}
public static class SplitRestaurant {
private final String name;
private final String cleanupDriverUserName;
SplitRestaurant(String name, String cleanupDriverUserName) {
this.name = name;
this.cleanupDriverUserName = cleanupDriverUserName;
}
public String getCleanupDriverUserName() {
return cleanupDriverUserName;
}
@Override
public boolean equals(Object obj) {
return ((obj instanceof SplitRestaurant)
&& (name.equals(((SplitRestaurant) obj).name))
&& (cleanupDriverUserName.equals(((SplitRestaurant) obj).cleanupDriverUserName)));
}
@Override
public int hashCode() {
return Objects.hash(name, cleanupDriverUserName);
}
@Override
public String toString() {
return (name + ", " + cleanupDriverUserName);
}
}
public static class OpsManager {
private final String userName;
private final String phone;
OpsManager(String userName, String phone) {
this.userName = userName;
this.phone = phone;
}
public String getUserName() {
return userName;
}
// FIX THIS, DS: add transformation for the phone number
public String getPhone() {
return phone;
}
@Override
public String toString() {
return userName + ", " + phone;
}
@Override
public boolean equals(Object obj) {
return ((obj instanceof OpsManager)
&& (userName.equals(((OpsManager) obj).userName)))
&& (phone.equals(((OpsManager)obj).phone));
}
@Override
public int hashCode() {
return Objects.hash(userName, phone);
}
}
private static class VersionParser {
final String[] lines;
VersionParser(String[] lines) {
this.lines = lines;
}
String version() {
boolean lookingForControlBlock = true;
int lineNumber = 0;
for (String line : lines) {
lineNumber++;
if (! line.startsWith("FALSE,FALSE,")) {
continue;
}
if (lookingForControlBlock && line.contains(Constants.CONTROL_BLOCK_BEGIN)) {
lookingForControlBlock = false;
continue;
}
if (line.contains(Constants.CONTROL_BLOCK_COMMENT)) {
continue;
}
if (line.contains(Constants.CONTROL_BLOCK_END)) {
break;
}
if (line.contains(Constants.CONTROL_BLOCK_VERSION)) {
return parseVersion(line, lineNumber);
}
}
return Constants.CONTROL_BLOCK_VERSION_UNKNOWN;
}
private String parseVersion(String line, int lineNumber) {
// remove whitespace and split into columns
String[] columns = line.replaceAll(" ", "").split(",");
String value = null;
int versionTags = 0;
int values = 0;
assert columns.length > 1 : lineNumber + ": " + line;
assert columns[0].equalsIgnoreCase("FALSE") : lineNumber + ": " + line;
assert columns[1].equalsIgnoreCase("FALSE") : lineNumber + ": " + line;
int columnNumber = 0;
for (String column : columns) {
columnNumber++;
if ((columnNumber == 1) || (columnNumber == 2) || column.isEmpty()) {
continue;
}
if (column.equals(Constants.CONTROL_BLOCK_VERSION)) {
versionTags++;
} else {
values++;
value = column;
}
}
if (versionTags != 1) {
raiseException(ERROR_WRONG_NUMBER_OF_VERSION_KEYS, line, lineNumber);
} else if (values != 1) {
raiseException(ERROR_WRONG_NUMBER_OF_VERSION_VALUES, line, lineNumber);
}
return value;
}
private void raiseException(String error, String line, int lineNumber) {
throw new MemberDataException("Line " + lineNumber + ": "
+ error + ":\n" + line + "\n");
}
}
} |
Fourier Transform Infrared Imaging Spectroscopy of the Diffusion Process of D2O into Polyamide 11 Fourier transform infrared (FT-IR) spectroscopic imaging with focal plane array detectors has proved a powerful technique for rapid chemical visualization of samples, with a lateral resolution up to 1015 m in the transmission micro mode. In the present communication the application of this technique is described for the study of the diffusion of D2O into a polyamide 11 (PA11) film. Apart from the in situ visualization of the diffusion front propagation in the time-resolved FT-IR images, the type of diffusion and the diffusion coefficient of D2O in the investigated polyamide have been determined. |
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.211028.7
#pragma once
#ifndef WINRT_Windows_UI_Xaml_Automation_Text_1_H
#define WINRT_Windows_UI_Xaml_Automation_Text_1_H
#include "winrt/impl/Windows.UI.Xaml.Automation.Text.0.h"
WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Automation::Text
{
}
#endif
|
Generating Audio-Visual Slideshows from Text Articles Using Word Concreteness We present a system that automatically transforms text articles into audio-visual slideshows by leveraging the notion of word concreteness, which measures how strongly a word or phrase is related to some perceptible concept. In a formative study we learn that people not only prefer such audio-visual slideshows but find that the content is easier to understand compared to text articles or text articles augmented with images. We use word concreteness to select search terms and find images relevant to the text. Then, based on the distribution of concrete words and the grammatical structure of an article, we time-align selected images with audio narration obtained through text-to-speech to produce audio-visual slideshows. In a user evaluation we find that our concreteness-based algorithm selects images that are highly relevant to the text. The quality of our slideshows is comparable to slideshows produced manually using standard video editing tools, and people strongly prefer our slideshows to those generated using a simple keyword-search based approach. |
Vacuum-assisted closure of necrotic and infected cranial wound with loss of dura mater: A technical note Background: Complex cranial wounds can be a problematic occurrence for surgeons. Vacuum-assisted closure devices have a wide variety of applications and have recently been used in neurosurgical cases involving complex cranial wounds. There is only one report regarding the use of a vacuum-assisted closure device with loss of dura mater. We report a complicated case of a necrotic cranial wound with loss of dura mater. Case Description: A 68-year-old female underwent an evacuation of a subdural hematoma. Postoperatively, the patient developed a wound infection that required removal of the bone flap. The wound developed a wedge-shaped necrosis of the scalp with exposure of brain tissue due to loss of dura mater from previous surgeries. She underwent debridement and excision of the necrotic tissue with placement of a synthetic dural graft (Durepair®, Medtronic, Inc.) and placement of a wound vac. The patient underwent a latissismus dorsi muscle flap reconstruction that subsequently failed. After the wound vac was replaced, the synthetic dural graft was replaced with a fascia lata graft and an anterolateral thigh free flap reconstruction. We describe the technical nuances of this complicated case, how the obstacles were handled, and the literature that discusses the utility. Conclusion: We describe a case of a complex cranial wound and technical nuances on how to utilize a wound-vac with loss of dura mater. INTRODUCTION Complex cranial wounds can be a problematic occurrence for surgeons. These can result from trauma, infection, malignancy, wound break down, and radiation. Possibilities of reconstruction have increased over the years, with options including rotational flaps, tissue expanders, and over 20 different free flaps. Despite the advancements in reconstruction of cranial defects, patients can have problems with healing due to other medical co-morbidities. Due to the complexity of this clinical scenario, a well-formulated plan and a multidisciplinary approach are often required. Decisions regarding the timing of reconstruction, type of reconstruction, and what to reconstruct are all taken into consideration. In 1997, Morykwas et al. introduced negative pressure therapy via vacuum-assisted closure (VAC) for complex wounds. Over the years, this concept has gained popularity and has been used for thoracic wounds, abdominal wounds, burn wounds, skin-grafting, and limb trauma. Over recent years, the utility of VACs has grown to involve complex cranial wounds. There are reports in the literature that describe the use of VACs in scalp defects, defects with exposed periosteum, and fewer reports describing defects in periosteum with exposed dura. To our knowledge, there is only one report on the use of VAC with the loss of dura. This study is a technical note of our experience with VAC device in a complex cranial wound complicated by infection, loss of dura, and a failed rotational flap. CASE REPORT Patient is a 68-year-old female who presented to the emergency room after a fall while walking her dog with complaints of headaches, nausea, and vomiting. Patient denied any loss of consciousness. Her past medical history consisted of hypertension and peripheral vascular disease. Patient smoked one pack of cigarette per day. On physical examination, she had no focal neurological deficits but was confused. Computed tomography (CT) scan showed a large left 1 cm convexity acute subdural hematoma (SDH) with 6 mm midline shift. Due to her disorientation and midline shift, the patient was taken back to the operating room (OR) for evacuation of the SDH. A reverse question mark incision was made with a standard trauma craniotomy. During the operation, the superficial temporal artery (STA) was mistakenly sacrificed. Patient tolerated the surgery well and continued to improve with her mental status postoperatively. She was discharged to rehab on postoperative day 7. The patient continued to smoke despite our recommendations. She returned to the emergency room 19 days later complaining of fever, erythema, swelling underneath the wound, and purulent drainage on her pillow. The radiographic findings suggested that the infection was superficial. After being evaluated in the emergency department, she was taken to the OR for surgical lavage and debridement. During the operating, her bone flap was felt to be viable and free of infection, so it was not removed. Intraoperative cultures were found to grow methicillin-sensitive Staphylococcus aureus, and the patient was started on IV Nafcillin. Approximately 2 weeks later, purulent drainage returned from the incision site. Radiographic findings suggested that there was an intracranial component. She was taken to the OR for a wound washout. Given the degree of infection identified during the operation, as well as the intracranial infection noted in the subdural space, the decision was made to remove the bone flap. Over the next week, the wound started to break down. Subsequently, there was a wedge-shaped necrosis that developed on the flap . Dura was visible in the area of wound breakdown. After consulting with plastic and oral maxillofacial surgery, the patient was taken back to the OR two weeks later for resection of necrotic scalp, dura repair and wound VAC placement. The dura was noted to be frail, shredded, and portions were missing [. Because of the risk of neurological sequelae and cerebrospinal fluid (CSF) diversion with a VAC device placed on exposed brain tissue, water-tight closure of the dura was a necessity prior to placement of the VAC device. After achieving securable edges, Durepair® (Medtronic, Inc.) . was sutured in to native dura with 4-0 Nurolon (Ethicon). Water-tight closure was confirmed with a Valsalva maneuver, and fibrin glue was not used. On gross inspection, the wound vac canister did not have any CSF contents. Negative pressure therapy was set to -50 mmHg . The wound vac was changed approximately every 3 days until adequate granulation tissue was noted and the infection had subsided . Intraoperative cultures during the wound vac changes grew Candida. Patient was started on diflucan. Two weeks later, the patient was taken to the OR with plastic and oral maxillofacial surgery for a latissimus dorsi muscle flap reconstruction. The patient was monitored in the intensive care unit (ICU) with daily Dopplers to ensure the viability of the flap. The flap went on to necros as a result of an infection caused by Pseudomonas. The patient went to the OR for removal of her flap. The dura with the synthetic graft still had a water-tight closure. The wound VAC was replaced and changed approximately every 3 days. To ensure the next flap would not fail, the granulation tissue on the Durepair ® (Medtronic, Inc.) was cultured. The intraoperative culture also grew Pseudomonas, but only on the synthetic dura. After a multidisciplinary discussion, we felt that a native substitute for the dura may decrease the risk of infection. Three weeks later, the patient was taken to the OR removal of dural substitute, harvest of fascia lata graft, and anterolateral thigh free flap. The fascia lata graft was harvested from the contralateral leg of the anterolateral thigh free flap. The fascial lata graft was secured in a water-tight fashion. The anterolateral thigh free flap was performed without any complications . Patient returned to the ICU on the ventilator with continued sedation due to flap anastomosis fragility. The ventilator was weaned off on postoperative day 1. Patient was at her neurological baseline after extubation and transferred to the floor on postoperative day 5. Patient continued her antibiotic regimen of Nafcillin and Diflucan postoperatively. Patient followed up with neurosurgery, plastic surgery, and oral maxillofacial surgery. At the 6-month follow-up, the flap had healed without any signs or symptoms of infection. The patient has been followed for 14 months after surgery with the reconstruction intact . DISCUSSION Morykwas et al. introduced negative pressure therapy with a VAC device improved blood flow, increased granulation tissue formation, and decreased bacterial cell counts. Other studies have shown that negative pressure therapy increases microvessel density, exudate removal, edema reduction, wound volume reduction, improves wound healing, decreases wound drainage, shortens the length of hospital stay, reduces the cost of wound care, and ultimately improves patient survival. [4,6,8,9,12,15,16,26,27, The application of this technology has increased over the years to treat a wide variety of wounds, such as degloving injuries, abdominal defects, enterocutaneous defects, gynecological wounds, sternal dehiscence, spinal wound infections, pressure sores, and augmentation of skin grafts. Recently, this technology has been applied to complex cranial wounds. Historically at our institution, small scalp defects have been treated with primary closure, scoring the galea to improve elasticity of the scalp, skin grafts, or small rotational flaps. Larger scalp defects have been treated with large rotational flaps or free flaps. One of the earliest reports describing treatment with VAC therapy on complex cranial wounds was by Andrews et al., where two patients with traumatic scalp injuries were successfully treated without any complications. Subotic et al. expanded the utility of VAC treatment by using it on scalp defects with coinciding calvarial defects. One case was on a young boy with Apert syndrome. This case had a chronic methicillin-resistant S. aureus infection with a coinciding bony defect and exposed dura. VAC treatment allowed protection while the infection was eradicated. After promoting granulation tissue, a full thickness skin graft was transplanted, which ultimately failed. After eradicating the infection, the VAC device was used as a stand-alone method for wound closure. Another case involved an eccrine gland carcinoma of the cranium that led to erosion of the calvarium. It is important to note that both cases did not violate the dura. Tanna et al. described a patient that underwent resection of the floor of his mouth with a subsequent cervical flap. The cervical flap dehisced on postoperative day 10, exposing the underlying bone. VAC treatment allowed the formation of granulation tissue, which was later treated with a full-thickness skin graft. The first report of a scalp and bony defect with a coinciding dural defect was described by Powers et al. They reported on five patients, of whom four had a loss of dura mater and one had a dural dehiscence. Different methods to reapproximately the dura were used prior to placing the VAC device. One patient had the dura closed primarily, one patient had a pericranial graft sutured into the native dura, and three patients had Alloderm (LifeCell Corp.) sutured into the native dura using 4-0 Nurolon (Ethicon). Our case was unique in many ways. The STA was iatrogenically sacrificed in the initial craniotomy for the SDH evacuation. Unfortunately, because the STA was sacrificed, blood flow to the scalp was compromised. The patient's cigarette use during the hospitalization and postoperative infection likely contributed to nerosis of the scalp. In the initial SDH evacuation and subsequent washout, dura mater was lost. Because the necrotic tissue had to be excised, and the bone flap was not secured back in an infected setting, there was a large defect exposing brain tissue. Before a flap could be performed, we felt that eradicating the infection would improve the chances of a successful flap reconstruction. Initially, we used Durepair® (Medtronic, Inc.) to create a water-tight closure with native dura. We confirmed the water-tight closure with a Valsalva maneuver. In retrospect, placing a synthetic dural substitute in the setting of a prior infection could have provided a medium of bacterial regrowth. This likely contributed to the latissimus muscle free flap to fail. For autologous dural patch, pericranium was available but would have required extending the incision; therefore, we decided to use fascia lata. After adequate long-term follow-up showing a viable free-flap reconstruction, a cranioplasty is an option to close the boneless defect. Due to the initial difficulty in free-flap reconstruction, history of infection, smoking status, and peripheral vascular disease, the treating physician team and patient do not feel closing a boneless defect outweighs the risks of a cranioplasty. CONCLUSION To our knowledge, there is only one study that discussed the use of VAC in a complex cranial wound with loss of dura mater. The aim of our study was to provide a technical note on a VAC in a patient with a complex cranial wound and loss of dura. This is the first report to discuss the use of fascia lata graft with wound-vac closures. The complications and obstacles encountered with this patient were unique to the literature and provide an option on how to treat complex cranial wounds. |
Stoof Bezuidenhout
Varsity Cup
Bezuidenhout played for Potchefstroom-based university side NWU Pukke in the Varsity Cup competition in 2009, 2010 and 2011. He made a total of 16 appearances, which included playing all nine of their matches during the 2009 campaign – with Bezuidenhout scoring one try against the TUT Vikings – as NWU Pukke reached the final of the competition, only to lose the final 11–6 to the Maties in Stellenbosch.
Leopards
In 2011, Bezuidenhout also became involved with the provincial rugby side based in Potchefstroom, the Leopards. He was included in their squad for the 2011 Vodacom Cup competition and made his debut in the first match of the season against the Border Bulldogs in East London, Eastern Cape, eventually starting all eight of their matches during the competition. He was also a regular for the side in the 2011 Currie Cup Premier Division, being named in the run-on side in ten of their fourteen matches. His debut in that competition was the Round One clash against the Free State Cheetahs in Bloemfontein, but he could not prevent the Leopards' relegation to the First Division as they only won one match during the competition.
He made fourteen appearances for them in the 2012 Currie Cup First Division to help them finish in fourth place. Two Vodacom Cup and six Currie Cup First Division appearances followed in 2013, with Bezuidenhout also scoring his first senior try in the latter competition in their match against the Falcons in a 38–27 victory. He started all seven of the Leopards' matches in the 2014 Vodacom Cup, also scoring his first try in this competition against the Limpopo Blue Bulls and made one appearance in the 2014 Currie Cup qualification competition as the Leopards lost out on qualification to the 2014 Currie Cup Premier Division by a single point. |
// State set for combining two textures. Used
// when rendering fullscreen tri pairs.
void
mrtStateSetTriPair( osg::StateSet* ss, osg::Texture2D* tex0, osg::Texture2D* tex1 )
{
ss->setTextureAttributeAndModes( 0, tex0, osg::StateAttribute::ON );
ss->setTextureAttributeAndModes( 1, tex1, osg::StateAttribute::ON );
ss->addUniform( new osg::Uniform( "tex0", 0 ) );
ss->addUniform( new osg::Uniform( "tex1", 1 ) );
std::string fragsource =
"uniform sampler2D tex0; \n"
"uniform sampler2D tex1; \n"
"void main() \n"
"{ \n"
"gl_FragData[0] = texture2D( tex0, gl_TexCoord[0].st ) \n"
" + texture2D( tex1, gl_TexCoord[0].st ); \n"
"} \n";
osg::Shader* fragShader = new osg::Shader();
fragShader->setType( osg::Shader::FRAGMENT );
fragShader->setShaderSource( fragsource );
osg::Program* program = new osg::Program();
program->addShader( fragShader );
ss->setAttribute( program, osg::StateAttribute::ON );
ss->setMode( GL_LIGHTING, osg::StateAttribute::OFF );
} |
<gh_stars>1000+
import * as React from "react"
import { fileName } from "../inc/file-name"
import { Container, Code } from "../styled"
import { WrongModuleShape } from "./WrongModuleShape"
const context = require["context"]("../examples", true, /\.(tsx?)$/)
const style: React.CSSProperties = {
font: "16px/1.6em 'Helvetica Neue'",
textRendering: "optimizeLegibility",
margin: "64px",
}
export const ExampleList = () => {
return (
<div style={style}>
<h2>Framer Examples</h2>
<p>
You can edit any of these in the <Code>dev/examples</Code>{" "}
folder.
</p>
<ul>
{context.keys().map((name: string) => (
<li key={name}>
<a href={`?example=${fileName(name)}`}>
{fileName(name)}
</a>{" "}
<Code>{name.replace("./", "examples/")}</Code>
</li>
))}
</ul>
</div>
)
}
export const Example = ({ id }: { id: string }) => {
const name = fileName(id)
const targetModule = require(`../examples/${name}`)
if (!targetModule.App) {
return <WrongModuleShape path={`examples/${name}`} />
}
document.title = name
return (
<Container>
<targetModule.App />
</Container>
)
}
|
/**
* Removes the HDFS/AMS alert definitions for the standard deviation alerts,
* including all history, notifications and groupings.
* <p/>
* These alerts shipped disabled and were not functional in prior versions of
* Ambari. This is the cleanest and simplest way to update them all as they
* will be read back into Ambari on server startup.
*
* @throws SQLException
*/
void removeStandardDeviationAlerts() throws SQLException {
List<String> deviationAlertNames = Lists.newArrayList(
"namenode_service_rpc_queue_latency_hourly",
"namenode_client_rpc_queue_latency_hourly",
"namenode_service_rpc_processing_latency_hourly",
"namenode_client_rpc_processing_latency_hourly",
"increase_nn_heap_usage_daily",
"namenode_service_rpc_processing_latency_daily",
"namenode_client_rpc_processing_latency_daily",
"namenode_service_rpc_queue_latency_daily",
"namenode_client_rpc_queue_latency_daily",
"namenode_increase_in_storage_capacity_usage_daily",
"increase_nn_heap_usage_weekly",
"namenode_increase_in_storage_capacity_usage_weekly");
AlertDefinitionDAO alertDefinitionDAO = injector.getInstance(AlertDefinitionDAO.class);
Clusters clusters = injector.getInstance(Clusters.class);
Map<String, Cluster> clusterMap = getCheckedClusterMap(clusters);
for (final Cluster cluster : clusterMap.values()) {
long clusterId = cluster.getClusterId();
for (String alertName : deviationAlertNames) {
AlertDefinitionEntity definition = alertDefinitionDAO.findByName(clusterId, alertName);
if (null != definition) {
alertDefinitionDAO.remove(definition);
}
}
}
} |
package net.serenitybdd.core.pages;
import net.thucydides.core.util.EnvironmentVariables;
import org.openqa.selenium.StaleElementReferenceException;
import java.util.function.Function;
import static net.thucydides.core.ThucydidesSystemProperty.WEBDRIVER_RETRY_ON_STALE_ELEMENT_EXCEPTION;
public class FindAllWithRetry {
private final EnvironmentVariables environmentVariables;
public FindAllWithRetry(EnvironmentVariables environmentVariables) {
this.environmentVariables = environmentVariables;
}
public ListOfWebElementFacades find(Function<PageObject, ListOfWebElementFacades> finder, PageObject page) {
ListOfWebElementFacades matchingElements = finder.apply(page);
if (shouldRetryOnStaleElementException()) {
matchingElements.setFallback(finder, page);
}
return matchingElements;
}
private boolean shouldRetryOnStaleElementException() {
return WEBDRIVER_RETRY_ON_STALE_ELEMENT_EXCEPTION.booleanFrom(environmentVariables, true);
}
}
|
<gh_stars>0
package com.codepath.apps.mysimpletweets.Fragments;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ProgressBar;
import com.codepath.apps.mysimpletweets.Activity.ActivityDetail;
import com.codepath.apps.mysimpletweets.Activity.ActivityTimeline.ItemClickSupport;
import com.codepath.apps.mysimpletweets.Adapters.EndlessRecyclerViewScrollListener;
import com.codepath.apps.mysimpletweets.Adapters.FollowAdapter;
import com.codepath.apps.mysimpletweets.Applications.TwitterApplication;
import com.codepath.apps.mysimpletweets.Clients.TwitterClient;
import com.codepath.apps.mysimpletweets.R;
import com.codepath.apps.mysimpletweets.SupportingClasses.RecyclerItemDecorator;
import com.codepath.apps.mysimpletweets.databinding.FragmentTweetBinding;
import com.codepath.apps.mysimpletweets.models.User;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.parceler.Parcels;
import java.util.ArrayList;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBarUtils;
import fr.castorflex.android.smoothprogressbar.SmoothProgressDrawable;
import static android.content.ContentValues.TAG;
import static com.codepath.apps.mysimpletweets.Fragments.TweetListFragment.NUM_GRID_COLUMNS;
/**
* Created by jsaluja on 4/1/2017.
*/
public class FollowProfileFragment extends Fragment {
private User user;
private TwitterClient client;
private String type;
public FollowAdapter followAdapter;
private EndlessRecyclerViewScrollListener scrollListener;
public RecyclerView rvUsers;
public StaggeredGridLayoutManager gridLayoutManager;
private int cursor = -1;
public ArrayList<User> mUsers;
public Context mContext;
public ProgressBar progressBar;
public SmoothProgressBar smoothProgressBar;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.fragment_tweet, container, false);
// Data binding
FragmentTweetBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_tweet, container, false);
View view = binding.getRoot();
dataBindFragmentValues(binding);
mContext = view.getContext();
progressBar.setIndeterminateDrawable(new SmoothProgressDrawable.Builder(getActivity()).interpolator(new AccelerateInterpolator()).build());
smoothProgressBar.setSmoothProgressDrawableBackgroundDrawable(
SmoothProgressBarUtils.generateDrawableWithColors(
getResources().getIntArray(R.array.pocket_background_colors),
((SmoothProgressDrawable) smoothProgressBar.getIndeterminateDrawable()).getStrokeWidth()));
progressBar.setVisibility(ProgressBar.INVISIBLE);
setupRecycleAdapter();
//Displaying activity details. Using parcel
ItemClickSupport.addTo(rvUsers).setOnItemClickListener(
(recyclerView, position, v) -> {
Intent userDetails = new Intent(getActivity(), ActivityDetail.class);
if(mUsers.get(position) != null) {
String name = mUsers.get(position).getName();
Log.d(TAG, "USERRR is " + mUsers.get(position).getProfileNameUrl());
userDetails.putExtra("user_name", mUsers.get(position).getName());
userDetails.putExtra("user_screen_name", mUsers.get(position).getScreenName());
userDetails.putExtra("user_pic_url", mUsers.get(position).getProfileNameUrl());
// tweetDetails.putExtra("tweet_object", Parcels.wrap(mUsers.get(position)));
userDetails.putExtra("position", position);
}
startActivityForResult(userDetails, 1);
}
);
return view;
}
public void dataBindFragmentValues(FragmentTweetBinding binding) {
rvUsers = binding.RecycleViewResultsId;
progressBar = binding.ProgressBarId;
smoothProgressBar = binding.SmoothProgressBarId;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Setup adapter
mUsers = new ArrayList<>();
followAdapter = new FollowAdapter(getActivity(), mUsers);
}
public void setupRecycleAdapter() {
rvUsers.setAdapter(followAdapter);
gridLayoutManager = new StaggeredGridLayoutManager(NUM_GRID_COLUMNS, StaggeredGridLayoutManager.VERTICAL);
gridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
rvUsers.setHasFixedSize(true);
rvUsers.setLayoutManager(gridLayoutManager);
rvUsers.addItemDecoration(new RecyclerItemDecorator.SimpleDividerItemDecoration(getActivity()));
}
} |
A family of three from Napanee, one elderly man from Belleville and a parolee in Scarborough have been charged by the Ontario Provincial Police following a joint investigation with the Correctional Service of Canada into drug trafficking.
A family of three from Napanee, one elderly man from Belleville and a parolee in Scarborough have been charged by Ontario Provincial Police following a joint investigation with Correctional Service Canada into drug trafficking.
On Monday, the OPP executed search warrants at a Napanee business and a Napanee residence, a Prince Edward County business and at a residence in Scarborough. A family of three were arrested in Napanee, one elderly man was arrested in Belleville, and a man on parole was arrested at the home in Scarborough. The parolee was returned to CSC.
During the searches, officers seized three firearms, ammunition, several thousand dollars in cash as well as a quantity of both powdered cocaine and cocaine pills, along with other paraphernalia.
“This investigation highlights perfectly how the mandates of various enforcement agencies have all contributed to public safety and well-being through collaboration and information sharing,” Insp. Scott Semple, Napanee OPP’s detachment commander, said in a news release. “This investigation would not have been such a success without the assistance of Correctional Service Canada, the Belleville Police Service and the Toronto Police Service.
The OPP have charged 22-year-old Shaye Murdoch of Napanee with five counts of unlawful possession and storage of firearms, and one count each of possession of cocaine for the purpose of trafficking, possession of proceeds of crime over $5,000, and conspiracy to commit an indictable offence.
Shaye’s father, 52-year-old Brian Murdoch, also of Napanee, has been charged by the OPP with five counts of unlawful possession and storage of firearms, and one count each of possession of cocaine for the purpose of trafficking, and possession of proceeds of crime over $5,000.
Brian’s wife, 51-year-old Sherry Murdoch, also also been charged by the OPP with five counts of unlawful possession and storage of firearms, and one count each of possession of cocaine for the purpose of trafficking, and possession of proceeds of crime over $5,000.
The OPP have also charged 86-year-old Edward Enright of Belleville with possession of proceeds of crime, and conspiracy to commit an indictable offence.
The parolee arrested by the OPP in Scarborough was 37-year-old Jermaine Martinborough. His parole has been revoked and the OPP have charged him with possession of cocaine for the purpose of trafficking, trafficking cocaine, conspiracy to commit an indictable offence, and possession of proceeds of crime.
The Murdoch’s, Enright and Martinborough are all scheduled to appear in the Ontario Court of Justice in Napanee in early March. The charges against the accused have not been proven in court.
OPP said their investigation is continuing. |
Manchester City have reached agreement with Valencia to sign Spain forward David Silva.
The 24-year-old, who is currently at the World Cup with his national squad, has agreed a five-year deal at Eastlands.
Silva will undergo a medical and the transfer will be formally completed once his involvement in South Africa is over.
Speaking from Spain's World Cup base, Silva told the club's website, www.mcfc.co.uk: "Firstly I would like to thank Valencia as a club and all of their loyal fans, and my team-mates there and staff.
"I have enjoyed six years at Valencia, they discovered me as a footballer and they will always be a special club for me.
"The time is right for me to seek a new challenge, and I am thrilled about playing in England with Manchester City.
"I believe the Premier League is one of the best competitions in the world and I want to bring success to City and win trophies for them.
"There has been a lot of speculation about me in the British and Spanish media, and I need to fully concentrate on playing for Spain in the World Cup.
"That is why my advisors have been dealing with City for me, so that I can have my attentions only on South Africa and playing well for my national team." |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/ppapi_plugin/broker_process_dispatcher.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/utf_string_conversions.h"
#include "content/common/child_process.h"
#include "ppapi/c/private/ppp_flash_browser_operations.h"
#include "ppapi/proxy/ppapi_messages.h"
namespace {
// How long we wait before releasing the broker process.
const int kBrokerReleaseTimeSeconds = 30;
} // namespace
BrokerProcessDispatcher::BrokerProcessDispatcher(
PP_GetInterface_Func get_plugin_interface,
PP_ConnectInstance_Func connect_instance)
: ppapi::proxy::BrokerSideDispatcher(connect_instance),
get_plugin_interface_(get_plugin_interface) {
ChildProcess::current()->AddRefProcess();
}
BrokerProcessDispatcher::~BrokerProcessDispatcher() {
DVLOG(1) << "BrokerProcessDispatcher::~BrokerProcessDispatcher()";
// Don't free the process right away. This timer allows the child process
// to be re-used if the user rapidly goes to a new page that requires this
// plugin. This is the case for common plugins where they may be used on a
// source and destination page of a navigation. We don't want to tear down
// and re-start processes each time in these cases.
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ChildProcess::ReleaseProcess,
base::Unretained(ChildProcess::current())),
base::TimeDelta::FromSeconds(kBrokerReleaseTimeSeconds));
}
bool BrokerProcessDispatcher::OnMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(BrokerProcessDispatcher, msg)
IPC_MESSAGE_HANDLER(PpapiMsg_ClearSiteData, OnMsgClearSiteData)
IPC_MESSAGE_UNHANDLED(return BrokerSideDispatcher::OnMessageReceived(msg))
IPC_END_MESSAGE_MAP()
return true;
}
void BrokerProcessDispatcher::OnMsgClearSiteData(
const FilePath& plugin_data_path,
const std::string& site,
uint64 flags,
uint64 max_age) {
Send(new PpapiHostMsg_ClearSiteDataResult(
ClearSiteData(plugin_data_path, site, flags, max_age)));
}
bool BrokerProcessDispatcher::ClearSiteData(const FilePath& plugin_data_path,
const std::string& site,
uint64 flags,
uint64 max_age) {
if (!get_plugin_interface_)
return false;
const PPP_Flash_BrowserOperations_1_0* browser_interface =
static_cast<const PPP_Flash_BrowserOperations_1_0*>(
get_plugin_interface_(PPP_FLASH_BROWSEROPERATIONS_INTERFACE_1_0));
if (!browser_interface)
return false;
// The string is always 8-bit, convert on Windows.
#if defined(OS_WIN)
std::string data_str = WideToUTF8(plugin_data_path.value());
#else
std::string data_str = plugin_data_path.value();
#endif
browser_interface->ClearSiteData(data_str.c_str(),
site.empty() ? NULL : site.c_str(),
flags, max_age);
return true;
}
|
/*
* drivers/firmware/qemu_fw_cfg.c
*
* Copyright 2015 Carnegie Mellon University
*
* Expose entries from QEMU's firmware configuration (fw_cfg) device in
* sysfs (read-only, under "/sys/firmware/qemu_fw_cfg/...").
*
* The fw_cfg device may be instantiated via either an ACPI node (on x86
* and select subsets of aarch64), a Device Tree node (on arm), or using
* a kernel module (or command line) parameter with the following syntax:
*
* [fw_cfg.]ioport=<size>@<base>[:<ctrl_off>:<data_off>]
* or
* [fw_cfg.]mmio=<size>@<base>[:<ctrl_off>:<data_off>]
*
* where:
* <size> := size of ioport or mmio range
* <base> := physical base address of ioport or mmio range
* <ctrl_off> := (optional) offset of control register
* <data_off> := (optional) offset of data register
*
* e.g.:
* fw_cfg.ioport=2@0x510:0:1 (the default on x86)
* or
* fw_cfg.mmio=0xA@0x9020000:8:0 (the default on arm)
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/acpi.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/ioport.h>
MODULE_AUTHOR("Gabriel L. Somlo <[email protected]>");
MODULE_DESCRIPTION("QEMU fw_cfg sysfs support");
MODULE_LICENSE("GPL");
/* selector key values for "well-known" fw_cfg entries */
#define FW_CFG_SIGNATURE 0x00
#define FW_CFG_ID 0x01
#define FW_CFG_FILE_DIR 0x19
/* size in bytes of fw_cfg signature */
#define FW_CFG_SIG_SIZE 4
/* fw_cfg "file name" is up to 56 characters (including terminating nul) */
#define FW_CFG_MAX_FILE_PATH 56
/* fw_cfg file directory entry type */
struct fw_cfg_file {
u32 size;
u16 select;
u16 reserved;
char name[FW_CFG_MAX_FILE_PATH];
};
/* fw_cfg device i/o register addresses */
static bool fw_cfg_is_mmio;
static phys_addr_t fw_cfg_p_base;
static resource_size_t fw_cfg_p_size;
static void __iomem *fw_cfg_dev_base;
static void __iomem *fw_cfg_reg_ctrl;
static void __iomem *fw_cfg_reg_data;
/* atomic access to fw_cfg device (potentially slow i/o, so using mutex) */
static DEFINE_MUTEX(fw_cfg_dev_lock);
/* pick appropriate endianness for selector key */
static inline u16 fw_cfg_sel_endianness(u16 key)
{
return fw_cfg_is_mmio ? cpu_to_be16(key) : cpu_to_le16(key);
}
/* read chunk of given fw_cfg blob (caller responsible for sanity-check) */
static inline void fw_cfg_read_blob(u16 key,
void *buf, loff_t pos, size_t count)
{
u32 glk = -1U;
acpi_status status;
/* If we have ACPI, ensure mutual exclusion against any potential
* device access by the firmware, e.g. via AML methods:
*/
status = acpi_acquire_global_lock(ACPI_WAIT_FOREVER, &glk);
if (ACPI_FAILURE(status) && status != AE_NOT_CONFIGURED) {
/* Should never get here */
WARN(1, "fw_cfg_read_blob: Failed to lock ACPI!\n");
memset(buf, 0, count);
return;
}
mutex_lock(&fw_cfg_dev_lock);
iowrite16(fw_cfg_sel_endianness(key), fw_cfg_reg_ctrl);
while (pos-- > 0)
ioread8(fw_cfg_reg_data);
ioread8_rep(fw_cfg_reg_data, buf, count);
mutex_unlock(&fw_cfg_dev_lock);
acpi_release_global_lock(glk);
}
/* clean up fw_cfg device i/o */
static void fw_cfg_io_cleanup(void)
{
if (fw_cfg_is_mmio) {
iounmap(fw_cfg_dev_base);
release_mem_region(fw_cfg_p_base, fw_cfg_p_size);
} else {
ioport_unmap(fw_cfg_dev_base);
release_region(fw_cfg_p_base, fw_cfg_p_size);
}
}
/* arch-specific ctrl & data register offsets are not available in ACPI, DT */
#if !(defined(FW_CFG_CTRL_OFF) && defined(FW_CFG_DATA_OFF))
# if (defined(CONFIG_ARM) || defined(CONFIG_ARM64))
# define FW_CFG_CTRL_OFF 0x08
# define FW_CFG_DATA_OFF 0x00
# elif (defined(CONFIG_PPC_PMAC) || defined(CONFIG_SPARC32)) /* ppc/mac,sun4m */
# define FW_CFG_CTRL_OFF 0x00
# define FW_CFG_DATA_OFF 0x02
# elif (defined(CONFIG_X86) || defined(CONFIG_SPARC64)) /* x86, sun4u */
# define FW_CFG_CTRL_OFF 0x00
# define FW_CFG_DATA_OFF 0x01
# else
# error "QEMU FW_CFG not available on this architecture!"
# endif
#endif
/* initialize fw_cfg device i/o from platform data */
static int fw_cfg_do_platform_probe(struct platform_device *pdev)
{
char sig[FW_CFG_SIG_SIZE];
struct resource *range, *ctrl, *data;
/* acquire i/o range details */
fw_cfg_is_mmio = false;
range = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!range) {
fw_cfg_is_mmio = true;
range = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!range)
return -EINVAL;
}
fw_cfg_p_base = range->start;
fw_cfg_p_size = resource_size(range);
if (fw_cfg_is_mmio) {
if (!request_mem_region(fw_cfg_p_base,
fw_cfg_p_size, "fw_cfg_mem"))
return -EBUSY;
fw_cfg_dev_base = ioremap(fw_cfg_p_base, fw_cfg_p_size);
if (!fw_cfg_dev_base) {
release_mem_region(fw_cfg_p_base, fw_cfg_p_size);
return -EFAULT;
}
} else {
if (!request_region(fw_cfg_p_base,
fw_cfg_p_size, "fw_cfg_io"))
return -EBUSY;
fw_cfg_dev_base = ioport_map(fw_cfg_p_base, fw_cfg_p_size);
if (!fw_cfg_dev_base) {
release_region(fw_cfg_p_base, fw_cfg_p_size);
return -EFAULT;
}
}
/* were custom register offsets provided (e.g. on the command line)? */
ctrl = platform_get_resource_byname(pdev, IORESOURCE_REG, "ctrl");
data = platform_get_resource_byname(pdev, IORESOURCE_REG, "data");
if (ctrl && data) {
fw_cfg_reg_ctrl = fw_cfg_dev_base + ctrl->start;
fw_cfg_reg_data = fw_cfg_dev_base + data->start;
} else {
/* use architecture-specific offsets */
fw_cfg_reg_ctrl = fw_cfg_dev_base + FW_CFG_CTRL_OFF;
fw_cfg_reg_data = fw_cfg_dev_base + FW_CFG_DATA_OFF;
}
/* verify fw_cfg device signature */
fw_cfg_read_blob(FW_CFG_SIGNATURE, sig, 0, FW_CFG_SIG_SIZE);
if (memcmp(sig, "QEMU", FW_CFG_SIG_SIZE) != 0) {
fw_cfg_io_cleanup();
return -ENODEV;
}
return 0;
}
/* fw_cfg revision attribute, in /sys/firmware/qemu_fw_cfg top-level dir. */
static u32 fw_cfg_rev;
static ssize_t fw_cfg_showrev(struct kobject *k, struct attribute *a, char *buf)
{
return sprintf(buf, "%u\n", fw_cfg_rev);
}
static const struct {
struct attribute attr;
ssize_t (*show)(struct kobject *k, struct attribute *a, char *buf);
} fw_cfg_rev_attr = {
.attr = { .name = "rev", .mode = S_IRUSR },
.show = fw_cfg_showrev,
};
/* fw_cfg_sysfs_entry type */
struct fw_cfg_sysfs_entry {
struct kobject kobj;
struct fw_cfg_file f;
struct list_head list;
};
/* get fw_cfg_sysfs_entry from kobject member */
static inline struct fw_cfg_sysfs_entry *to_entry(struct kobject *kobj)
{
return container_of(kobj, struct fw_cfg_sysfs_entry, kobj);
}
/* fw_cfg_sysfs_attribute type */
struct fw_cfg_sysfs_attribute {
struct attribute attr;
ssize_t (*show)(struct fw_cfg_sysfs_entry *entry, char *buf);
};
/* get fw_cfg_sysfs_attribute from attribute member */
static inline struct fw_cfg_sysfs_attribute *to_attr(struct attribute *attr)
{
return container_of(attr, struct fw_cfg_sysfs_attribute, attr);
}
/* global cache of fw_cfg_sysfs_entry objects */
static LIST_HEAD(fw_cfg_entry_cache);
/* kobjects removed lazily by kernel, mutual exclusion needed */
static DEFINE_SPINLOCK(fw_cfg_cache_lock);
static inline void fw_cfg_sysfs_cache_enlist(struct fw_cfg_sysfs_entry *entry)
{
spin_lock(&fw_cfg_cache_lock);
list_add_tail(&entry->list, &fw_cfg_entry_cache);
spin_unlock(&fw_cfg_cache_lock);
}
static inline void fw_cfg_sysfs_cache_delist(struct fw_cfg_sysfs_entry *entry)
{
spin_lock(&fw_cfg_cache_lock);
list_del(&entry->list);
spin_unlock(&fw_cfg_cache_lock);
}
static void fw_cfg_sysfs_cache_cleanup(void)
{
struct fw_cfg_sysfs_entry *entry, *next;
list_for_each_entry_safe(entry, next, &fw_cfg_entry_cache, list) {
/* will end up invoking fw_cfg_sysfs_cache_delist()
* via each object's release() method (i.e. destructor)
*/
kobject_put(&entry->kobj);
}
}
/* default_attrs: per-entry attributes and show methods */
#define FW_CFG_SYSFS_ATTR(_attr) \
struct fw_cfg_sysfs_attribute fw_cfg_sysfs_attr_##_attr = { \
.attr = { .name = __stringify(_attr), .mode = S_IRUSR }, \
.show = fw_cfg_sysfs_show_##_attr, \
}
static ssize_t fw_cfg_sysfs_show_size(struct fw_cfg_sysfs_entry *e, char *buf)
{
return sprintf(buf, "%u\n", e->f.size);
}
static ssize_t fw_cfg_sysfs_show_key(struct fw_cfg_sysfs_entry *e, char *buf)
{
return sprintf(buf, "%u\n", e->f.select);
}
static ssize_t fw_cfg_sysfs_show_name(struct fw_cfg_sysfs_entry *e, char *buf)
{
return sprintf(buf, "%s\n", e->f.name);
}
static FW_CFG_SYSFS_ATTR(size);
static FW_CFG_SYSFS_ATTR(key);
static FW_CFG_SYSFS_ATTR(name);
static struct attribute *fw_cfg_sysfs_entry_attrs[] = {
&fw_cfg_sysfs_attr_size.attr,
&fw_cfg_sysfs_attr_key.attr,
&fw_cfg_sysfs_attr_name.attr,
NULL,
};
/* sysfs_ops: find fw_cfg_[entry, attribute] and call appropriate show method */
static ssize_t fw_cfg_sysfs_attr_show(struct kobject *kobj, struct attribute *a,
char *buf)
{
struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
struct fw_cfg_sysfs_attribute *attr = to_attr(a);
return attr->show(entry, buf);
}
static const struct sysfs_ops fw_cfg_sysfs_attr_ops = {
.show = fw_cfg_sysfs_attr_show,
};
/* release: destructor, to be called via kobject_put() */
static void fw_cfg_sysfs_release_entry(struct kobject *kobj)
{
struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
fw_cfg_sysfs_cache_delist(entry);
kfree(entry);
}
/* kobj_type: ties together all properties required to register an entry */
static struct kobj_type fw_cfg_sysfs_entry_ktype = {
.default_attrs = fw_cfg_sysfs_entry_attrs,
.sysfs_ops = &fw_cfg_sysfs_attr_ops,
.release = fw_cfg_sysfs_release_entry,
};
/* raw-read method and attribute */
static ssize_t fw_cfg_sysfs_read_raw(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t pos, size_t count)
{
struct fw_cfg_sysfs_entry *entry = to_entry(kobj);
if (pos > entry->f.size)
return -EINVAL;
if (count > entry->f.size - pos)
count = entry->f.size - pos;
fw_cfg_read_blob(entry->f.select, buf, pos, count);
return count;
}
static struct bin_attribute fw_cfg_sysfs_attr_raw = {
.attr = { .name = "raw", .mode = S_IRUSR },
.read = fw_cfg_sysfs_read_raw,
};
/*
* Create a kset subdirectory matching each '/' delimited dirname token
* in 'name', starting with sysfs kset/folder 'dir'; At the end, create
* a symlink directed at the given 'target'.
* NOTE: We do this on a best-effort basis, since 'name' is not guaranteed
* to be a well-behaved path name. Whenever a symlink vs. kset directory
* name collision occurs, the kernel will issue big scary warnings while
* refusing to add the offending link or directory. We follow up with our
* own, slightly less scary error messages explaining the situation :)
*/
static int fw_cfg_build_symlink(struct kset *dir,
struct kobject *target, const char *name)
{
int ret;
struct kset *subdir;
struct kobject *ko;
char *name_copy, *p, *tok;
if (!dir || !target || !name || !*name)
return -EINVAL;
/* clone a copy of name for parsing */
name_copy = p = kstrdup(name, GFP_KERNEL);
if (!name_copy)
return -ENOMEM;
/* create folders for each dirname token, then symlink for basename */
while ((tok = strsep(&p, "/")) && *tok) {
/* last (basename) token? If so, add symlink here */
if (!p || !*p) {
ret = sysfs_create_link(&dir->kobj, target, tok);
break;
}
/* does the current dir contain an item named after tok ? */
ko = kset_find_obj(dir, tok);
if (ko) {
/* drop reference added by kset_find_obj */
kobject_put(ko);
/* ko MUST be a kset - we're about to use it as one ! */
if (ko->ktype != dir->kobj.ktype) {
ret = -EINVAL;
break;
}
/* descend into already existing subdirectory */
dir = to_kset(ko);
} else {
/* create new subdirectory kset */
subdir = kzalloc(sizeof(struct kset), GFP_KERNEL);
if (!subdir) {
ret = -ENOMEM;
break;
}
subdir->kobj.kset = dir;
subdir->kobj.ktype = dir->kobj.ktype;
ret = kobject_set_name(&subdir->kobj, "%s", tok);
if (ret) {
kfree(subdir);
break;
}
ret = kset_register(subdir);
if (ret) {
kfree(subdir);
break;
}
/* descend into newly created subdirectory */
dir = subdir;
}
}
/* we're done with cloned copy of name */
kfree(name_copy);
return ret;
}
/* recursively unregister fw_cfg/by_name/ kset directory tree */
static void fw_cfg_kset_unregister_recursive(struct kset *kset)
{
struct kobject *k, *next;
list_for_each_entry_safe(k, next, &kset->list, entry)
/* all set members are ksets too, but check just in case... */
if (k->ktype == kset->kobj.ktype)
fw_cfg_kset_unregister_recursive(to_kset(k));
/* symlinks are cleanly and automatically removed with the directory */
kset_unregister(kset);
}
/* kobjects & kset representing top-level, by_key, and by_name folders */
static struct kobject *fw_cfg_top_ko;
static struct kobject *fw_cfg_sel_ko;
static struct kset *fw_cfg_fname_kset;
/* register an individual fw_cfg file */
static int fw_cfg_register_file(const struct fw_cfg_file *f)
{
int err;
struct fw_cfg_sysfs_entry *entry;
/* allocate new entry */
entry = kzalloc(sizeof(*entry), GFP_KERNEL);
if (!entry)
return -ENOMEM;
/* set file entry information */
memcpy(&entry->f, f, sizeof(struct fw_cfg_file));
/* register entry under "/sys/firmware/qemu_fw_cfg/by_key/" */
err = kobject_init_and_add(&entry->kobj, &fw_cfg_sysfs_entry_ktype,
fw_cfg_sel_ko, "%d", entry->f.select);
if (err)
goto err_register;
/* add raw binary content access */
err = sysfs_create_bin_file(&entry->kobj, &fw_cfg_sysfs_attr_raw);
if (err)
goto err_add_raw;
/* try adding "/sys/firmware/qemu_fw_cfg/by_name/" symlink */
fw_cfg_build_symlink(fw_cfg_fname_kset, &entry->kobj, entry->f.name);
/* success, add entry to global cache */
fw_cfg_sysfs_cache_enlist(entry);
return 0;
err_add_raw:
kobject_del(&entry->kobj);
err_register:
kfree(entry);
return err;
}
/* iterate over all fw_cfg directory entries, registering each one */
static int fw_cfg_register_dir_entries(void)
{
int ret = 0;
u32 count, i;
struct fw_cfg_file *dir;
size_t dir_size;
fw_cfg_read_blob(FW_CFG_FILE_DIR, &count, 0, sizeof(count));
count = be32_to_cpu(count);
dir_size = count * sizeof(struct fw_cfg_file);
dir = kmalloc(dir_size, GFP_KERNEL);
if (!dir)
return -ENOMEM;
fw_cfg_read_blob(FW_CFG_FILE_DIR, dir, sizeof(count), dir_size);
for (i = 0; i < count; i++) {
dir[i].size = be32_to_cpu(dir[i].size);
dir[i].select = be16_to_cpu(dir[i].select);
ret = fw_cfg_register_file(&dir[i]);
if (ret)
break;
}
kfree(dir);
return ret;
}
/* unregister top-level or by_key folder */
static inline void fw_cfg_kobj_cleanup(struct kobject *kobj)
{
kobject_del(kobj);
kobject_put(kobj);
}
static int fw_cfg_sysfs_probe(struct platform_device *pdev)
{
int err;
/* NOTE: If we supported multiple fw_cfg devices, we'd first create
* a subdirectory named after e.g. pdev->id, then hang per-device
* by_key (and by_name) subdirectories underneath it. However, only
* one fw_cfg device exist system-wide, so if one was already found
* earlier, we might as well stop here.
*/
if (fw_cfg_sel_ko)
return -EBUSY;
/* create by_key and by_name subdirs of /sys/firmware/qemu_fw_cfg/ */
err = -ENOMEM;
fw_cfg_sel_ko = kobject_create_and_add("by_key", fw_cfg_top_ko);
if (!fw_cfg_sel_ko)
goto err_sel;
fw_cfg_fname_kset = kset_create_and_add("by_name", NULL, fw_cfg_top_ko);
if (!fw_cfg_fname_kset)
goto err_name;
/* initialize fw_cfg device i/o from platform data */
err = fw_cfg_do_platform_probe(pdev);
if (err)
goto err_probe;
/* get revision number, add matching top-level attribute */
fw_cfg_read_blob(FW_CFG_ID, &fw_cfg_rev, 0, sizeof(fw_cfg_rev));
fw_cfg_rev = le32_to_cpu(fw_cfg_rev);
err = sysfs_create_file(fw_cfg_top_ko, &fw_cfg_rev_attr.attr);
if (err)
goto err_rev;
/* process fw_cfg file directory entry, registering each file */
err = fw_cfg_register_dir_entries();
if (err)
goto err_dir;
/* success */
pr_debug("fw_cfg: loaded.\n");
return 0;
err_dir:
fw_cfg_sysfs_cache_cleanup();
sysfs_remove_file(fw_cfg_top_ko, &fw_cfg_rev_attr.attr);
err_rev:
fw_cfg_io_cleanup();
err_probe:
fw_cfg_kset_unregister_recursive(fw_cfg_fname_kset);
err_name:
fw_cfg_kobj_cleanup(fw_cfg_sel_ko);
err_sel:
return err;
}
static int fw_cfg_sysfs_remove(struct platform_device *pdev)
{
pr_debug("fw_cfg: unloading.\n");
fw_cfg_sysfs_cache_cleanup();
fw_cfg_kset_unregister_recursive(fw_cfg_fname_kset);
fw_cfg_kobj_cleanup(fw_cfg_sel_ko);
fw_cfg_io_cleanup();
return 0;
}
static const struct of_device_id fw_cfg_sysfs_mmio_match[] = {
{ .compatible = "qemu,fw-cfg-mmio", },
{},
};
MODULE_DEVICE_TABLE(of, fw_cfg_sysfs_mmio_match);
#ifdef CONFIG_ACPI
static const struct acpi_device_id fw_cfg_sysfs_acpi_match[] = {
{ "QEMU0002", },
{},
};
MODULE_DEVICE_TABLE(acpi, fw_cfg_sysfs_acpi_match);
#endif
static struct platform_driver fw_cfg_sysfs_driver = {
.probe = fw_cfg_sysfs_probe,
.remove = fw_cfg_sysfs_remove,
.driver = {
.name = "fw_cfg",
.of_match_table = fw_cfg_sysfs_mmio_match,
.acpi_match_table = ACPI_PTR(fw_cfg_sysfs_acpi_match),
},
};
#ifdef CONFIG_FW_CFG_SYSFS_CMDLINE
static struct platform_device *fw_cfg_cmdline_dev;
/* this probably belongs in e.g. include/linux/types.h,
* but right now we are the only ones doing it...
*/
#ifdef CONFIG_PHYS_ADDR_T_64BIT
#define __PHYS_ADDR_PREFIX "ll"
#else
#define __PHYS_ADDR_PREFIX ""
#endif
/* use special scanf/printf modifier for phys_addr_t, resource_size_t */
#define PH_ADDR_SCAN_FMT "@%" __PHYS_ADDR_PREFIX "i%n" \
":%" __PHYS_ADDR_PREFIX "i" \
":%" __PHYS_ADDR_PREFIX "i%n"
#define PH_ADDR_PR_1_FMT "0x%" __PHYS_ADDR_PREFIX "x@" \
"0x%" __PHYS_ADDR_PREFIX "x"
#define PH_ADDR_PR_3_FMT PH_ADDR_PR_1_FMT \
":%" __PHYS_ADDR_PREFIX "u" \
":%" __PHYS_ADDR_PREFIX "u"
static int fw_cfg_cmdline_set(const char *arg, const struct kernel_param *kp)
{
struct resource res[3] = {};
char *str;
phys_addr_t base;
resource_size_t size, ctrl_off, data_off;
int processed, consumed = 0;
/* only one fw_cfg device can exist system-wide, so if one
* was processed on the command line already, we might as
* well stop here.
*/
if (fw_cfg_cmdline_dev) {
/* avoid leaking previously registered device */
platform_device_unregister(fw_cfg_cmdline_dev);
return -EINVAL;
}
/* consume "<size>" portion of command line argument */
size = memparse(arg, &str);
/* get "@<base>[:<ctrl_off>:<data_off>]" chunks */
processed = sscanf(str, PH_ADDR_SCAN_FMT,
&base, &consumed,
&ctrl_off, &data_off, &consumed);
/* sscanf() must process precisely 1 or 3 chunks:
* <base> is mandatory, optionally followed by <ctrl_off>
* and <data_off>;
* there must be no extra characters after the last chunk,
* so str[consumed] must be '\0'.
*/
if (str[consumed] ||
(processed != 1 && processed != 3))
return -EINVAL;
res[0].start = base;
res[0].end = base + size - 1;
res[0].flags = !strcmp(kp->name, "mmio") ? IORESOURCE_MEM :
IORESOURCE_IO;
/* insert register offsets, if provided */
if (processed > 1) {
res[1].name = "ctrl";
res[1].start = ctrl_off;
res[1].flags = IORESOURCE_REG;
res[2].name = "data";
res[2].start = data_off;
res[2].flags = IORESOURCE_REG;
}
/* "processed" happens to nicely match the number of resources
* we need to pass in to this platform device.
*/
fw_cfg_cmdline_dev = platform_device_register_simple("fw_cfg",
PLATFORM_DEVID_NONE, res, processed);
if (IS_ERR(fw_cfg_cmdline_dev))
return PTR_ERR(fw_cfg_cmdline_dev);
return 0;
}
static int fw_cfg_cmdline_get(char *buf, const struct kernel_param *kp)
{
/* stay silent if device was not configured via the command
* line, or if the parameter name (ioport/mmio) doesn't match
* the device setting
*/
if (!fw_cfg_cmdline_dev ||
(!strcmp(kp->name, "mmio") ^
(fw_cfg_cmdline_dev->resource[0].flags == IORESOURCE_MEM)))
return 0;
switch (fw_cfg_cmdline_dev->num_resources) {
case 1:
return snprintf(buf, PAGE_SIZE, PH_ADDR_PR_1_FMT,
resource_size(&fw_cfg_cmdline_dev->resource[0]),
fw_cfg_cmdline_dev->resource[0].start);
case 3:
return snprintf(buf, PAGE_SIZE, PH_ADDR_PR_3_FMT,
resource_size(&fw_cfg_cmdline_dev->resource[0]),
fw_cfg_cmdline_dev->resource[0].start,
fw_cfg_cmdline_dev->resource[1].start,
fw_cfg_cmdline_dev->resource[2].start);
}
/* Should never get here */
WARN(1, "Unexpected number of resources: %d\n",
fw_cfg_cmdline_dev->num_resources);
return 0;
}
static const struct kernel_param_ops fw_cfg_cmdline_param_ops = {
.set = fw_cfg_cmdline_set,
.get = fw_cfg_cmdline_get,
};
device_param_cb(ioport, &fw_cfg_cmdline_param_ops, NULL, S_IRUSR);
device_param_cb(mmio, &fw_cfg_cmdline_param_ops, NULL, S_IRUSR);
#endif /* CONFIG_FW_CFG_SYSFS_CMDLINE */
static int __init fw_cfg_sysfs_init(void)
{
int ret;
/* create /sys/firmware/qemu_fw_cfg/ top level directory */
fw_cfg_top_ko = kobject_create_and_add("qemu_fw_cfg", firmware_kobj);
if (!fw_cfg_top_ko)
return -ENOMEM;
ret = platform_driver_register(&fw_cfg_sysfs_driver);
if (ret)
fw_cfg_kobj_cleanup(fw_cfg_top_ko);
return ret;
}
static void __exit fw_cfg_sysfs_exit(void)
{
platform_driver_unregister(&fw_cfg_sysfs_driver);
#ifdef CONFIG_FW_CFG_SYSFS_CMDLINE
platform_device_unregister(fw_cfg_cmdline_dev);
#endif
/* clean up /sys/firmware/qemu_fw_cfg/ */
fw_cfg_kobj_cleanup(fw_cfg_top_ko);
}
module_init(fw_cfg_sysfs_init);
module_exit(fw_cfg_sysfs_exit);
|
/*
Copyright 2015 The Kubernetes Authors.
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 testapi
import (
"encoding/json"
"reflect"
"testing"
metav1 "k8s.io/kubernetes/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/runtime"
)
// TODO these tests don't add much value for testing things that have groups
func TestResourcePathWithPrefix(t *testing.T) {
testCases := []struct {
prefix string
resource string
namespace string
name string
expected string
}{
{"prefix", "resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/prefix/namespaces/mynamespace/resource/myresource"},
{"prefix", "resource", "", "myresource", "/api/" + Default.GroupVersion().Version + "/prefix/resource/myresource"},
{"prefix", "resource", "mynamespace", "", "/api/" + Default.GroupVersion().Version + "/prefix/namespaces/mynamespace/resource"},
{"prefix", "resource", "", "", "/api/" + Default.GroupVersion().Version + "/prefix/resource"},
{"", "resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource/myresource"},
}
for _, item := range testCases {
if actual := Default.ResourcePathWithPrefix(item.prefix, item.resource, item.namespace, item.name); actual != item.expected {
t.Errorf("Expected: %s, got: %s for prefix: %s, resource: %s, namespace: %s and name: %s", item.expected, actual, item.prefix, item.resource, item.namespace, item.name)
}
}
}
func TestResourcePath(t *testing.T) {
testCases := []struct {
resource string
namespace string
name string
expected string
}{
{"resource", "mynamespace", "myresource", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource/myresource"},
{"resource", "", "myresource", "/api/" + Default.GroupVersion().Version + "/resource/myresource"},
{"resource", "mynamespace", "", "/api/" + Default.GroupVersion().Version + "/namespaces/mynamespace/resource"},
{"resource", "", "", "/api/" + Default.GroupVersion().Version + "/resource"},
}
for _, item := range testCases {
if actual := Default.ResourcePath(item.resource, item.namespace, item.name); actual != item.expected {
t.Errorf("Expected: %s, got: %s for resource: %s, namespace: %s and name: %s", item.expected, actual, item.resource, item.namespace, item.name)
}
}
}
var status = &metav1.Status{
Status: metav1.StatusFailure,
Code: 200,
Reason: metav1.StatusReasonUnknown,
Message: "",
}
func TestV1EncodeDecodeStatus(t *testing.T) {
v1Codec := Default.Codec()
encoded, err := runtime.Encode(v1Codec, status)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
typeMeta := metav1.TypeMeta{}
if err := json.Unmarshal(encoded, &typeMeta); err != nil {
t.Errorf("unexpected error: %v", err)
}
if typeMeta.Kind != "Status" {
t.Errorf("Kind is not set to \"Status\". Got %v", string(encoded))
}
if typeMeta.APIVersion != "v1" {
t.Errorf("APIVersion is not set to \"v1\". Got %v", string(encoded))
}
decoded, err := runtime.Decode(v1Codec, encoded)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(status, decoded) {
t.Errorf("expected: %#v, got: %#v", status, decoded)
}
}
func testEncodeDecodeStatus(t *testing.T, codec runtime.Codec) {
encoded, err := runtime.Encode(codec, status)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
typeMeta := metav1.TypeMeta{}
if err := json.Unmarshal(encoded, &typeMeta); err != nil {
t.Errorf("unexpected error: %v", err)
}
if typeMeta.Kind != "Status" {
t.Errorf("Kind is not set to \"Status\". Got %s", encoded)
}
if typeMeta.APIVersion != "v1" {
t.Errorf("APIVersion is not set to \"\". Got %s", encoded)
}
decoded, err := runtime.Decode(codec, encoded)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(status, decoded) {
t.Errorf("expected: %v, got: %v", status, decoded)
}
}
func TestAutoscalingEncodeDecodeStatus(t *testing.T) {
testEncodeDecodeStatus(t, Autoscaling.Codec())
}
func TestBatchEncodeDecodeStatus(t *testing.T) {
testEncodeDecodeStatus(t, Batch.Codec())
}
func TestExperimentalEncodeDecodeStatus(t *testing.T) {
testEncodeDecodeStatus(t, Extensions.Codec())
}
|
Software Assembly for Real Time Applications Based on a Distributed Shared Memory Model Development time and cost of real-time applications can be significantly reduced by reusing software from previous applications. With todays systems, however, even if some software is reused, a large amount of new code is still required to create the glue which integrates modules created by programmers at different sites. A new software engineering paradigm, called software assembly, is the process of developing an application simply by combining software modules from distributed libraries, without the need to write nor automatically generate any glue code. In this paper, the underlying framework to support software assembly of real-time applications is presented. The primary contribution is the notion of port-based objects, which combine object-based design with the port-automaton theory, in order to model and develop reconfigurable software modules. The integration of these modules in a distributed shared memory environment is possible through the use of a global state variable communication mechanism. Support for the framework has been implemented as part of the Chimera Real-Time Operating System. We have also designed a hypermedia user interface called Onika which allows real-time applications to be assembled graphically. |
Advertisement
Last week, the London Stock Exchange experienced an embarrassing outage involving its new trading system that lasted four hours and left many traders angry.
Now there is word that the Australian Securities Exchange's (ASX) new trading platform had to be shut down at 1448 local time Monday because of the inability to send trade "confirmation messages" to about 20% of the market, the Herald Sun reported. The problem first arose about 30 minutes before ASX officials decided a fix wasn't forthcoming and the exchange had to be completely shut down. The ASX normally closes at 1600.
According to this story at the Sydney Morning Herald, an exchange official said they did not yet know if it was a hardware or software issue that was causing the problem. In addition, ASX did not know if the problem would be fixed in time for Tuesday morning trading, although all trades made before the stoppage on Monday would be honored.
The Herald reported that the closure, given past average trading volumes, meant about A$1.5 billion in trading was likely lost, as well.
The ASX adopted the Nasdaq Genium INET trading platform (see PDF here) last November. At least the ASX was able to operate a few months with their new trading system before having a problem, unlike the LSE.
Speaking of the LSE, there is a report today that the LSE has inadvertently hosted a virus-infected advert on its web site.
When it rains, it pours. |
<filename>src/jwt.strategy.ts<gh_stars>1-10
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { Strategy, StrategyOptions } from 'passport-jwt';
import { UnauthorizedError } from './errors/UnauthorizedError';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(configService: ConfigService) {
super({
ignoreExpiration: false,
secretOrKey: configService.get('JWT_SECRET'),
jwtFromRequest: (request: Request) => {
let data = request?.cookies?.['access_token'];
if (!data) {
return null;
}
return data;
},
} as StrategyOptions);
}
async validate(payload: any) {
if (payload === null) {
throw new UnauthorizedError('Payload not found');
}
return payload;
}
}
|
Residential characteristics aggravating infestation by Culex quinquefasciatus in a region of Northeastern Brazil. OBJECTIVE Analyse how basic sanitation conditions, water supply and housing conditions affect the concentration of Culex quinquefasciatus METHODS Populations of C. quinquefasciatus in 61 houses in the municipality of Olinda, PE, were monitored between October 2009 and October 2010. Observations were carried out in homes without the presence of preferred breeding sites in order to identify characteristics that may be aggravating factors for the development of the mosquito. Five aggravating factors were analysed: vegetation cover surrounding the home, number of residents/home, water storage, sewage drainage and water drainage. These characteristics were analysed in terms of presence or absence and as indicators of the degree of infestation, which was estimated through monitoring the concentration of eggs (oviposition traps - BR-OVT) and adults (CDC light traps). RESULTS Sewage drainage to a rudimentary septic tank or to the open air was the most frequent aggravating factor in the homes (91.8%), although the presence of vegetation was the only characteristic that significantly influenced the increase in the number of egg rafts (p = 0.02). The BR-OVT achieved positive results in 95.1% of the evaluations, with the presence of at least one egg raft per month. A total of 2,366 adults were caught, with a mosquito/room/night ratio of 32.9. No significant difference was found in the number of mosquitoes caught in the homes. CONCLUSIONS Although the sanitation and water supply influence the population density of C. quinquefasciatus, residence features that are not usually considered in control measures can be aggravating factors in sustaining the mosquito population. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.