content
stringlengths 10
4.9M
|
---|
/*
* The MIT License
*
* Copyright 2010 Sony Ericsson Mobile Communications. All rights reserved.
* Copyright 2013 Sony Mobile Communications AB. All rights reserved.
*
* 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 com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data;
import static com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer.ANY_SERVER;
import hudson.Extension;
import hudson.RelativePath;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.util.ComboBoxModel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import com.sonyericsson.hudson.plugins.gerrit.trigger.GerritServer;
import com.sonyericsson.hudson.plugins.gerrit.trigger.PluginImpl;
/**
* Base settings for one matcher rule of a Gerrit project.
* @author Robert Sandell <[email protected]>
*/
public class GerritProject implements Describable<GerritProject> {
/** Magical file name which represents the commit message. */
private static final String MAGIC_FILE_NAME_COMMIT_MSG = "/COMMIT_MSG";
/** Magical file name which represents the merge list of a merge commit. */
private static final String MAGIC_FILE_NAME_MERGE_LIST = "/MERGE_LIST";
/** Magical file name which doesn't represent a file. Used specifically for patchset-level comments. */
private static final String MAGIC_FILE_NAME_PATCHSET_LEVEL = "/PATCHSET_LEVEL";
private CompareType compareType;
private String pattern;
private List<Branch> branches;
private List<FilePath> filePaths;
private List<Topic> topics;
private List<FilePath> forbiddenFilePaths;
private boolean disableStrictForbiddenFileVerification;
/**
* Default empty constructor.
*/
public GerritProject() {
}
/**
* DataBound Constructor.
* @param compareType the compareType
* @param pattern the project-name pattern
* @param branches the branch-rules
* @param topics the topic-rules
* @param filePaths the file-path rules.
* @param forbiddenFilePaths the forbidden file-path rules.
* @param disableStrictForbiddenFileVerification whether to be strict or not.
*/
@DataBoundConstructor
public GerritProject(
CompareType compareType,
String pattern,
List<Branch> branches,
List<Topic> topics,
List<FilePath> filePaths,
List<FilePath> forbiddenFilePaths,
boolean disableStrictForbiddenFileVerification) {
this.compareType = compareType;
this.pattern = pattern;
this.branches = branches;
this.topics = topics;
this.filePaths = filePaths;
this.forbiddenFilePaths = forbiddenFilePaths;
this.disableStrictForbiddenFileVerification = disableStrictForbiddenFileVerification;
}
/**
* Whether to disable strict verification of forbidden files.
* @return true if disabled.
*/
public boolean isDisableStrictForbiddenFileVerification() {
return disableStrictForbiddenFileVerification;
}
/**
* Set whether to disable strict verification of forbidden files.
* @param disableStrictForbiddenFileVerification true to disable.
*/
public void setDisableStrictForbiddenFileVerification(boolean disableStrictForbiddenFileVerification) {
this.disableStrictForbiddenFileVerification = disableStrictForbiddenFileVerification;
}
/**
* Which algorithm-type to use with the pattern.
* @return the compareType
*/
public CompareType getCompareType() {
return compareType;
}
/**
* Which algorithm-type to use with the pattern.
* @param compareType the compareType
*/
public void setCompareType(CompareType compareType) {
this.compareType = compareType;
}
/**
* The pattern for the project-name to match on.
* @return the pattern
*/
public String getPattern() {
return pattern;
}
/**
* The pattern for the project-name to match on.
* @param pattern the pattern
*/
public void setPattern(String pattern) {
this.pattern = pattern;
}
/**
* The list of branch-rules.
* @return the branch-rules
*/
public List<Branch> getBranches() {
return branches;
}
/**
* The list of branch-rules.
* @param branches the branch-rules
*/
public void setBranches(List<Branch> branches) {
this.branches = branches;
}
/**
* The list of filepath-rules.
* @return the filepath-rules
*/
public List<FilePath> getFilePaths() {
return filePaths;
}
/**
* The list of filepath-rules.
* @param filePaths the filepath-rules
*/
public void setFilePaths(List<FilePath> filePaths) {
this.filePaths = filePaths;
}
/**
* The list of topic-rules.
* @return the topic-rules
*/
public List<Topic> getTopics() {
return topics;
}
/**
* The list of topic-rules.
* @param topics the topic-rules
*/
public void setTopics(List<Topic> topics) {
this.topics = topics;
}
/**
* The list of the forbidden file-path rules.
* @return the forbidden file-path rules.
*/
public List<FilePath> getForbiddenFilePaths() {
return forbiddenFilePaths;
}
/**
* The list of the forbidden file-path rules.
* @param forbiddenFilePaths the forbidden file-path rules.
*/
public void setForbiddenFilePaths(List<FilePath> forbiddenFilePaths) {
this.forbiddenFilePaths = forbiddenFilePaths;
}
/**
* Compares the project, branch and files to see if the rules specified is a match.
* @param project the Gerrit project
* @param branch the branch.
* @param topic the topic.
* @param files a closure which returns the list of files in the change.
* @return true is the rules match.
*/
public boolean isInteresting(String project, String branch, String topic, Supplier<List<String>> files) {
if (isInteresting(project, branch, topic)) {
return isInterestingFile(files.get());
}
return false;
}
/**
* Compares the project and branch to see if the rules specified is a match.
* @param project the Gerrit project
* @param branch the branch.
* @param topic the topic.
* @return true is the rules match.
*/
public boolean isInteresting(String project, String branch, String topic) {
if (compareType.matches(pattern, project)) {
for (Branch b : branches) {
if (b.isInteresting(branch)) {
return isInterestingTopic(topic);
}
}
}
return false;
}
/**
* Compare topics to see if the rules specified is a match.
*
* @param topic the topic.
* @return true if the rules match or no rules.
*/
private boolean isInterestingTopic(String topic) {
if (topics != null && topics.size() > 0) {
for (Topic t : topics) {
if (t.isInteresting(topic)) {
return true;
}
}
return false;
}
return true;
}
/**
* Compare files to see if the rules specified is a match.
*
* @param files the files.
* @return true if the rules match or no rules.
*/
private boolean isInterestingFile(List<String> files) {
List<String> tmpFiles = new ArrayList<String>(files);
tmpFiles.remove(MAGIC_FILE_NAME_COMMIT_MSG);
tmpFiles.remove(MAGIC_FILE_NAME_MERGE_LIST);
tmpFiles.remove(MAGIC_FILE_NAME_PATCHSET_LEVEL);
boolean foundInterestingForbidden = false;
if (forbiddenFilePaths != null) {
Iterator<String> i = tmpFiles.iterator();
while (i.hasNext()) {
String file = i.next();
for (FilePath ffp : forbiddenFilePaths) {
if (ffp.isInteresting(file)) {
if (!disableStrictForbiddenFileVerification) {
return false;
} else {
foundInterestingForbidden = true;
i.remove();
break;
}
}
}
}
}
if (foundInterestingForbidden && tmpFiles.isEmpty()) {
// All changed files are forbidden, so this is not interesting
return false;
}
if (filePaths != null && filePaths.size() > 0) {
for (FilePath f : filePaths) {
if (f.isInteresting(tmpFiles)) {
return true;
}
}
return false;
}
return true;
}
@Override
public Descriptor<GerritProject> getDescriptor() {
return Jenkins.get().getDescriptor(getClass());
}
/**
* Descriptor allowing for communication within the Repeatable.
* Necessary for editable combobox.
*/
@Extension
public static final class DescriptorImpl extends Descriptor<GerritProject> {
/**
* Used to fill the project pattern combobox with AJAX.
* The filled values will depend on the server that the user has chosen from the dropdown.
*
* @param project the current project.
* @param serverName the name of the server that the user has chosen.
* @return ComboBoxModels containing a list of all Gerrit Projects found on that server.
*/
public ComboBoxModel doFillPatternItems(@AncestorInPath Item project, @QueryParameter("serverName")
@RelativePath("..") final String serverName) {
if (project == null) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
} else {
project.checkPermission(Item.CONFIGURE);
}
Collection<String> projects = new HashSet<String>();
if (serverName != null && !serverName.isEmpty()) {
if (ANY_SERVER.equals(serverName)) {
for (GerritServer server : PluginImpl.getServers_()) {
projects.addAll(server.getGerritProjects());
}
} else {
GerritServer server = PluginImpl.getServer_(serverName);
if (server != null) {
projects.addAll(server.getGerritProjects());
}
}
}
return new ComboBoxModel(projects);
}
@Override
public String getDisplayName() {
return "";
}
}
}
|
/**
* Configures the email sending layer using provided properties.
*
* @param properties properties containing email configuration.
* @return email configuration.
* @throws ConfigurationException if any property value was invalid.
*/
@Override
public MailConfiguration configure(final Properties properties)
throws ConfigurationException {
if (mConfiguration != null) {
return mConfiguration;
}
if (properties == null) {
mConfiguration = new MailConfigurationImpl();
} else {
mConfiguration = new MailConfigurationImpl(properties);
}
EmailSender.getInstance();
return mConfiguration;
} |
// Let's just say writing the template boilerplate gets real annoying
// after a while.
func renderTemplate(w http.ResponseWriter, filename string, data interface{}) {
templates = template.Must(template.ParseFiles(filename, mainlayout))
err := templates.ExecuteTemplate(w, "base", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} |
Energy dependence of bound-electron-positron pair production at very-high-energy ion-ion transits.
The problem of calculating the cross section for bound-electron\char21{}positron pair creation in very-high-energy heavy-ion colliders (100 GeV/u or higher, an effective \ensuremath{\gamma}\ensuremath{\gtrsim}2\ifmmode\times\else\texttimes\fi{}${10}^{4}$) is addressed. The multipole decomposition of the basic time-varying interaction is explicitly written in terms of simple and compact forms that display the energy (\ensuremath{\gamma}) dependence directly. Then, specific gauge transforms remove the \ensuremath{\gamma} dependence for smaller impact parameters, up to negligible terms of higher order in 1/\ensuremath{\gamma}. For larger impact parameters b, the interaction is shown to weaken as 1/b, where the known perturbative results apply. Only at small impact parameters are strong-coupling calculations necessary, but the gauge choices show that the contributions from these regions are \ensuremath{\gamma} independent. Putting these results together leads to a simple form for the cross section, A ln\ensuremath{\gamma}+B, where A and B are energy independent and A is known from the perturbative calculations. This form and its weak dependence on energy makes extrapolation from lower-energy results reliable and indicates the usefulness of a possible experiment at comparatively low energies (\ensuremath{\gamma}\ensuremath{\sim}200). |
def _upgrade_logging_config_section(config_dict: dict) -> dict:
latest = {}
for k, val in config_dict.items():
if isinstance(val, dict) and not val.get('type'):
key = k.replace('Handler', '').lower()
new_conf = {key: deepcopy(val)}
new_conf[key]['type'] = k
latest.update(new_conf)
else:
latest[k] = val
return latest |
class RealTimeVehicle:
""" A vehicle that's spawned on a server can have a corresponding real time vehicle object to track it.
:param Id: Refractor id of the vehicle.
:param position: Position of the vehicle as numpy array.
:param rotation: Rotation of the vehicle as numpy array.
:param velocity: Velocity of the vehicle.
:param acceleration: Acceleration of the vehicle.
:param is_fake: 1 if fake vehicle otherwise 0.
:param seats: A dictionary containing seat ids as keys and real time players as values if the seat
with id is occupied by real time player.
note:: Author(s): Mitch, henk """
def __init__(self, Id: int = None, position: array = None, rotation: array = None, velocity: float = None,
acceleration: float = None, is_fake: int = None, seats: dict = None):
self.Id = Id
self.position = position
self.rotation = rotation
self.velocity = velocity
self.acceleration = acceleration
self.is_fake = is_fake
if seats:
self.seats = seats
else:
self.seats = {}
@staticmethod
def typeHint():
return {
'Id': int,
'position': str,
'rotation': str,
'velocity': float,
'acceleration': float,
'is_fake': int
}
def toLocalDict(self):
""" Function for getting the real time vehicle object as a dictionary of strings representing attributes and the
values for the local bfa perspective so it can also be json serialised. (without seats)
:return: Real time vehicle as a dictionary.
note:: Author(s): Mitch """
return {
'Id': self.Id,
'position': "".join(array2string(self.position, separator='/')[1:-1].split()),
'rotation': "".join(array2string(self.rotation, separator='/')[1:-1].split()),
'velocity': self.velocity,
'acceleration': self.acceleration,
'is_fake': self.is_fake
} |
<reponame>denosawr/ucat-bot
// Require the necessary discord.js classes
import { Bot } from "./bot";
require("source-map-support").install();
import {
Client,
Intents,
Interaction,
BaseCommandInteraction,
} from "discord.js";
// import type { Interaction } from "discord.js";
// configure environment params
require("dotenv").config();
// this adds an object to process.env (ROLE_IDS). it's illegal, but it works.
// ROLE_IDS will be serialised
const bot = new Bot(process.env.DISCORD_TOKEN as string);
bot.listen();
|
Overview of Properties, Features and Developments of PM HIP 316L and 316LN
PM HIP 316L is an alloy that is of increased intere st for nuclear applications since its recent ASME code case approval. Over the years, com prehensive data and understanding of the properties and features have been collected and evaluated which will be summarized in this article. Since the early developments of the P M HIP technology it has been observed that PM HIP alloys generally exhibit higher yield streng ths compared to their conventional counterparts, a feature that applies well for 316L. In this article this is demonstrated, both by using the Hall-Petch relationship as well as Picker ing ́s and Irvine ́s empirically derived relationship between composition and grain size for austenitic stainless steels. Furthermore, a mechanism generating the increased yield strength i n PM HIP 316L vs conventionally manufactured 316L will be proposed. Results also sh ow t at low oxygen contents itself is not a guarantee for good or increased performance in fo rm of mechanical properties, but that there are other features that is of similar or perhaps ev en higher importance in order to achieve good properties. The results of this article includ e microstructural properties derived from EBSD measurements as well as tensile and impact pro perties in a wide range of test temperatures of PM HIP 316L from several powder bat ches manufactured at different locations and processed with various HIP and heat t r ment procedures. Finally, some results regarding creep properties of PM HIP 316L is presen ted. Introduction Austenitic stainless steel 316L is one of the most c mmonly known and used stainless steel grades and the performance and properties of this a lloy in different product forms is well known. Powder Metallurgical manufacturing via Gas A tomization and Hot Isostatic Pressing is a manufacturing technology known to generate iso tropic microstructures, high cleanliness and often improved mechanical properties. In light of he recent ASME code case approval for PM HIP 316L , the properties of this alloy v ia this manufacturing process has become of increasing interest . This article will giv e an overview of the properties of PM HIP 316L/316LN, how properties can be affected by varyi ng manufacturing process parameters and compare how they differ from the conventionally manufactured counterparts. Microstructure One of the large benefits with PM HIP manufacturing s that the microstructures of the manufactured components are homogeneous, isotropic and have high cleanliness. All these features apply also for PM HIP 316L/316LN and trans l tes into excellent ultrasonic inspectability . Regarding cleanliness, the clea r majority of the non-metallic inclusions found in PM HIP 316L/316LN are well below 2.8 μm in size and are predominately constituted by oxides . The oxides can origina te either from the melt which are later trapped within the powder particles (bulk oxides) o r fr m the surface oxide layer and oxide |
def _find_bad_frames(fnames, cutout_size=2048, corner_check=False):
quality = np.zeros(len(fnames), int)
warned = False
log.info("Extracting quality")
for idx, fname in enumerate(fnames):
try:
quality[idx] = fitsio.read_header(fname, 1)["DQUALITY"]
except KeyError:
if warned is False:
log.warning("Quality flags are missing.")
warned = True
continue
bad = (quality & (2048 | 175)) != 0
if warned | corner_check:
log.info("Using corner check")
corner = np.zeros((4, len(fnames)))
for tdx, fname in enumerate(fnames):
corner[0, tdx] = fitsio.read(fname)[:30, 45 : 45 + 30].mean()
corner[1, tdx] = fitsio.read(fname)[-30:, 45 : 45 + 30].mean()
corner[2, tdx] = fitsio.read(fname)[
:30, 45 + cutout_size - 30 : 45 + cutout_size
].mean()
corner[3, tdx] = fitsio.read(fname)[
-30:, 45 + cutout_size - 30 - 1 : 45 + cutout_size
].mean()
c = corner.T - np.median(corner, axis=1)
c /= np.std(c, axis=0)
bad = (np.abs(c) > 2).any(axis=1)
return bad, quality |
// doFold performs a "fold" by transposing any coordinates on the far side of it
func doFold(points []Point, fold Fold) []Point {
newPoints := make([]Point, 0)
for _, point := range points {
newPoint := point
if fold.dir == "y" && point.y > fold.line {
newPoint.y = fold.line - (point.y - fold.line)
} else if fold.dir == "x" && point.x > fold.line {
newPoint.x = fold.line - (point.x - fold.line)
}
if !containsPoint(newPoints, newPoint) {
newPoints = append(newPoints, newPoint)
}
}
return newPoints
} |
He arrested me, and while searching my bag found documents that bore my real name and date of birth but a made-up Social Security number. I needed these to apply for a third job — on top of the two, as a house cleaner and a janitor, I was already doing. I pleaded guilty to a third-degree misdemeanor for attempted possession of a forged instrument.
Advertisement Continue reading the main story
To many, this sounds like a serious charge, but what some might call criminal is a question of survival for most of the people who build your homes and keep them clean. You accept our labor but won’t provide the piece of paper that recognizes our equal humanity.
I decided not to hide my battle against deportation but to fight publicly to draw attention to the unfairness of the system. I wanted to inspire my community to step out of the shadows and raise its voices. In 2011, a judge denied my application for cancellation of removal, saying that my family’s suffering if I was deported would be neither extreme nor unusual. I appealed the ruling.
My three younger children, aged 6, 10 and 12, are all citizens (I also have an adult daughter who has Deferred Action for Childhood Arrivals status); my husband is a noncitizen. What would become of them if I was deported? What I see is that when my children are with me they feel safe, and their grades and self-esteem improve. But because of the fear of separation, they have also received treatment for depression and anxiety. There are millions of children like them in the United States.
While I was waiting for my appeal proceedings, in September 2012 I received news that my mother was gravely ill. After so many years, I had to say goodbye or something inside me would die. Leaving my children with their father, I made the journey to Mexico.
My mother died while I was on the plane. I made it just for her funeral. In April 2013, I returned to the United States, walking across mountains and desert until my feet were destroyed. I was detained by Border Patrol in Texas. While I was held there, I called my family and activist friends to tell them what had happened. Thanks to my community and my lawyer, I was released with a stay of removal and an order of supervision. That stay was renewed five times.
My sixth stay of removal expired this month. On Feb. 15, I had a check-in scheduled with I.C.E. officials. But, after seeing how, in Arizona, I.C.E. had arrested and immediately deported another mother the week before, I followed my intuition and sought sanctuary. When my lawyer and the pastor at the First Unitarian Church went to the appointment in my place, I.C.E. agents were waiting, ready to arrest me.
Sign Up for the Opinion Today Newsletter Every weekday, get thought-provoking commentary from Op-Ed columnists, the Times editorial board and contributing writers from around the world. Please verify you're not a robot by clicking the box. Invalid email address. Please re-enter. You must select a newsletter to subscribe to. Sign Up Receive occasional updates and special offers for The New York Times's products and services. Recaptcha requires verification I'm not a robot reCAPTCHA Privacy - Terms Thank you for subscribing. An error has occurred. Please try again later. You are already subscribed to this email. View all New York Times newsletters. See Sample
Manage Email Preferences
Not you?
Privacy Policy
Now that President Trump has unveiled his plan to criminalize us and make us live in fear, entire communities are under threat. My people here in Denver are keeping their heads held high. The nation saw this spirit in the Day Without Immigrants actions, and we have allies countrywide, in schools and faith communities, on farm fields and in restaurants. |
/**
Binary Trees With Factors
Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.
Example 1:
Input: arr = [2,4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
Input: arr = [2,4,5,10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].
Constraints:
1 <= arr.length <= 1000
2 <= arr[i] <= 109
*/
function numFactoredBinaryTrees(arr: number[]): number {
if (!arr || arr.length === 0) {
return 0;
}
const modulo = Math.pow(10, 9) + 7;
arr.sort((a, b) => a - b);
const map = new Map<number, number>();
let sum = 0;
arr.forEach((e, i) => {
let count = 1;
sum -= map.get(e) ?? 0;
for (let j = 0; j < i; j++) {
const e2 = arr[j];
const div = Math.floor(e / e2);
if (e % e2 === 0 && map.has(div)) {
count += map.get(e2) * map.get(div);
}
}
sum += count;
if (sum > modulo) {
sum %= modulo;
}
map.set(e, count);
});
return sum;
}
function numFactoredBinaryTrees_(arr: number[]): number {
const sets = new Set(arr);
const modulo = Math.pow(10, 9) + 7;
let count = 0;
arr.forEach((e) => {
arr.forEach((e2) => {
if (sets.has(e * e2)) {
count++;
if (count > modulo) {
count %= modulo;
}
}
});
});
return (count + sets.size) % modulo;
}
|
Just when we are getting used to the idea of having a mix of public and private schools in Australia, along comes a development with the potential to upset everything once again. Over the years our federal and state governments, apparently without comparing notes, have raised private school funding to the point where those schools can no longer be considered to be private.
How did this happen? Years ago we began to widen school choice by increasing public funding of private schools. We were told this would not only increase choice but the competition would also lift overall school achievement. Even better, it would be a good deal for taxpayers when families paid much of the schooling bill. Armed with the power of such promises both levels of government, especially the federal, rolled out the cash.
Commonwealth v states: Gonski schoolyard fight is just getting started | Gabrielle Chan Read more
Alas, these promises have amounted to very little. Choice widened, but has remained an illusion for most: only one in every two average families can afford a fee-charging school – and even then just for one child. As for the second promise, an overall lift in school achievement … you’d have to be brave to back that claim.
And now the third promise – that publicly subsidised private schools would actually save public funds – is under challenge. The public funding of private schools has risen to the level where the running costs of most private schools are now substantially met by combined state and federal funding. If a private school is defined by who pays then they are rapidly becoming public.
They still collect fees, a hangover from when they needed the money to match the investment in public schools. But for all but the wealthiest schools the fee income seems to be icing on the cake. When we realise that schools enrolling similar students churn out similar results, it becomes harder to justify the icing – especially when governments are such big partners.
Of course, from the federal minister down, the standard claim is that private schools get less than 60% of the public money going to public schools. True on average, but grossly misleading. Public schools are expensive. They alone have to be available to all students, from all families in all places and in all circumstances. Anyone who has visited a remote school, a disadvantaged school or a special school will know this is a very expensive obligation. My School data shows which students go to which schools. Comparing the sectors as if they were equally sharing the load is a nonsense.
We can now compare schools which enrol similar students and hence face similar needs and challenges – and how much they are paid each year to operate. The My School website shows that two-thirds of our schools lie in the 950-1150 index of community socio-educational advantage range. Ninety-three per cent of Catholic schools fall in this range and they receive not 60% but between 90.8% and 99.5% of the public dollars going to similar public schools. Seventy-nine per cent of independent schools fall in this range and they receive between 79.5% and 94.6% of what goes to similar public schools.
So should it matter that governments are now effectively paying for the running of public schools and the “private” competition? Leaving aside all the other oddities of doing this the problem is that each system has very different obligations, accountabilities and operational rules. Aside from fees, private schools can impose other criteria for admission or exclusion of students, on grounds that aren’t (and shouldn’t be) permitted in the government school system.
They can apply additional discriminators in the form of entry tests, previous school reports, test results and other restrictive (including religious) criteria. As a general rule, they also have a statutory exemption from a range of anti-discrimination provisions. They can hire and fire staff, and refuse admission to students on various grounds including sexual orientation, sex, age, marital or domestic status. They are not “government agencies” under freedom of information legislation.
If there’s a magic bullet to fix education outcomes, it starts with equity | Chris Bonnor and Bernie Shepherd Read more
In short, by getting the public funding and holding on to the privacy of their operation they have got the money and the box. As a consequence our playing field of schools has become very tilted: in the fair go country there is very little in our framework of schools that is fair.
Solutions to this seemingly intractable problem might range from abolishing all private schools through to integrating most of them into the state’s provision of education and having them operate under consistent rules – something that is standard practice overseas. Maybe an alternative might be to seek a stronger alignment between each school’s level of public funding and the “publicness” of their obligations and operation.
Whatever happens, the do nothing solution isn’t an option.
To read the full report by Chris Bonnor and Bernie Shepherd go here. |
package com.bootslee.leetcode;
import java.util.HashSet;
public class SingleNumber136 {
/**
* 给定一个非空整数数组,除了某个元素只出现一次以外,
* 其余每个元素均出现两次。找出那个只出现了一次的元素。
* @param nums
* @return
*/
public int singleNumber(int[] nums) {
int num = 0;
for(int i=0;i<nums.length;i++){
num=num^nums[i];
}
return num;
}
public int singleNumber2(int[] nums) {
HashSet<Integer> set=new HashSet<>();
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])){
set.remove(nums[i]);// 扔掉
}else {
set.add(nums[i]);
}
}
Integer[] ints=set.toArray(new Integer[0]);
return ints[0];
}
}
|
"""Helper function to setup the run from the command line.
Adapted from https://github.com/atomistic-machine-learning/schnetpack/blob/dev/src/schnetpack/utils/script_utils/setup.py
"""
import os
import logging
from shutil import rmtree
from nff.utils.tools import to_json, set_random_seed, read_from_json
__all__ = ["setup_run"]
def setup_run(args):
argparse_dict = vars(args)
jsonpath = os.path.join(args.model_path, "args.json")
# absolute paths
argparse_dict['data_path'] = os.path.abspath(argparse_dict['data_path'])
argparse_dict['model_path'] = os.path.abspath(argparse_dict['model_path'])
if args.mode == "train":
if args.overwrite and os.path.exists(args.model_path):
logging.info("existing model will be overwritten...")
rmtree(args.model_path)
if not os.path.exists(args.model_path):
os.makedirs(args.model_path)
to_json(jsonpath, argparse_dict)
set_random_seed(args.seed)
train_args = args
else:
train_args = read_from_json(jsonpath)
return train_args
|
#include<stdio.h>
#include<stdlib.h>
void Prime_Fact(unsigned int);
void Rec_Prime_Fact1(unsigned int);
void Rec_Prime_Fact2(unsigned int,unsigned int);
int main()
{
unsigned int Num;
//clrscr();
printf("Program to obtain the prime factors of the number\n");
printf("\nEnter a Positive No. : ");
scanf("%d",&Num);
Prime_Fact(Num);
printf("\nPrime factors of %d (using recursion method1) are: ",Num);
Rec_Prime_Fact1(Num);
printf("\nPrime factors of %d (using recursion method2) are: ",Num);
Rec_Prime_Fact2(Num,2);
}
void Prime_Fact(unsigned int N) // Normal Function
{
unsigned int i=2;
printf("\nPrime factors of %d are: ",N);
while(N>1)
{
while(N%i==0)
{
printf("%d ",i);
N=N/i;
}
i++;
}
}
/************************* Recursive Approach 1 *************************/
void Rec_Prime_Fact1(unsigned int N)
{
static unsigned int i = 2 ; // defined static so as to initialize only once
while(N%i==0)
{
printf("%d ",i);
N=N/i;
}
if(N>1)
{
i++;
Rec_Prime_Fact1(N); //recursion
}
}
/************************* Recursive Approach 2 *************************/
void Rec_Prime_Fact2(unsigned int N, unsigned int i)
{
if(N%i==0)
{
printf("%d ",i);
N=N/i;
if(N>1)
Rec_Prime_Fact2(N,i); //recursion
else
exit(1);
}
else
{
i++;
Rec_Prime_Fact2(N,i); //recursion
}
}
|
/**
* Methode steuert User-Eingabe und führt die entsprechenden Operationen aus.
* @param input die Eingabe
*/
private static void selectInput(int input) {
switch (input) {
case PUSH:
Student newStudi = null;
try {
newStudi = studentInput();
studentStack.push(newStudi);
} catch (IllegalArgumentException e) {
System.out.println("Angabe fehlerhaft!");
showMenu();
}
if (studentStack.peek() == newStudi && newStudi != null) {
System.out.println("Sie haben einen Studi" + " erfolgreich angelegt\n");
}
showMenu();
case PEEK:
try {
Student toShow = studentStack.peek();
System.out.println("Letzter Student\n" + toShow + "\n");
} catch (NullPointerException e) {
System.out.println(e.getMessage());
System.out.println("Diese Auswahl kann jetzt nicht ausgefuehrt werden."
+ "\nSie muessen mindestens einen Studenten anlegen.\n");
}
showMenu();
case POP:
try {
System.out.println("Student " + studentStack.peek() + " wurde aus der Database entfernt.\n");
studentStack.pop();
} catch (NullPointerException e) {
System.out.println(e.getMessage() + "\n");
}
showMenu();
case PRINT:
System.out.println("Database: ");
studentStack.print();
case PRINT_SIZE:
System.out.println("Database-Kapazitaet: " + studentStack.size());
showMenu();
case CLEAR:
studentStack.clear();
if (studentStack.isEmpty())
System.out.println("Database erfolgreich geloescht!\n");
showMenu();
case ADD_INDEX:
System.out.println("Bitte geben Sie einen gueltigen Index. Index soll zwischen 0 und " + (studentStack.size()-1) + " liegen");
Scanner sc = new Scanner(System.in);
int eingabe = sc.nextInt();
if(eingabe > 0 && eingabe <= studentStack.size()){
Student neu1 = studentInput();
boolean added = studentStack.addAtIndex(neu1, eingabe);
if(added) System.out.println("Student erfolgreich hinzugefuegt!");
} else {
System.out.println("Leider ist etwas schief gelaufen!");
}
showMenu();
case REMOVE_LAST:
Student last = studentStack.removeLast();
System.out.println("Sie haben folgenden Studenten erfolgreich entferntn: \n" + last);
showMenu();
case REMOVE_AT:
System.out.println("Bitte geben Sie einen gueltigen Index. Index soll zwischen 0 und " + (studentStack.size()-1) + " liegen");
Scanner sc1 = new Scanner(System.in);
int in1 = sc1.nextInt();
if(in1 >=0 && in1 <= studentStack.size()){
Student removed = new Student();
try{
removed = studentStack.removeAtIndex(in1);
System.out.println("Sie haben folgenden Studenten erfolgreich entfernt:\n " + removed);
} catch (NullPointerException e){
System.out.println(e.getMessage());
}
}
showMenu();
case EXIT:
System.exit(1);
break;
default:
System.out.println("Achtung! Auswahl nicht korrekt. " + "Versuchen Sie es nochmals");
showMenu();
}
} |
<gh_stars>100-1000
package com.github.tdurieux.repair.maven.plugin;
import fr.inria.astor.core.entities.ProgramVariant;
import fr.inria.main.evolution.AstorMain;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.model.Build;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@Mojo( name = "jGenProg", aggregator = true,
defaultPhase = LifecyclePhase.TEST,
requiresDependencyResolution = ResolutionScope.TEST)
public class GenProgMojo extends AbstractRepairMojo {
private static String HARDCODED_ASTOR_VERSION = "0.0.2-SNAPSHOT";
@Parameter( defaultValue = "${project.build.directory}/astor", property = "out", required = true )
private File outputDirectory;
@Parameter(property = "packageToInstrument")
private String packageToInstrument;
@Parameter(defaultValue = "local", property = "scope")
private String scope;
@Parameter( defaultValue = "0.1", property = "thfl")
private double localisationThreshold;
@Parameter( defaultValue = "10", property = "seed")
private int seed;
@Parameter( defaultValue = "200", property = "maxgen")
private int maxgen;
@Parameter( defaultValue = "100", property = "maxtime")
private int maxtime;
@Parameter( defaultValue = "true", property = "stopfirst")
private boolean stopfirst;
@Parameter( defaultValue = "false", property = "skipfaultlocalization")
private boolean skipfaultlocalization;
protected String mode = "statement";
private List<ProgramVariant> output;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
final List<URL> astorClasspath = getAstorClasspath();
final String systemClasspath = System.getProperty("java.class.path");
final String strClasspath = getStringClasspathFromList(astorClasspath, systemClasspath);
if (!outputDirectory.exists()) {
outputDirectory.mkdirs();
}
try {
setGzoltarDebug(true);
System.setProperty("java.class.path", strClasspath);
AstorMain astor = new AstorMain();
AstorContext context = createAstorContext();
astor.execute(context.getAstorArgs());
this.output = astor.getEngine().getSolutions();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.setProperty("java.class.path", systemClasspath);
}
}
private AstorContext createAstorContext() {
AstorContext context = new AstorContext();
context.out = outputDirectory.getAbsolutePath();
context.Package = packageToInstrument;
context.scope = scope;
context.flThreshold = localisationThreshold;
context.seed = seed;
context.maxGen = maxgen;
context.maxTime = maxtime;
context.location = project.getBasedir().getAbsolutePath();
context.stopFirst = stopfirst;
context.mode = mode;
context.javaComplianceLevel = getComplianceLevel();
context.skipfaultlocalization = skipfaultlocalization;
for (int i = 0; i < getFailingTests().size(); i++) {
String test = getFailingTests().get(i);
context.failing.add(test);
}
final List<URL> dependencies = getClasspath();
for (MavenProject mavenProject : reactorProjects) {
Build build = mavenProject.getBuild();
context.srcJavaFolder.add(getRelativePath(build.getSourceDirectory()));
context.srcTestFolder.add(getRelativePath(build.getTestSourceDirectory()));
context.binJavaFolder.add(getRelativePath(build.getOutputDirectory()));
context.binTestFolder.add(getRelativePath(build.getTestOutputDirectory()));
}
for (int i = 0; i < dependencies.size(); i++) {
URL url = dependencies.get(i);
String path = url.getPath();
if (context.binTestFolder.contains(getRelativePath(path))
|| context.binJavaFolder.contains(getRelativePath(path))) {
continue;
}
context.dependencies.add(path);
}
if (context.dependencies.isEmpty()) {
context.dependencies.add(dependencies.get(0).getPath());
}
return context;
}
private String getRelativePath(String path) {
if (path == null) {
return null;
}
if (!new File(path).exists()) {
return null;
}
path = path.replace(project.getBasedir().getAbsolutePath(), "");
if (!path.startsWith("/")) {
path = "/" + path;
}
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
return path;
}
private List<URL> getAstorClasspath() {
List<URL> classpath = new ArrayList<>();
Artifact artifactPom = artifactFactory.createArtifact("org.inria.sacha.automaticRepair","astor", HARDCODED_ASTOR_VERSION, null, "pom");
Artifact artifactJar = artifactFactory.createArtifact("org.inria.sacha.automaticRepair","astor", HARDCODED_ASTOR_VERSION, null, "jar");
File filePom = new File(localRepository.getBasedir() + "/" + localRepository.pathOf(artifactPom));
File fileJar = new File(localRepository.getBasedir() + "/" + localRepository.pathOf(artifactJar));
classpath.addAll(getClassPathFromPom(filePom, fileJar));
return classpath;
}
public List<ProgramVariant> getResult() {
return output;
}
}
|
/**
* Create a copy of the source table with the specified columns materialized.
*
* Other columns are passed through to the output without changes.
*
* @param source the input table
* @param columnNames the columns to materialize in the output
*
* @return a copy of the source table with materialized columns
*/
public static Table partialSparseSelect(Table source, String... columnNames) {
final Set<String> columnsToCopy = new HashSet<>(Arrays.asList(columnNames));
final String[] preserveColumns = source.getDefinition().getColumnStream().map(ColumnDefinition::getName)
.filter(x -> !columnsToCopy.contains(x)).toArray(String[]::new);
return sparseSelect((QueryTable) source.coalesce(), preserveColumns, columnNames);
} |
def find_first_match(search, source):
for i in range(len(source) - len(search)):
if source[i:(i + len(search))] == search:
return i
return -1 |
/**
* A method to strip out common packages and a few rare type prefixes from types' string
* representation before being used in error messages.
*
* <p>This type assumes a String value that is a valid fully qualified (and possibly
* parameterized) type, and should NOT be used with arbitrary text, especially prose error
* messages.
*
* <p>TODO(user): Tighten these to take type representations (mirrors and elements) to avoid
* accidental mis-use by running errors through this method.
*/
public static String stripCommonTypePrefixes(String type) {
Matcher matcher = COMMON_PACKAGE_PATTERN.matcher(type);
StringBuilder result = new StringBuilder();
int index = 0;
while (matcher.find()) {
result.append(type.subSequence(index, matcher.start(1)));
index = matcher.end(1);
}
result.append(type.subSequence(index, type.length()));
return result.toString();
} |
<reponame>gilsonsf/oauth-fiware<filename>oauth-manager/src/main/java/com/gsf/executor/api/service/ManagerService.java
package com.gsf.executor.api.service;
import com.gsf.executor.api.entity.UserTemplate;
import com.gsf.executor.api.enums.AttackTypes;
import com.gsf.executor.api.event.ClientCaptureEventObject;
import com.gsf.executor.api.event.ClientCaptureEventPublisher;
import com.gsf.executor.api.event.ClientEventObject;
import com.gsf.executor.api.event.ClientEventPublisher;
import com.gsf.executor.api.repository.UserTemplateMemoryRepository;
import com.gsf.executor.api.task.GenericTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import static com.gsf.executor.api.enums.AttackTypes.MIXUP;
import static com.gsf.executor.api.enums.AttackTypes.NONE;
@Service
public class ManagerService {
private Logger LOGGER = LoggerFactory.getLogger(ManagerService.class);
@Autowired
private ClientEventPublisher publisher;
@Autowired
private ClientCaptureEventPublisher clientCaptureEventPublisher;
@Autowired
@Qualifier("taskExecutor")
private Executor executor;
@Autowired
private OAuthTaskService oAuthTaskService;
@Async
public CompletableFuture<GenericTask> createTask(UserTemplate user, AttackTypes attackType) {
LOGGER.info("attackType " + attackType);
GenericTask genericTask = createGenericTask(user, attackType);
return CompletableFuture.completedFuture(genericTask);
}
public void createTaskSync(UserTemplate user, AttackTypes attackType) {
LOGGER.info("attackType " + attackType);
UserTemplate userTemplate = UserTemplateMemoryRepository.copyValues(user);
if (attackType == MIXUP) {
userTemplate.setAs(user.getAs()+"_mixup");
}
createGenericTask(userTemplate, attackType);
}
private GenericTask createGenericTask(UserTemplate user, AttackTypes attackType) {
if (attackType == NONE) {
return oAuthTaskService.getOAuthHonestClientTask(user);
}
GenericTask task = null;
switch (attackType) {
case MIXUP:
task = oAuthTaskService.getOAuthMixUpAttackTask(user);
break;
case CSRF:
task = oAuthTaskService.getOAuthCSRFAttackTask(user);
break;
default:
task = oAuthTaskService.getOAuthHonestClientTask(user);
}
return task;
}
public void startProcess(int minutes) {
List<UserTemplate> clients = new ArrayList<>();
UserTemplateMemoryRepository.getAll().forEach( u -> {
if(u.getAs().equalsIgnoreCase("dummy")
|| u.getAs().equalsIgnoreCase("keyrock")) {
clients.add(u);
}
});
ClientEventObject eventObject = new ClientEventObject(clients, minutes);
publisher.publishCustomEvent(eventObject);
clientCaptureEventPublisher.publishCustomEvent(new ClientCaptureEventObject(minutes));
}
public boolean hasExecution() {
ThreadPoolTaskExecutor ex = (ThreadPoolTaskExecutor)executor;
return ex.getActiveCount() > 0;
}
}
|
Customer Experience: Extracting Topics From Tweets
The ubiquity of social media platforms facilitates free flow of online chatter related to customer experience. Twitter is a prominent social media platform for sharing experiences, and e-retail firms are rapidly emerging as the preferred shopping destination. This study explores customers’ online shopping experience tweets. Customers tweet about their online shopping experience based on moments of truth shaped by encounters across different touchpoints. We aggregate 25,173 such tweets related to six e-retailers tweeted over a 5-year period. Grounded on agency theory, we extract the topics underlying these customer experience tweets using unsupervised latent Dirichlet allocation. The output reveals five topics which manifest into customer experience tweets related to online shopping—ordering, customer service interaction, entertainment, service outcome failure, and service process failure. Topics extracted are validated through inter-rater agreement with human experts. The study, thus, derives topics from tweets about e-retail customer experience and thereby facilitates prioritization of decision-making pertaining to critical service encounter touchpoints. |
<reponame>dlecocq/nsq-py<gh_stars>10-100
'''Base socket wrapper'''
class SocketWrapper(object):
'''Wraps a socket in another layer'''
# Methods for which we the default should be to simply pass through to the
# underlying socket
METHODS = (
'accept', 'bind', 'close', 'connect', 'fileno', 'getpeername',
'getsockname', 'getsockopt', 'setsockopt', 'gettimeout', 'settimeout',
'setblocking', 'listen', 'makefile', 'shutdown'
)
@classmethod
def wrap_socket(cls, socket, **options):
'''Returns a socket-like object that transparently does compression'''
return cls(socket, **options)
def __init__(self, socket):
self._socket = socket
for method in self.METHODS:
# Check to see if this class overrides this method, and if not, then
# we should have it simply map through to the underlying socket
if not hasattr(self, method):
setattr(self, method, getattr(self._socket, method))
def send(self, data, flags=0):
'''Same as socket.send'''
raise NotImplementedError()
def sendall(self, data, flags=0):
'''Same as socket.sendall'''
count = len(data)
while count:
sent = self.send(data, flags)
# This could probably be a buffer object
data = data[sent:]
count -= sent
def recv(self, nbytes, flags=0):
'''Same as socket.recv'''
raise NotImplementedError()
def recv_into(self, buff, nbytes, flags=0):
'''Same as socket.recv_into'''
raise NotImplementedError('Wrapped sockets do not implement recv_into')
|
/// map a scalar into some other item.
pub fn map<F, U>(self, f: F) -> Field<U> where F: FnOnce(T) -> U {
match self {
Field::Scalar(x) => Field::Scalar(f(x)),
Field::BackReference(req, idx) => Field::BackReference(req, idx),
}
} |
<reponame>BearerPipelineTest/m3
// Copyright (c) 2017 Uber Technologies, Inc.
//
// 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 integration
import (
"testing"
"github.com/stretchr/testify/require"
clientv3 "go.etcd.io/etcd/client/v3"
"go.etcd.io/etcd/tests/v3/framework/integration"
"github.com/m3db/m3/src/cluster/services"
"github.com/m3db/m3/src/cluster/services/leader"
)
var (
testClusterSize = 1
testEnvironment = "testEnv"
testServiceName = "testSvc"
testZone = "testZone"
testElectionTTLSecs = 5
)
type testCluster struct {
t *testing.T
cluster *integration.Cluster
}
func newTestCluster(t *testing.T) *testCluster {
integration.BeforeTestExternal(t)
return &testCluster{
t: t,
cluster: integration.NewCluster(t, &integration.ClusterConfig{
Size: testClusterSize,
}),
}
}
func (tc *testCluster) LeaderService() services.LeaderService {
svc, err := leader.NewService(tc.etcdClient(), tc.options())
require.NoError(tc.t, err)
return svc
}
func (tc *testCluster) Close() {
tc.cluster.Terminate(tc.t)
}
func (tc *testCluster) etcdClient() *clientv3.Client {
return tc.cluster.RandClient()
}
func (tc *testCluster) options() leader.Options {
sid := services.NewServiceID().
SetEnvironment(testEnvironment).
SetName(testServiceName).
SetZone(testZone)
eopts := services.NewElectionOptions().
SetTTLSecs(testElectionTTLSecs)
return leader.NewOptions().
SetServiceID(sid).
SetElectionOpts(eopts)
}
|
New Bio-Marker Gene Discovery Algorithms for Cancer Gene Expression Profile
Several hybrid gene selection algorithms for cancer classification that employ bio-inspired evolutionary wrapper algorithm have been proposed in the literature and show good classification accuracy. In our recent previous work, we proposed a new wrapper gene selection method based-on firefly algorithm named FF-SVM. In this work, we will improve the classification performance of FF-SVM algorithm by proposed a new hybrid gene selection algorithm. Our new biomarker gene discovery algorithm for microarray cancer gene expression analysis that integrates f-score filter method with Firefly feature selection method alongside with SVM classifier named FFF-SVM is proposed. The classification accuracy for the selected gene subset is measured by support vector machine SVM classifier with leave-one-out cross validation LOOCV. The evaluation of the FFF-SVM algorithm done by using five benchmark microarray datasets of binary and multi class. To show result validation of the proposed we compare it with other related state-of-the-art algorithms. The experiment proves that the FFF-SVM outperform other hybrid algorithm in terms of high classification accuracy and low number of selected genes. In addition, we compare the proposed algorithm with previously proposed wrapper-based gene selection algorithm FF-SVM. The result show that the hybrid-based algorithm shoe higher performance than wrapper based. The proposed algorithm is an improvement of our previous proposed algorithm. |
/**
* Invokes a rollback on the connection if auto-commit is turned off
*/
public static void rollback(Connection conn)
throws SQLException
{
if (conn != null && !conn.isClosed())
{
if (!conn.getAutoCommit())
conn.rollback();
}
else
{
LOG.error("Invoking a rollback after the connection is closed ");
}
} |
Two-order-parameter phenomenological theory of the phase diagram of liquid helium.
A two order-parameter phenomenological theory is proposed to explain some essential features of the phase diagram of liquid {sup 4}He. Among other things, the theory (i) distinguishes the liquid phase from the gas phase in the {ital P}-{ital T} plane, (ii) yields a {lambda} line in the liquid phase with a negative slope, and (iii) gives a coexistence line between an ordered liquid phase and a normal gas phase which is a continuation below {ital T}{sub {lambda}} of the normal liquid-gas coexistence line but with a smaller curvature. These results are in general agreement with the experimental situation in liquid {sup 4}He. The coupled nonlinear equations of the theory are also solved numerically to gauge the accuracy of analytical results. {copyright} {ital 1996 The American Physical Society.} |
// GetPostByID : gets post by postid
func GetPostByID(postid string) (Post, error) {
var err error
result := Post{}
if database.CheckConnection() {
session := database.Mongo.Copy()
defer session.Close()
c := session.DB(database.ReadConfig().Database).C("post")
if bson.IsObjectIdHex(postid) {
err = c.FindId(bson.ObjectIdHex(postid)).One(&result)
} else {
err = ErrNoResult
}
} else {
err = ErrUnavailable
}
return result, standardizeError(err)
} |
<reponame>jonrzhang/MegEngine<gh_stars>1-10
/**
* \file dnn/src/fallback/batched_matrix_mul/opr_impl.cpp
* MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
*
* Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
#include "./opr_impl.h"
#include "src/naive/handle.h"
using namespace megdnn;
using namespace fallback;
BatchedMatrixMulImpl::BatchedMatrixMulImpl(Handle *handle):
BatchedMatrixMulForwardImpl(handle),
m_storage(new CpuOprDelegationStorage<>),
m_opr(m_storage->get<MatrixMul>())
{
}
size_t BatchedMatrixMulImpl::get_workspace_in_bytes(
const TensorLayout &A, const TensorLayout &B,
const TensorLayout &C) {
auto A_ = A.remove_axis(0), B_ = B.remove_axis(0), C_ = C.remove_axis(0);
m_opr->param() = param();
return m_opr->get_workspace_in_bytes(A_, B_, C_);
}
void BatchedMatrixMulImpl::exec(_megdnn_tensor_in A,
_megdnn_tensor_in B,
_megdnn_tensor_out C,
_megdnn_workspace workspace) {
check_exec(A.layout, B.layout, C.layout, workspace.size);
m_opr->param() = this->param();
auto kern = [this, A, B, C, workspace]() {
auto N = A.layout.shape[0];
TensorND A_, B_, C_;
A_.raw_ptr = A.raw_ptr;
A_.layout = A.layout.remove_axis(0);
B_.raw_ptr = B.raw_ptr;
B_.layout = B.layout.remove_axis(0);
C_.raw_ptr = C.raw_ptr;
C_.layout = C.layout.remove_axis(0);
auto Astrd = A.layout.dtype.size() * A.layout.stride[0],
Bstrd = B.layout.dtype.size() * B.layout.stride[0],
Cstrd = C.layout.dtype.size() * C.layout.stride[0];
auto advance_ptr = [](TensorND &dest, ptrdiff_t d) {
dest.raw_ptr = static_cast<void*>(
static_cast<dt_byte*>(dest.raw_ptr) + d);
};
rep(n, N) {
m_opr->exec(A_, B_, C_, workspace);
advance_ptr(A_, Astrd);
advance_ptr(B_, Bstrd);
advance_ptr(C_, Cstrd);
}
};
static_cast<naive::HandleImpl*>(handle())->dispatch_kern(kern);
}
// vim: syntax=cpp.doxygen
|
def list_projects(cls) -> None:
config = cls._load_config()
if len(config) == 0:
print("No projects registered!")
for project_hint in config:
print("{}: {}".format(project_hint, config[project_hint]['path'])) |
// Search for label. Create if nonexistant. If created, give it flags "Flags".
// The label name must be held in GlobalDynaBuf.
label_t* Label_find(zone_t zone, int flags) {
node_ra_t* node;
label_t* label;
bool node_created;
int force_bits = flags & MVALUE_FORCEBITS;
node_created = Tree_hard_scan(&node, Label_forest, zone, TRUE);
if(node_created) {
label = safe_malloc(sizeof(label_t));
label->flags = flags;
label->value = 0;
label->usage = 0;
label->pass = pass_count;
node->body = label;
} else
label = node->body;
if((node_created == FALSE) && force_bits)
if((label->flags & MVALUE_FORCEBITS) != force_bits)
Throw_error("Too late for postfix.");
return(label);
} |
from fastapi import HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from models import model
from schemas import schema
from pydantic import ValidationError
def get_atividade(db: Session, id_atividade: int):
return db.query(model.Atividade).filter(model.Atividade.ID_ATIVIDADE == id_atividade).first()
def get_atividades(db: Session, skip: int = 0, limit: int = 100):
return db.query(model.Atividade).offset(skip).limit(limit).all()
#Erro de Validação
def create_atividade(db: Session, atividade: schema.AtividadeCreate):
try:
db_atividade = model.Atividade(NOME_ATIVIDADE=atividade.NOME_ATIVIDADE, CNAE=atividade.CNAE)
db.add(db_atividade)
db.commit()
db.refresh(db_atividade)
return db_atividade
except ValidationError as e:
return e
#raise HTTPException(status_code=404, detail="Informações inseridas incorretamente!")
def delete_atividade(db: Session, id_atividade: int):
db_atividade = get_atividade(db, id_atividade)
if db_atividade is None:
return {"erro": "Esta atividade não está cadastrada!"}
else:
db.delete(db_atividade)
db.commit()
return {"id_atividade": id_atividade ,"mensagem": "atividade Excluído!"}
|
Immune Response Characterization after Controlled Infection with Lyophilized Shigella sonnei 53G
Correlate(s) of immunity have yet to be defined for shigellosis. As previous disease protects against subsequent infection in a serotype-specific manner, investigating immune response profiles pre- and postinfection provides an opportunity to identify immune markers potentially associated with the development of protective immunity and/or with a reduced risk of developing shigellosis postchallenge. This study is the first to report such an extensive characterization of the immune response after challenge with S. sonnei 53G. Results demonstrate an association of progression to shigellosis with robust intestinal inflammatory and mucosal gut-homing responses. An important finding in this study was the association of elevated Shigella LPS-specific serum IgA and memory B cell IgA responses at baseline with reduced risk of disease. The increased baseline IgA responses may contribute to the lack of dose response observed in the study and suggests that IgA responses should be further investigated as potential correlates of immunity.
S higella is a significant cause of bacillary dysentery, causing moderate to severe diarrhea (MSD) in travelers, as well as in children in low-and middle-income countries (LMIC) (1)(2)(3)(4). Shigella has also been shown to be a significant cause of watery diarrhea using more sensitive molecular methods (5). In 2016, Shigella was identified as the second leading cause of diarrhea-associated mortality across all age groups, with an increased disease burden among children under the age of 5 (6,7). Children are also at risk of impaired development after repeated enteric infections (8)(9)(10)(11)(12). Infection with Shigella species can lead to reduced gut permeability, causing a reduction in intestinal absorption of nutrients and subsequently leading to childhood cognitive and physical stunting (11,13). Children stunted from the heavy burden of Shigella infection are also at higher risk of dying from other infectious diseases (14). Shigella remains a highpriority vaccine target for the World Health Organization because of its high global burden and increasing antibiotic resistance (15).
Although several vaccine candidates are in clinical development, there is currently no licensed Shigella vaccine. A tool that is useful for early assessment of vaccine efficacy and, at times, utilized to support licensure is the controlled human infection model (CHIM) (16)(17)(18). In response to recent calls for model standardization (19)(20)(21)(22)(23)(24), a lyophilized strain of Shigella sonnei 53G was produced using current good manufacturing practice (cGMP) and evaluated in a dose-escalation manner to determine a dose that safely and reproducibly yielded a Ն60% attack rate for shigellosis (25). Disease outcomes and attack rates with the lyophilized strain of S. sonnei 53G are described elsewhere (25).
That study offered a unique opportunity to characterize systemic and mucosal immune responses given the repeated collection of multiple samples throughout the study. Although S. sonnei is traditionally associated with infection in industrialized nations, recent reports have indicated a paradigm shift in the incidence of S. sonnei infection across developing nations with impacts on adult, child, and infant health (26)(27)(28)(29)(30). For this reason, intestinal inflammatory responses were also characterized preand postinfection, given its association with stunting and enteric enteropathy in infants and young children in low-resource settings. Since prior disease caused by Shigella infection can result in protection from subsequent infection in a serotype-specific manner (31)(32)(33)(34)(35), investigation of the immune responses associated with multiple disease outcomes postinfection could provide further insights into potential mechanistic or nonmechanistic immune correlates of protection. Investigating correlates, or surrogates, of protection can also help guide vaccine development and interpretation of results in future Shigella CHIMs aimed at assessing vaccine efficacy.
As previously reported, lipopolysaccharide (LPS)-specific serum and fecal IgG and IgA responses postchallenge were not associated with challenge dose or clinical disease outcomes, including dysentery, diarrhea severity, and disease severity score (25). These findings highlight potential gaps in understanding the contribution of other immunological or nonimmunological protective mechanisms and may also confirm the importance of immune responses to nonpolysaccharide antigens (36)(37)(38).
Finally, a subset of orally challenged volunteers did not exhibit disease symptoms postchallenge, regardless of dose received (567 to 1,760 CFU ). Therefore, a more comprehensive evaluation of the Shigella-specific immune responses at baseline and at several time points postchallenge was undertaken. Investigating potential immunological mechanisms associated with observed resistance to infection and subsequent lack of association between immune responses and disease outcomes may also provide insights into potential correlates of protection.
RESULTS
Fecal inflammatory marker responses. Fecal calprotectin and myeloperoxidase concentrations were determined in stool samples from volunteers with (n ϭ 18) or without (n ϭ 26) shigellosis. A substantial increase in calprotectin and myeloperoxidase (all P Յ 0.002; 2-way analysis of variance ) concentrations was observed 3 days postchallenge, regardless of shigellosis outcome, with concentrations returning to baseline levels by day 14 (Fig. 1A and B). Volunteers with shigellosis had significantly higher concentrations of both fecal inflammatory markers whether day 3 concentrations (all P Յ 0.018; 2-way ANOVA) ( Fig. 1A and B) or peak (observed on day 3 or 7) concentrations (P ϭ 0.0002 and P ϭ 0.008 ; t test) ( Fig. 1C and D) were compared, demonstrating an association of increased intestinal inflammation with progression to shigellosis. In addition, fecal inflammatory marker peak concentrations were associated with multiple other disease outcomes, including diarrhea severity, disease severity score, and dysentery ( Fig. S1 and S2).
Serum antibody responses. Shigella antigen-specific serum IgG, IgA, IgM, and IgG subclass responses were determined for all volunteers and compared across groups with or without shigellosis. LPS-specific serum IgG, IgA, and IgM levels peaked 14 days postchallenge and remained elevated over baseline levels 14 and 28 days postchallenge (all P Յ 0.003; 2-way ANOVA) (Fig. 2). There were no significant differences in LPS-specific serum IgG or IgA titers postchallenge between volunteers with or without shigellosis ( Fig. 2A and B). LPS-specific serum IgM levels on day 14 were higher (P ϭ 0.033; 2-way ANOVA) in volunteers with shigellosis (Fig. 2C). Serum IgG and IgA responses directed to additional antigens, including the native Invaplex (IVP) antigen (39) and invasion plasmid antigens IpaB and IpaC, were investigated; however, no differences in peak serum titers postinfection were observed across shigellosis outcome groups (Table S1). IVP-specific titers showed the highest magnitude of response, followed by IpaB and IpaC. Although a moderate increase (P ϭ 0.0008; 1-way ANOVA) in LPS-specific serum IgG1 titers was observed by day 14 across all volunteers, there was no difference in peak LPS-specific serum IgG1 responses across volunteers with or without shigellosis (Table S1). There were minimal or undetectable increases in LPSspecific serum IgG2, IgG3, and IgG4 responses postinfection and no differences in peak titer in these IgG subclass responses across shigellosis outcome (Table S1).
Volunteers progressing to shigellosis had substantially higher ␣47 ϩ responses on day 7 than volunteers without shigellosis (all P Ͻ 0.0001; 2-way ANOVA) (Fig. 3). Interestingly, IVP-specific ␣47 Ϫ IgA and IgG responses on day 7 were significantly increased (P ϭ 0.011 and P Ͻ 0.0001, respectively; 2-way ANOVA) ( Fig. 3C and D) in volunteers with shigellosis, but this difference was not observed in the LPS-specific ␣47 Ϫ antibody responses ( Fig. 3A and B). In addition to the association with shigellosis, LPS-and IVP-specific ␣47 ϩ IgA responses were associated with diarrhea severity, disease severity score, and dysentery ( Fig. S3 and S4). LPS-and IVP-specific ␣47 ϩ IgG responses showed similar trends and were also associated with all aforementioned disease outcomes at similar levels of significance (data not shown).
Fecal antibody responses. Fecal IgA and IgG responses were determined for all volunteers and compared across shigellosis outcome groups. In volunteers with shigellosis, peak titers of LPS-specific fecal IgA and IgG were observed 7 days postinfection, and although they were lower by day 14, they remained elevated over baseline (all P Ͻ 0.0001; 2-way ANOVA) ( Fig. 4A and B). In contrast, LPS-specific fecal IgA and IgG responses in volunteers without shigellosis continued to increase through study day 14 (all P Յ 0.049; 2-way ANOVA) ( Fig. 4A and B). LPS-specific fecal IgA and IgG titers on day 7 were higher in volunteers with shigellosis than volunteers without (all P Յ 0.045; 2-way ANOVA) ( Fig. 4A and B), with similar trends and levels of significance observed in the IVP-specific fecal antibody responses (data not shown). Fecal antibody responses were compared with ␣47 ϩ ALS antibody responses, revealing a moderate correlation Immune Responses Postinfection in an S. sonnei CHIM when peak rise (fold) in fecal IgA or IgG was compared with peak rise in ␣47 ϩ ALS IgA or IgG (r ϭ 0.51 , r ϭ 0.53 ; P Ͻ 0.0001; Spearman correlation) ( Fig. 4C and D).
Memory B cell responses. ALS titers of LPS-and IVP-specific memory B cell IgG and IgA on day 28 were elevated over baseline (all P Յ 0.013; 2-way ANOVA), and although responses decreased by day 56, ALS titers remained elevated over baseline levels (data not shown). With the exception of the LPS-specific memory B cell IgG responses, volunteers with shigellosis had larger rises in LPS-specific IgA and IVP-specific IgG and IgA memory B cell ALS titers than volunteers without shigellosis (all P Յ 0.027; Mann-Whitney U test) (Fig. 5).
SBA responses. Peak S. sonnei-specific serum bactericidal activity (SBA) was observed 14 days postchallenge; however, levels were increased over baseline by day 7 (all P Ͻ 0.0001; 2-way ANOVA) (Fig. 6A) and remained elevated through study day 56 (all P Յ 0.024; 2-way ANOVA) (Fig. 6A), regardless of shigellosis outcome. There were no differences in peak S. sonnei-specific bactericidal activity across volunteers with or FIG 3 Individual ALS IgA and IgG ELISA endpoint titers with group geometric mean and 95% confidence intervals for ␣47 ϩ (gray bars) and ␣47 Ϫ (white bars) populations prior to challenge (day Ϫ1) and 5 and 7 days postchallenge, grouped by volunteers with (n ϭ 22) and without (n ϭ 34) shigellosis. (A) S. sonnei LPS-specific ALS IgA; (B) S. sonnei LPS-specific ALS IgG; (C) S. sonnei IVP-specific ALS IgA; (D) S. sonnei IVP-specific ALS IgG. §, significant compared to matched ␣47 ϩ or ␣47 Ϫ baseline titers within the shigellosis group. P values in red compare ␣47 ϩ and ␣47 Ϫ titers on a given study day within the shigellosis group. P values in black compare matched ␣47 ϩ or ␣47 Ϫ titers on a given study day across shigellosis groups. Significance across all parameters was determined by 2-way ANOVA of log-transformed ALS titers with a Bonferroni post hoc test. without shigellosis (Fig. 6B), and although the difference was not significant, it is interesting that volunteers without shigellosis had higher S. sonnei-specific bactericidal titers 28 and 56 days postinfection (Fig. 6A). Minimal increases in Shigella flexneri 2a-specific SBA over baseline were observed, and there were no differences in peak titer (data not shown) or peak rise over baseline (Fig. 6C) across shigellosis outcome groups. A total of 8 volunteers had a 4-fold or greater rise over baseline in S. flexneri 2a-specific bactericidal titers, and interestingly, of these 8 volunteers, 7 did not progress to shigellosis (Fig. 6C).
Baseline immune responses. A thorough evaluation of pre-existing immunity was conducted to better understand the lack of association between disease severity and certain immune parameters (Fig. 7) in this study population. As described in the accompanying article (25), 171 volunteers were screened for study inclusion. After exclusions based on other criteria, 130 volunteers were screened for S. sonnei LPSspecific serum IgG titers between study days Ϫ45 to Ϫ2. Of these 130, 4 volunteers (ϳ3%) had titers greater than the 2,500 cutoff used for study inclusion and were excluded from the study (Table S2). and IgG geometric mean ELISA endpoint titers (B) with 95% confidence intervals at baseline ("B" on the x axis) and 3, 7, and 14 days postchallenge, grouped by volunteers with (n ϭ 22) or without (n ϭ 34) shigellosis. *, significant difference compared to baseline titers within the shigellosis group; §, significant difference in titers between shigellosis groups at the same time point. Significance was determined by 2-way ANOVA of log-transformed titers with a Bonferroni post hoc test. (C and D) Spearman correlation of peak fold rise in S. sonnei LPS-specific ␣47 ϩ ALS and fecal IgA titers (C) and S. sonnei LPS-specific ␣47 ϩ ALS and fecal IgG titers (D).
Immune Responses Postinfection in an S. sonnei CHIM Of the enrolled volunteers, there were no differences in the LPS-specific serum IgG titers at baseline (study day Ϫ1) across shigellosis outcome group, and with the exception of one individual, all volunteers had baseline LPS-specific serum IgG titers within 2-fold of the 2,500 cutoff for inclusion (Fig. 7A). In contrast, increased LPSspecific serum IgA baseline titers were associated with volunteers not progressing to shigellosis (P ϭ 0.027; t test) (Fig. 7A). A similar association was observed with baseline S. sonnei-specific SBA (P ϭ 0.038; Mann-Whitney U test) (Fig. 7B) as well as LPS-specific fecal IgA and IgG titers at baseline (P ϭ 0.027 and P ϭ 0.035, respectively; Mann-Whitney U test) (Fig. 7C). There was also a significant association of increased LPSspecific memory B IgA baseline titers with volunteers not progressing to shigellosis (P ϭ 0.034; t test) (Fig. 7D); however, the same association was not observed in the LPS-specific memory B IgG baseline titers (P ϭ 0.082; t test) (data not shown). LPSspecific serum IgA baseline titers were also inversely associated with diarrhea severity, dysentery, and disease severity score (Fig. S5). Logistic regression analyses were used to investigate the association of increasing baseline LPS-specific serum IgG or IgA enzymelinked immunosorbent assay (ELISA) titers with progression to either MSD or shigellosis (Table 1). Neither the unadjusted nor adjusted models showed an association of increasing baseline LPS-specific serum IgG with either outcome of interest. In contrast, both the unadjusted and adjusted models showed a significant association between progression to shigellosis or MSD and increasing baseline LPS-specific serum IgA titers. In the adjusted model, each fold increase in baseline LPS-specific serum IgA titer resulted in nearly a 40% reduction in odds of progression to shigellosis (odds ratio ϭ 0.61; 95% confidence interval ϭ 0.40 to 0.94) (Table 1), with an area under the receiver operating characteristic (ROC) curve of 0.777. Similarly, increasing baseline LPS-specific serum IgA titers resulted in nearly a 50% reduction in odds of progression to MSD (OR ϭ 0.51; CI ϭ 0.32 to 0.80) ( Table 1) with an area under the ROC curve of 0.831. Additional cut-point analyses suggest LPS-specific serum IgA titers of Յ300 and Յ150 as optimal cut-points for predicting progression to MSD or shigellosis, respectively (data not shown).
DISCUSSION
The primary objective of the S. sonnei 53G CHIM was to determine a dose of a cGMP-manufactured lyophilized strain that would safely and reproducibly induce a Ն60% shigellosis rate in challenged volunteers (25). The study also provided a unique opportunity to extensively characterize the Shigella-specific systemic, mucosal, and functional antibody immune responses before and after infection with S. sonnei 53G in a more robust manner than previous studies. The more expansive immune response characterization further facilitates the understanding of host resistance to infection and could lead to determining immune markers that may be associated with recovery from shigellosis and/or protection against illness upon re-exposure. While the study did not include uninfected or placebo-challenged controls, comparisons of postchallenge immune responses to baseline responses strengthened the analyses of immune response associations with disease outcomes. Infection with S. sonnei induced robust intestinal inflammatory and mucosal responses, as observed by sharp increases in fecal inflammatory markers and ␣47 ϩ ALS antibody responses in diseased volunteers, and both of these immune parameters were significantly associated with multiple disease outcomes. Interestingly, there was a lack of association with postinfection systemic immune responses (serum antibodies and bactericidal activity) and disease outcomes. The relationship between intestinal inflammatory markers and disease outcomes noted above is intriguing and deserves further investigation into its potential relationship to immune outcomes that are associated with recovery from acute illness or may be predictive of a reduced risk of illness upon re-exposure to Shigella sonnei.
Fecal IgA responses are often used as a measure of the mucosal immune response postinfection with Shigella. In this study, fecal IgG responses were also evaluated. Antibody responses from B cells positive for the gut homing marker ␣47 were also determined and presented as a measure of the mucosal immune response. Because ␣47 ϩ cells home to the intestinal mucosa and secrete IgA and IgG antibodies, which are actively transported or passively transudated into the lumen of the large intestine, the correlation of these two mucosal measurements was of particular interest. The observed correlation of ␣47 ϩ ALS IgG and fecal IgG suggests that the IgG-secreting ␣47 ϩ cells may be partially responsible for the antigen-specific IgG detected in stool samples in addition to IgG transudate from systemic circulation.
Antecedent shigellosis reduces the risk of subsequent infection in a serotypespecific manner, indicating a role for LPS-specific immune responses in protection (31)(32)(33)40). LPS-specific serum IgG has been indicated as an immune correlate of protection responsible for this observed serotype-specific protection (41,42); however, several of these studies have investigated serum IgG levels after parenteral immunization with conjugate vaccines, which would be expected to induce large amounts of LPS-specific serum IgG (41,(43)(44)(45)(46). Furthermore, immunological analyses in many previous studies has been limited with incomplete analysis of other immune parameters outside serum IgG. In contrast, results from this study and other studies evaluating mucosal routes of immunization or infection (42,(47)(48)(49) suggest that LPS-specific IgA also contributes to protection. Together, these data provide evidence that there exist alternate mechanisms to induce a protective immune response, depending on the route of antigen exposure. Interestingly, increased LPS-specific serum IgA, IgA-secreting memory B cells, and SBA titers at baseline were inversely associated with risk of shigellosis. Increased baseline serum IgA titers have also been associated with reduced risk of disease in enterotoxigenic Escherichia coli (ETEC) CHIMs (50) as well as reduced susceptibility to cholera infection in endemic settings (49). In an effort to recruit immunologically naive volunteers, exclusion criteria for this study included recent travel to areas where Shigella is endemic, known history of culture-confirmed Shigella infection, and a titer of S. sonnei LPS-specific serum IgG, determined by ELISA, of Ͼ2,500; however, LPS-specific serum IgA responses were not assessed during study screening. The serum IgG exclusion criterion used in this study has been applied to several Shigella vaccine studies and CHIMs (51-53); however, this immunoassay-based exclusion criterion may be insufficient, even when combined with exclusion based on previous Shigella exposure and travel.
As outlined above, memory B cell IgA responses directed to LPS correlated with resistance to shigellosis. In addition, LPS-specific serum IgA responses and SBA also were associated with decreased risk of shigellosis, albeit at a lower magnitude. These results demonstrate that immune parameters other than serum IgG may contribute to resistance to shigellosis. Given these associations with resistance to shigellosis, it may be reasonable to expand the immunological parameters utilized for excluding volunteers from Shigella vaccine studies or CHIMs when a naive population is critical. While data presented here suggest that LPS-specific IgA-secreting memory B cell responses at baseline may be the most suitable predictor of resistance to shigellosis, a balance needs to be maintained between volunteer exclusion criteria and the ability to successfully recruit volunteers. Therefore, impractical, costly, or technically difficult screening assays must be weighed against study objectives. Functional immune responses at baseline, as determined by SBA, could also be considered; however, the association of baseline SBA with disease outcomes was less robust than LPS-specific serum IgA responses, and the assay is also more technically challenging and time-consuming than an ELISA. Collectively, these results suggest that LPS-specific serum IgA titers should be considered a potentially useful and practical tool to more reliably exclude volunteers with pre-existing immunity to Shigella, similar to ETEC CHIMs (54). Setting additional or more stringent exclusion criteria may be problematic in the development of CHIMs in LMICs; however, an alternative strategy may be to stratify and/or randomize volunteers based on baseline immunity.
Logistic regression analyses indicated approximate 40% and 50% reductions in odds of progression to shigellosis or MSD, respectively; however, these associations were not observed with baseline LPS-specific serum IgG titers. This lack of association with baseline LPS-specific serum IgG and progression to shigellosis or MSD may be due to the fact that volunteers with high baseline serum IgG titers were excluded from the study, potentially providing a biased population after study enrollment. However, of the 130 volunteers that underwent LPS-specific serum IgG screening, only 4 (3.1%) were excluded based on high S. sonnei LPS-specific serum IgG titers (Table S2). Additionally, of the 56 enrolled volunteers, 41 (73%) had a LPS-specific serum IgG screening titer of Յ625.
ROC analyses revealed an optimal baseline LPS-specific serum IgA cut-point of Յ300 for predicting progression to MSD. In an effort to investigate the lack of a dose response observed in this CHIM (25), systemic immune responses were reanalyzed by approximate Shigella dose (500, 1,000, or 1,500 CFU), excluding volunteers with a baseline LPS-specific serum IgA titer of Ͼ400; however, removal of these volunteers did not result in a dose-dependent LPS-specific serum IgG response or SBA response. This lack of association could be a function of the sample size (n ϭ 40) resulting in insufficient power to determine significant differences, or it could imply that there are other host factors, such as microbiome or genetics, that have not yet been measured or explored.
There are multiple immune mechanisms that could be employed to protect against Shigella, which can be effective during the intracellular and extracellular phases of the bacterial infection. Protective immune responses could be driven, in part, by antibodies in the lumen preventing transcytosis of the bacteria across the epithelial cell layer (whether secretory IgA or IgG transudate), complement activation in the lamina propria, or antibody-dependent cellular cytotoxicity once Shigella has reached the intracellular phase of its life cycle. While assessing mechanistic correlates of protection is important, investigating immunological surrogates that represent the mechanistic correlates of protection is also informative. Additionally, rather than one immune parameter being responsible for protection, there may be multiple immune parameters working in concert, effectively defining a protective immune profile (55; R. W. Kaminski and K. A. Clarkson, unpublished data). Furthermore, depending on the initial route of antigenic exposure, there may be distinct protective immune profiles generated. Additional analyses, including Shigella-specific salivary antibody responses, determination of Fc glycosylation patterns, Shigella microarray analyses, transcriptomics, and systems serology, are currently planned to parse out more nuanced differences in immune responses across the disease spectrum. Similarly, ongoing analyses and determination of a protective immune profile in the context of parenterally administered Shigella vaccines could offer additional insights.
Disease outcomes and immune responses postinfection may also be affected by the duration of antigenic exposure. In the S. sonnei 53G CHIM, the majority of volunteers were administered antibiotics 5 days postinoculation (or sooner if clinically indicated ), which often does not occur during natural infection. Interrupting the infection with antibiotics may reduce the amount of and exposure time to Shigella antigens, potentially impacting the magnitude, specificity, duration, maturation, and phenotype of the immune response induced in a CHIM (56), compared to settings where the disease is endemic. Depending on the duration of antigenic stimulation, more robust or perhaps different immune responses could occur, including generation of antibodies with higher affinity or avidity, antibodies with different Fc glycosylation patterns, or increased activation of cell-mediated immune mechanisms.
Additional immune response analyses by time and length of shedding S. sonnei in stool samples could also provide important insights into the relationship between Shigella infection and immune responses. Unfortunately, the present study was not powered to detect differences in immune responses across culture-confirmed S. sonnei shedding, as the majority of volunteers had culture-negative stools within 3 to 5 days after their first culture-positive stool sample. Efforts are under way to quantify S. sonnei in stool samples using quantitative PCR (qPCR) detection methods. As qPCR is highly sensitive compared to culture detection methods, these analyses may allow better comparisons between immune responses and S. sonnei shedding in stool samples postinfection.
Other nonimmunological factors may also contribute to the resistance to infection and lack of association of some immune parameters with disease outcomes observed in this study. While a CHIM attempts to control for many variables, such as challenge dose and age, there remain several uncontrolled factors in both CHIMs and natural infection settings that could contribute to differences in disease outcomes. Population genetics, prior exposure, and contemporaneous host immune status or coinfections, as well as microbiome and nutritional status may affect immune response profiles and disease outcomes postinfection (57)(58)(59)(60). Finally, this study was conducted in healthy, North American adults, who constitute a distinctly different population than the target population of children Ͻ2 years of age living in LMICs. Infant immune systems do not fully mature until approximately 24 months of age and have been shown to have lower levels of circulating immunoglobulin and complement effectors, leading to different immune responses being required to induce protection in this population (61). Furthermore, infant health and immune status can vary greatly in settings where the disease is endemic, so caution is required when postinfection immune responses in healthy North American adults are extrapolated to other populations.
Nonetheless, data collected in this study are invaluable, as comparable characterization of the immune response following a Shigella CHIM in the target population is unlikely. In addition to the immune response characterization postinfection, this study provides important information about immune status preinfection. Increased levels of serum IgA may be a contributing factor to resistance after oral Shigella challenge, and while additional investigations with increased group numbers are important, this study has been able to provide some guidance on immunological screening assays for use in future Shigella CHIMs.
Ideally, protective immunity against shigellosis would be assessed in the context of a challenge-rechallenge CHIM study design; however, the current study was designed and powered to address only the primary clinical outcome. Nonetheless, as prior disease results in protective immunity against subsequent infection with the same Shigella serotype, volunteers in this trial provide an important population for the investigation of potential immune correlates or surrogates of protection, as those with moderate to severe disease would likely be protected against reinfection (31,32,35,40). With the dose of S. sonnei 53G now established, next steps should focus on the conduct of a challenge-rechallenge study in order to fully elucidate the immunological mechanisms responsible for protection from shigellosis. Additionally, a heterologous challenge-rechallenge study to investigate the potential of cross-protection provided across different Shigella species is in the planning stages. The S. sonnei 53G CHIM has confirmed the relevance of robust mucosal immune responses postinfection and their potential role as a mechanistic correlate of protection in this model (36), while suggesting that systemic immune responses may play a lesser role, as they were not as reflective of disease outcome and severity in this study. The observations that baseline levels of LPS-specific serum IgA and IgA-secreting memory B cells are associated with reduced odds of disease point to these immune measures as being potentially more sensitive markers for underlying protective immunity, and therefore, they should be further studied. Together, these data may help guide the rational design of future Shigella vaccines while representing a framework for future studies and functioning as a benchmark for comparisons across CHIMs.
MATERIALS AND METHODS
Study design and inoculation. The study was an open-label dose-finding CHIM designed to determine a target dose of lyophilized cGMP S. sonnei 53G for use in future Shigella CHIMs that would induce shigellosis in Ն60% of volunteers, as described elsewhere (25). Five days postchallenge (or sooner if clinically warranted), all volunteers initiated antibiotic treatment and were discharged from the inpatient facility after producing 2 culture-negative stool samples. Volunteers returned 14, 28, and 56 days postchallenge for additional blood and stool sample collections.
Blood processing. Whole blood was collected on study days Ϫ1, 5, 7, 14, 28, and 56. Serum samples were stored at Ϫ80 Ϯ 10°C until assayed. Peripheral blood mononuclear cells (PBMCs) were isolated on a Ficoll gradient with Leucosep tubes, frozen using BioCision Cool Cells, and stored in liquid nitrogen until used in immunoassays.
Stool processing. Stool samples for immunoassays were collected on study days Ϫ1, 0, 3, 7, and 14 and immediately frozen at Ϫ80 Ϯ 10°C. Archived stool samples were thawed and processed for immunoassays by resuspending 2 g of stool in a protease inhibitor buffer (Roche cOmplete EDTA-free protease inhibitor tablets, 1ϫ phosphate-buffered saline , 0.05% Tween 20, 0.1% bovine serum albumin ), vortexed, and centrifuged for 30 min at 4°C at ϳ1,900 ϫ g. Fecal extract supernatants were collected and frozen at Ϫ80 Ϯ 10°C. Stool samples for inflammatory marker analyses were processed in myeloperoxidase or calprotectin-specific collection and processing kits according to the manufacturer's instructions (Epitope Diagnostics) and frozen at Ϫ80 Ϯ 10°C.
Fecal inflammatory markers. Stool samples processed for inflammatory marker analyses were assayed by enzyme-linked immunosorbent assay (ELISA) to determine calprotectin and myeloperoxidase concentrations per manufacturer's instructions (Epitope Diagnostics). Inflammatory marker concentrations were interpolated from a standard curve, with values below the assay limit of detection (LOD) being assigned a value of half the lowest concentration in the standard curve (1/2 LOD). As this was a post hoc analysis, only stool from volunteers consenting the use of their samples in future or additional investigations were used for this analysis. The assessment of fecal inflammatory marker concentrations in stool samples was a post hoc analysis and therefore limited to a smaller subset of volunteers (i.e., 45 of the 56 volunteers).
␣47 PBMC separation. Frozen PBMCs from study days Ϫ1, 5, and 7 were thawed, washed, and suspended at 1 ϫ 10 7 cells/ml in complete RPMI medium prior to incubation with an Alexa Fluor 647 (AF647)-conjugated anti-␣47 monoclonal antibody (Act-1; NIH AIDS Reagent Program) for 10 min at 4 Ϯ 2°C, protected from light. After washing, the cells were incubated with anti-AF647 MicroBeads (Miltenyi) for 15 min at 4 Ϯ 2°C, protected from light. PBMCs were then washed and passed through a 30-m cell strainer prior to separation of ␣47-positive and -negative PBMC populations using a Miltenyi AutoMACS cell separator. Both the ␣47 ϩ and ␣47 Ϫ populations were adjusted to 5 ϫ 10 6 cells/ml and cultured as described above to collect ␣47 ϩ and ␣47 Ϫ ALS. Immediately prior to ALS culture, 100 l of both the ␣47 ϩ and ␣47 Ϫ populations was removed to assess population purity by flow cytometry. As ␣47 ϩ cells were bound by the AF647-conjugated anti-␣47 monoclonal antibody, it was expected that only the positive population would fluoresce when analyzed by flow cytometry. The ␣47 ϩ and ␣47 Ϫ populations for a given volunteer and time point were analyzed using a FACSCanto II flow cytometer and determined to be Ն90% pure postseparation (data not shown).
Memory B cell expansion and quality control. Frozen PBMCs from study days Ϫ1, 28, and 56 were thawed, washed, and expanded as previously described (62) with minor modifications. Briefly, cells were suspended at 1 ϫ 10 6 cells/ml in complete RPMI medium with 2-mercaptoethanol and polyclonal mitogens: pokeweed mitogen extract at a 1:20,000 dilution (Sigma), CpG-ODN-2006 at 6 g/ml (Invivogen), and Staphylococcus aureus Cowan at a 1:10,000 dilution (Sigma). Cells were plated in a sterile 6-well tissue culture plate (3 to 5 ml/well) and cultured for 6 days at 37 Ϯ 1°C with 5% CO 2 . After expansion, the cells were washed twice with mitogen-free complete RPMI medium, adjusted to 5 ϫ 10 6 cells/ml, and cultured as described above to collect memory B cell ALS. A novel method was developed to characterize the memory B cell expansion and establish acceptability criteria in order to objectively determine successful expansion of memory B cell populations (R. W. Kaminski and K. A. Clarkson, unpublished data). Briefly, samples were analyzed by flow cytometry before and after polyclonal mitogen stimulation using T and B cell-specific markers (CD3-BV711, CD19-BV421, CD27-APC, and CD20-PE-Cy7; BD Biosciences) and analyzed by flow cytometry using a FACSCanto II flow cytometer. Acceptance criteria for a successful expansion included assessing cell viability and cell concentrations pre-and postexpansion as well as ensuring an overall increase postexpansion in the percentage of cells positive for the CD19 B cell marker. Additionally, an expansion was considered successful if B cell populations postexpansion showed a Ն20% increase in B cells positive for the CD27 memory marker, compared to pre-expansion B cell populations.
Enzyme-linked immunosorbent assay. Serum, stool extracts, and ALS samples were assayed by ELISA to determine Shigella antigen-specific antibody endpoint titers as previously described (39), with the exception of the use of Immulon 1-B ELISA plates and human-specific secondary antibodies (reserve allophycocyanin -conjugated goat-anti-human IgG, IgA, or IgM ; AP-conjugated mouse anti-human IgG1, IgG2, IgG3, or IgG4 ). Samples that were negative at the starting dilution were assigned a titer corresponding to half the starting dilution (1/2 LOD). Immune responders were defined a priori as having a Ն4-fold increase over their baseline titer.
Serum bactericidal activity. Antibody functionality was assessed by determining Shigella-specific serum bactericidal activity (SBA) as previously described (63). Serum samples were assayed starting at a 1:40 dilution, and titers were interpolated from a standard curve using NICE software (64). A titer of 20, corresponding to half of the lowest serum dilution tested (1/2 LOD), was assigned to samples not exhibiting detectable serum bactericidal activity at the starting dilution. Immune responders were defined a priori as those with a Ն4-fold increase in SBA titer over baseline. Bactericidal activity directed to S. sonnei Moseley was determined, as well as that to the S. flexneri 2a strain 2457T to investigate the cross-reactivity of functional antibodies with other Shigella serotypes.
Disease outcomes and definitions. Immune responses pre-and postchallenge were compared across shigellosis outcome to determine the association of these immune parameters with progression to and severity of disease postchallenge. The outcome of shigellosis was chosen because it is often the focus of Shigella vaccine development. However, immune responses demonstrating differences across additional disease outcomes are also presented in the supplemental material. Diarrhea severity, dysentery (25), and disease severity score (19) were defined as previously described. While the primary clinical shigellosis endpoint was defined a priori, all analyses were conducted using an alternative shigellosis definition developed through a convening of Shigella CHIM experts to standardize Shigella CHIM clinical endpoints (23). All disease outcomes used for analyses are also described in Table S3.
Statistical analyses. All immune response data in the current study were assessed for normality using distribution plots. Normally distributed continuous immune response data were analyzed using appropriate parametric tests (t test or ANOVA) with Bonferroni post hoc analyses as applicable. Nonnormally distributed data were log 10 transformed in order to meet the assumptions for the parametric tests. If the log transformation did not correct the distribution of the data set, then nonparametric statistical tests were used (Mann-Whitney U test) (51,65). A multivariate logistic regression model was developed to assess the association between various immune parameters at baseline and the odds of progressing either to shigellosis MSD or to no or mild diarrhea. Continuous variables were analyzed for assumption of linearity by plotting the variable against the log odds of the outcome. As age did not demonstrate a linear relationship with either outcome, it was appropriately categorized (for MSD, categories were 18 to 25, 26 to 40, and 41 to 49 years of age; for shigellosis, they were 18 to 25 and 26 to 49 years of age). Covariates of interest (gender, age category, race, and log-transformed dose) were investigated in univariate models (␣ ϭ 0.20) and included in the final model if they were significantly associated (P Յ 0.05) with the outcome of interest or influenced the effect estimate of baseline immune responses by Ն10% (gender, age category, and log-transformed dose). Race did not meet either inclusion criterion and was excluded from the multivariate model. Cut-point analyses were performed by plotting receiver operating characteristics (ROC) and investigating sensitivity and specificity across different areas under the curve. Additional cut-point analyses were performed using Liu and Youden cut-point methods. All statistical tests were interpreted in a two-tailed fashion (␣ ϭ 0.05), with P values of Յ0.05 being considered statistically significant in either Stata (version 14 for Mac) or Prism (version 7 for Mac).
SUPPLEMENTAL MATERIAL
Supplemental material is available online only. |
// Tests if all timer digits are zero
bool IsTimerValueZero(const TTimerValue* pTimerValue)
{
return ((pTimerValue->secLSValue == 0) && (pTimerValue->secMSValue == 0) &&
(pTimerValue->minLSValue == 0) && (pTimerValue->minMSValue == 0));
} |
def invite_create():
return "/api/ops/invite" |
Hitting to an extraordinary length in Dubai today, Andy Murray completely dismantled the game of the man who has dominated world tennis for the last 14 months. The Scot, who recovered from a wobble when serving for the match, outplayed Novak Djokovic 6-2 7-5 to reach the final of the Desert Classic.
Murray got off to a great start, converting for 4-2 with some mix-and-match slice and topspin that consistently caught the world number one off guard.
The Scot survived a mini crisis on serve, but then forced the issue at 0-40 on the Serb's delivery with some agile movement. Searing groundshots of astonishing, Lendl-esque length then sealed the first set.
In the early part of the match, it was Murray's first serve that did most of the damage, with a 71% success rate backed up with 94% of first-serve points won. That trend continued in the second set, with powerhouse deliveries constantly forcing Djokovic onto his back foot and allowing the Scot to dictate the rallies.
Murray's defence was equally outstanding, though. After breaking serve immediately at the start of the second set, the world number four began to produce recoveries, such as the one at 15-40 in the second game, that simply defied the known laws of physics.
With the Serb's game looser than a bucket of fishing worms, the British number one's imperious groundshots powered him onwards to a 5-3 lead.
But, earlier this week, Murray had suggested that he rarely had issues serving out matches and, when he hooked three routine groundshots into the net to concede the game, he might have wished he'd kept quiet.
Djokovic took full advantage, but a solid service game from Murray at 5-5 steadied the ship and, when he dug deep in game 12 to wring the errors from the world number one's racket, it was all over and Djokovic's embrace at the net seemed warm and sincere.
This result may well owe much to his recent spell with new coach Ivan Lendl in Miami. However, just as a break of serve means nothing until it's consolidated, the win might need to be rubber-stamped in a probable meeting with Roger Federer in the final over the weekend.
Nevertheless, this remains an astonishing victory that will surely open up the eyes of the tennis establishment to new and intriguing possibilities at the top of the men's game. |
Week two of the Chucktown Check-In! We recap the Battery's 0-0 draw against Orlando City B and get the latest news and notes from our man in Charleston, our Battery beat reporter, Seamus Grady.
The Charleston Battery came away with a disappointing draw against Orlando City B after OCB went down a man just five minutes into the second half. The Battery out shot OCB 21-3, dominated possession and stifled all of the OCB attacking opportunities.
Alex Tambakis recorded a second clean sheet and was barely tested, especially in the second half. The Greek international recorded two total save in the game and was seen directing and organizing his back line, which put the Battery in great positions to suppress the OCB chances.
The Battery next take on the Wilmington Hammerheads in the Southern Derby on Saturday, April 9 at 7:30 p.m. That game (and all USL games) can be found online on the USL Youtube.com page. |
<gh_stars>1000+
#include "caffe/layers/warp_ctc_loss_layer.hpp"
#ifdef USE_WARP_CTC
#include <ctcpp.h>
#include <limits>
using namespace CTC;
namespace caffe {
template <typename Dtype>
WarpCTCLossLayer<Dtype>::WarpCTCLossLayer(const LayerParameter& param)
: LossLayer<Dtype>(param),
T_(0),
N_(0),
C_(0) {
blank_index_ = param.ctc_loss_param().blank_index();
}
template <typename Dtype>
WarpCTCLossLayer<Dtype>::~WarpCTCLossLayer() {
}
template <typename Dtype>
void WarpCTCLossLayer<Dtype>::LayerSetUp(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::LayerSetUp(bottom, top);
const Blob<Dtype>* probs = bottom[0];//TxNxC
T_ = probs->num();
N_ = probs->channels();
C_ = probs->height();
CHECK_EQ(probs->width(), 1);
if (bottom.size() == 3) {
const Blob<Dtype>* seq_ind = bottom[1];
const Blob<Dtype>* label_seq = bottom[2];
CHECK_EQ(T_, seq_ind->num());
CHECK_EQ(N_, seq_ind->channels());
CHECK_EQ(N_, label_seq->channels());
} else if (bottom.size() == 4) {
const Blob<Dtype>* seq_len_blob = bottom[1];
const Blob<Dtype>* lab_len_blob = bottom[2];
const Blob<Dtype>* label_seq_blob = bottom[3];
CHECK_EQ(N_, seq_len_blob->count());
CHECK_EQ(N_, lab_len_blob->count());
CHECK_EQ(N_, label_seq_blob->channels());
}
else if (bottom.size() == 2)//input seq + labels
{
const Blob<Dtype>* label_seq = bottom[1];
CHECK_EQ(N_, label_seq->num());
}
else {
LOG(FATAL) << "Unsupported blobs shape";
}
label_lengths_.resize(N_);
input_lengths_.resize(N_);
}
template <typename Dtype>
void WarpCTCLossLayer<Dtype>::Reshape(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
vector<int> loss_shape(0); // Loss layers output a scalar; 0 axes.
top[0]->Reshape(loss_shape);
}
template <typename Dtype>
void WarpCTCLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* const activations = bottom[0]->cpu_data();
Dtype* gradients = bottom[0]->mutable_cpu_diff();
const int alphabet_size = C_;
const int minibatch = N_;
vector<Dtype> costs(N_);
flat_labels_.clear();
if (bottom.size() == 2) {//bottom[0]=activations, bottom[1] is labels, shape: Batchsize*seq len
const Blob<Dtype>* label_seq_blob = bottom[1];
const Dtype *label_seq_d = label_seq_blob->cpu_data();
int label_len_per_batch = label_seq_blob->channels();
for (int n = 0; n < N_; ++n)
{
int curlen = 0;
for (int l = 0; l < label_len_per_batch; ++l)
{
int label = label_seq_d[n*label_len_per_batch + l];
if(label == blank_index_)
continue;
flat_labels_.push_back(label);
curlen++;
}
label_lengths_[n] = curlen;
input_lengths_[n] = T_;
}
}
else if (bottom.size() == 3) {
ExtractInputData(bottom[1], bottom[2],
&flat_labels_, &label_lengths_, &input_lengths_);
} else if (bottom.size() == 4) {
const Blob<Dtype>* seq_len_blob = bottom[1];
const Blob<Dtype>* lab_len_blob = bottom[2];
const Blob<Dtype>* label_seq_blob = bottom[3];
const Dtype *seq_len_d = seq_len_blob->cpu_data();
const Dtype *lab_len_d = lab_len_blob->cpu_data();
const Dtype *label_seq_d = label_seq_blob->cpu_data();
int accumulated = 0;
CHECK_EQ(seq_len_blob->count(), lab_len_blob->count());
for (int i = 0; i < seq_len_blob->count(); ++i) {
label_lengths_[i] = lab_len_d[i];
input_lengths_[i] = seq_len_d[i];
accumulated += lab_len_d[i];
}
flat_labels_.clear();
flat_labels_.reserve(accumulated);
for (int n = 0; n < N_; ++n) {
for (int t = 0; t < label_lengths_[n]; ++t) {
flat_labels_.push_back(label_seq_d[label_seq_blob->offset(t, n)]);
}
}
} else {
LOG(FATAL) << "Unsupported blobs shape";
}
//remove repeat blank labels
size_t workspace_alloc_bytes_;
ctcOptions options;
options.loc = CTC_CPU;
options.num_threads = 8;
options.blank_label = blank_index_;
ctcStatus_t status = get_workspace_size<Dtype>(label_lengths_.data(),
input_lengths_.data(),
alphabet_size,
minibatch,
options,
&workspace_alloc_bytes_);
CHECK_EQ(status, CTC_STATUS_SUCCESS) << "CTC Error: " << ctcGetStatusString(status);
if (!workspace_ || workspace_->size() < workspace_alloc_bytes_) {
workspace_.reset(new SyncedMemory(workspace_alloc_bytes_ * sizeof(char)));
}
status = compute_ctc_loss_cpu(activations,
gradients,
flat_labels_.data(),
label_lengths_.data(),
input_lengths_.data(),
alphabet_size,
minibatch,
costs.data(),
workspace_->mutable_cpu_data(),
options
);
CHECK_EQ(status, CTC_STATUS_SUCCESS) << "CTC Error: " << ctcGetStatusString(status);
// output loss
Dtype &loss = top[0]->mutable_cpu_data()[0];
loss = 0;
int num = 0;
for (int n = 0; n < N_; ++n) {
if (costs[n] < std::numeric_limits<Dtype>::infinity()) {
loss += costs[n];
++num;
}
}
loss /= num;
int gcnt = bottom[0]->count();
Dtype sumg = 0;
for (int i=0;i<gcnt;i++)
{
sumg += fabs(gradients[i]);
}
//LOG(INFO) << "mean ctc loss=" << loss << ",N_="<<N_<<",num="<<num << ", mean gradients="<<sumg/gcnt;
}
template <typename Dtype>
void WarpCTCLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
CHECK_EQ(propagate_down[0], true)
<< "Required to propagate to probabilities";
if (propagate_down.size() >= 3)
{
CHECK_EQ(propagate_down[1], false)
<< "Cannot propagate to sequence indicators";
CHECK_EQ(propagate_down[2], false)
<< "Cannot propagate to target label sequence";
}
else if (propagate_down.size() == 2)
{
CHECK_EQ(propagate_down[1], false)
<< "Cannot propagate to target label sequence";
}
}
template <typename Dtype>
void WarpCTCLossLayer<Dtype>::ExtractInputData(const Blob<Dtype>* seq_ind_blob,
const Blob<Dtype>* labels_blob,
vector<int>* flat_labels,
vector<int>* label_lengths,
vector<int>* input_lengths) {
const Dtype* seq_ind = CHECK_NOTNULL(seq_ind_blob)->cpu_data();
const Dtype* target_seq = CHECK_NOTNULL(labels_blob)->cpu_data();
CHECK_NOTNULL(flat_labels)->clear();
flat_labels->reserve(T_ * N_); // maximum required
CHECK_NOTNULL(label_lengths)->resize(N_);
CHECK_NOTNULL(input_lengths)->resize(N_);
// compute the sequence length and label length
int* seq_len = input_lengths->data();
int* label_len = label_lengths->data();
int label_offset = 0;
//if (blank_index_ == -1) {
if (blank_index_ == 0) {//modified by jxs
label_offset = 1;
}
for (int n = 0; n < N_; ++n) {
seq_len[n] = T_; // default value is maximal allowed length
label_len[n] = T_; // default value is maximal allowed length
const Dtype *seq = seq_ind + n;
const Dtype *label = target_seq + n;
// sequence indicators start with seq == 0.0 to indicate the start of a
// sequence. Skip at t = 0, so start at t = 1
seq += N_;
for (int t = 1; t < T_; ++t) {
if (static_cast<int>(*seq + 0.5) == 0) {
seq_len[n] = t;
break;
}
seq += N_;
}
// label indicators are negative if the sequence has ended
for (int t = 0; t < T_; ++t) {
if (*label < 0.0) {
label_len[n] = t;
break;
}
// Note that the blank label will be 0
flat_labels->push_back(static_cast<int>(*label + 0.5) + label_offset);
label += N_;
}
// if the label length is 0, the seq_len is 1 (0 following 0)
// set seq_len to 0 in this case aswell, to skip this example
if (label_len[n] == 0) {
CHECK_LE(seq_len[n], 1);
seq_len[n] = 0;
}
CHECK_LE(label_len[n], seq_len[n])
<< "The label length must be smaller or equals the sequence length!";
}
}
#ifdef CPU_ONLY
STUB_GPU(WarpCTCLossLayer);
#endif
INSTANTIATE_CLASS(WarpCTCLossLayer);
REGISTER_LAYER_CLASS(WarpCTCLoss);
} // namespace caffe
#endif // USE_WARP_CTC
|
pub use crate::traits::errors::PSP22TokenTimelockError;
use brush::traits::{
AccountId,
Timestamp,
};
#[brush::wrapper]
pub type PSP22TokenTimelockRef = dyn PSP22TokenTimelock;
#[brush::trait_definition]
pub trait PSP22TokenTimelock {
/// Returns the token address
#[ink(message)]
fn token(&self) -> AccountId;
/// Returns the beneficiary of the tokens
#[ink(message)]
fn beneficiary(&self) -> AccountId;
/// Returns the timestamp when the tokens are released
#[ink(message)]
fn release_time(&self) -> Timestamp;
/// Transfers the tokens held by timelock to the beneficairy
#[ink(message)]
fn release(&mut self) -> Result<(), PSP22TokenTimelockError>;
}
|
/**
* Config for rate limiter, which is used to control write rate of flush and
* compaction.
*/
public class GenericRateLimiterConfig extends RateLimiterConfig {
private static final long DEFAULT_REFILL_PERIOD_MICROS = (100 * 1000);
private static final int DEFAULT_FAIRNESS = 10;
public GenericRateLimiterConfig(long rateBytesPerSecond,
long refillPeriodMicros, int fairness) {
rateBytesPerSecond_ = rateBytesPerSecond;
refillPeriodMicros_ = refillPeriodMicros;
fairness_ = fairness;
}
public GenericRateLimiterConfig(long rateBytesPerSecond) {
this(rateBytesPerSecond, DEFAULT_REFILL_PERIOD_MICROS, DEFAULT_FAIRNESS);
}
@Override protected long newRateLimiterHandle() {
return newRateLimiterHandle(rateBytesPerSecond_, refillPeriodMicros_,
fairness_);
}
private native long newRateLimiterHandle(long rateBytesPerSecond,
long refillPeriodMicros, int fairness);
private final long rateBytesPerSecond_;
private final long refillPeriodMicros_;
private final int fairness_;
} |
int(input())
l=list ( map(int,input().split()))
mn =abs(min(l))+abs(max(l))
mx =0
for i in range(len(l)):
if i !=0 and i != (len(l)-1) :
mn=min(abs(l[i]-l[i+1]),abs(l[i]-l[i-1]))
mx=max(abs(l[i]-l[0]),abs(l[i]-l[-1]))
elif(i ==0 ):
mn=abs(l[i]-l[i+1])
mx=abs(l[i]-l[-1])
elif(i == (len(l)-1)):
mn=abs(l[i]-l[i-1])
mx=abs(l[i]-l[0])
print(mn, mx) |
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
s=input()
s=sorted(s)
if k == n:
print("".join(map(str,s[-1])))
else:
if s[0]==s[k-1]:
ans=[s[k-1]]
if s[k]==s[n-1]:
times=(n-1-k+1)//k
if (n-1-k+1)%k is not 0:
times += 1
for i in range(times):
ans.append(s[k])
print("".join(map(str,ans)))
else:
for i in range(k,n):
ans.append(s[i])
print("".join(map(str,ans)))
else:
print(s[k-1]) |
<reponame>calewis/ClusterableExample
#include "Clusterable.h"
#include "common.h"
#include "molecule.h"
#include <boost/optional.hpp>
#include <iostream>
// Center for our molecule class.
Vector center(Molecule const& m) { return libint2::center(m.atoms()); }
// Specialization of Collapse needed to collapse the Molecule class
namespace clustering {
template <>
std::vector<Atom> collapse<Atom, Molecule>(Molecule const& m) {
return m.atoms();
}
} // namespace clustering
template <typename... Types>
class ChargeVisitor : public clustering::ClusterConceptVisitor,
public clustering::ClusterModelVisitor<Types>... {
private:
boost::optional<int> charge_ = boost::optional<int>(boost::none);
public:
void visit(Atom const& a) override {
charge_ = boost::optional<int>(boost::none);
charge_ = a.atomic_number;
}
void visit(std::vector<Atom> const& as) override {
charge_ = boost::optional<int>(boost::none);
int c = 0;
for (auto const& a : as) {
c += a.atomic_number;
}
charge_ = c;
}
boost::optional<int> get_charge() {
auto mycopy = charge_;
charge_ = boost::optional<int>(boost::none);
return mycopy;
}
};
int main(int argc, char** argv) {
// Clusterable of an Atom, see nearest_neighbor.cpp for an example that
// actually does clustering
clustering::Clusterable<Atom> c1(Atom{});
ChargeVisitor<Atom, std::vector<Atom>> a{};
c1.accept(a);
auto charge = a.get_charge();
if (charge) {
std::cout << "Charge was available\n";
} else {
std::cout << "Charge was not available\n";
}
// Some other type we have provided an external interface to work with
// clusterable, std::vector<Atom>
clustering::Clusterable<Atom> c2(std::vector<Atom>(2, Atom{}));
c2.accept(a);
charge = a.get_charge();
if (charge) {
std::cout << "Charge was available\n";
} else {
std::cout << "Charge was not available\n";
}
// Nested Vectors of Atoms
std::vector<std::vector<Atom>> meta_vec{c1.collapse(), c2.collapse()};
clustering::Clusterable<Atom> c3(std::move(meta_vec));
c3.accept(a);
charge = a.get_charge();
if (charge) {
std::cout << "Charge was available\n";
} else {
std::cout << "Charge was not available\n";
}
// A class representing a collection of Atoms
Molecule mol(std::vector<Atom>(4, Atom{}));
clustering::Clusterable<Atom> c4(std::move(mol));
// Even though we have 4 different collections of atoms we can hold a vector
// to all of them similar to haveing something like
// std::vector<Clusterable*> if we were inheriting from some common base type
// Clusterable instead of using type erasure
std::vector<clustering::Clusterable<Atom>> clusterable_vec;
clusterable_vec.emplace_back(std::move(c1));
clusterable_vec.emplace_back(std::move(c2));
clusterable_vec.emplace_back(std::move(c3));
clusterable_vec.emplace_back(std::move(c4));
// Loop over all of the differnt types and print their types, centers, and
// member atoms.
auto i = 1;
for (auto const& c : clusterable_vec) {
std::cout << "Clusterable " << i << "\n";
std::cout << "\tstored type: " << boost::core::demangle(c.type().name())
<< "\n";
std::cout << "\tcenter: " << c.center().transpose() << "\n";
std::cout << "\tAtoms:\n";
for (auto const& a : c.collapse()) {
std::cout << "\t\t" << a.atomic_number << " " << center(a).transpose()
<< "\n";
}
std::cout << std::flush;
++i;
}
return 0;
}
|
/**
* Handles the persistence of LimboPlayers.
*/
public class LimboPersistence implements SettingsDependent {
private final Factory<LimboPersistenceHandler> handlerFactory;
private LimboPersistenceHandler handler;
@Inject
LimboPersistence(Settings settings, Factory<LimboPersistenceHandler> handlerFactory) {
this.handlerFactory = handlerFactory;
reload(settings);
}
/**
* Retrieves the LimboPlayer for the given player if available.
*
* @param player the player to retrieve the LimboPlayer for
* @return the player's limbo player, or null if not available
*/
public LimboPlayer getLimboPlayer(Player player) {
try {
return handler.getLimboPlayer(player);
} catch (Exception e) {
ConsoleLogger.logException("Could not get LimboPlayer for '" + player.getName() + "'", e);
}
return null;
}
/**
* Saves the given LimboPlayer for the provided player.
*
* @param player the player to save the LimboPlayer for
* @param limbo the limbo player to save
*/
public void saveLimboPlayer(Player player, LimboPlayer limbo) {
try {
handler.saveLimboPlayer(player, limbo);
} catch (Exception e) {
ConsoleLogger.logException("Could not save LimboPlayer for '" + player.getName() + "'", e);
}
}
/**
* Removes the LimboPlayer for the given player.
*
* @param player the player whose LimboPlayer should be removed
*/
public void removeLimboPlayer(Player player) {
try {
handler.removeLimboPlayer(player);
} catch (Exception e) {
ConsoleLogger.logException("Could not remove LimboPlayer for '" + player.getName() + "'", e);
}
}
@Override
public void reload(Settings settings) {
LimboPersistenceType persistenceType = settings.getProperty(LimboSettings.LIMBO_PERSISTENCE_TYPE);
// If we're changing from an existing handler, output a quick hint that nothing is converted.
if (handler != null && handler.getType() != persistenceType) {
ConsoleLogger.info("Limbo persistence type has changed! Note that the data is not converted.");
}
handler = handlerFactory.newInstance(persistenceType.getImplementationClass());
}
} |
import pytest
from flask import Blueprint
from flask_controller_bundle import Controller, Resource
from flask_controller_bundle.attr_constants import (
CONTROLLER_ROUTES_ATTR, FN_ROUTES_ATTR)
from flask_controller_bundle.decorators import route as route_decorator
from flask_controller_bundle.routes import (
controller, func, include, resource, _normalize_args)
bp = Blueprint('test', __name__)
bp2 = Blueprint('test2', __name__)
def undecorated_view():
pass
@route_decorator
def decorated_view():
pass
@route_decorator('/first', endpoint='first')
@route_decorator('/second', endpoint='second')
def multi_route_view():
pass
@route_decorator(endpoint='default')
@route_decorator('/first', endpoint='first')
@route_decorator('/second', endpoint='second')
def implicit_multi_route_view():
pass
class SiteController(Controller):
@route_decorator('/')
def index(self):
pass
def about(self):
pass
class UserResource(Resource):
def list(self):
pass
def get(self, id):
pass
class RoleResource(Resource):
def list(self):
pass
def get(self, id):
pass
class TestController:
def test_it_works_with_only_a_controller_cls(self):
routes = list(controller(SiteController))
assert len(routes) == 2
assert routes[0].endpoint == 'site_controller.index'
assert routes[0].rule == '/'
assert routes[1].endpoint == 'site_controller.about'
assert routes[1].rule == '/about'
def test_it_works_with_a_prefix_and_controller_cls(self):
routes = list(controller('/prefix', SiteController))
assert len(routes) == 2
assert routes[0].endpoint == 'site_controller.index'
assert routes[0].rule == '/prefix'
assert routes[1].endpoint == 'site_controller.about'
assert routes[1].rule == '/prefix/about'
def test_it_requires_a_controller_cls(self):
with pytest.raises(ValueError):
list(controller('/fail'))
with pytest.raises(ValueError):
list(controller('/fail', None))
with pytest.raises(ValueError):
list(controller(None))
with pytest.raises(ValueError):
list(controller(None, SiteController))
with pytest.raises(TypeError):
list(controller(UserResource))
with pytest.raises(TypeError):
list(controller('/users', UserResource))
def test_it_does_not_mutate_existing_routes(self):
routes = list(controller('/prefix', SiteController))
orig_routes = [route
for routes in getattr(SiteController,
CONTROLLER_ROUTES_ATTR).values()
for route in routes]
assert orig_routes[0].endpoint == routes[0].endpoint
assert orig_routes[0].rule == '/'
assert routes[0].rule == '/prefix'
class TestFunc:
def test_it_works_with_undecorated_view(self):
route = list(func(undecorated_view))[0]
assert route.view_func == undecorated_view
assert route.rule == '/undecorated-view'
assert route.blueprint is None
assert route.endpoint == 'tests.test_routes.undecorated_view'
assert route.defaults is None
assert route.methods == ['GET']
assert route.only_if is None
def test_override_rule_options_with_undecorated_view(self):
route = list(func('/a/<id>', undecorated_view, blueprint=bp,
endpoint='overridden.endpoint',
defaults={'id': 1}, methods=['GET', 'POST'],
only_if='only_if'))[0]
assert route.rule == '/a/<id>'
assert route.view_func == undecorated_view
assert route.blueprint == bp
assert route.endpoint == 'overridden.endpoint'
assert route.defaults == {'id': 1}
assert route.methods == ['GET', 'POST']
assert route.only_if is 'only_if'
def test_it_works_with_decorated_view(self):
route = list(func(decorated_view))[0]
assert route.view_func == decorated_view
assert route.rule == '/decorated-view'
assert route.blueprint is None
assert route.endpoint == 'tests.test_routes.decorated_view'
assert route.defaults is None
assert route.methods == ['GET']
assert route.only_if is None
def test_override_rule_options_with_decorated_view(self):
route = list(func('/b/<id>', decorated_view, blueprint=bp,
endpoint='overridden.endpoint',
defaults={'id': 1}, methods=['GET', 'POST'],
only_if='only_if'))[0]
assert route.rule == '/b/<id>'
assert route.view_func == decorated_view
assert route.blueprint == bp
assert route.endpoint == 'overridden.endpoint'
assert route.defaults == {'id': 1}
assert route.methods == ['GET', 'POST']
assert route.only_if == 'only_if'
def test_it_requires_a_callable(self):
with pytest.raises(ValueError):
list(func('/fail'))
with pytest.raises(ValueError):
list(func('/fail', None))
with pytest.raises(ValueError):
list(func(None))
with pytest.raises(ValueError):
list(func(None, undecorated_view))
def test_it_makes_new_route_if_decorated_with_multiple_other_routes(self):
route = list(func(multi_route_view))[0]
assert route.endpoint == 'tests.test_routes.multi_route_view'
def test_it_reuses_route_if_url_matches_a_decorated_route(self):
route = list(func('/first', multi_route_view, methods=['PUT']))[0]
assert route.methods == ['PUT']
assert route.endpoint == 'first'
def test_it_reuses_route_url_implicitly_matches(self):
route = list(func(implicit_multi_route_view))[0]
assert route.endpoint == 'default'
def test_it_does_not_mutate_existing_routes(self):
route = list(func('/foo', decorated_view))[0]
orig_route = getattr(decorated_view, FN_ROUTES_ATTR)[0]
assert orig_route.endpoint == route.endpoint
assert orig_route.rule == '/decorated-view'
assert route.rule == '/foo'
class TestInclude:
def test_it_raises_if_no_routes_found(self):
with pytest.raises(ImportError):
# trying to import this.should.fail prints the zen of python!
list(include('should.not.exist'))
with pytest.raises(AttributeError):
list(include('tests.fixtures.routes'))
with pytest.raises(AttributeError):
list(include('tests.fixtures.routes', attr='fail'))
def test_it_only_includes_only(self):
routes = list(include('tests.fixtures.other_routes',
only=['views.one']))
assert len(routes) == 1
assert routes[0].endpoint == 'views.one'
def test_it_does_not_include_excludes(self):
routes = list(include('tests.fixtures.other_routes',
exclude=['views.three']))
assert len(routes) == 2
assert routes[0].endpoint == 'views.one'
assert routes[1].endpoint == 'views.two'
class TestResource:
def test_it_works_with_only_resource(self):
routes = list(resource(UserResource))
assert len(routes) == 2
assert routes[0].endpoint == 'user_resource.list'
assert routes[0].rule == '/users'
assert routes[1].endpoint == 'user_resource.get'
assert routes[1].rule == '/users/<int:id>'
def test_it_works_with_a_prefix(self):
routes = list(resource('/prefix', UserResource))
assert len(routes) == 2
assert routes[0].endpoint == 'user_resource.list'
assert routes[0].rule == '/prefix'
assert routes[1].endpoint == 'user_resource.get'
assert routes[1].rule == '/prefix/<int:id>'
def test_it_requires_a_controller(self):
with pytest.raises(ValueError):
list(resource('/fail'))
with pytest.raises(ValueError):
list(resource('/fail', None))
with pytest.raises(ValueError):
list(resource(None))
with pytest.raises(ValueError):
list(resource(None, UserResource))
def test_it_does_not_mutate_existing_routes(self):
routes = list(resource('/prefix', UserResource))
orig_routes = [route
for routes in getattr(UserResource,
CONTROLLER_ROUTES_ATTR).values()
for route in routes]
assert orig_routes[0].endpoint == routes[0].endpoint
assert orig_routes[0].rule == '/'
assert routes[0].rule == '/prefix'
def test_it_does_not_mutate_subresource_routes(self):
routes = list(resource('/one', UserResource, subresources=[
resource('/two', RoleResource)
]))
orig_routes = [route
for routes in getattr(RoleResource,
CONTROLLER_ROUTES_ATTR).values()
for route in routes]
assert orig_routes[0].endpoint == routes[2].endpoint
assert orig_routes[0].rule == '/'
assert routes[2].rule == '/one/<int:user_id>/two'
def test_it_warns_if_overriding_subresource_bp_with_none(self):
class UserResource(Resource):
blueprint = None
def list(self):
pass
class RoleResource(Resource):
blueprint = bp
def list(self):
pass
with pytest.warns(None) as warnings:
list(resource('/one', UserResource, subresources=[
resource('/two', RoleResource)
]))
msg = "overriding subresource blueprint 'test' with None"
assert msg in str(warnings[0])
def test_it_warns_if_overriding_subresource_bp_with_another_bp(self):
class UserResource(Resource):
blueprint = bp
def list(self):
pass
class RoleResource(Resource):
blueprint = bp2
def list(self):
pass
with pytest.warns(None) as warnings:
list(resource('/one', UserResource, subresources=[
resource('/two', RoleResource)
]))
msg = "overriding subresource blueprint 'test2' with 'test'"
assert msg in str(warnings[0])
def test_normalize_args():
def is_bp(maybe_bp, has_rule):
return isinstance(maybe_bp, Blueprint)
assert _normalize_args(bp, None, is_bp) == (None, bp)
assert _normalize_args('str', bp, is_bp) == ('str', bp)
# this use case makes no sense, but it completes coverage
assert _normalize_args(None, 'str', lambda *args, **kw: False) is None
assert _normalize_args('str', None, lambda *args, **kw: False) is None
|
class DownloadLink:
def __init__(self, folder_name: str, file_name: str) -> None:
self.folder_name = folder_name.replace('\\\\', '\\')
self.file_name = file_name
def download_path(self):
return f'/Simulate/Download?folderName={self.folder_name}&fileName={self.file_name}' |
package compiler
import (
"io"
"strings"
"github.com/adnsv/go-build/compiler/clang"
"github.com/adnsv/go-build/compiler/gcc"
"github.com/adnsv/go-build/compiler/msvc"
"github.com/adnsv/go-build/compiler/toolchain"
)
type Installation interface {
PrintSummary(w io.Writer)
}
func DiscoverInstallations(types []string, feedback func(string)) []Installation {
ret := []Installation{}
if fltShow("msvc", types) {
ii, _ := msvc.DiscoverInstallations(feedback)
for _, i := range ii {
ret = append(ret, i)
}
}
if fltShow("gcc", types) || fltShow("gnu", types) {
ii := gcc.DiscoverInstallations(feedback)
for _, i := range ii {
ret = append(ret, i)
}
}
if fltShow("clang", types) || fltShow("llvm", types) {
ii := clang.DiscoverInstallations(feedback)
for _, i := range ii {
ret = append(ret, i)
}
}
return ret
}
func DiscoverToolchains(wantCxx bool, types []string, feedback func(string)) []*toolchain.Chain {
ret := []*toolchain.Chain{}
if fltShow("msvc", types) {
ret = append(ret, msvc.DiscoverToolchains(feedback)...)
}
if fltShow("gcc", types) || fltShow("gnu", types) {
ret = append(ret, gcc.DiscoverToolchains(wantCxx, feedback)...)
}
if fltShow("clang", types) || fltShow("llvm", types) {
ret = append(ret, clang.DiscoverToolchains(wantCxx, feedback)...)
}
return ret
}
func archNorm(arch string) string {
var archNorm = map[string]string{
"x64": "x64",
"amd64": "x64",
"x86_64": "x64",
"x32": "x32",
"86": "x32",
"x86": "x32",
"386": "x32",
"486": "x32",
"586": "x32",
"686": "x32",
"arm": "arm32",
"arm32": "arm32",
"arm64": "arm64",
"aarch64": "arm64",
}
arch = strings.ToLower(arch)
if norm, ok := archNorm[arch]; ok {
arch = norm
}
return arch
}
func FindArch(arch string, tt []*toolchain.Chain) []*toolchain.Chain {
arch = archNorm(arch)
ret := []*toolchain.Chain{}
for _, t := range tt {
if t.Compiler == "MSVC" {
if arch == archNorm(t.VisualStudioArch) {
ret = append(ret, t)
}
} else {
pp := strings.Split(t.Target, "-")
if len(pp) > 0 && arch == archNorm(pp[0]) {
ret = append(ret, t)
}
}
}
return ret
}
func fltShow(t string, tt []string) bool {
if len(tt) == 0 || (len(tt) == 1 && tt[0] == "") {
return true
}
for _, it := range tt {
if it == t {
return true
}
}
return false
}
|
<reponame>spremi/build-smith<gh_stars>1-10
//
// [build-smith-client]
//
// <NAME> <<EMAIL>>
//
// Available under terms of the BSD-3-Clause license.
//
import { initEmailNotification, EmailNotification } from './notifications';
import { ProjectRepo } from './repo';
import { initTriggers, Triggers } from './triggers';
import { initWorkspace, Workspace } from './workspace';
/**
* Access permissions of a project.
*/
export class ProjectAccess {
/** Can be viewed by any user. */
public static readonly PUBLIC = 'P';
/** Can be viewed by verified users only. */
public static readonly VERIFIED = 'V';
/** Can be viewed by specific users only. */
public static readonly SPECIFIC = 'S';
/** Can be viewed by admins only. */
public static readonly ADMIN = 'A';
}
/**
* Health rating of a project.
*/
export class ProjectHealth {
/** None of 5 recent builds passed. */
public static readonly LEVEL0 = 'L0';
/** 1 of 5 recent builds passed. */
public static readonly LEVEL1 = 'L1';
/** 2 of 5 recent builds passed. */
public static readonly LEVEL2 = 'L2';
/** 3 of 5 recent builds passed. */
public static readonly LEVEL3 = 'L3';
/** 4 of 5 recent builds passed. */
public static readonly LEVEL4 = 'L4';
/** All of recent 5 builds passed. */
public static readonly LEVEL5 = 'L5';
}
/**
* Status of a project.
*/
export class ProjectStatus {
/** Never built. */
public static readonly NEVER = 'never';
/** Build is in progress. */
public static readonly ONGOING = 'ongoing';
/** Previous build was successful. */
public static readonly SUCCESS = 'success';
/** Previous build failed. */
public static readonly FALIURE = 'failure';
/** Previous build was aborted. */
public static readonly ABORT = 'abort';
/** Builds are disabled. */
public static readonly DISABLED = 'disabled';
}
/**
* Build related information for a project.
*/
export interface ProjectBuildInfo {
/** Identifier for latest build. */
latest: string;
/** Identifier for last successful build. */
lastSuccess: string;
/** Identifier for last failed build. */
lastFailure: string;
/** Duration of latest build (in seconds). */
lastDuration: number;
}
/**
* Initializer for interface 'ProjectBuildInfo'.
*/
export const initProjectBuildInfo = (): ProjectBuildInfo => ({
latest: null,
lastSuccess: null,
lastFailure: null,
lastDuration: 0,
});
/**
* Brief information about a project.
*/
export interface ProjectBrief {
/** Project identifier. */
id: string;
/** Project name. */
name: string;
/** Short description. */
desc: string;
/** Is project enabled? */
enabled: boolean;
/** Project status. */
status: ProjectStatus;
/** Project health. */
health: ProjectHealth;
/** Build information */
build: ProjectBuildInfo;
}
/**
* Initializer for interface 'ProjectBrief'.
*/
export const initProjectBrief = (): ProjectBrief => ({
id: null,
name: null,
desc: null,
enabled: false,
status: ProjectStatus.NEVER,
health: ProjectHealth.LEVEL0,
build: initProjectBuildInfo(),
});
/**
* Project permissions.
*/
export interface ProjectPermissions {
/** Project access. */
access: ProjectAccess;
/** List of users with UserRoles.OBSERVER access. */
viewers: string[];
/** List of users with UserRoles.BUILDER access. */
builders: string[];
/** List of users with UserRoles.ADMIN access. */
admins: string[];
}
/**
* Initializer for interface 'ProjectPermissions'.
*/
export const initProjectPermissions = (): ProjectPermissions => ({
access: ProjectAccess.SPECIFIC,
viewers: [],
builders: [],
admins: [],
});
/**
* Project notifications.
*/
export interface ProjectNotifications {
/** Notify via Email. */
useEmail: boolean;
/** Data related to email notifications. */
emailData: EmailNotification;
}
/**
* Initializer for interface 'ProjectNotifications'.
*/
export const initProjectNotifications = (): ProjectNotifications => ({
useEmail: false,
emailData: initEmailNotification(),
});
/**
* Detailed information about a project.
*/
export interface Project extends ProjectBrief {
/** Source repositories in the project. */
repos: ProjectRepo[];
/** Permissions. */
perms: ProjectPermissions;
/** Triggers. */
triggers: Triggers;
/** Workspace. */
workspace: Workspace;
/** Notifications. */
notifications: ProjectNotifications;
}
/**
* Initializer for interface 'Project'.
*/
export const initProject = (): Project => ({
...initProjectBrief(),
repos: [],
perms: initProjectPermissions(),
triggers: initTriggers(),
workspace: initWorkspace(),
notifications: initProjectNotifications(),
});
|
package com.github.hiwepy.soap.type;
import java.util.Arrays;
import java.util.List;
public enum SoapTypes {
string("字符串(string,java.lang.String)", new StringSoapType()),
number("数字(number,java.lang.Integer,java.lang.Long,java.math.BigDecimal)", new NumberSoapType()),
date("时间/日期(date,java.util.Date,dateTime)", new DateSoapType()),
bean("复合类型(bean,serializable)", new BeanSoapType()),
list("列表类型(List)", new ListSoapType());
private SoapType soapType;
private String name;
private SoapTypes(String name, SoapType soapType) {
this.name = name;
this.soapType = soapType;
}
public SoapType getSoapType() {
return this.soapType;
}
public String getName() {
return this.name;
}
public String toString() {
return name();
}
public static SoapType getTypeByBean(Class<?> klass) {
if (klass == null) {
return bean.getSoapType();
}
for (SoapTypes types : values()) {
if (Arrays.asList(types.getSoapType().getBeanTypes()).contains(klass)) {
return types.getSoapType();
}
}
return bean.getSoapType();
}
public static SoapType getTypeBySoap(String type) {
if (type == null) {
return bean.getSoapType();
}
if (type.matches("List\\{\\w*\\}")) {
return new ListSoapType();
}
for (SoapTypes types : values()) {
if (Arrays.asList(types.getSoapType().getSoapTypes()).contains(type)) {
return types.getSoapType();
}
}
return bean.getSoapType();
}
}
|
// MustHaveResponse checks the Response field, panics if the field is not initialized.
func (s *ApiState) MustHaveResponse() {
if s.Response == nil {
PanicApiError(s, nil, "ApiState.Response not initialized")
}
} |
// Repr return cluster string representation according to format
func (c *Cluster) Repr(format string) (s string) {
switch format {
case "yaml", "y":
return c.YAML()
case "json", "j":
return c.JSON()
case "detail", "d", "summary", "s":
return c.Summary()
default:
return c.String()
}
} |
<filename>src/storage/f2fs/inline.cc<gh_stars>100-1000
// Copyright 2021 The Fuchsia 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 <dirent.h>
#include "src/storage/f2fs/f2fs.h"
namespace f2fs {
namespace {
inline InlineDentry *GetInlineDentryAddr(Page *page) {
Node *rn = static_cast<Node *>(PageAddress(page));
Inode &ri = rn->i;
return reinterpret_cast<InlineDentry *>(&(ri.i_addr[1]));
}
} // namespace
DirEntry *Dir::FindInInlineDir(const std::string_view &name, Page **res_page) {
Page *node_page = nullptr;
if (zx_status_t ret = Vfs()->Nodemgr().GetNodePage(Ino(), &node_page); ret != ZX_OK)
return nullptr;
f2fs_hash_t namehash = DentryHash(name.data(), name.length());
InlineDentry *dentry_blk = GetInlineDentryAddr(node_page);
DirEntry *de = nullptr;
for (uint64_t bit_pos = 0; bit_pos < kNrInlineDentry;) {
bit_pos = FindNextBit(dentry_blk->dentry_bitmap, kNrInlineDentry, bit_pos);
if (bit_pos >= kNrInlineDentry)
break;
de = &dentry_blk->dentry[bit_pos];
if (EarlyMatchName(name.data(), name.length(), namehash, de)) {
if (!memcmp(dentry_blk->filename[bit_pos], name.data(), name.length())) {
*res_page = node_page;
#if 0 // porting needed
// unlock_page(node_page);
#endif
return de;
}
}
// For the most part, it should be a bug when name_len is zero.
// We stop here for figuring out where the bugs are occurred.
#if 0 // porting needed
// f2fs_bug_on(F2FS_P_SB(node_page), !de->name_len);
#else
ZX_ASSERT(de->name_len > 0);
#endif
bit_pos += GetDentrySlots(LeToCpu(de->name_len));
}
de = nullptr;
F2fsPutPage(node_page, 0);
#if 0 // porting needed
// unlock_page(node_page);
#endif
return de;
}
DirEntry *Dir::ParentInlineDir(Page **p) {
Page *node_page = nullptr;
if (zx_status_t ret = Vfs()->Nodemgr().GetNodePage(Ino(), &node_page); ret != ZX_OK)
return nullptr;
InlineDentry *dentry_blk = GetInlineDentryAddr(node_page);
DirEntry *de = &dentry_blk->dentry[1];
*p = node_page;
#if 0 // porting needed
unlock_page(node_page);
#endif
return de;
}
zx_status_t Dir::MakeEmptyInlineDir(VnodeF2fs *vnode, VnodeF2fs *parent) {
Page *ipage = nullptr;
if (zx_status_t err = Vfs()->Nodemgr().GetNodePage(vnode->Ino(), &ipage); err != ZX_OK)
return err;
InlineDentry *dentry_blk = GetInlineDentryAddr(ipage);
DirEntry *de = &dentry_blk->dentry[0];
de->name_len = CpuToLe(static_cast<uint16_t>(1));
de->hash_code = 0;
de->ino = CpuToLe(vnode->Ino());
memcpy(dentry_blk->filename[0], ".", 1);
SetDeType(de, vnode);
de = &dentry_blk->dentry[1];
de->hash_code = 0;
de->name_len = CpuToLe(static_cast<uint16_t>(2));
de->ino = CpuToLe(parent->Ino());
memcpy(dentry_blk->filename[1], "..", 2);
SetDeType(de, vnode);
TestAndSetBit(0, dentry_blk->dentry_bitmap);
TestAndSetBit(1, dentry_blk->dentry_bitmap);
#if 0 // porting needed
// set_page_dirty(ipage);
#else
FlushDirtyNodePage(Vfs(), ipage);
#endif
if (vnode->GetSize() < kMaxInlineData) {
vnode->SetSize(kMaxInlineData);
vnode->SetFlag(InodeInfoFlag::kUpdateDir);
}
F2fsPutPage(ipage, 1);
return ZX_OK;
}
unsigned int Dir::RoomInInlineDir(InlineDentry *dentry_blk, int slots) {
int bit_start = 0;
while (true) {
int zero_start = FindNextZeroBit(dentry_blk->dentry_bitmap, kNrInlineDentry, bit_start);
if (zero_start >= static_cast<int>(kNrInlineDentry))
return kNrInlineDentry;
int zero_end = FindNextBit(dentry_blk->dentry_bitmap, kNrInlineDentry, zero_start);
if (zero_end - zero_start >= slots)
return zero_start;
bit_start = zero_end + 1;
if (zero_end + 1 >= static_cast<int>(kNrInlineDentry))
return kNrInlineDentry;
}
}
zx_status_t Dir::ConvertInlineDir(InlineDentry *inline_dentry) {
Page *page;
if (page = GrabCachePage(this, Ino(), 0); page == nullptr)
return ZX_ERR_NO_MEMORY;
DnodeOfData dn;
SetNewDnode(&dn, this, nullptr, nullptr, 0);
if (zx_status_t err = Vfs()->Nodemgr().GetDnodeOfData(&dn, 0, 0); err != ZX_OK)
return err;
if (dn.data_blkaddr == kNullAddr) {
if (zx_status_t err = ReserveNewBlock(&dn); err != ZX_OK) {
F2fsPutPage(page, 1);
F2fsPutDnode(&dn);
return err;
}
}
F2fsPutDnode(&dn);
WaitOnPageWriteback(page);
ZeroUserSegment(page, 0, kPageCacheSize);
DentryBlock *dentry_blk = static_cast<DentryBlock *>(PageAddress(page));
/* copy data from inline dentry block to new dentry block */
memcpy(dentry_blk->dentry_bitmap, inline_dentry->dentry_bitmap, kInlineDentryBitmapSize);
memcpy(dentry_blk->dentry, inline_dentry->dentry, sizeof(DirEntry) * kNrInlineDentry);
memcpy(dentry_blk->filename, inline_dentry->filename, kNrInlineDentry * kNameLen);
// TODO: inode update after data page flush
// Since there is no pager, inode information in UpdateInode and FlushDirtyDataPage are not
// synchronized. So, inode update should run first, then FlushDirtyDataPage will use correct inode
// information. When pager is available, inode update can run after setting data page dirty
Page *ipage = nullptr;
if (zx_status_t err = Vfs()->Nodemgr().GetNodePage(Ino(), &ipage); err != ZX_OK)
return err;
// clear inline dir and flag after data writeback
ZeroUserSegment(ipage, kInlineDataOffset, kInlineDataOffset + kMaxInlineData);
ClearFlag(InodeInfoFlag::kInlineDentry);
if (GetSize() < kPageCacheSize) {
SetSize(kPageCacheSize);
SetFlag(InodeInfoFlag::kUpdateDir);
}
UpdateInode(ipage);
F2fsPutPage(ipage, 1);
#if 0 // porting needed
// kunmap(page);
#endif
SetPageUptodate(page);
#if 0 // porting needed
// set_page_dirty(page);
#else
FlushDirtyDataPage(Vfs(), page);
#endif
#if 0 // porting needed
// stat_dec_inline_inode(dir);
#endif
F2fsPutPage(page, 1);
return ZX_OK;
}
zx_status_t Dir::AddInlineEntry(std::string_view name, VnodeF2fs *vnode, bool *is_converted) {
*is_converted = false;
f2fs_hash_t name_hash = DentryHash(name.data(), name.length());
Page *ipage = nullptr;
if (zx_status_t err = Vfs()->Nodemgr().GetNodePage(Ino(), &ipage); err != ZX_OK)
return err;
InlineDentry *dentry_blk = GetInlineDentryAddr(ipage);
int slots = GetDentrySlots(name.length());
unsigned int bit_pos = RoomInInlineDir(dentry_blk, slots);
if (bit_pos >= kNrInlineDentry) {
ZX_ASSERT(ConvertInlineDir(dentry_blk) == ZX_OK);
*is_converted = true;
F2fsPutPage(ipage, 1);
return ZX_OK;
}
WaitOnPageWriteback(ipage);
#if 0 // porting needed
// down_write(&F2FS_I(inode)->i_sem);
#endif
if (zx_status_t err = InitInodeMetadata(vnode); err != ZX_OK) {
#if 0 // porting needed
// up_write(&F2FS_I(inode)->i_sem);
#endif
if (TestFlag(InodeInfoFlag::kUpdateDir)) {
UpdateInode(ipage);
ClearFlag(InodeInfoFlag::kUpdateDir);
}
F2fsPutPage(ipage, 1);
return err;
}
DirEntry *de = &dentry_blk->dentry[bit_pos];
de->hash_code = name_hash;
de->name_len = CpuToLe(name.length());
memcpy(dentry_blk->filename[bit_pos], name.data(), name.length());
de->ino = CpuToLe(vnode->Ino());
SetDeType(de, vnode);
for (int i = 0; i < slots; i++)
TestAndSetBit(bit_pos + i, dentry_blk->dentry_bitmap);
#if 0 // porting needed
// set_page_dirty(ipage);
#else
FlushDirtyNodePage(Vfs(), ipage);
#endif
vnode->SetParentNid(Ino());
vnode->UpdateInode(ipage);
UpdateParentMetadata(vnode, 0);
#if 0 // porting needed
// up_write(&F2FS_I(inode)->i_sem);
#endif
if (TestFlag(InodeInfoFlag::kUpdateDir)) {
WriteInode(nullptr);
ClearFlag(InodeInfoFlag::kUpdateDir);
}
F2fsPutPage(ipage, 1);
return ZX_OK;
}
void Dir::DeleteInlineEntry(DirEntry *dentry, Page *page, VnodeF2fs *vnode) {
#if 0 // porting needed
// lock_page(page);
#endif
WaitOnPageWriteback(page);
InlineDentry *inline_dentry = GetInlineDentryAddr(page);
unsigned int bit_pos = dentry - inline_dentry->dentry;
int slots = GetDentrySlots(LeToCpu(dentry->name_len));
for (int i = 0; i < slots; i++)
TestAndClearBit(bit_pos + i, inline_dentry->dentry_bitmap);
#if 0 // porting needed
// set_page_dirty(page);
#else
FlushDirtyNodePage(Vfs(), page);
#endif
if (vnode) {
timespec cur_time;
clock_gettime(CLOCK_REALTIME, &cur_time);
SetCTime(cur_time);
SetMTime(cur_time);
vnode->SetCTime(cur_time);
vnode->DropNlink();
if (vnode->IsDir()) {
vnode->DropNlink();
vnode->SetSize(0);
}
vnode->WriteInode(NULL);
if (vnode->GetNlink() == 0)
Vfs()->AddOrphanInode(vnode);
}
F2fsPutPage(page, 1);
}
bool Dir::IsEmptyInlineDir() {
Page *ipage = nullptr;
if (zx_status_t err = Vfs()->Nodemgr().GetNodePage(Ino(), &ipage); err != ZX_OK)
return false;
InlineDentry *dentry_blk = GetInlineDentryAddr(ipage);
unsigned int bit_pos = 2;
bit_pos = FindNextBit(dentry_blk->dentry_bitmap, kNrInlineDentry, bit_pos);
F2fsPutPage(ipage, 1);
if (bit_pos < kNrInlineDentry)
return false;
return true;
}
zx_status_t Dir::ReadInlineDir(fs::VdirCookie *cookie, void *dirents, size_t len,
size_t *out_actual) {
fs::DirentFiller df(dirents, len);
uint64_t *pos_cookie = reinterpret_cast<uint64_t *>(cookie);
if (*pos_cookie == kNrInlineDentry) {
*out_actual = 0;
return ZX_OK;
}
Page *ipage = nullptr;
if (zx_status_t err = Vfs()->Nodemgr().GetNodePage(Ino(), &ipage); err != ZX_OK)
return err;
const unsigned char *types = kFiletypeTable;
unsigned int bit_pos = *pos_cookie % kNrInlineDentry;
InlineDentry *inline_dentry = GetInlineDentryAddr(ipage);
while (bit_pos < kNrInlineDentry) {
bit_pos = FindNextBit(inline_dentry->dentry_bitmap, kNrInlineDentry, bit_pos);
if (bit_pos >= kNrInlineDentry)
break;
DirEntry *de = &inline_dentry->dentry[bit_pos];
unsigned char d_type = DT_UNKNOWN;
if (de->file_type < static_cast<uint8_t>(FileType::kFtMax))
d_type = types[de->file_type];
std::string_view name(reinterpret_cast<char *>(inline_dentry->filename[bit_pos]),
LeToCpu(de->name_len));
if (de->ino && name != "..") {
if (zx_status_t ret = df.Next(name, d_type, LeToCpu(de->ino)); ret != ZX_OK) {
*pos_cookie = bit_pos;
F2fsPutPage(ipage, 1);
*out_actual = df.BytesFilled();
return ZX_OK;
}
}
bit_pos += GetDentrySlots(LeToCpu(de->name_len));
*pos_cookie = bit_pos;
}
*pos_cookie = kNrInlineDentry;
F2fsPutPage(ipage, 1);
*out_actual = df.BytesFilled();
return ZX_OK;
}
} // namespace f2fs
|
//Confirm that the active FSN has 1 x US acceptability == preferred
private void fixFsnAcceptability(Concept c) throws TermServerScriptException {
List<Description> fsns = c.getDescriptions(Acceptability.BOTH, DescriptionType.FSN, ActiveState.ACTIVE);
if (fsns.size() != 1) {
String msg = "Concept has " + fsns.size() + " active fsns";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
} else {
String msg = "[" + fsns.get(0).getDescriptionId() + "]: ";
List<LangRefsetEntry> langRefEntries = fsns.get(0).getLangRefsetEntries(ActiveState.BOTH, US_ENG_LANG_REFSET);
if (langRefEntries.size() != 1) {
if (langRefEntries.size() == 2) {
List<LangRefsetEntry> uslangRefEntries = fsns.get(0).getLangRefsetEntries(ActiveState.BOTH, refsets, SCTID_US_MODULE);
List<LangRefsetEntry> corelangRefEntries = fsns.get(0).getLangRefsetEntries(ActiveState.BOTH, refsets, SCTID_CORE_MODULE);
if (uslangRefEntries.size() > 1 || corelangRefEntries.size() >1) {
msg += "Two acceptabilities in the same module";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
} else {
if (!uslangRefEntries.get(0).isActive() && corelangRefEntries.get(0).isActive() ) {
long usET = Long.parseLong(uslangRefEntries.get(0).getEffectiveTime());
long coreET = Long.parseLong(corelangRefEntries.get(0).getEffectiveTime());
msg += "US langrefset entry inactivated " + (usET > coreET ? "after":"before") + " core row activated - " + usET;
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
uslangRefEntries.get(0).setActive(true);
c.setModified();
String action = "Reactivated US FSN LangRefset entry";
report(c, c.getFSNDescription(), Severity.MEDIUM, ReportActionType.DESCRIPTION_CHANGE_MADE, action);
} else {
msg += "Unexpected configuration of us and core lang refset entries";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
}
}
} else {
msg += "FSN has " + langRefEntries.size() + " US acceptability values.";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
}
} else if (!langRefEntries.get(0).getAcceptabilityId().equals(SCTID_PREFERRED_TERM)) {
msg += "FSN has an acceptability that is not Preferred.";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
} else if (!langRefEntries.get(0).isActive()) {
msg += "FSN's US acceptability is inactive.";
report(c, c.getFSNDescription(), Severity.HIGH, ReportActionType.VALIDATION_CHECK, msg);
}
}
} |
declare namespace Browser {
interface Aptitude {
listenNavigation: Common.Listenable<NavigationDetails>;
listenTextSelection: Common.Listenable<string>;
openTab: Common.ReadableWithParam<string, number>;
openWindow: Common.ReadableWithParam<string, number>;
}
interface NavigationDetails {
frameId: number;
parentFrameId: number;
tabId: number;
timestamp: number;
url: string;
}
}
|
<gh_stars>0
// sheetView
use super::BooleanValue;
use super::EnumValue;
use super::Pane;
use super::Selection;
use super::SheetViewValues;
use super::UInt32Value;
use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;
use quick_xml::Writer;
use reader::driver::*;
use std::io::Cursor;
use writer::driver::*;
#[derive(Clone, Default, Debug)]
pub struct SheetView {
tab_selected: BooleanValue,
workbook_view_id: UInt32Value,
pane: Option<Pane>,
view: EnumValue<SheetViewValues>,
zoom_scale: UInt32Value,
zoom_scale_normal: UInt32Value,
zoom_scale_page_layout_view: UInt32Value,
zoom_scale_sheet_layout_view: UInt32Value,
selection: Vec<Selection>,
}
impl SheetView {
pub fn get_tab_selected(&self) -> &bool {
self.tab_selected.get_value()
}
pub fn set_tab_selected(&mut self, value: bool) -> &mut Self {
self.tab_selected.set_value(value);
self
}
pub fn get_workbook_view_id(&self) -> &u32 {
self.workbook_view_id.get_value()
}
pub fn set_workbook_view_id(&mut self, value: u32) -> &mut Self {
self.workbook_view_id.set_value(value);
self
}
pub fn get_pane(&self) -> &Option<Pane> {
&self.pane
}
pub fn get_pane_mut(&mut self) -> &mut Option<Pane> {
&mut self.pane
}
pub fn set_pane(&mut self, value: Pane) -> &mut Self {
self.pane = Some(value);
self
}
pub fn get_view(&self) -> &SheetViewValues {
self.view.get_value()
}
pub fn set_view(&mut self, value: SheetViewValues) -> &mut Self {
self.view.set_value(value);
self
}
pub fn get_zoom_scale(&self) -> &u32 {
self.zoom_scale.get_value()
}
pub fn set_zoom_scale(&mut self, value: u32) -> &mut Self {
self.zoom_scale.set_value(value);
self
}
pub fn get_zoom_scale_normal(&self) -> &u32 {
self.zoom_scale_normal.get_value()
}
pub fn set_zoom_scale_normal(&mut self, value: u32) -> &mut Self {
self.zoom_scale_normal.set_value(value);
self
}
pub fn get_zoom_scale_page_layout_view(&self) -> &u32 {
self.zoom_scale_page_layout_view.get_value()
}
pub fn set_zoom_scale_page_layout_view(&mut self, value: u32) -> &mut Self {
self.zoom_scale_page_layout_view.set_value(value);
self
}
pub fn get_zoom_scale_sheet_layout_view(&self) -> &u32 {
self.zoom_scale_sheet_layout_view.get_value()
}
pub fn set_zoom_scale_sheet_layout_view(&mut self, value: u32) -> &mut Self {
self.zoom_scale_sheet_layout_view.set_value(value);
self
}
pub fn get_selection(&self) -> &Vec<Selection> {
&self.selection
}
pub fn get_selection_mut(&mut self) -> &mut Vec<Selection> {
&mut self.selection
}
pub fn set_selection(&mut self, value: Selection) -> &mut Self {
self.selection.push(value);
self
}
pub(crate) fn set_attributes<R: std::io::BufRead>(
&mut self,
reader: &mut Reader<R>,
e: &BytesStart,
empty_flag: bool,
) {
match get_attribute(e, b"tabSelected") {
Some(v) => {
self.tab_selected.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"workbookViewId") {
Some(v) => {
self.workbook_view_id.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"view") {
Some(v) => {
self.view.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"zoomScale") {
Some(v) => {
self.zoom_scale.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"zoomScaleNormal") {
Some(v) => {
self.zoom_scale_normal.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"zoomScalePageLayoutView") {
Some(v) => {
self.zoom_scale_page_layout_view.set_value_string(v);
}
None => {}
}
match get_attribute(e, b"zoomScaleSheetLayoutView") {
Some(v) => {
self.zoom_scale_sheet_layout_view.set_value_string(v);
}
None => {}
}
if empty_flag {
return;
}
let mut buf = Vec::new();
loop {
match reader.read_event(&mut buf) {
Ok(Event::Empty(ref e)) => match e.name() {
b"pane" => {
let mut obj = Pane::default();
obj.set_attributes(reader, e);
self.set_pane(obj);
}
b"selection" => {
let mut obj = Selection::default();
obj.set_attributes(reader, e);
self.set_selection(obj);
}
_ => (),
},
Ok(Event::End(ref e)) => match e.name() {
b"sheetView" => return,
_ => (),
},
Ok(Event::Eof) => panic!("Error not find {} end element", "sheetView"),
Err(e) => panic!("Error at position {}: {:?}", reader.buffer_position(), e),
_ => (),
}
buf.clear();
}
}
pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) {
let empty_flag = self.pane.is_none() && self.selection.is_empty();
// sheetView
let mut attributes: Vec<(&str, &str)> = Vec::new();
if self.tab_selected.get_value() == &true {
attributes.push(("tabSelected", self.tab_selected.get_value_string()));
}
if self.view.has_value() {
attributes.push(("view", self.view.get_value_string()));
}
let zoom_scale = self.zoom_scale.get_value_string();
if self.zoom_scale.has_value() {
attributes.push(("zoomScale", &zoom_scale));
}
let zoom_scale_normal = self.zoom_scale_normal.get_value_string();
if self.zoom_scale_normal.has_value() {
attributes.push(("zoomScaleNormal", &zoom_scale_normal));
}
let zoom_scale_page_layout_view = self.zoom_scale_page_layout_view.get_value_string();
if self.zoom_scale_page_layout_view.has_value() {
attributes.push(("zoomScalePageLayoutView", &zoom_scale_page_layout_view));
}
let zoom_scale_sheet_layout_view = self.zoom_scale_sheet_layout_view.get_value_string();
if self.zoom_scale_sheet_layout_view.has_value() {
attributes.push(("zoomScaleSheetLayoutView", &zoom_scale_sheet_layout_view));
}
let workbook_view_id = self.workbook_view_id.get_value_string();
attributes.push(("workbookViewId", &workbook_view_id));
write_start_tag(writer, "sheetView", attributes, empty_flag);
if !empty_flag {
// pane
match &self.pane {
Some(v) => v.write_to(writer),
None => {}
}
// selection
for obj in &self.selection {
obj.write_to(writer);
}
write_end_tag(writer, "sheetView");
}
}
}
|
def make_event(self, start_time, end_time, places=[]):
self.event_count += 1
return Event(
meetup_id = "m{:06d}".format(self.event_count),
name = "Event {}".format(self.event_count),
start_time = start_time,
end_time = end_time,
places = places,
location = "Location {}".format(self.event_count)) |
/**
* Created by Eric on 7/7/16.
*/
public class ScheduleServlet extends MainServlet {
public static final String SERVLET_NAME = "dataModelViewSchedule";
private static final String PARAM_VIEW = "view";
private static final String PARAM_SCHED_NAME = "scheduleName";
private static final String PARAM_ANTIGEN_SERIES = "antigenSeries";
private static final String VIEW_ANTIGEN = "antigen";
/*
* public static String makeLink(Schedule schedule) { return "<a href=\"" + SERVLET_NAME +
* "?\" target=\"dataModelView\">" "</a>"; }
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
HttpSession session = req.getSession(true);
DataModel dataModel = (DataModel) session.getAttribute("dataModel");
if (dataModel == null) {
return;
}
resp.setContentType("text/html");
String view = req.getParameter(PARAM_VIEW);
if (view == null) {
view = "";
}
PrintWriter out = new PrintWriter(resp.getOutputStream());
try {
printHeader(out, "Schedule");
if (view.equals(VIEW_ANTIGEN)) {
String scheduleName = req.getParameter(PARAM_SCHED_NAME);
String antigenSeriesName = req.getParameter(PARAM_ANTIGEN_SERIES);
for (Schedule schedule : dataModel.getScheduleList()) {
if (schedule.getScheduleName().equals(scheduleName)) {
for (AntigenSeries antigenSeries : schedule.getAntigenSeriesList()) {
if (antigenSeries.getSeriesName().equals(antigenSeriesName)) {
printAntigenSeries(antigenSeries, out);
}
}
}
}
} else {
printSchedule(dataModel, out);
}
printFooter(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
private void printSchedule(DataModel dataModel, PrintWriter out) {
out.println(" <table>");
out.println(" <tr>");
out.println(" <caption>Schedule</caption>");
out.println(" <th>Schedule Name</th>");
out.println(" <th>Contraindication List</th>");
out.println(" <th>Live Virus Conflict List</th>");
out.println(" <th>Antigen Series List</th>");
out.println(" <th>Immunity</th>");
out.println(" </tr>");
for (Schedule schedule : dataModel.getScheduleList()) {
printRowSchedule(schedule, out);
}
out.println(" </table>");
}
private void printRowSchedule(Schedule schedule, PrintWriter out) {
out.println(" <tr>");
out.println(" <td><a href=\"dataModelViewAntigen?search_term="
+ schedule.getScheduleName() + "\" >" + schedule.getScheduleName() + "</td>");
out.println(" <td>" + schedule.getContraindicationList() + "</td>");
out.println(" <td>" + schedule.getLiveVirusConflictList() + "</td>");
out.println(" <td>");
out.println(" <ul>");
for (AntigenSeries antigenSeries : schedule.getAntigenSeriesList()) {
try {
String link = SERVLET_NAME + "?" + PARAM_VIEW + "=" + VIEW_ANTIGEN + "&" + PARAM_SCHED_NAME
+ "=" + URLEncoder.encode(schedule.getScheduleName(), "UTF-8") + "&"
+ PARAM_ANTIGEN_SERIES + "="
+ URLEncoder.encode(antigenSeries.getSeriesName(), "UTF-8");
out.println(" <li><a href=\"" + link + "\" target=\"dataModelView\">"
+ antigenSeries.getSeriesName() + "</a></li>");
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
}
}
out.println(" </ul>");
out.println(" </td>");
out.println(" <td>");
if (schedule.getImmunity() != null) {
if (schedule.getImmunity().getClinicalHistoryList().size() > 0) {
out.println(" <ul>");
for (ClinicalHistory clinicalHistory : schedule.getImmunity().getClinicalHistoryList()) {
out.println(" <li>" + clinicalHistory.getImmunityGuideline() + "</li>");
}
out.println(" </ul>");
}
out.println(" </td>");
out.println(" </tr>");
}
}
private void printAntigenSeries(AntigenSeries antigenSeries, PrintWriter out) {
out.println(" <table>");
out.println(" <tr>");
out.println(" <caption>Antigen Series</caption>");
out.println(" <th>Series Name</th>");
out.println(" <th>Series Dose List</th>");
out.println(" <th>Target Disease</th>");
out.println(" <th>Vaccine Group</th>");
out.println(" </tr>");
out.println(" <tr>");
out.println(" <td>" + antigenSeries.getSeriesName() + "</td>");
out.println(" <td>");
if (antigenSeries.getSeriesDoseList().size() > 0) {
out.println(" <ul>");
for (SeriesDose seriesDose : antigenSeries.getSeriesDoseList()) {
out.println(" <li>" + seriesDose.getDoseNumber() + "</li>");
}
out.println(" </ul>");
}
out.println(" </td>");
out.println(" <td>" + antigenSeries.getTargetDisease() + "</td>");
out.println(" <td>" + antigenSeries.getVaccineGroup() + "</td>");
out.println(" </tr>");
out.println(" </table>");
out.println(" <table>");
out.println(" <tr>");
out.println(" <caption>Select Best Patient Series</caption>");
out.println(" <th>Default Series</th>");
out.println(" <th>Product Path</th>");
out.println(" <th>Series Preference</th>");
out.println(" <th>Max Age To Start</th>");
out.println(" </tr>");
out.println(" <tr>");
out.println(
" <td>" + antigenSeries.getSelectBestPatientSeries().getDefaultSeries() + "</td>");
out.println(
" <td>" + antigenSeries.getSelectBestPatientSeries().getProductPath() + "</td>");
out.println(" <td>" + antigenSeries.getSelectBestPatientSeries().getSeriesPreference()
+ "</td>");
out.println(
" <td>" + antigenSeries.getSelectBestPatientSeries().getMaxAgeToStart() + "</td>");
out.println(" </tr>");
out.println(" </table>");
}
} |
<gh_stars>1-10
{-# LANGUAGE TemplateHaskell #-}
module Types.Player(
Player(..),
playerSnippet,
alive,
moveToEntity
) where
import Data.Default
import Control.Lens
import Data.List(intercalate)
import Data.Direction
import Types.Consumable
import Types.Item
import Types.Block
import Types.Enemy
import Types.Jewel
import Types.GroundItem
import Types.Entity
import Data.Vectors
import Types.PState
data Player = Player{
_loc :: Vector3 Int,
_hp :: Int,
_bombs :: Int,
_ropes :: Int,
_gold :: Int,
_items :: [Item], -- | Passive items
_holding :: Maybe Entity, -- | Current Item in hands
_favor :: Int, -- | Kali favor
_p_state :: PState
} deriving Eq
-- | Starting Player
instance Default Player where
def = Player (fromTriple (0,0,0)) 4 4 4 0 [] Nothing 0 Standing
makeLenses ''Player
-- | Full show, exclude favor since it's a hidden stat
instance Show Player where
show p = unlines $ filter (not . null)
[ "You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc))
++ " of the room."
, "You have " ++ show (p^.hp) ++ " hp remaining."
, "You have " ++ show (p^.bombs) ++ " bombs remaining."
, "You have " ++ show (p^.ropes) ++ " ropes remaining."
, "You have collected " ++ show (p^.gold) ++ " gold so far."
, if null (p^.items) then []
else "You have collected the following items: "
++ (intercalate ", " $ map show (p^.items))
, case (p^.holding) of
Nothing -> []
Just a -> "You are holding : " ++ show a
]
-- | Information to show on each round
playerSnippet :: Player -> String
playerSnippet p =
"You are in the "
++ (showRelativeDirection (fromVector3 $ p^.loc)) ++ "."
++ case p^.holding of
Just x -> "\nYou are holding a " ++ show x ++ "."
_ -> []
----- Extras -----
alive :: Player -> Bool
alive = (<=0) . view hp
pickupConsumbale :: Consumable -> Player -> Player
pickupConsumbale BombBox = bombs +~ 12
pickupConsumbale BombBag = bombs +~ 4
pickupConsumable RopePile = ropes +~ 4
-- What when the player moves onto another an entity?
-- NB. This should happen LAST: player should have the opportunity to
-- whip or whatever on the current spot and move out of the way
-- before this fires.
moveToEntity :: Vector3 Int -- | Location
-> Entity -- | Target
-> Player -- | Source
-> Player -- | Result
moveToEntity v (Jewel' j) = (loc .~ v) . (gold +~ value j)
moveToEntity v (Block' b) = case b of
Spikes -> (loc .~ v) . (p_state .~ Falling)
Web -> (loc .~ v) . (p_state .~ Stunned)
PowderKeg -> hp .~ 0
Exit -> loc .~ v
_ -> id
moveToEntity v (Enemy' e) = case e of
(BigSpider _ _) -> hp -~ 2
(Arrow True _ _) -> hp -~ 2
(Arrow False _ _) -> id
(Shopkeeper True _ _) -> (hp -~ 1) . (p_state .~ Stunned)
(Boulder True _ _) -> hp -~ 5
(Boulder False _ _) -> id
_ -> hp -~ 1
moveToEntity v (GroundItem' g) = case g of
Floor c -> pickupConsumable c . (loc .~ v)
_ -> loc .~ v
moveToEntity v _ = loc .~ v |
// InvokeCallThatMightExit run passed function, catching any calls to mocked os.Exit().
func (emh *OsExitHarness) InvokeCallThatMightExit(wrapped func() error) error {
defer func() {
if r := recover(); r != nil {
if v, ok := r.(*OsExitHarness); !ok || (v != emh) {
panic(r)
}
}
}()
return wrapped()
} |
def _std_prm(self, prm, shape):
backend = dict(dtype=prm.dtype, device=prm.device)
trl_factor = torch.as_tensor(shape, **backend) / 2.
rot_factor = 1. / (3. if self.mode == 'classic' else 2.)
zom_factor = 0.5 if self.mode == 'classic' else 0.2
shr_factor = 1.
if self.group == 'T':
prm = prm * trl_factor
elif self.group == 'SO':
prm = prm * rot_factor
elif self.group == 'SE':
trl = prm[:, :self.dim] * trl_factor
rot = prm[:, self.dim:] * rot_factor
prm = torch.cat([trl, rot], dim=1)
elif self.group == 'D':
trl = prm[:, :self.dim] * trl_factor
zom = prm[:, self.dim:] * rot_factor
prm = torch.cat([trl, zom], dim=1)
elif self.group == 'CSO':
trl = prm[:, :self.dim] * trl_factor
rot = prm[:, self.dim:-1] * rot_factor
zom = prm[:, -1:] * zom_factor
prm = torch.cat([trl, rot, zom], dim=1)
elif self.group == 'SL':
trl = prm[:, :self.dim] * trl_factor
rot = prm[:, self.dim:-(self.dim-1)] * rot_factor
zom = prm[:, -(self.dim-1):] * zom_factor
prm = torch.cat([trl, rot, zom], dim=1)
elif self.group == 'GL+':
rot = prm[:, :(self.dim)*(self.dim-1)//2] * rot_factor
zom = prm[:, (self.dim)*(self.dim-1)//2:-((self.dim)*(self.dim-1)//2)] * zom_factor
shr = prm[:, -((self.dim)*(self.dim-1)//2):] * shr_factor
prm = torch.cat([rot, zom, shr], dim=1)
elif self.group == 'Aff+':
trl = prm[:, :self.dim] * trl_factor
rot = prm[:, self.dim:self.dim+(self.dim)*(self.dim-1)//2] * rot_factor
zom = prm[:, self.dim+(self.dim)*(self.dim-1)//2:-((self.dim)*(self.dim-1)//2)] * zom_factor
shr = prm[:, -((self.dim)*(self.dim-1)//2):] * shr_factor
prm = torch.cat([trl, rot, zom, shr], dim=1)
return prm |
Indexing for Visual Recognition from a Large Model Base
This paper describes a new approach to the model base indexing stage of visual object recognition. Fast model base indexing of 3D objects is achieved by accessing a database of encoded 2D views of the objects using a fast 2D matching algorithm. The algorithm is specifically intended as a plausible solution for the problem of indexing into very large model bases that general purpose vision systems and robots will have to deal with in the future. Other properties that make the indexing algorithm attractive are that it can take advantage of most geometric and non-geometric properties of features without modification, and that it addresses the incremental model acquisition problem for 3D objects. |
<reponame>mewa/haskell-server
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Types.Event where
import Types.Imports
data Event = Event { eventId :: Maybe Int,
eventName :: String,
creator :: Int } deriving (Show, Generic)
instance HasId Event where
getId a = eventId a
setId a id = a { eventId = id }
instance FromRow Event where
fromRow = Event <$> field <*> field <*> field
instance ToRow Event where
toRow e = [toField $ eventName e, toField $ creator e]
instance ToJSON Event
instance FromJSON Event where
parseJSON (Object v) = Event <$>
v .:? "eventId" <*>
v .: "eventName" <*>
v .: "creator"
|
def fail(self, msg="internal error", ret=1):
self.logger.error(msg)
self._deinit()
sys.exit(ret) |
<reponame>Tea-n-Tech/chia-tea
from chia.rpc.harvester_rpc_client import HarvesterRpcClient
from chia.util.config import load_config
from chia.util.default_root import DEFAULT_ROOT_PATH
from chia.util.ints import uint16
from ....models.ChiaWatchdog import ChiaWatchdog
from ....utils.logger import log_runtime_async
from .shared_settings import API_EXCEPTIONS
@log_runtime_async(__file__)
async def update_from_harvester(chia_dog: ChiaWatchdog):
"""Updates the chia dog with harvester data
Parameters
----------
chia_dog : ChiaWatchdog
watchdog instance to be modified
"""
try:
config = load_config(DEFAULT_ROOT_PATH, "config.yaml", exit_on_error=False)
self_hostname = config["self_hostname"]
harvester_rpc_port = config["harvester"]["rpc_port"]
harvester_client = await HarvesterRpcClient.create(
self_hostname, uint16(harvester_rpc_port), DEFAULT_ROOT_PATH, config
)
plots_response = await harvester_client.get_plots()
chia_dog.harvester_service.is_running = True
if plots_response["success"]:
chia_dog.harvester_service.plots = plots_response["plots"]
chia_dog.harvester_service.failed_to_open_filenames = plots_response[
"failed_to_open_filenames"
]
chia_dog.harvester_service.not_found_filenames = plots_response["not_found_filenames"]
chia_dog.harvester_service.plot_directories = await harvester_client.get_plot_directories()
# pylint: disable=catching-non-exception
except API_EXCEPTIONS:
chia_dog.harvester_service.is_running = False
finally:
if "harvester_client" in locals():
harvester_client.close()
await harvester_client.await_closed()
chia_dog.harvester_service.is_ready = True
|
Produced by Carol Brown and the Online Distributed
Proofreading Team at http://www.pgdp.net (This file was
produced from images generously made available by The
Internet Archive)
The Cure of Rupture
BY
Paraffin Injections
BY
CHARLES C. MILLER, M. D.
_Comprising a description of a method of treatment destined
to occupy an important place as a cure for rupture
owing to the extreme simplicity of the technic
and its advantages from an economic
standpoint_
CHICAGO
Oak Printing Co., 9 Wendell St.
1908
Copyright 1908
By Charles C. Miller
FOREWORD.
In taking up the description of the injection of paraffin for the cure
of hernia a number of remarks of a prefatory nature are called for, as
it is necessary to justify a treatment which has come in for a
considerable censure from surgeons who have had no experience with the
method and who have judged solely from a few mishaps which came to
their attention and which in no way permit of an accurate estimate of
the treatment.
Paraffin injections have been in use only a few years. When first
introduced their value for the closing of hernial openings was
mentioned. At the time the factors which made injections valuable for
such treatment were not appreciated. Paraffin was merely looked upon
as an agent which might be used to plug a hernial opening and such
plugging of a hernial opening is impracticable without histologic
changes in the tissues to cause permanent closure of the hernial
passage.
The need which Paraffin fulfills in Hernia.
Paraffin has a tendency to promote the formation of connective tissue
and in hernial cases there is invariably a state of the parts which
will be benefitted by the throwing out of connective tissue in the
neighborhood of the deficiency which gives passage to the hernial
contents. Besides this production of connective tissue, the occlusion
of the hernial sac and glueing together of the walls of the hernial
canal, the plugging and supportive action of a material like paraffin
is likely to be in a measure useful as the paraffin does not lie in
the tissues as a single mass, but it is traversed by trabeculae of
connective tissue.
OPERATION WITHOUT ANESTHESIA A GREAT ADVANTAGE.
Injections of paraffin are accomplished with such ease without
anesthesia that the mere fact that a hernia is curable without the
taking of an anesthetic is an advantage on the part of the paraffin
method which will be highly appreciated by a very large percentage of
patients suffering from rupture.
It is safe to say that for every patient suffering from rupture who is
willing to submit to the cutting operation four or five patients will
be met who are afraid to submit to such operation because a general
anesthetic is to be taken.
Applicable in the Physician's Office.
Paraffin injections may be made in the physician's office and there is
no condition produced which renders it difficult for the patient after
injection to go to his home, if he must not travel more than a
moderate distance. The reaction may be such as to make it advisable for
the patient to remain quiet for a week or even two weeks, though this
is exceptional, yet such avoidance of exertion is not looked upon in
the same light by patients as two weeks strict confinement to bed.
The probability of escaping confinement is a great incentive to a
patient to submit to an injection, when he would refuse operation.
Injections are not necessarily unphysiologic as the sufferer from a
hernia has a physiologic deficiency which the paraffin accurately
fills with normal connective tissue.
The dangers of injection can be eliminated. The technic is not
difficult even when all precautions are taken.
There is less likelihood of suppuration following the injection
treatment than following the cutting operation.
The consequences of suppuration are less. If suppuration occur after
the open operation failure is likely, not to mention the danger of
peritonitis. Such is not the case following injection, and while
consequences are less serious suppuration is avoided much more readily
than following the open operation.
Only the operator thoroughly acquainted with the manner of disposition
of paraffin should attempt the injection of hernia.
Simplicity.
To the skilled operator the injection treatment is exceedingly simple
and the injection method must always be far more simple than the open
operation can ever become.
A hernia can be injected without haste in from two to four minutes.
An assistant is of no use.
The open operation cannot be performed without the aid of several
trained assistants, and without elaborate and expensive preparations,
it is not feasable as anything but a hospital operation.
Hospital surgeons may be expected to condemn the injection treatment
of hernia, as it will open to thousands of the profession a field
which has hitherto been monopolized by the surgeons with hospital
facilities.
Experimental injections before human injections.
Before injecting a hernia the operator should be thoroughly <a
acquainted with the manner of diffusion of paraffin in the tissues.
This experience can be gained by the making of numerous injections
into the carcass of a small animal and the subsequent careful
dissection of the animal. A dead cat, dog, rabbit, or chicken may be
used for experimental injections and many such injections should be
made.
Hyperinjection of a hernial canal should be religiously avoided.
Should the operation fail and the patient suffer from the presence of
the paraffin it can be removed by surgical means and at the same time
the open operation performed.
The presence of the paraffin will not interfere with the successful
performance of the open operation nor will it complicate the operation
so that the chances of a radical cure are not diminished from this
method, nor is the patient liable to a slower convalescence.
Vehement protests against the use of paraffin injections are to be
expected from surgeons doing the open operation, and unbiased readers
should not be misled by condemnatory remarks from inexperienced
sources.
PREPARATION OF THE SKIN.
The hair over the pubes and the groin of the affected side should be
cut rather close and then the parts scrubbed with a solution of green
soap. A small amount of a forty per cent. solution of formaldehyde may
be added to the soap solution as this agent is a very powerful
antiseptic.
Soap solution.
Formaldehyde solution, one dram (40%).
Green soap, four ounces.
Dilute alcohol to make one pint.
The dilute alcohol is made up of equal parts of ninety-five per cent
alcohol and water.
After the parts are thoroughly scrubbed with this solution the soap
should be removed with moist compresses and then the parts mopped with
a solution of seventy per cent alcohol. Finally the field of operation
should be flooded with ether as this agent is an effective antiseptic
and also acts as a solvent for any greasy matter not removed by the
soap.
PREPARATION OF THE HANDS OF THE OPERATOR.
Antiseptics cannot be as freely used upon the hands of the operator as
upon the skin of the patient as the repeated application of the
stronger antiseptics cause a scaling of the epithelial cells and
finally the development of an irritated state which prevents cleansing
of the hands sufficiently to permit operating.
It is well to scrub the hands with the soap solution and then to
follow with the use of the seventy per cent alcohol. The alcohol
solution is the least irritating of effective antiseptics and it is
the solution in which needles and leather washers should be kept, so
that they are at all times ready for use.
THE SYRINGE.
The sterilized paraffin syringe should not be handled until the hands
have been scrubbed. The washers and needles, just before using, should
be removed from the alcohol solution. It is unnecessary to wash the
alcohol from the fingers, washers or needles, in fact, it is
preferable to leave it upon them.
Using an extra large syringe it is possible to operate upon several
patients without resterilizing the syringe. This instrument may be
soaked in the alcohol solution, the needle changed and the operator
may continue until the syringe is empty.
Even though one have a syringe capable of holding enough for several
operations it is well to have a second at hand ready for use as the
instruments sometimes break or spring a leak when least expected.
Never use a syringe which leaks, as one cannot tell how much is going
into the tissues and how much is escaping. Leaks invariably occur at
the side of the needle base or at the point of juncture of the barrel
of the instrument with its anterior portion. Paraffin in the solid
state will seldom if ever escape along the side of the plunger within
the barrel of the instrument when the all metal paraffin syringe is
used and the all metal syringe is the only instrument which should be
used for paraffin injections.
The screw piston is preferable to the sliding piston under all
circumstances as it gives the operator a better control over the
injection. Injections are made with the paraffin compounds cold so
that considerable pressure must be brought to bear to cause the harder
mixtures to flow through a long needle.
PREPARATION OF THE SYRINGE.
The plunger should be removed from the syringe and the instrument in
two parts should be thoroughly boiled before filling. It should be
scrubbed with soap and water if dirty or corroded before it is dropped
into the boiling water. After boiling for a half hour the barrel of
the syringe which is closed anteriorly, except for the needle opening,
is held up and the melted paraffin poured in until the instrument is
quite full, then the plunger is fitted in and pressed down until it is
possible to assemble the instrument ready for use.
Needles should be boiled. Leather washers when not in use should be
kept in solutions of alcohol.
Preparations for operation, such as sterilizing syringe and needles
should be done hours before operation. If the sterilized loaded
syringe is placed in a sterile towel it may be kept for days and then
before use to insure sterilization it should be soaked in a seventy
per cent solution of alcohol. If a needle is attached to the syringe
when it is thrown in the alcohol solution it will be found that the
paraffin in the syringe will not be affected by the alcohol. The
instrument may be used from the alcohol without even drying it.
Before inserting the needle for the injection of the paraffin start
its flow and observe that the paraffin is escaping from the needle in
a perfectly smooth string.
The same words as to preparation apply when the white vaseline is
used. This agent should always be sterilized by heat before placing it
in the syringe and when syringe and vaseline are sterile the exterior
of the instrument may be re-sterilized at the time of using by alcohol
soaking.
Paraffin in the liquid state may be drawn from a large container
directly into the syringe when the needle has been removed. The needle
may then be screwed in place and the instrument held with the point of
the needle directly upward and pressure made upon the piston until all
air escapes and the liquid paraffin begins to flow. Then the
instrument may be allowed to cool and its contents to consolidate.
Material injected at room temperature.
All these injections are made with the material in the syringe at room
temperature. The syringe may be left filled for days and not heated at
all when the injections are finally made. In mid-winter if the syringe
has been kept in a cold room its temperature may be so low that it may
be advisable to warm it somewhat, but at an average temperature of
seventy degrees Fahrenheit the mixture first described should flow
freely through an ordinary hypodermic needle.
PREPARATION OF THE PARAFFIN.
Some operators have said a good deal about the paraffin and the proper
place to secure it. As nearly as can be learned the compounds used in
this country are products of the Standard Oil Company. The paraffin
used in the formulae of this book has an average melting point of 130.
For reducing the melting point of the paraffin mix the paraffin with
the white vaseline of the Chesborough company. If an agent is sold in
a tin stamped white vaseline it should have the name on the tin of the
Chesborough company as this is the only firm having the right to use
this name. Petrolatum albi or white petrolatum is a few cents cheaper
than the vaseline but the difference is of so small an amount that it
is better to use the vaseline rather than packages which may vary more
than the Chesborough product.
FORMULA NUMBER ONE.
White vaseline, one-half pound.
Paraffin, one-half pound.
Melt together.
This should be sterilized by having the mixture stand in a covered
container in a vessel of water which is also covered and the water
should be kept boiling for a half hour.
Containers for sterilized compounds.
With the paraffin may be boiled a number of test tubes. These after
boiling one-half hour may be lifted from the boiling water with
forceps. As they will be quite hot if they are held with opening
downward the water will drain from them and their own heat will
evaporate the few drops in the interior and they will be left dry.
Into each test tube sufficient paraffin may be poured to fill a
syringe and then they should be plugged with sterile cotton or corks
which have been boiled. The test tubes containing the paraffin
mixture may then be put away and when taken out at a later time for
filling the syringe the paraffin may be melted by heat and poured into
the sterile syringe or the paraffin may be boiled by holding the test
tube over a Bunsen burner, or other heater. When paraffin boils the
temperature of the boiling mixture is higher than that of boiling
water but the boiling causes dense black smoke to be given off and
this is objectionable in a closed room. Repeated boiling of paraffin
causes it to discolor but this does not occur when the vessel
containing the paraffin is placed in a water bath and the water around
the paraffin container boiled. No smoking of the paraffin occurs when
it is heated in a water bath and this means of sterilization is the
most satisfactory though the first time the paraffin is sterilized it
should be kept in the boiling water for a half hour.
A softer mixture of paraffin, which may be used when in fear of the
effects of the injection of the harder mixture, is made as follows:
FORMULA NUMBER TWO.
Paraffin, two ounces.
White vaseline, eight ounces.
Melt together and sterilize.
This second paraffin compound is advisable when the operator is
anxious to secure a plugging action with a mixture which will always
be fairly soft, and which is less likely to be absorbed than plain
sterilized white vaseline.
Vaseline.
The third compound is the sterilized white vaseline. It is probable
that this agent is frequently absorbed in a comparatively short time
but it has the valuable property of diffusing freely through the
tissues so that it produces a more extensive reaction and when it is
used in connection with the harder mixtures the operator may be more
certain of securing an occlusive inflammation of the sac of the hernia
and the more extensive production of connective tissues so that the
parts separated to make way for the passage of the hernial sac are
more certainly bound together.
None of these mixtures are hard. If a portion of the mixture first
described is secured under the arm for a half hour or held in the
mouth for that length of time and it is raised to body temperature it
will be found that it is comparatively soft. It is not a liquid and it
is not likely to be absorbed, yet it is not a hard waxy mass.
The great danger of the untrained operator is to inject too much at
one point and should the operator do this and get it in the canal it
will make a lump at one point and press unnecessarily upon the tissues
and in time will be displaced and will drag involved tissues with it,
producing discomfort by the distortion.
POSTURE OF PATIENT FOR INJECTION.
The patient for injection should be placed upon the back. When the
thigh is slightly flexed the wall of the abdomen is relaxed and should
the external ring be not dilated by the protrusion of a large hernia
the relaxation obtained by the flexing of the thigh and allowing the
flexed leg to rest against the other will relax and dilate the
external ring somewhat so that it may facilitate the free passage of
the needle and it will also permit of the more free moving of the
point of the needle in the loose cellular tissues as the needle is
gradually withdrawn.
Pelvis high and head low.
If the head is dropped low and the pelvis is high, a position easily
possible with some surgical chairs, the veins of the cord are depleted
and the likelihood of opening or entering a vein is diminished. This
posture should only be used where there is a well marked varicocele
and the suction method of inserting the needle should always be used.
When the veins are dilated the elevation and their depletion may
prevent the operator making several efforts to pass the needle without
striking them, a thing which is easily possible in the presence of a
canal full of dilated vessels.
Should there be a well marked varicocele the blunted needle should be
used so that it will not be possible to cut a vein by the moving of
the needle and at the same time the operator should move the point of
the needle slowly from side to side as it is withdrawn.
SKIN INFILTRATION TO PERMIT OF INSERTION OF LONG NEEDLE
WITHOUT UNDUE PAIN.
It may be well to infiltrate the skin slightly at the site of the
puncturing of the skin with the larger needle. To do this a weak
cocain or alypin solution should be used. This solution is made by the
addition of the cocain or alypin tablets to one or two drams of boiled
water.
A tablet containing six tenths of a grain of alypin or cocain is
sufficient for a dram solution. A few drops of this injected over the
external ring will permit of the passage of the needle through the
tough skin without pain. The pressing of the needle along the roof of
the canal is not usually sufficiently painful to call for much
complaint from the patient.
If the patients are nervous a preliminary injection of a one per cent
solution of cocain or alypin into the inguinal canal is not
contraindicated. To accomplish this the larger needle should be
screwed upon the infiltrating syringe and as the needle is pressed
into the canal the solution is slowly forced in front of the needle
point. If sufficient solution is thrown ahead of the needle the
passage of the needle along the inguinal canal is entirely painless.
The infiltration of skin or canal being complete the needle must be
withdrawn and the syringe emptied and the plunger pressed down so that
the empty syringe is attached to the needle through which the paraffin
injection is to be made when the operator has assured himself that the
needle has been passed as far as desired without traversing or
puncturing a vein.
THE EFFECT OF PARAFFIN COMPOUNDS UPON THE TISSUES.
No matter what precautions are taken, paraffin deposited in the
tissues causes an increased flow of blood to the parts. The reaction
is in the nature of a distinct active hyperemic state and it is
sufficient to cause the proliferation of connective tissue. Even if
pure white vaseline alone is injected there will be such connective
tissue proliferation and if the paraffin is deposited close along the
peritoneal surfaces of the sac sufficient of a circulatory disturbance
will be produced to result in the sticking together of the serous
surfaces of the sac and such sticking together of the walls will mean
an elimination of the patency of the sac, one of the essential
features of a radical cure.
The paraffin compound number one is of such consistency that it is
unlikely to be absorbed and properly placed with discretion it will
favor the retention of the hernia by acting as a plug. This plugging
action is not likely to be successful if the paraffin is simply thrown
in as a mass, as it will be displaced, and when displaced it will make
undue traction upon parts with which it is intimately connected so
that should the paraffin be thrown in in the form of an irregular mass
closing only a small part of the canal and such displacement occur the
patient may suffer considerable discomfort.
The corking action of the paraffin is not to be disregarded, yet at
the same time it must be remembered that the injection must be so
diffused that the supporting mass has quite a universal support from
all the tissues from the internal ring clear out to the external ring.
It must also be remembered that the paraffin thrown into the tissues
causes a thickening of the tissues and should the canal be filled with
paraffin with the thickening which so rapidly develops the canal will
be unduly crowded.
If the canal is plugged up tightly and marked pressure is made upon
the nerves of the cord at one point it is likely that discomfort will
be produced which will last for some time.
Object of operator.
The object of the operator is to secure a diffusion of the injection
through the loose cellular tissues by the directing of the needle in
all directions as it is withdrawn. This diffusion is facilitated by
the nature of the paraffin. It is not to be forgotten that the
vaseline diffuses very readily and extensively and if the operator is
fearful of overinjecting the parts it is best to use it in excess
rather than the harder mixture.
If the needle is simply withdrawn the paraffin is not thrown into the
canal in a regular pencil-like plug but it lumps irregularly with
small diverticula projecting from each irregular mass.
The free moving of the needle point in all directions as the needle is
withdrawn favors the diffusion and avoids the unsatisfactory lumping
of the injection.
THE IMMEDIATE AFTER EFFECTS OF THE PARAFFIN INJECTIONS.
Within twelve hours after the operation the tissues are almost certain
to become quite sensitive to pressure. The reaction may be followed by
considerable pressure pain for a day or two. Should the patient not be
comfortable while at rest, that is sitting about or lying down; then
something should be given to relieve the pain. Codeine is the most
satisfactory agent for preventing the patient from feeling pain during
the most acute stage of the reaction. Codeine does not put the patient
to sleep as does morphine, nor does codeine constipate or make the
skin itch. Codeine is only about one-third or one-fourth as toxic as
morphine and consequently it may be given in a proportionately larger
dose. It may be given in tablet form or in solution by the mouth. The
best way to administer it is in doses of one-half grain every hour
while the patient is suffering actual pain. Tell the patient that it
will relieve him of unpleasant symptoms during the reaction and that
it is undesirable that he should suffer from the reaction. In this way
the patient will be kept quite comfortable during the time that the
reaction is sufficient to cause pain. It is impossible to tell whether
the reaction will be such as to cause any pain or not. In case it does
not develop no internal treatment is necessary. Other agents may be
used to relieve pain, though none offer the advantages of codeine
without disadvantages. It is not advisable to let these patients
suffer from a severe reaction. It is better to meet the first
indications of pain with the free administration of codeine. The
patient should not know the nature of the drug, and as it produces
none of the peculiar effects of morphine it is not really a drug at
all dangerous from the habit forming standpoint.
Local applications of heat or cold may be used if the reaction is well
marked.
THE PRECAUTION USED TO PREVENT THROWING OF PARAFFIN
INTO THE CIRCULATION.
In all cases precautions should be taken to avoid throwing of the
paraffin mixture directly into the circulation. This is accomplished
by passing the needle slowly into the tissues which are to be injected
and while the needle is passing through the tissues it should have a
strong vacuum suction upon it so that should it strike a vein the
blood will immediately begin to flow into the needle. To illustrate
how easily blood may be sucked from a vein a hypodermic with a glass
barrel may be taken armed with a small needle. If the arm of a patient
be allowed to hang down the veins will distend and the point of the
needle may be slipped through the skin and into the vein. If the vein
is punctured by the needle point the instant the piston of the syringe
is drawn back a vacuum forms in the syringe and the blood will flow
into the syringe. This same method is to be used in the passage of the
larger paraffin needle or any paraffin needle only as the needle is
passed along its course the suction should be constantly exerted. This
constant suction is secured by simply attaching the half glass syringe
to the needle and then as soon as the point of the needle is under the
skin the piston is withdrawn and a vacuum formed. Then holding the
piston of the syringe out, maintaining the vacuum, the needle is
pushed slowly in as far as the operator desires to inject. Should
blood begin to flow into the needle at any point the onward passage of
the needle is stopped and is withdrawn and re-inserted in a somewhat
different direction, particularly if during the withdrawal a point is
found where the blood flows steadily into the syringe.
If at no point blood flows into the syringe it is plain that no vessel
of dangerous size has been punctured by the needle. The veins of the
cord are found rather closely around the cord and the cord usually
lies below and behind the sac so that should the operator aim to carry
his needle point along rather high in the canal he will be least
likely to encounter these vessels. It is not to be forgotten that the
veins of the cord are particularly likely to be somewhat dilated in
these cases of hernia and the operator is taking more or less of a
hazard in neglecting the suction technic outlined. It is not safe to
trust to the fact that the paraffin is injected in a solid state as is
asserted by some operators. It is true that paraffin in a liquid state
is more likely to flow into an opened vein than the paraffin in the
solid state, yet it is possible to throw a very small amount of solid
paraffin into a vein if no precaution is taken to prevent it, and
while a very small mass thrown directly into a vein would be harmless
in nearly all instances it might do considerable damage should it be
so unfortunate as to lodge in certain vessels.
FACTORS TO BE CONSIDERED IN DEALING WITH INGUINAL HERNIA.
The inguinal canal gives passage to the spermatic cord. It is an
oblique canal extending from a point one-half an inch above the center
of Poupart's ligament to the spine of the pubes. The cord emerging
from the external ring continues into the scrotum, and the most
definite manner of finding the external ring is by picking up the cord
in the scrotum and following it with the index finger until the point
of the index finger is pressed into the canal, the scrotum being
invaginated at the same time. In scrotal hernia when the patient is
placed in the recumbent posture the contents of the hernial sac may be
pressed into the abdomen and the finger following the receding hernial
contents will slip into the opening of the external ring.
OPERATOR MUST BE SURE HERNIA IS REDUCED.
A hernia should always be completely reduced before any operation is
attempted and the size and situation of the external ring definitely
determined. The larger and the longer a hernia has been allowed to go
unreduced the shorter the inguinal canal will be, as the inner margin
of the internal ring is gradually forced toward the median line of the
body, and in very large hernia the external ring is stretched somewhat
outward so that an opening exists directly through the abdominal wall.
This character of hernia is such that three fingers may easily be
pressed directly into the hernial interval and as a rule so much of
the abdominal contents have been outside the abdomen for so long that
the hernia cannot be overcome without decidedly increasing abdominal
pressure. These cases in which hernial contents can be pressed into
the abdomen by force and which markedly increase the intra-abdominal
pressure when reduced are unsuited for any operative treatment which
does not include excision of a quantity of omentum.
The average case.
In the average case the examination of the external ring will not show
a canal so greatly dilated and it may be taken for granted that it has
not been shortened to a considerable extent by the giving of the
internal margin of the internal ring toward the median line. Under
these circumstances the operator may decide that he has a canal of
from two to three inches in length and lying parallel to Poupart's
ligament and slightly above this structure.
The sac of the hernia usually lies above and in front of the cord.
Running closely connected with the cord are the veins which go to make
up the pampiniform plexus. These veins being close to the cord and the
cord itself quite susceptible to pressure it is advisable to pass the
needle along near the roof of the inguinal canal and to attain this
end it is well to locate definitely the external ring and to have a
distinct knowledge of the exact situation of the upper margin of the
ring.
Considerable cellular tissue is found in the inguinal canal so that in
passing the needle through the canal should it meet with considerable
resistance it has no doubt missed the canal and entered some of the
more resistant tissues making up its walls.
The cellular tissue in the canal is to receive the injection of the
operator and it will be his object to facilitate the diffusion of the
various materials injected so that an extensive formation of
connective tissue will be promoted. The plug action of the injection
is not alone to be considered for the operator is then likely to throw
too much into the canal and with the development of the connective
tissue the canal is unduly crowded.
The ill consequences of hyperinjection should not be forgotten. It is
the error to which the beginner is most liable.
WHERE THE INJECTION SHOULD BE PLACED.
Some operators have been content to insert a needle over the
approximate site of the internal ring and then to force it downward
until it lies as close to the internal ring as they can approximate
and then to throw in a mass of paraffin sufficient to occlude the
canal at this point.
If the needle is inserted about half an inch above the middle of
Poupart's ligament it will be over the site of the normal internal
ring. After the needle passes through the subcutaneous fat it will be
felt to strike the firm fibrinous layers of the external wall of the
inguinal canal. After the needle has passed through this firm layer it
will enter the loose cellular tissue in the neighborhood of the
internal ring. If the injection is diffused over an area of an inch or
an inch and a half in circumference the internal ring is likely to be
plugged for the time by the injection.
The larger Hernia.
Should the hernia be large the injection should be made closer to the
pubes, but injection at the internal ring is not sufficient, the canal
should also be injected with a certain amount of the paraffin and
vaseline.
The canal may be injected by passing the needle directly through the
outer wall of the inguinal canal, remembering its course about
one-half inch above the line of Poupart's ligament.
The most satisfactory plan of injecting where the operator can
successfully follow the technic is to find the external ring and then
insert the needle directly into the external ring close to its upper
margin and to carry the needle along for at least two inches. The
suction technic should be followed and the needle should be moved in
all directions as it is withdrawn and the deposit diffused as much as
possible.
About the external ring itself and directly between the pillars of the
external ring a certain amount of the injection should be placed.
THE AMOUNT OF PARAFFIN TO BE INTRODUCED IN A GIVEN CASE.
The tendency is to overinject a case. One must not forget that the
tissues will probably thicken to twice the size of the mass injected.
The operator must estimate as nearly as possible the size of the tract
to be filled and then aim to throw in enough to about half fill it.
The diffusion of the paraffin will usually safely hold the hernia when
the patient rises from the table.
Should the operator throw in mixtures one and two until the parts are
fairly distended and the hernia be not held it is better to use only
the plain sterile vaseline for a subsequent injection at the site of
the internal ring. If a half dram of vaseline at this point does not
hold the hernia a small amount of vaseline may then be thrown in the
central portion of the canal.
At first the vaseline injections should be used whenever in doubt as
to the amount needed above a certain point. As the operator becomes
acquainted with the needs of cases by experience the vaseline can be
largely substituted by the paraffin mixture number one.
TECHNIC TO BE USED IN INJECTING INGUINAL HERNIA.
Have a syringe loaded with paraffin mixture number one and another
loaded with sterile vaseline. See that the paraffin flows smoothly
from the syringe without leaks. See also that the vaseline syringe is
working smoothly.
Have needles intended for injection of paraffin free from this agent.
Place patient on back, thighs flexed slightly or straight if the
external ring is easily accessible. Follow the spermatic cord and
locate definitely the external ring.
Attach empty syringe to needle. Pass needle point through skin. As
soon as needle point is through skin exhaust syringe. That is draw
piston out to form vacuum in syringe and obtain suction. Pass the
needle slowly through external ring and along close to the roof of
inguinal canal.
When needle is in full length, if no vein has been struck and blood
aspirated into the syringe, detach syringe and screw the paraffin
syringe tightly to needle.
Inject a few drops of paraffin by screwing down syringe. As paraffin
is flowing move the point of the needle about in the loose cellular
tissue and continuing the injection slowly withdraw the needle.
Continue moving the point of the needle in all directions as the
needle is withdrawn so that the paraffin will be diffused as much as
possible. As the point of the needle emerges between the pillars of
the external ring discontinue the injection.
Test the effectiveness of the injection.
Allow patient to stand on feet. If the hernia reappears have the
patient lie down again and reinsert the needle as before described and
inject sterile vaseline rather than the paraffin mixture.
Not more than enough paraffin to half fill the canal should be
injected. If such quantity does not hold hernia sterile vaseline
should be used discreetly until hernia is held.
The surgeon must estimate the approximate size of the inguinal canal
by the size of the external ring.
If a vein is struck the needle should be withdrawn and the syringe
emptied of blood; then the needle should be reinserted, using the
syringe for suction. If a vein is struck a second time it will be well
to insert the needle through the abdominal wall at the site of the
internal ring and if no vein is struck at this point an injection may
be made. If this holds the hernia it may be well to make no injection
of canal for two weeks. During the interval even if the hernia does
not recur it will be well for patient to wear web bandage truss or a
spica bandage with a pad pressure over the inguinal canal. At the end
of two weeks inject canal moderately with paraffin or vaseline to
promote formation of connective tissue.
If the injection of the canal at the site of the internal ring does
not hold the hernia, reduce the same and make a puncture with a small
needle through the external wall of the canal just above the external
ring. If no vein is struck inject moderately and see if such injection
holds hernia. In such a case place pad of moderate size over the canal
and put on firm spica and have the patient stay off of feet as much as
possible for ten days or two weeks. In this case the permanence of the
cure will depend upon the amount of connective tissue formed.
Injection at Internal ring.
To inject through the abdominal wall at the internal ring select a
point midway between the anterior superior spine of the ilium and the
pubes and one-half an inch above the line of Poupart's ligament. This
represents the site of the internal ring. The needle should be pressed
through the fibrinous wall of the canal at this point and should be
directed towards the pubes. If the hernia is at all large remember
that the canal is shortened and select a point one-half or
three-quarters of an inch nearer the pubes as the site of the ring.
When through the outer wall of the inguinal canal the needle point
will have a considerable freedom in the loose cellular tissue and the
injection should be diffused in a circle of an inch or an inch and a
half in diameter. Before taking off the suction syringe after the
passage of the needle sweep the point slowly in a circle to make sure
that no vein has been opened or is likely to be opened as the needle
is swept about.
The hypodermic needle for injection.
A hypodermic needle may be used for an internal ring injection or an
injection through the anterior wall of the canal, but in moving it
about the operator should watch carefully and not break such needle.
If a needle breaks it will be at the shoulder formed by the point of
attachment of the shaft of the needle with the butt.
The advantage of the small hypodermic needle is that it may be passed
with very little discomfort to the patient and it throws a finer
string of paraffin and favors diffusion of the agent.
A hypodermic needle is lacking in length to inject the canal when
passed through the external ring along the canal.
Should the surgeon attempt injection along the canal and find the
patient too nervous or the technic too difficult the hypodermic may be
used and an injection made through the anterior wall of the canal at
the internal ring, at about the center of the canal and about one-half
an inch from the external ring.
The hypodermic needle injections are simple and should be accomplished
even on a very nervous patient without troubling to infiltrate with
cocain or alypin.
BE DISCREET IF INJECTION IS PAINFUL.
Should a patient complain that the injection is painful inject very
discreetly or better check the injection there, move the point of the
needle and again try slowly. If the cold injection causes pain try at
another point. Put in a drop or two and should the patient still
complain discontinue and put on a spica or truss for a few days.
Observe the reaction and then if it is not severe inject again.
Remember that several injections may be made upon a patient but
hyperinjection, that is the injection of too much, will cause no
little distress and that it is impossible to remove all the paraffin
mixture or the vaseline without an open operation, if they are not
absorbed.
Needle punctures should be sealed with collodion. No other dressings
are required.
Begin codeine early and use freely when a painful reaction develops.
THE INJECTION OF FEMORAL HERNIA.
The femoral ring is below Poupart's ligament. When the femoral hernia
protrudes through the crural canal it is directed upward over
Poupart's ligament. To reduce it press the mass toward the feet of the
patient and then upward toward the abdominal cavity. The saphenous
opening may then be felt. On the outer side of the opening is the
large vein of the thigh. The needle should be inserted at the inner
extremity of the opening, that is toward the median line. Aspirating
of blood may mean the puncture of this large vein and it may not be
advisable to inject carelessly when this vein has been wounded owing
to its size. The crural canal is only about a half inch in length. The
injection of it may be accomplished with a hypodermic needle. It is
not well to sweep the point of the needle externally with too great
freedom as the vein may be wounded. Inject slowly and move the point
of the syringe carefully so that the injection may be diffused in the
canal.
INJECTION OF UMBILICAL HERNIA.
Reduce the hernia and examine the margins of the hernial ring with
care so as to be thoroughly acquainted with the character and
situation of these margins. Remember that the tissues are often very
thin and that an injection in the center of the hernia may simply go
through the peritoneum and thus be placed directly in the abdomen.
Injections of paraffin into the peritoneal cavity of animals have not
proven to be dangerous, the agent not causing irritation of the
surface of the peritoneum when sterile.
Umbilical hernia may be injected with a hypodermic needle building out
from the margins of the hernial opening, but it is well not to inject
with too great freedom. After diffusing the tissues of the canal or
ring a pad and binder should be applied and the patient given two
weeks interval to see if sufficient of the connective tissue has
developed to close the canal. If the hernia is not overcome and recurs
injections may be repeated.
Case Reports
Case 1.
Case 1 A. G.--Italian child, age twenty-eight months, female. (Ass.
Civ. Char. Disp.) Umbilical hernia protruding about one-half inch and
with an opening which may be filled by tip of index finger.
Parts thoroughly sterilized, hernia reduced and contents held in
abdominal cavity by pressure of index finger of assistant. The margins
of ring and the skin covering hernial opening injected with paraffin
of melting point 108. In effort to avoid puncturing of hernial sac and
throwing paraffin into the peritoneal cavity the skin of sac injected
with the paraffin. About half dram amount used. Operation Jan. 17,
1905. Jan. 18, 1905. Temp. normal. Parts sensitive. Cries and
struggles when parts touched. May 13, 1905. Last examination. Skin
somewhat red. Paraffin mass easily palpable. Skin red but not
sensitive.
Case 2.
Case 2 A. C. C.--Disp. W. P. Swedish boy, age 2 years and 9 months.
Injected Feb. 3, 1905. Hernia as large as walnut. Reduced. Finger of
assistant holding in contents. Injection made into tissue surrounding
the hernial opening with view of crowding margins together. Half dram
injected. Child crying forced contents into sac. Reduced and injection
under skin of sac and around margins of opening to plug. Nearly dram
paraffin used, melting point 108.
Parts moderately sensitive at end of week. No redness though paraffin
mass palpable close under skin and intimately connected with it. April
11, 1905. Last examination. No redness, no tenderness, no recurrence.
Case 3.
Case 3 T. F.--Teamster. Irish parentage. Age 20. A. C. C. Disp.
Bubonocele, left side. First noted four weeks previously. Operation
May 14, 1905. Area sterilized. Small area of skin infiltrated with a
one percent solution of cocain. Paraffin melting point 108, injected
over area of prominence of bubonocele and into upper portion of canal.
Two punctures made a dram and a half of paraffin injected. Parts
sensitive for three days so that patient walked without bending thigh
at hip joint. No temperature. Local applications. Codeine given in
quarter grain doses every two hours. Fourth day parts much less
sensitive, can bend leg freely in sitting or walking. Area prominent
from swelling but no impulse. Examination June 25, 1905. No pain, no
tenderness, no impulse, prominence in region of internal ring slightly
greater than on opposite side.
Case 4.
Case 4 A. P.--Sicilian. Worker in shoe factory. Age 24. Hernia four
months duration. Never retained by truss. Sac extends half way to
bottom of scrotum. Pubes shaved, skin sterilized. Operation Aug. 26,
1905. Skin infiltrated to allow passage of large needle without pain.
Injection at internal ring of forty minims. Injections into canal of
about thirty minims. In attempting to inject paraffin in cold state
screw piston syringe broken. All metal syringe used for infiltrating,
warmed and filled with melted paraffin. In using syringe to inject the
canal near the external ring the needle plugged. Using all force
possible the plug forced from needle and over a dram of melted
paraffin thrown between the pillars of the external ring. Patient
complained of considerable pain. Codeine used one-fourth grain every
hour. On the third day after injection skin over the external ring
infiltrated and with sharp spoon about a half dram of paraffin
removed. Operation painless. Formaldehyde solutions one to five
thousand used as moist dressings. Codeine continued for two days
longer. Patient lost one week from work. Sept. 24, 1905. No
recurrence, no pain or tenderness. Area at former site of hernia
slightly more prominent than opposite side, no redness of skin.
Case 5.
Case 5 F. C.--American born, age 18. Private patient. Hernia about
size of average marble midway between ensiform cartilage and
umbilicus. Spontaneous origin. Injected at office with half dram of
paraffin, melting point 115. Operation Dec. 2, 1905. About half dram
total quantity used. No reaction when adhesive strip removed on fourth
day. Slightly tender on pressure. Examination Feb. 7, 1906. No
recurrence, no redness, no pain.
Case 6.
Case 6 J. C.--Italian barber. A. C. C. Disp. Inguinal hernia on right
side. Noted three weeks before. Sac protruding through external ring.
Injection after infiltration. Forty minims injected about internal
ring. Twenty minims in canal. Twelve or fifteen minims thrown between
the pillars of external ring. Codeine prescribed but not taken. Parts
quite sensitive on third day. No fever. Sleeps well with two pillows
under thigh of affected side. Fifth day, no pain, tenderness very much
less, able to bend leg almost as freely as ever. Twelfth day impulse
at internal ring? (Questionable.) Injection of twenty minims at
internal ring, ten into canal and ten between pillars, melting point
104. March 4, 1906. Last examination. No recurrence, no pain or
tenderness.
Case 7.
Case 7 A. Y.--Femoral hernia. Female, age 35, A. C. C. Disp. Worker in
tailor shop. History of case indefinite as to length of time present.
Never been treated in any way. Operation March 21, 1906. Injection of
forty minims of paraffin through saphenous opening and about ten
minims through Poupart's ligament. Codeine discontinued at end of
fourth night. Tenderness slight. No recurrence at end of twenty days.
Patient not seen subsequently.
Case 8.
Case 8 E. H.--Marshalltown, Iowa. Private patient. American born.
Varicocele on left side and oblique inguinal hernia. Operation April
16, 1906. Infiltration and removal of dilated veins in scrotum. Wound
closed and inguinal canal followed by large needle. No blood aspirated
and cold paraffin mixture with melting point 115 injected along canal.
About forty minims thrown along canal and then puncture made at site
of internal ring and half dram diffused at this point.
Personal communication one year later making final payment for
operation. Patient cured and grateful.
Case 9.
Case 9--Italian section worker wearing spring truss for holding of
inguinal hernia. Strong pressure of truss making marked depression at
site of internal ring. Patient injected with dram and half of paraffin
of melting point 115. May 20, 1906. Agent deposited along canal and at
internal ring. One week later no pain, no tenderness to moderate
pressure. Cord somewhat larger than normal and epididimus thickened
but not tender. Shreds in urine. Through interpreter information
gleaned that epididimus had been somewhat tender following operation.
History of acute epididimitis some months before.
Case 10.
Case 10 A. J.--Patient first consulted at Harvey dispensary. Treated
for urethral stricture by internal urethrotomy. Subsequently
referred to A. C. C. Disp. for treatment. Developed acute appendicitis
and operation for removal after development of abscess. Abscess
drained and healing of abdominal incision imperfect leaving hernial
protrusion internally and near superior angle of scar. Injected with
seventy minims of paraffin, 115 melting point, on Aug. 2, 1906. No
pain following injection, no discoloration, and no recurrence over a
year and a half after operation.
CONCLUSION.
These cases represent the ten first which were seen subsequent to
injection. Cases which were injected and which did not return
subsequent to injection have not been included as they would be of no
value in estimating as to the usefulness of this method. In no
instance has an ill consequence been suffered which would cause the
patient to seek surgical aid elsewhere, or at least no case has come
to the knowledge of the author directly or indirectly.
Large hernia which have gone unreduced for years have not been treated
by injection and discretion demands that for some time, or until
injection treatments have been practiced upon many patients, that
large ruptures which have been outside the abdomen for long periods be
left to the surgeon or be injected only by practitioners capable of
doing the cutting operation in the advent of the failure of the
injection treatment.
The author for his own part has felt no hesitancy in injecting cases
which promised a fair degree of success, realizing full well that
untoward symptoms of a local character may be overcome by free
dissection, removal of the paraffin and restoration of the inguinal
canal by the usual surgical means.
CONTENTS
PAGE
Foreword 3
Preparation of the skin 10
Preparation of the hands of the operator 12
Preparation of the syringe 15
Preparation of the paraffin 18
Posture of patient for injection 23
Skin infiltration to permit of insertion of long needle
without undue pain 25
The effect of paraffin compounds upon the tissues 27
The immediate after effects of the paraffin injections 30
The precaution used to prevent throwing of paraffin
into the circulation 32
Factors to be considered in dealing with inguinal
hernia 35
Where the injection should be placed 39
The amount of paraffin to be introduced in a given
case 42
Technic to be used in injecting inguinal hernia 44
The injection of femoral hernia 51
Injection of umbilical hernia 53
Case reports 69
Cosmetic Surgery
The Correction of Featural Imperfections
BY
CHARLES C. MILLER, M. D.
Very excellent and practical. _Southern Practitioner._
Will fill a distinct place in the realm of surgery.
_Cleveland Medical Journal._
Covers a most important field of special surgery.
_Southern Clinic._
The book is certainly a valuable contribution to the subject.
_Ophthalmology._
Has gone far beyond the limits of surgery as understood and
practiced in this country.
_British Medical Journal._
The author has done the profession a service in offering his
work upon the subject.
_Yale Medical Journal._
The book furnishes in an extremely convenient and accessible form
much information concerning a branch of surgery which is daily
growing in importance and interest.
_Military Surgeon._
Dr. Miller has made out a good case as to why the regular surgeon
should give this question some considerable attention rather than
leave such things to the charlatan and quack.
_Canadian Journal of Medicine and Surgery._
160 Pages. 98 Illustrations. Price $1.50.
Transcriber's Notes:
Words and phrases in italics are surrounded by underscores, _like this_.
Spelling changes:
acqainted to acquainted, ... thoroughly acquainted with ...
patrolatum to petrolatum, ... white petrolatum is a few cents ...
PRACAUTION to PRECAUTION, ... THE PRECAUTION USED TO PREVENT ...
pertoneal to peritoneal, ... into the peritoneal cavity ...
urtehrotomy to urethrotomy, ... by internal urethrotomy ...
protrusian to protrusion, ... leaving hernial protrusion,...
Opthalmology to Ophthalmology, advertisement at end of book
Added missing period at end of chapter, ... reaction is well marked.
End of the Project Gutenberg EBook of The Cure of Rupture by Paraffin
Injections, by Charles C. Miller
*** |
Exploitation of Ontology Languages for Both Persistence and Reasoning Purposes - Mapping PLIB, OWL and Flight Ontology Models
Ontologies are seen like the more relevant way to solve data understanding problem and to allow programs to perform meaningful operations on data in various domains. However, it appears that none of the proposed models is complete enough by itself to cover all aspects of knowledge applications. In this paper, we analyse existing modeling approaches and classify them according to some revelant characteristics of knowledge modeling we have identified. Finally, this paper present transformation rules between ontology models in order to get benefits of their strengths and to allow a powerful usage of ontologies in data management and knowledge |
Investigation of the early-age performance and microstructure of nano-C–S–H blended cement-based materials
Nano calcium silicate hydrate (nano-C–S–H) has become a novel additive for advanced cement-based materials. In this paper, the effect of nano-C–S–H on the early-age performance of cement paste has been studied, and some micro-characterization methods were used to measure the microstructure of nano-C–S–H-modified cement-based material. The results showed that the initial fluidity of cement paste was improved after addition of nano-C–S–H, but the fluidity gradual loss increased with the dosage of nano-C–S–H. The autogenous shrinkage of cement paste can be reduced by up to 42% maximum at an appropriate addition of nano-C–S–H. The mechanical property of cement paste was enhanced noticeably after adding nano-C–S–H, namely, the compressive strengths were improved by 52% and 47.74% at age of 1 day and 7 days, respectively. More hydration products were observed and pore diameter of cement matrix was refined after adding nano-C–S–H, indicating that the early hydration process of cement was accelerated by nano-C–S–H. This was mainly attributed to seed effect of nano-C–S–H. The detailed relationship between microstructure and early-age performance was also discussed.
Introduction
Cement has been invented for more than 100 years and become one of the fundamental building materials in modern society. Generally, the mechanical property of cement paste developed with curing time . In practice, the mechanical property of normal cement paste is relatively poor at the early age, which cannot meet the demand of strength, and as a result, the curing and demoulding time must be prolonged, reducing the efficiency of construction and leading to a higher cost. At present, researchers have proposed many solutions to improve the early-age strength of cement paste, such as high-temperature steam curing and addition of early strength agents . The high-temperature steam curing method can rapidly improve the early-age strength of cement paste, but it consumes a large amount of energy and produces a mass of greenhouse gases. Moreover, this method is difficult to be widely applied due to its high cost and site limitation . Previous researches have demonstrated that adding a small amount of early strength agent into cement can significantly improve the early-age strength of hardened cement paste. Traditional early strength agents are mainly divided into inorganic and organic category, such as, calcium chloride , sodium sulfate , and calcium formate . Early strength agent is an additional component for cement hydration system, and it's always challengeable to deal with the compatibility between cement and additives. Traditional early strength agents can effectively improve the early strength of concrete or mortar, but it also brings a series of negative effects. For instance, chloride ions will accelerate the electrochemical corrosion of steel bars and reduce the reliability of concrete structures . The introduction of sodium ions will cause excessive alkalinity in concrete, which will adversely affect the long-term strength of concrete . Formate ions have a certain impact on the corrosion resistance and freeze-thaw resistance of concrete . In recent decades, scientists have done much work to reduce the negative effects of traditional early strength agents, but the situation remains unchanged. Therefore, it's urgent to develop a novel and harmless early strength agent.
Recently, with the development of nanotechnology, some nanomaterials have been introduced into cement to improve its comprehensive performance by regulating the nanostructure . For example, nano-SiO 2 is of high activity and can react with Ca(OH) 2 easily, generating calcium silicate hydrate (C-S-H), which can promote the secondary hydration of cement and improve the mechanical property and durability of cement-based materials . It is well-known that the hydration process of cement is complicated and main hydration products contain C-S-H gel, Ca(OH) 2 , ettringite, etc. In light of avoiding the adverse impact of heterogenous component, some researchers proposed that nano calcium silicate hydrate (nano-C-S-H) should be added into cement to adjust the hydration process at nanoscale . Previous works proved that nano-C-S-H can improve the mechanical property of cement-based materials greatly without any risk of electrochemical corrosion or other damages . The mechanism of this enhanced effect of nano-C-S-H has been extensively studied; however, there is no academic viewpoint accepted by all people . At present, most researchers tend to support this view that nano-C-S-H is similar in chemical composition and microscopic morphology to C-S-H formed in the hydration reaction, and nano-C-S-H can participate in the hydration reaction as a seed crystal, and thus the nucleation barrier of C-S-H on the heterogenous interface is reduced. Consequently, the hydration rate of cement is accelerated and the mechanical property is improved . In general, the performance degradation of cement-based materials is usually induced at initial stage, and the early-age performance is vital to the long-term performance. Through summarizing the literatures, it can be found that researchers paid more attention to explain the modification mechanism of nano-C-S-H on cement than to investigate the relationship between the early-age performance and microstructure.
In this paper, the aim is to investigate the effect of nano-C-S-H on the early-age performance of cement paste and figure out the relationship between microstructure and early-age performance including mechanical property and workability. Specifically, the fluidity, autogenous shrinkage, and compressive strength were measured under different addition of nano-C-S-H. And the micromorphology, crystal phases, and pore structure parameters were used to explain the variation of early-age performance. This work may provide a guidance for how to use nano-C-S-H efficiently in improving the early-age comprehensive performance of cement-based materials.
2 Experimental procedure 2.1 Raw materials Cement used in study was Conch brand P.O. 42.5 cement with specific surface area of 350 m 2 /kg and apparent density of 3.15 g/cm 3 , and the chemical composition is shown in Table 1. Solid polycarboxylic superplasticizer with water reducing rate of over 30% was used. Nano-C-S-H suspension was a commercial product with a solid content of 20%, purchased from Changan Construction Material Co., Ltd.
Samples preparation
The water to cement ratio was fixed as 0.36 for all samples, and the content of superplasticizer was 0.025% by mass of cement. And different amounts of nano-C-S-H suspension were added as shown in Table 2. First, 700 g cement and corresponding amount of water were added into the agitator kettle and mixed for 1 min at a low speed mode. And then 0.175 g superplasticizer and corresponding amount of nano-C-S-H were added into the cement paste and mixed for another 1 min at a fast speed mode. Subsequently, the fresh cement paste was casted in the mould (40 mm × 40 mm × 40 mm) and demoulded after one day. At last, samples were cured in a standard room for 3 days and 7 days. The samples were labeled as S-n, where n% stood for the content of solid nano-C-S-H. For instance, S-0.25 meant that the content of solid nano-C-S-H was 0.25% by mass of cement.
Characterization methods
The fluidity of cement paste was measured according to Chinese standard GB/T 8077-2012. After the initial measurement, the fluidity was tested every half an hour until 60 min. The autogenous shrinkage of cement paste was continuously monitored for 7 days by a special apparatus recommended by American standard ASTM C1698. The apparatus was equipped with a bellows (Φ20 mm × 420 mm) and an electronic dial gauge. In a typical test process, the fresh cement paste was poured to the bellow with continuous vibration on a mini-vibrostand until the bellow was filled with cement paste. And then the bellow was laid on a holder with free motion on horizontal. The deformation of the bellow was recorded by an electronic dial gauge. The compressive strength of hardened cement paste was measured according to Chinese standard GB/T 17671-2020. After measuring the compressive strength, the crushed sample was collected and then immersed in absolute ethyl alcohol for 7 days to stop further hydration, and finally, these treated samples were dried at 80°C for micro characterizations. The crystal phases of hydration products were identified with an X-ray diffraction detector (Rigaku, D/max 2550VB/PC) with a Cu Ka ray source operating at 40 kV and 100 mA. The diffraction intensity between 10°and 70°was continuously recorded with the interval of 0.02°at the speed of 4°/min. The pore structure of hardened cement paste was measured by mercury intrusion porosimetry (Quantachrome, Poremaster). Scanning electron microscope (Hitachi, TM4000Plus) was used to observe the micromorphology of hydration products.
Results and discussion
3.1 Property of nano-C-S-H Figure 1(a) shows that the nano-C-S-H suspension was milky white and there was no precipitation, indicating that the nano-C-S-H suspension has good dispersion and high stability. Figure 1(b) shows the particle size distribution curve of nano-C-S-H suspension. It can be seen that the particle size of most particles was lower than 100 nm, and the proportion of the particle (about 70 nm) was the highest (18%), suggesting that the nanoparticles in the suspension were well-dispersed. Figure 1(c) is the X-ray diffraction pattern of the solid particles obtained by centrifugal treatment of the suspension, and diffraction peaks at 2θ = 29.355°, 32.053°, and 50.077°were obviously observed, which corresponded to the characteristic diffraction peaks of Ca 1.5 SiO 3.5 ·H 2 O according to PDF#33-0306. In Figure 1(d), TEM image of nano-C-S-H is shown, and the particle size was less than 100 nm, which was consistent with the particle size distribution curve. Based on the aforementioned analysis, it can be inferred that the C-S-H nanoparticles adopted in this study had good dispersion, high crystallinity, and good compatibility with Portland cement system. Table 3 shows the effect of nano-C-S-H on the fluidity of cement paste. The initial fluidity of cement paste increased continuously with the dosage of nano-C-S-H. When the content of C-S-H increased to 0.5%, the fluidity reached the maximum value of 172.5 mm; however, as nano-C-S-H dosage was over 0.5%, the fluidity did not increase any more, indicating that nano-C-S-H can only improve the initial fluidity of cement paste within a certain range, which may be related to the organic stabilizer in C-S-H suspension. Nanoparticle stabilizers were usually surfactants, which can improve the fluidity of cement paste as an air entraining agent . Specifically, the organic stabilizer has charges on its surface and would be adsorbed on the surface of cement particles, and under the effect of electrostatic repulsion, cement particles would not aggregate, and consequently water would be released and the fluidity of cement is improved. Therefore, the initial fluidity was increased after incorporating nano-C-S-H suspension. As hydration proceeded, the fluidity loss of S-0 was smaller than that of others, and the fluidity gradual loss of the cement paste increased with the content of nano-C-S-H. The fluidity loss rates of S-0.25 at 30 and 60 min were 7.2 and 11.3%, respectively, and the corresponding values of S-0.5 were 8.8 and 16.4%, respectively. The fluidity loss of S-0.75 was close to that of S-0.5, which indicated that the addition of nano-C-S-H can promote the setting process of cement paste. Specifically, the fluidity loss of cement paste was mainly attributed to the formation of C-S-H gel , which is a continuous silica tetrahedron network structure and can prevent the flow of hydration products. And the amount of C-S-H gel was determined by the hydration degree of cement, and consequently it can be inferred that the incorporation of nano-C-S-H can promote the hydration process and improve the hydration degree. Figure 2 displays the effect of nano-C-S-H on the autogenous shrinkage of cement paste. It can be seen that the samples held a similar trend in early-age deformation within 7 days. And the autogenous shrinkage process can be approximately divided into three stages. In the first stage (0-5 h), there was a sharp shrinkage, which may be related to the redistribution of water in the solid-liquid system. It can be simply understood from the fact that most water would be rapidly adsorbed by cement particles and the wet cement particles tend to aggregate, thus leading to a huge deformation. The second stage ranged from 5 to 20 h, in which an obvious expansion can be observed. This stage corresponded to the accelerating stage of cement hydration reaction and massive heat would be generated in this stage. Therefore, the volume of cement paste would expand noticeably under the effect of hydration heat . Moreover, a small amount of free CaO in cement reacted with water and produced Ca(OH) 2 , resulting in a certain micro-expansion. After 20 h of hydration, the shrinkage deformation got into a relatively stable stage and gradually increased with time. This was considered as the sign of autogenous shrinkage of cement paste. It is well-known that autogenous shrinkage is caused by the chemical shrinkage of cement hydration and the self-drying shrinkage inside the cement paste . In the autogenous shrinkage stage, the autogenous shrinkage of S-0.25 was the largest, which reached 550 µε after 160 h of hydration. The autogenous shrinkage of S-0.5 was lower than that of S-0.25, but much higher than that of S-0. And only the autogenous shrinkage of S-0.75 was lower than that of S-0. Generally, the autogenous shrinkage cement paste is determined by the capillary pressure in pore structure, and capillary pressure is a function of the difference of relative humidity . Moreover, early-age relative humidity can be regarded as an indicator of hydration degree, because faster hydration means larger difference of relative humidity, which will lead to larger autogenous shrinkage. From this perspective, it can be deduced that addition of nano-C-S-H into cement can accelerate hydration reaction and promote the consumption of water, thus reducing the relative humidity and increasing the autogenous shrinkage. And the hydration rate increased with the dosage of nano-C-S-H, so the autogenous shrinkage also increased with nano-C-S-H. However, it should be noticed that the autogenous shrinkage of S-0.75 was much lower than that of S-0. This was probably due to the surfactant component contained in the nano-C-S-H suspension, which can decrease the surface tension of the liquid, thereby reducing the pore pressure . The shrinkage reduction effect of surfactant surpassed the hydration acceleration effect of nano-C-S-H, so the autogenous shrinkage of S-0.75 was the smallest. Among all samples, S-0.5 had the highest strength reaching up to 12.04 MPa, which was increased by 52% compared to S-0, but there was slight decline in strength when the nano-C-S-H content exceeded 5%. According to the strength theory of cement-based materials, the early-age strength of cement paste is determined by the gel to space ratio and micro cracks . The 1-day strength indicated that nano-C-S-H can promote the hydration process of cement and produce more hydration products, thus enhancing the gel to space ratio and improving the strength.
Compressive strength
When the content of nano-C-S-H was excess, the surfactant components in nano-C-S-H suspension were adsorbed on the surface of cement particles, which prevented the migration and diffusion of ions in the cement paste to some extent and thus slowed down the hydration rate of cement. The compressive strength of all samples increased with curing age. The compressive strength of S-0.25 was close to that of S-0.5 at the age of 3 days and 7 days. And the compressive strength of S-0.75 at 7 days was the highest (30.2 MPa) which was 1.48 times higher than that of S-0. This can be explained by the fact that nano-C-S-H can promote hydration of cement, which will pose two effects on the strength of cement paste, namely, increasing gel to space ratio and autogenous shrinkage. Although the gel to space ratio of S-0.75 was close to that of S-0.5, the autogenous shrinkage of S-0.75 was much lower than that of S-0.5 as shown in Figure 2, and therefore the compressive strength of S-0.5 was dramatically reduced by the micro cracks induced by autogenous shrinkage. Figure 4 shows the X-ray diffraction patterns of hydration products at different age. During the hydration process (within 7 days), there was little change in the crystal phases of the hydration products, and the main phases were Ca(OH) 2 and some unhydrated cement including tricalcium silicate (C 3 S) and dicalcium silicate (C 2 S). The diffraction intensity of Ca(OH) 2 increased with the curing time and the content of nano-C-S-H, indicating that nano-C-S-H had a significant promoting effect on the hydration of cement. However, no diffraction peak of C-S-H was observed, which may be due to the fact that C-S-H gel generated in hydration reaction was amorphous, so there is no diffraction peak. The diffraction intensity of C 3 S and C 2 S also differed in S-0 and S-0.5, proving that the hydration degree of cement paste was affected by nano-C-S-H. The diffraction peaks of CaCO 3 and SiO 2 were observed, which may be caused by the mineral admixtures in clinker. Figure 5 presents the micromorphology of S-0 and S-0.5 at 1 day. In Figure 5(a), it can be found that S-0 cement matrix was porous and loose, and there were spherical particles distributed homogenously, and a small amount of flocculent substances were formed on the surface of spherical particles. And these flocculent substances were proved to be C-S-H gel by other researchers . Therefore, the further hydration of cement particles was hindered by newly generated C-S-H. This was the main reason that the compressive strength of S-0 was much lower than that of nano-C-S-H-modified samples. In the amplificated image of S-0 as shown in Figure 5(b), needlerod ettringite can be observed, but the space between Figure 5(c) and (d). It can be observed that the matrix of S-0.5 was denser than S-0, and no unhydrated clinker particles were observed, and the number of macropores was significantly reduced, indicating that after the incorporation of nano-C-S-H, the hydration rate was significantly accelerated. From the amplificated image of S-0.5, it's clear that the amount of C-S-H gel was increased and the ettringite was wrapped by C-S-H gel closely. Figure 6 shows the effect of nano-C-S-H on the pore size distribution of cement paste. The pore size of pure cement paste sample S-0 showed an obvious unimodal distribution after 1 day of hydration, and the most probable pore size was about 80 nm. After addition of nano-C-S-H, the most probable pore size of S-0.5 was still 80 nm, but the porosity decreased significantly as show in Table 4, and some smaller pores with diameter between 10 and 80 nm appeared. This can be easily explained by that nano-C-S-H provided more nucleation sites and more hydration products were produced and distributed homogenously, and consequently the macro pores were filled by C-S-H gel and more nanopores were generated inside C-S-H gel, which is not detrimental to the mechanical property of cement-based materials. The porosity of S-0 and S-0.5 samples decreased with hydration time. S-0 still presented a unimodal distribution at the age of 7 days and the most probable pore size decreased to 60 nm, but the pore size distribution range was narrowed. S-0.5 displayed a multimodal distribution and its porosity was the lowest after 7 days of hydration, and additionally the pore size distribution became more complicated. In Table 4, it can be seen that the porosity of cement pastes was noticeably reduced after adding nano-C-S-H at the same hydration age. The pore structure information directly proved that the porosity was refined after adding nano-C-S-H, that is, the macro pores were filled with hydration products and more micropores were produced inside the C-S-H gel.
Conclusion
In summary, nano-C-S-H suspension can improve the initial fluidity of cement paste, and the fluidity gradual loss rate increased with the dosage of nano-C-S-H, reaching up to 16.4% at 60 min. The autogenous shrinkage of cement paste decreased with the content of nano-C-S-H, and the sample with addition of 0.75% nano-C-S-H by mass of cement had the smallest autogenous shrinkage (184 µε), which was even lower than that of pure cement paste (317 µε). Overall, the compressive strength of samples increased with the content of nano-C-S-H and curing time, and the sample doped with 0.75% nano-C-S-H by mass of cement had the highest compressive strength at 7 days (30.2 MPa), which was about 1.48 times higher than that of pure cement paste. This enhanced effect was attributed to the reduction of gel to space ratio and less micro cracks induced by addition of appropriate amount of nano-C-S-H. Microstructure results confirmed that the early hydration reaction of cement was promoted by nano-C-S-H, and nano-C-S-H provided massive nucleation sites and accelerated the mass transfer process, and thus more hydration products were produced. The pore structure was refined by these C-S-H gel, leading to a cement matrix of low porosity and less defect. Author contributions: All authors have accepted responsibility for the entire content of this manuscript and approved its submission. |
Evaluation of a Particle Filter to Track People for Visual Surveillance
Previously a particle filter has been proposed to detect colour objects in video . In this work, the particle filter is adapted to track people in surveillance video. Detection is based on automated background modelling rather than a manually-generated object colour model. A labelling method is proposed that tracks objects through the scene rather than detecting them. A methodical comparison between the new method and two other multi-object trackers is presented on the PETS 2004 benchmark data set. The particle filter gives significantly fewer false alarms due to explicit modelling of the object birth and death processes, while maintaining a good detection rate. |
A House subcommittee on Wednesday approved a bill that would cut the Internal Revenue Service’s budget by nearly one-quarter for fiscal 2014.
The measure would give the IRS $9 billion for fiscal 2014, representing a 24-percent reduction compared to the previous budget cycle and the lowest amount of funding for the agency since 2001.
A House Appropriations subcommittee approved the proposal with a party-line voice vote, moving the measure to the full committee for consideration on a date that is yet to be determined, according to the panel’s staff.
“This bill right-sizes federal agencies and programs that are simply not working efficiently or effectively,” said committee Chairman Hal Rogers (R-Ky.) in a statement before the vote.
Republican lawmakers have shown hostility toward the IRS since a pair of inspector general reports revealed this year that the agency had subjected conservative groups to inappropriate scrutiny and spent lavishly on a 2010 conference in Anaheim.
The National Treasury Employees Union, which represents many IRS and Treasury Department employees, criticized the GOP appropriations bill.
“The drastic cuts to IRS’s budget come at a time when the IRS work force is already facing a dramatically increased workload, with staffing levels down by more than 20 percent below what they were just 15 years ago,” said NTEU President Colleen M. Kelley.
IRS staffing has dropped from 114,000 in 1995 to 91,000 in 2012, according to the NTEU. Meanwhile, the number of tax returns has increased from 205 million to 236 million over that same period, the union said.
The Office of the Taxpayer Advocate in its 2012 report to Congress listed underfunding at the IRS as the third most serious problem facing taxpayers.
Treasury Secretary Jack Lew told lawmakers in May that every dollar appropriated to the IRS brings in $6 to federal coffers.
Obama’s 2014 budget proposal calls for a 9 percent increase in IRS spending, which would bring the agency’s appropriations to about $13 billion for the next fiscal year.
House GOP leaders announced this week that they would advance a series of proposals seemingly aimed at addressing the IRS controversies.
The measures would: allow agencies to place senior career officials on unpaid leave while they are under investigation for abuse; hold agency officials accountable for over-the-top spending on conferences; and prohibit the IRS from enforcing the insurance mandate from President Obama’s health-care law.
Republicans have also criticized the IRS for considering $70 million in bonuses for IRS officials this year.
To connect with Josh Hicks, follow his Twitter feed, friend his Facebook page or e-mail [email protected]. For more federal news, visit The Federal Eye, The Fed Page and Post Politics. E-mail [email protected] with news tips and other suggestions. |
def generate_point_set(n_list, random_seed = 42):
points_list = []
np.random.seed(random_seed)
for n in n_list:
points_list.append(np.random.rand(n,2))
return points_list |
def assess_gradient(self, pixel_a, pixel_b):
diff = np.abs(pixel_a - pixel_b).sum()
return diff |
#include <iostream>
#include <vector>
using namespace std;
int n, x, d[(1 << 20) + 5];
vector<int> ans;
int main(int argc, const char * argv[]) {
cin >> n >> x;
if (x == 0) {
if (n == 2) {
cout << "NO";
return 0;
}
if (n % 3 == 2) {
ans.push_back(1);
ans.push_back(2);
ans.push_back(131072);
ans.push_back(131075);
ans.push_back(0);
d[1] = d[2] = d[131072] = d[131075] = 0;
n -= 5;
}
for (int i = 0; i <= 16 && n > 2; ++i) {
int b = (1 << (i + 1));
for (int a = (1 << i); a < (1 << (i + 1)) && n > 2; ++a) {
if (d[a])
continue;
while (d[b] || d[a ^ b])
++b;
d[a] = d[b] = d[a ^ b] = 1;
ans.push_back(a);
ans.push_back(b);
ans.push_back(a ^ b);
n -= 3;
}
}
if (n == 1)
ans.push_back(0);
} else {
d[x] = 1;
for (int i = 0; i <= 16 && n > 3; ++i) {
int b = (1 << (i + 1));
for (int a = (1 << i); a < (1 << (i + 1)) && n > 3; ++a) {
if (d[a])
continue;
while (d[b] || d[a ^ b])
++b;
d[a] = d[b] = d[a ^ b] = 1;
ans.push_back(a);
ans.push_back(b);
ans.push_back(a ^ b);
n -= 3;
}
}
if (n == 1)
ans.push_back(x);
else if (n == 2) {
ans.push_back(0);
ans.push_back(x);
} else if (n == 3) {
ans.push_back(0);
int magic = (1 << 19) - 1;
ans.push_back(magic);
ans.push_back(x ^ magic);
} else if (n > 0) {
cout << "NO";
return 0;
}
}
cout << "YES\n";
for (int i: ans)
cout << i << ' ';
}
|
<filename>petstagram/petstagram/accounts/tests.py
import logging
from datetime import date
from django import test as django_test
from django.contrib.auth import get_user_model
from django.urls import reverse
from petstagram.accounts.models import Profile
from petstagram.main.models import Pet, PetPhoto
UserModel = get_user_model()
class ProfileDetailsViewTests(django_test.TestCase):
VALID_USER_CREDENTIALS = {
'username': 'testuser',
'password': '<PASSWORD>',
}
VALID_PROFILE_DATA = {
'first_name': 'Test',
'last_name': 'User',
'picture': 'http://test.picture/url.png',
'date_of_birth': date(1990, 4, 13),
}
VALID_PET_DATA = {
'name': 'The pet',
'type': Pet.CAT,
}
VALID_PET_PHOTO_DATA = {
'photo': 'asd.jpg',
'publication_date': date.today(),
}
def __create_user(self, **credentials):
return UserModel.objects.create_user(**credentials)
def __create_valid_user_and_profile(self):
user = self.__create_user(**self.VALID_USER_CREDENTIALS)
profile = Profile.objects.create(
**self.VALID_PROFILE_DATA,
user=user,
)
return (user, profile)
def __create_pet_and_pet_photo_for_user(self, user):
pet = Pet.objects.create(
**self.VALID_PET_DATA,
user=user,
)
pet_photo = PetPhoto.objects.create(
**self.VALID_PET_PHOTO_DATA,
user=user,
)
pet_photo.tagged_pets.add(pet)
pet_photo.save()
return (pet, pet_photo)
def __get_response_for_profile(self, profile):
return self.client.get(reverse('profile details', kwargs={'pk': profile.pk}))
def test_when_opening_not_existing_profile__expect_404(self):
response = self.client.get(reverse('profile details', kwargs={
'pk': 1,
}))
self.assertEqual(404, response.status_code)
def test_expect_correct_template(self):
_, profile = self.__create_valid_user_and_profile()
self.__get_response_for_profile(profile)
self.assertTemplateUsed('accounts/profile_details.html')
def test_when_user_is_owner__expect_is_owner_to_be_true(self):
_, profile = self.__create_valid_user_and_profile()
self.client.login(**self.VALID_USER_CREDENTIALS)
response = self.__get_response_for_profile(profile)
self.assertTrue(response.context['is_owner'])
def test_when_user_is_not_owner__expect_is_owner_to_be_false(self):
_, profile = self.__create_valid_user_and_profile()
credentials = {
'username': 'testuser2',
'password': '<PASSWORD>',
}
self.__create_user(**credentials)
self.client.login(**credentials)
response = self.__get_response_for_profile(profile)
self.assertFalse(response.context['is_owner'])
def test_when_no_photo_likes__expect_total_likes_count_to_be_0(self):
user, profile = self.__create_valid_user_and_profile()
self.__create_pet_and_pet_photo_for_user(user)
response = self.__get_response_for_profile(profile)
self.assertEqual(0, response.context['total_likes_count'])
def test_when_photo_likes__expect_total_likes_count_to_be_correct(self):
likes = 3
user, profile = self.__create_valid_user_and_profile()
_, pet_photo = self.__create_pet_and_pet_photo_for_user(user)
pet_photo.likes = likes
pet_photo.save()
response = self.__get_response_for_profile(profile)
self.assertEqual(likes, response.context['total_likes_count'])
def test_when_no_photos__no_photos_count(self):
# same as likes
pass
def test_when_user_has_pets__expect_to_return_only_users_pets(self):
user, profile = self.__create_valid_user_and_profile()
credentials = {
'username': 'testuser2',
'password': '<PASSWORD>',
}
user2 = self.__create_user(**credentials)
pet, _ = self.__create_pet_and_pet_photo_for_user(user)
# Create a pet/pets for different user
self.__create_pet_and_pet_photo_for_user(user2)
response = self.__get_response_for_profile(profile)
self.assertListEqual(
[pet],
response.context['pets'],
)
def test_when_user_has_no_pets__pets_should_be_empty(self):
_, profile = self.__create_valid_user_and_profile()
response = self.__get_response_for_profile(profile)
self.assertListEqual(
[],
response.context['pets'],
)
def test_when_no_pets__likes_and_photos_count_should_be_0(self):
pass
|
#!/usr/bin/env python3
import os
import argparse
from pygithub3 import Github
def main():
gh = Github(user='acemod', repo='ACE3')
pull_requests = gh.pull_requests.list().all()
for request in pull_requests:
files = gh.pull_requests.list_files(request.number).all()
for file in files:
# print file.filename
if '.sqf' in file.filename:
print file
if __name__ == "__main__":
main() |
package com.twist.mqtt.pojo;
import java.io.Serializable;
/**
* @description: PUBREL重发消息存储
* @author: chenyingjie
* @create: 2019-01-07 21:19
**/
public class DupPubRelMessageStore implements Serializable {
private static final long serialVersionUID = -7663550911852542322L;
private String clientId;
private int messageId;
public DupPubRelMessageStore(){
}
public String getClientId() {
return this.clientId;
}
public DupPubRelMessageStore setClientId(String clientId) {
this.clientId = clientId;
return this;
}
public int getMessageId() {
return this.messageId;
}
public DupPubRelMessageStore setMessageId(int messageId) {
this.messageId = messageId;
return this;
}
}
|
def _is_index(self, data, payload):
return payload["name"] == settings.STATICPAGES_INDEX_NAME |
def location_search_to_csv(data):
return meta_data_in_row_to_csv(data, LOCATION_SEARCH_META_FIELDS,
SEARCH_DATA_FIELDS) |
def convolution2d(image, kernel):
im_h, im_w = image.shape
ker_h, ker_w = kernel.shape
out_h = im_h - ker_h + 1
out_w = im_w - ker_w + 1
output = np.zeros((out_h, out_w))
for out_row in range(out_h):
for out_col in range(out_w):
current_product = 0
for i in range(ker_h):
for j in range(ker_w):
current_product += image[out_row + i, out_col + j] * kernel[i, j]
output[out_row, out_col] = current_product
return output |
In the last installment of this series, I looked at the math behind attack rolls in Warmachine. This time, I’m going to move onto damage rolls, as once you scratch the surface and get past the notion that “average dice equals seven,” there is some interesting stuff going on in the probabilities.
For the uninitiated, Warmachine uses 2d6 to resolve most attack and damage rolls. Generally, when making an attack against an enemy model, you must roll 2d6, add your attack modifier, and equal or beat the opposing model’s DEF to score a hit. Once you have hit, you determine how much damage you do by again rolling 2d6, adding the POW/P+S of the weapon you are attacking with, and comparing it to the ARM value of the opposing model. For every point that this roll exceeds ARM, you do one point of damage to the opposing model. Models in Warmachine have anywhere from one to sixty or more hit points or “boxes,” and to make it easier, players usually mentally subtract the opposing player’s ARM from their POW before rolling damage — calculating that, for example, with a POW of 16 up against an ARM of 20, they will do 2d6-4 or “dice minus four” damage.
Single wound or multi-wound?
Before I get started, I would like to point out that there is a difference between single wound and multi-wound models. For single wound models, you only have to do a single point of damage to kill them, which means that you get the same result (usually, a dead enemy model) whether your roll beats their ARM by one or by a lot. Since we don’t care how much we overkill a single-wound model by**, our math actually resembles the to-hit rolls we discussed last week in that we’re essentially rolling to hit a target number, which in this case is one higher than their ARM value, in order to do at least one point of damage and kill the opposing model.
Additionally, for a multi-wound model, you can also use a similar principle to calculate your odds of one-shot killing the model, by simply adding up the number of boxes and the ARM to figure out what you need to roll to one-shot kill the enemy model.
Since the math on trying to roll a target number or better and not caring how much you beat the target number by was discussed extensively last week, right now I’m going to focus on a case where you are up against a multi-wound model, and assume you are just trying to do as much damage as you can.
Widowmakers vs. Forge Seer
A couple weeks ago, I was playing a game and having some Khador-on-Khador action. My opponent had a Greylord Forge Seer marshalling a warjack, and had left it in the open and within striking distance of an entire four-man squad of Widowmaker Scouts and a single Widowmaker Marksman.
Due to the accuracy of the sniper rifles on the Widowmakers (who says the Khadorans don’t have a knack for precision engineering?), hitting the target wasn’t a big problem. At anything but snakes to hit, each individual shot had a 97.2% chance of connecting and I have an over 85% chance of hitting with all five.
The problem, however, comes when it is time to do damage. The opposing Greylord Forge Seer has an ARM of 16 and eight boxes. On the Widowmakers, I have a choice. Due to their Sniper rule, with the Scouts, on a hit, I can choose to either do one point of damage automatically or roll a POW 10, and with the Marksman, I can choose to either do three points of damage or roll a POW 12.
Adding up the automatic damage, we see that if I take advantage of the Sniper rule, doing one point of damage four times and three points of damage once, I will end up doing seven points of damage — just shy of what I need to kill this Forge Seer. Since I would rather him not survive until the next turn, that won’t do.
So, if I want any chance of killing him at all, I use my POW 10s and POW 12s and roll it out. Here is where the math gets interesting…
Dice minus X…
“Average dice” theory states that since “average dice” on 2d6 equals seven, my Scouts, doing 2d6-6 damage, will on average do one point of damage each, while my Marksman, doing 2d6-4, will on average do three points. Again, this adds up to seven damage, which means that I will probably not manage to kill the Greylord Forge Seer.
Fortunately for me, the math of the “average dice” theory is wrong. To calculate the expected value of a random discrete variable such as a series of die rolls, it’s a simple matter of, for each possible outcome, multiplying the probability by the outcome. The formula for the expected value*** on a damage roll, thus, is:
E(x) = x 1 p 1 + x 2 p 2 + x 3 p 3 + … x n p n
Where, for each possible outcome on the dice, p is the probability of said outcome and x is the damage.
When we start calculating this for 2d6, we start to notice something interesting…
From dice minus two upwards, for every +1 you add to the roll, the expected value of your damage increases by one. In this area, the “average dice” theory seems to more or less work out, in that the expected value of 2d6-1 is equal to 6, the expected value of 2d6 is equal to 7, and so on. However, as we go into dice minus three and lower, the curve starts to flatten out and trail off, only hitting zero when we get to dice minus 12 and can’t possibly roll a thirteen or better on two dice.
This is because you can’t roll negative damage. Think of it this way — if you are rolling damage at dice minus seven, and you roll snakes (2) once and boxcars (12) once, you have rolled perfectly average over those two rolls, but you still did five points of damage. That time you rolled snakes, you didn’t heal the opposing warjack for five points of damage, you simply failed to crack ARM and did nothing. As such, you did five more points of damage than the “average dice equals seven” theory would imply because your low roll didn’t “cancel out” your high roll in any way.
Looking at the blue curve, even at dice minus seven and below, you still have a chance of rolling high and doing damage. In fact, the expected value on 2d6-7 damage is almost a full point higher than what the “average dice” theory states!
So, what does this mean?
Remember my situation with the Widowmakers and the Forge Seers? “Average Dice” implies that I would do seven damage, but if we add up the expected values of four shots at 2d6-6 and one shot at 2d6-4, we get an expected value of 9.333. With the Forge Seer having eight boxes, that means that assuming I hit all my shots, I have a pretty good chance of killing it.
Which is what I did — failing to crack armour on the first two shots, rolling boxcars on the third for six damage, using the fourth to kill some random single-wound mook, and then using the Marksman to do an automatic three points to finish him off.
To-hit and damage
Of course, this is Warmachine and you can always miss. If you want to factor in your odds of hitting, all you have to do is multiply the expected value on your damage roll by the probability that your attack roll will hit. In this case, since I need not snakes on all my shots, I simply multiply the EV by my the probaility of hitting. In the Widowmakers case, it’s an easy calculation, multiplying the EV by 0.972, as I have a 97.2% chance of not rolling snakes, but this can be done for any to-hit value and dice plus/minus value on damage
Final thoughts
Against single-wound models, or when you want to calculate the probaility that you will one-shot something, you can simply adapt last week’s to-hit results
Below 2d6-2, the “average dice” theory of calculating damage breaks down
The expected value on your damage roll at this point is higher than you might otherwise expect, because low rolls do zero damage instead of negative damage that might cancel out the high rolls
To factor in your chance of missing, simply multiply the EV of your damage roll by your hit probability, and you can figure out the EV of the amount of damage you will do before you even make the attack roll.
For multiple attacks, simply add up the EV of each individual attack, factoring in your hit probability. Doing so, you can figure out the “DPS” of a multi-attacking model such as a warjack or warbeast against models of a certain DEF and ARM value.
As always, the dice gods are fickle and literally any possible outcome, even some extreme outcome with very low odds, can happen.
Stay tuned next time for when I discuss what happens when you start throwing additional dice into the mix, and maybe if you’re lucky, why Vlad1 is really really good!
**Except maybe for bragging rights and to laugh at how badly some guy got splattered. Like last weekend, where I overkilled a Cygnaran warcaster by 34 points…
***Again, I’m using the term “expected value” in the mathematical sense to represent the mean outcome, weighted by probability. Over hundreds and thousands of rolls, you would expect your average outcome to converge on this value. But on one individual trial, you can still roll anything from snakes to boxcars. Just because something is the expected value, don’t count on it, because about 50% of the time, you will be disappointed.
Advertisements |
def create(self, schema, bases=None):
if not bases:
bases = []
extra_bases = []
if schema['id'] == 'ProjectSchema':
extra_bases = [ftrack_api.entity.project_schema.ProjectSchema]
elif schema['id'] == 'Location':
extra_bases = [ftrack_api.entity.location.Location]
elif schema['id'] == 'AssetVersion':
extra_bases = [ftrack_api.entity.asset_version.AssetVersion]
elif schema['id'].endswith('Component'):
extra_bases = [ftrack_api.entity.component.Component]
elif schema['id'] == 'Note':
extra_bases = [ftrack_api.entity.note.Note]
elif schema['id'] == 'Job':
extra_bases = [ftrack_api.entity.job.Job]
elif schema['id'] == 'User':
extra_bases = [ftrack_api.entity.user.User]
bases = extra_bases + bases
if not bases:
bases = [ftrack_api.entity.base.Entity]
if 'notes' in schema.get('properties', {}):
bases.append(
ftrack_api.entity.note.CreateNoteMixin
)
if 'thumbnail_id' in schema.get('properties', {}):
bases.append(
ftrack_api.entity.component.CreateThumbnailMixin
)
cls = super(StandardFactory, self).create(schema, bases=bases)
return cls |
package net.floodlightcontroller.sos;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.projectfloodlight.openflow.protocol.match.MatchField;
import org.projectfloodlight.openflow.protocol.OFFactory;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPacketIn;
import org.projectfloodlight.openflow.protocol.OFPacketOut;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.types.DatapathId;
import org.projectfloodlight.openflow.types.EthType;
import org.projectfloodlight.openflow.types.IPv4Address;
import org.projectfloodlight.openflow.types.IPv6Address;
import org.projectfloodlight.openflow.types.IpProtocol;
import org.projectfloodlight.openflow.types.MacAddress;
import org.projectfloodlight.openflow.types.OFBufferId;
import org.projectfloodlight.openflow.types.OFPort;
import org.projectfloodlight.openflow.types.U64;
import org.projectfloodlight.openflow.types.VlanVid;
import org.projectfloodlight.openflow.protocol.OFType;
import org.projectfloodlight.openflow.protocol.action.OFAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.IOFSwitchListener;
import net.floodlightcontroller.core.PortChangeType;
import net.floodlightcontroller.core.internal.IOFSwitchService;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.SwitchPort;
import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryService;
import net.floodlightcontroller.packet.ARP;
import net.floodlightcontroller.packet.Data;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.packet.TCP;
import net.floodlightcontroller.packet.UDP;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.Link;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.sos.web.SOSWebRoutable;
import net.floodlightcontroller.staticflowentry.IStaticFlowEntryPusherService;
import net.floodlightcontroller.threadpool.IThreadPoolService;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.topology.NodePortTuple;
/**
* Steroid OpenFlow Service Module
* @author <NAME>, <EMAIL>
*
*/
public class SOS implements IOFMessageListener, IOFSwitchListener, IFloodlightModule, ISOSService {
private static final Logger log = LoggerFactory.getLogger(SOS.class);
protected static IFloodlightProviderService floodlightProvider;
protected static IOFSwitchService switchService;
private static IRoutingService routingService;
private static IDeviceService deviceService;
protected static IStaticFlowEntryPusherService sfp;
private static IRestApiService restApiService;
private static ITopologyService topologyService;
private static IThreadPoolService threadPoolService;
private static ILinkDiscoveryService linkDiscoveryService;
private static ScheduledFuture<?> agentMonitor;
private static MacAddress controllerMac;
private static SOSConnections sosConnections;
private static Set<SOSAgent> agents;
private static boolean enabled;
/* These needs to be constant b/t agents, thus we'll keep them global for now */
private static int bufferSize;
private static int agentQueueCapacity;
private static int agentNumParallelSockets;
private static short flowTimeout;
private static long routeMaxLatency; //TODO
private static long latencyDifferenceThreshold = 20;
private static SOSStatistics statistics;
/* Keep tabs on our agents; make sure dev mgr will have them cached */
private class SOSAgentMonitor implements Runnable {
@Override
public void run() {
try {
for (SOSAgent a : agents) {
/* Lookup agent's last known location */
Iterator<? extends IDevice> i = deviceService.queryDevices(MacAddress.NONE, null, a.getIPAddr(), IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO);
SwitchPort sp = null;
if (i.hasNext()) {
IDevice d = i.next();
SwitchPort[] agentAps = d.getAttachmentPoints();
if (agentAps.length > 0) {
SwitchPort agentTrueAp = findTrueAttachmentPoint(agentAps);
if (agentTrueAp == null) {
log.error("Could not determine true attachment point for agent {} when ARPing for agent. Report SOS bug.", a);
} else {
sp = agentTrueAp;
}
}
} else {
log.error("Device manager could not locate agent {}", a);
}
if (sp != null) { /* We know specifically where the agent is located */
log.trace("ARPing for agent {} with known true attachment point {}", a, sp);
arpForDevice(
a.getIPAddr(),
(a.getIPAddr().and(IPv4Address.of("255.255.255.0"))).or(IPv4Address.of("0.0.0.254")) /* Doesn't matter really; must be same subnet though */,
MacAddress.BROADCAST /* Use broadcast as to not potentially confuse a host's ARP cache */,
VlanVid.ZERO /* Switch will push correct VLAN tag if required */,
switchService.getSwitch(sp.getSwitchDPID())
);
} else { /* We don't know where the agent is -- flood ARP everywhere */
Set<DatapathId> switches = switchService.getAllSwitchDpids();
log.warn("Agent {} does not have known/true attachment point(s). Flooding ARP on all switches", a);
for (DatapathId sw : switches) {
log.trace("Agent {} does not have known/true attachment point(s). Flooding ARP on switch {}", a, sw);
arpForDevice(
a.getIPAddr(),
(a.getIPAddr().and(IPv4Address.of("255.255.255.0"))).or(IPv4Address.of("0.0.0.254")) /* Doesn't matter really; must be same subnet though */,
MacAddress.BROADCAST /* Use broadcast as to not potentially confuse a host's ARP cache */,
VlanVid.ZERO /* Switch will push correct VLAN tag if required */,
switchService.getSwitch(sw)
);
}
}
}
} catch (Exception e) {
log.error("Caught exception in ARP monitor thread: {}", e);
}
}
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
l.add(IOFSwitchService.class);
l.add(IRoutingService.class);
l.add(IDeviceService.class);
l.add(IStaticFlowEntryPusherService.class);
l.add(IRestApiService.class);
l.add(ITopologyService.class);
l.add(IThreadPoolService.class);
l.add(ILinkDiscoveryService.class);
return l;
}
@Override
public void init(FloodlightModuleContext context) throws FloodlightModuleException {
floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
switchService = context.getServiceImpl(IOFSwitchService.class);
routingService = context.getServiceImpl(IRoutingService.class);
deviceService = context.getServiceImpl(IDeviceService.class);
sfp = context.getServiceImpl(IStaticFlowEntryPusherService.class);
restApiService = context.getServiceImpl(IRestApiService.class);
topologyService = context.getServiceImpl(ITopologyService.class);
threadPoolService = context.getServiceImpl(IThreadPoolService.class);
linkDiscoveryService = context.getServiceImpl(ILinkDiscoveryService.class);
agents = new HashSet<SOSAgent>();
sosConnections = new SOSConnections();
}
@Override
public void startUp(FloodlightModuleContext context) {
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
switchService.addOFSwitchListener(this);
restApiService.addRestletRoutable(new SOSWebRoutable());
/* Read our config options */
int connectionHistorySize = 100;
Map<String, String> configOptions = context.getConfigParams(this);
try {
controllerMac = MacAddress.of(configOptions.get("controller-mac"));
connectionHistorySize = Integer.parseInt(configOptions.get("connection-history-size") == null ? "100" : configOptions.get("connection-history-size"));
/* These are defaults */
bufferSize = Integer.parseInt(configOptions.get("buffer-size") == null ? "30000" : configOptions.get("buffer-size"));
agentQueueCapacity = Integer.parseInt(configOptions.get("queue-capacity") == null ? "3" : configOptions.get("queue-capacity"));
agentNumParallelSockets = Integer.parseInt(configOptions.get("parallel-tcp-sockets") == null ? "1000" : configOptions.get("parallel-tcp-sockets"));
flowTimeout = Short.parseShort(configOptions.get("flow-timeout") == null ? "60" : configOptions.get("flow-timeout"));
enabled = Boolean.parseBoolean(configOptions.get("enabled") == null ? "true" : configOptions.get("enabled")); /* enabled by default if not present --> listing module is enabling */
routeMaxLatency = Long.parseLong(configOptions.get("max-route-to-agent-latency") == null ? "10" : configOptions.get("max-route-to-agent-latency"));
latencyDifferenceThreshold = Long.parseLong(configOptions.get("route-latency-difference-threshold") == null ? "10" : configOptions.get("route-latency-difference-threshold"));
} catch (IllegalArgumentException | NullPointerException ex) {
log.error("Incorrect SOS configuration options. Required: 'controller-mac', 'buffer-size', 'queue-capacity', 'parallel-tcp-sockets', 'flow-timeout', 'enabled', 'max-route-to-agent-latency', 'route-latency-difference-threshold'", ex);
throw ex;
}
if (log.isInfoEnabled()) {
log.info("Initial config options: connection-history-size:{}, buffer-size:{}, queue-capacity:{}, parallel-tcp-sockets:{}, flow-timeout:{}, enabled:{}",
new Object[] { connectionHistorySize, bufferSize, agentQueueCapacity, agentNumParallelSockets, flowTimeout, enabled });
}
statistics = SOSStatistics.getInstance(connectionHistorySize);
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Collection<Class<? extends IFloodlightService>> l =
new ArrayList<Class<? extends IFloodlightService>>();
l.add(ISOSService.class);
return l;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
m.put(ISOSService.class, this);
return m;
}
@Override
public String getName() {
return SOS.class.getSimpleName();
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
/*
* Allow the CONTEXT_SRC/DST_DEVICE field to be populated by
* the DeviceManager. This makes our job easier :)
*/
if (type == OFType.PACKET_IN && name.equalsIgnoreCase("devicemanager")) {
log.trace("SOS is telling DeviceManager to run before.");
return true;
} else {
return false;
}
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
if (type == OFType.PACKET_IN && (name.equals("forwarding") || name.equals("hub"))) {
log.trace("SOS is telling Forwarding/Hub to run later.");
return true;
} else {
return false;
}
}
/**
* Send a UDP information packet to an agent. This informs the agent of the SOS
* connection about to take place. For example, a client-side agent is informed of
* the server-side agent to connect to, the number of parallel sockets to open up,
* and so forth. A server-side agent is informed of the the number of parallel
* connections to establish server sockets, the server IP itself, and so forth.
*
* @param conn, The associated SOSConnection for the UDP info packets.
* @param isSourceAgent, Send to source agent (true); send to destination agent (false).
*/
private void sendInfoToAgent(FloodlightContext cntx, SOSConnection conn, boolean isClientSideAgent) {
OFFactory factory;
/* Both use route last-hop, since the packets are destined for the agents */
if (isClientSideAgent) {
factory = switchService.getSwitch(conn.getClientSideRoute().getRouteLastHop().getNodeId()).getOFFactory();
} else {
factory = switchService.getSwitch(conn.getServerSideRoute().getRouteLastHop().getNodeId()).getOFFactory();
}
OFPacketOut.Builder ofPacket = factory.buildPacketOut();
ofPacket.setBufferId(OFBufferId.NO_BUFFER);
/* L2 of packet */
Ethernet l2 = new Ethernet();
l2.setSourceMACAddress(controllerMac);
l2.setDestinationMACAddress(isClientSideAgent ? conn.getClientSideAgent().getMACAddr() : conn.getServerSideAgent().getMACAddr());
l2.setEtherType(EthType.IPv4);
log.trace("Set info packet destination MAC to {}", l2.getDestinationMACAddress());
/* L3 of packet */
IPv4 l3 = new IPv4();
l3.setSourceAddress(isClientSideAgent ? conn.getServerSideAgent().getIPAddr() : conn.getServer().getIPAddr());
l3.setDestinationAddress(isClientSideAgent ? conn.getClientSideAgent().getIPAddr() : conn.getServerSideAgent().getIPAddr());
l3.setProtocol(IpProtocol.UDP);
l3.setTtl((byte) 64);
log.trace("Set info packet source IP to {}", l3.getSourceAddress());
log.trace("Set info packet destination IP to {}", l3.getDestinationAddress());
/* L4 of packet */
UDP l4 = new UDP();
l4.setSourcePort(conn.getServer().getTcpPort());
l4.setDestinationPort(isClientSideAgent ? conn.getClientSideAgent().getControlPort() : conn.getServerSideAgent().getControlPort());
log.trace("Set info packet source port to {}", l4.getSourcePort());
log.trace("Set info packet destination port to {}", l4.getDestinationPort());
/*
* Convert the string into IPacket. Data extends BasePacket, which is an abstract class
* that implements IPacket. The only class variable of Data is the byte[] 'data'. The
* deserialize() method of Data is the following:
*
* public IPacket deserialize(byte[] data, int offset, int length) {
* this.data = Arrays.copyOfRange(data, offset, data.length);
* return this;
* }
*
* We provide the byte[] form of the string (ASCII code bytes) as 'data', and 0 as the
* 'offset'. The 'length' is not used and instead replaced with the length of the byte[].
* Notice 'this' is returned. 'this' is the current Data object, which only has the single
* byte[] 'data' as a class variable. This means that when 'this' is returned, it will
* simply be a byte[] form of the original string as an IPacket instead.
*/
String agentInfo = null;
if (isClientSideAgent) {
/*payload = "CLIENT " + str(transfer_id) +
" " + ip_to_str(packet.next.srcip) +
" " + str(packet.next.next.srcport) +
" " + ip_to_str(inst.Agent[FA]['ip']) +
" " + str(NUM_CONNECTIONS) +
" " + str(BUFSIZE) +
" " +str(MAX_QUEUE_SIZE) */
log.debug(conn.getTransferID().toString());
agentInfo = "CLIENT " + conn.getTransferID().toString() +
" " + conn.getClient().getIPAddr().toString() +
" " + conn.getClient().getTcpPort().toString() +
" " + conn.getServerSideAgent().getIPAddr().toString() +
" " + Integer.toString(conn.getNumParallelSockets()) +
" " + Integer.toString(conn.getBufferSize()) +
" " + Integer.toString(conn.getQueueCapacity());
} else {
/*payload = "AGENT " + str(transfer_id) +
" " + ip_to_str(packet.next.dstip) +
" " + str(packet.next.next.dstport) +
" " + str(NUM_CONNECTIONS) +
" " + str(BUFSIZE) +
" " + str(MAX_QUEUE_SIZE) */
agentInfo = "AGENT " + conn.getTransferID().toString() +
" " + conn.getServer().getIPAddr().toString() +
" " + conn.getServer().getTcpPort().toString() +
/*
* The server-side agent will learn the client-side agent IP
* after it receives the first TCP SYN packets from the
* client-side agent.
*/
" " + Integer.toString(conn.getNumParallelSockets()) +
" " + Integer.toString(conn.getBufferSize()) +
" " + Integer.toString(conn.getQueueCapacity());
}
Data payloadData = new Data();
/* Construct the packet layer-by-layer */
l2.setPayload(l3.setPayload(l4.setPayload(payloadData.setData(agentInfo.getBytes()))));
/*
* Tell the switch what to do with the packet. This is specified as an OFAction.
* i.e. Which port should it go out?
*/
ofPacket.setInPort(OFPort.ANY);
List<OFAction> actions = new ArrayList<OFAction>();
if (isClientSideAgent) {
log.debug("Sending client-side info packet to agent {} out switch+port {}", conn.getClientSideAgent(), conn.getClientSideRoute().getRouteLastHop());
actions.add(factory.actions().output(conn.getClientSideRoute().getRouteLastHop().getPortId(), 0xffFFffFF));
} else {
log.debug("Sending server-side info packet to agent {} out switch+port {}", conn.getServerSideAgent(), conn.getServerSideRoute().getRouteLastHop());
actions.add(factory.actions().output(conn.getServerSideRoute().getRouteLastHop().getPortId(), 0xffFFffFF));
}
ofPacket.setActions(actions);
/* Put the UDP packet in the OF packet (encapsulate it as an OF packet) */
byte[] udpPacket = l2.serialize();
ofPacket.setData(udpPacket);
/*
* Send the OF packet to the agent switch.
* The switch will look at the OpenFlow action and send the encapsulated
* UDP packet out the port specified.
*/
if (isClientSideAgent) {
switchService.getSwitch(conn.getClientSideRoute().getRouteLastHop().getNodeId()).write(ofPacket.build());
} else {
switchService.getSwitch(conn.getServerSideRoute().getRouteLastHop().getNodeId()).write(ofPacket.build());
}
}
/**
* Send an OF packet with the TCP "spark" packet (the packet that "sparked" the SOS session)
* encapsulated inside. This packet is destined for the client-side agent.
*
* @param l2, the Ethernet packet received by the SOS module.
* @param conn, The associated SOSConnection
*/
private void sendClientSideAgentSparkPacket(FloodlightContext cntx, Ethernet l2, SOSConnection conn) {
OFFactory factory = switchService.getSwitch(conn.getClientSideRoute().getRouteLastHop().getNodeId()).getOFFactory();
OFPacketOut.Builder ofPacket = factory.buildPacketOut();
ofPacket.setBufferId(OFBufferId.NO_BUFFER);
/*
* L2 of packet
* Change the dst MAC to the client-side agent
*/
l2.setDestinationMACAddress(conn.getClientSideAgent().getMACAddr());
/*
* L3 of packet
* Change the dst IP to the client-side agent
*/
IPv4 l3 = (IPv4) l2.getPayload();
l3.setDestinationAddress(conn.getClientSideAgent().getIPAddr());
/*
* L4 of packet
* Change destination TCP port to the one the agent is listening on
*/
TCP l4 = (TCP) l3.getPayload();
l4.setDestinationPort(conn.getClientSideAgent().getDataPort());
/*
* Reconstruct the packet layer-by-layer
*/
l3.setPayload(l4);
l2.setPayload(l3);
/*
* Tell the switch what to do with the packet. This is specified as an OFAction.
* i.e. Which port should it go out?
*/
ofPacket.setInPort(OFPort.ANY);
List<OFAction> actions = new ArrayList<OFAction>();
/* Output to the client-side agent -- this is the last hop of the route */
actions.add(factory.actions().output(conn.getClientSideRoute().getRouteLastHop().getPortId(), 0xffFFffFF));
ofPacket.setActions(actions);
/* Put the TCP spark packet in the OF packet (encapsulate it as an OF packet) */
ofPacket.setData(l2.serialize());
/*
* Send the OF packet to the agent switch.
* The switch will look at the OpenFlow action and send the encapsulated
* TCP packet out the port specified.
*/
switchService.getSwitch(conn.getClientSideRoute().getRouteLastHop().getNodeId()).write(ofPacket.build());
}
/**
* Send an OF packet with the TCP "spark" packet (the packet that "sparked" the SOS session)
* encapsulated inside. This packet is destined for the server from the server-side agent.
*
* @param l2, the Ethernet packet received by the SOS module.
* @param conn, The associated SOSConnection
*/
private void sendServerSparkPacket(FloodlightContext cntx, Ethernet l2, SOSConnection conn) {
OFFactory factory = switchService.getSwitch(conn.getServerSideRoute().getRouteFirstHop().getNodeId()).getOFFactory();
OFPacketOut.Builder ofPacket = factory.buildPacketOut();
ofPacket.setBufferId(OFBufferId.NO_BUFFER);
/*
* L2 of packet
* Change the dst MAC to the server
*/
l2.setSourceMACAddress(conn.getClient().getMACAddr());
/*
* L3 of packet
* Change the dst IP to the server
*/
IPv4 l3 = (IPv4) l2.getPayload();
l3.setSourceAddress(conn.getClient().getIPAddr());
/*
* L4 of packet
* Change source TCP port to the one the agent has opened
*/
TCP l4 = (TCP) l3.getPayload();
l4.setSourcePort(conn.getServerSideAgentTcpPort());
/*
* Reconstruct the packet layer-by-layer
*/
l3.setPayload(l4);
l2.setPayload(l3);
/*
* Tell the switch what to do with the packet. This is specified as an OFAction.
* i.e. Which port should it go out?
*/
ofPacket.setInPort(OFPort.ANY);
List<OFAction> actions = new ArrayList<OFAction>();
/* Output to the port facing the server -- route first hop is the server's AP */
actions.add(factory.actions().output(conn.getServerSideRoute().getRouteFirstHop().getPortId(), 0xffFFffFF));
ofPacket.setActions(actions);
/* Put the TCP spark packet in the OF packet (encapsulate it as an OF packet) */
ofPacket.setData(l2.serialize());
/*
* Send the OF packet to the switch.
* The switch will look at the OpenFlow action and send the encapsulated
* TCP packet out the port specified.
*/
switchService.getSwitch(conn.getServerSideRoute().getRouteFirstHop().getNodeId()).write(ofPacket.build());
}
/**
* Synchronized, so that we don't want to have to worry about multiple connections starting up at the same time.
*/
@Override
public synchronized net.floodlightcontroller.core.IListener.Command receive(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
/*
* If we're disabled, then just stop now
* and let Forwarding/Hub handle the connection.
*/
if (!enabled) {
log.trace("SOS disabled. Not acting on packet; passing to next module.");
return Command.CONTINUE;
} else {
/*
* SOS is enabled; proceed
*/
log.trace("SOS enabled. Inspecting packet to see if it's a candidate for SOS.");
}
OFPacketIn pi = (OFPacketIn) msg;
Ethernet l2 = IFloodlightProviderService.bcStore.get(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
if (l2.getEtherType() == EthType.IPv4) {
log.trace("Got IPv4 Packet");
IPv4 l3 = (IPv4) l2.getPayload();
log.trace("Got IpProtocol {}", l3.getProtocol());
if (l3.getProtocol().equals(IpProtocol.TCP)) {
log.debug("Got TCP Packet on port " + (pi.getVersion().compareTo(OFVersion.OF_12) < 0 ?
pi.getInPort().toString() :
pi.getMatch().get(MatchField.IN_PORT).toString()) + " of switch " + sw.getId());
TCP l4 = (TCP) l3.getPayload();
/*
* If this source IP and source port (or destination IP and destination port)
* have already been assigned a connection then we really shouldn't get to
* this point. Flows matching the source IP and source port should have already
* been inserted switching those packets to the source agent.
*/
/* Lookup the source IP address to see if it belongs to a client with a connection */
log.trace("(" + l4.getSourcePort().toString() + ", " + l4.getDestinationPort().toString() + ")");
SOSPacketStatus packetStatus = sosConnections.getSOSPacketStatus(
l3.getSourceAddress(), l3.getDestinationAddress(),
l4.getSourcePort(), l4.getDestinationPort());
if (packetStatus == SOSPacketStatus.INACTIVE_REGISTERED){
/* Process new TCP SOS session */
log.info("Packet status was inactive but registered. Proceed with SOS.");
IDevice srcDevice = IDeviceService.fcStore.get(cntx, IDeviceService.CONTEXT_SRC_DEVICE);
IDevice dstDevice = IDeviceService.fcStore.get(cntx, IDeviceService.CONTEXT_DST_DEVICE);
if (srcDevice == null) {
log.error("Source device was not known. Is DeviceManager running before SOS as it should? Report SOS bug.");
return Command.STOP;
} else {
log.trace("Source device is {}", srcDevice);
}
if (dstDevice == null) {
log.warn("Destination device was not known. ARPing for destination to try to learn it. Dropping TCP packet; TCP should keep retrying.");
arpForDevice(l3.getDestinationAddress(), l3.getSourceAddress(), l2.getSourceMACAddress(), VlanVid.ofVlan(l2.getVlanID()), sw);
return Command.STOP;
} else {
log.trace("Destination device is {}", dstDevice);
}
/* Init Agent/Client */
SOSClient client = new SOSClient(l3.getSourceAddress(), l4.getSourcePort(), l2.getSourceMACAddress());
SOSRoute clientRoute = routeToFriendlyNeighborhoodAgent(client, srcDevice.getAttachmentPoints(), IPv4Address.NONE);
if (clientRoute == null) {
log.error("Could not compute route from client {} to neighborhood agent. Report SOS bug.", client);
for (SOSAgent agent : agents) {
log.warn("Possibly lost agent {}. Emergency ARPing", agent);
for (DatapathId dpid : switchService.getAllSwitchDpids()) {
arpForDevice(
agent.getIPAddr(),
(agent.getIPAddr().and(IPv4Address.of("255.255.255.0"))).or(IPv4Address.of("0.0.0.254")) /* Doesn't matter really; must be same subnet though */,
MacAddress.BROADCAST /* Use broadcast as to not potentially confuse a host's ARP cache */,
VlanVid.ZERO /* Switch will push correct VLAN tag if required */,
switchService.getSwitch(dpid)
);
}
}
return Command.STOP;
} else {
log.debug("Client-to-agent route {}", clientRoute);
}
/* Init Agent/Server */
SOSServer server = new SOSServer(l3.getDestinationAddress(), l4.getDestinationPort(), l2.getDestinationMACAddress());
SOSRoute serverRoute = routeToFriendlyNeighborhoodAgent(server, dstDevice.getAttachmentPoints(),
clientRoute.getRoute() != null ? clientRoute.getDstDevice().getIPAddr() : IPv4Address.NONE);
if (serverRoute == null) {
log.error("Could not compute route from server {} to neighborhood agent. Report SOS bug.", server);
for (SOSAgent agent : agents) {
log.warn("Possibly lost agent {}. Emergency ARPing", agent);
for (DatapathId dpid : switchService.getAllSwitchDpids()) {
arpForDevice(
agent.getIPAddr(),
(agent.getIPAddr().and(IPv4Address.of("255.255.255.0"))).or(IPv4Address.of("0.0.0.254")) /* Doesn't matter really; must be same subnet though */,
MacAddress.BROADCAST /* Use broadcast as to not potentially confuse a host's ARP cache */,
VlanVid.ZERO /* Switch will push correct VLAN tag if required */,
switchService.getSwitch(dpid)
);
}
}
return Command.STOP;
} else {
log.debug("Server-to-agent route {}", serverRoute);
}
SOSRoute interAgentRoute = routeBetweenAgents((SOSAgent) clientRoute.getDstDevice(), (SOSAgent) serverRoute.getDstDevice());
if (interAgentRoute == null) {
log.error("Could not compute route from agent {} to agent {}. Report SOS bug.", (SOSAgent) clientRoute.getDstDevice(), (SOSAgent) serverRoute.getDstDevice());
return Command.STOP;
} else {
log.debug("Inter-agent route {}", interAgentRoute);
}
/* Establish connection */
SOSConnection newSOSconnection = sosConnections.addConnection(clientRoute, interAgentRoute, serverRoute,
agentNumParallelSockets, agentQueueCapacity, bufferSize, flowTimeout);
statistics.addActiveConnection(newSOSconnection);
log.debug("Starting new SOS session: \r\n" + newSOSconnection.toString());
/* Send UDP messages to the home and foreign agents */
log.debug("Sending UDP information packets to client-side and server-side agents");
sendInfoToAgent(cntx, newSOSconnection, true); /* home */
sendInfoToAgent(cntx, newSOSconnection, false); /* foreign */
/* Push flows and add flow names to connection (for removal upon termination) */
log.debug("Pushing client-side SOS flows");
pushRoute(newSOSconnection.getClientSideRoute(), newSOSconnection);
log.debug("Pushing inter-agent SOS flows");
pushRoute(newSOSconnection.getInterAgentRoute(), newSOSconnection);
/* Send the initial TCP packet that triggered this module to the home agent */
log.debug("Sending client-side spark packet to client-side agent");
sendClientSideAgentSparkPacket(cntx, l2, newSOSconnection);
} else if (packetStatus == SOSPacketStatus.ACTIVE_SERVER_SIDE_AGENT_TO_SERVER) {
SOSConnection conn = sosConnections.getConnection(l3.getSourceAddress(), l3.getDestinationAddress(), l4.getDestinationPort());
if (conn == null) {
log.error("Should have found an SOSConnection in need of a server-side agent TCP port!");
} else {
conn.setServerSideAgentTcpPort(l4.getSourcePort());
log.debug("Finalizing SOS session: \r\n" + conn.toString());
log.debug("Pushing server-side SOS flows");
pushRoute(conn.getServerSideRoute(), conn);
log.debug("Sending server-side spark packet to server");
sendServerSparkPacket(cntx, l2, conn);
}
} else if (packetStatus == SOSPacketStatus.INACTIVE_UNREGISTERED) {
log.debug("Received an unregistered TCP packet. Register the connection to have it operated on by SOS.");
return Command.CONTINUE; /* Short circuit default return for unregistered -- let Forwarding/Hub handle it */
} else {
log.error("Received a TCP packet w/status {} that belongs to an ongoing SOS session. Report SOS bug", packetStatus);
}
/* We don't want other modules messing with our SOS TCP session (namely Forwarding/Hub) */
return Command.STOP;
} /* END IF TCP packet */
else if (l3.getProtocol().equals(IpProtocol.UDP)) {
UDP l4 = (UDP) l3.getPayload();
for (SOSAgent agent : agents) {
if (agent.getIPAddr().equals(l3.getSourceAddress()) /* FROM known agent */
&& agent.getFeedbackPort().equals(l4.getDestinationPort())) { /* TO our feedback port */
ISOSTerminationStats stats = SOSTerminationStats.parseFromJson(new String(((Data) l4.getPayload()).getData()));
log.debug("Got termination message from agent {} for UUID {}", agent.getIPAddr(), stats.getTransferID());
SOSConnection conn = sosConnections.getConnection(stats.getTransferID());
if (conn == null) {
log.error("Could not locate UUID {} in connection storage. Report SOS bug", stats.getTransferID());
return Command.STOP; /* This WAS for us, but there was an error; no need to forward */
}
if (conn.getClientSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
conn.getClientSideAgent().getIPAddr().equals(l3.getSourceAddress()) &&
stats.isClientSideAgent()) {
log.warn("Received termination message from client side agent {} for transfer ID {}", conn.getClientSideAgent().getIPAddr(), stats.getTransferID());
conn.getClientSideAgent().removeTransferId(stats.getTransferID());
if (stats.getSentBytesAvg() != 0) { /* only record valid set of stats; dependent on direction of transfer */
log.info("Setting stats for client side agent {} for transfer ID {}", conn.getClientSideAgent().getIPAddr(), stats.getTransferID());
conn.setTerminationStats(stats);
}
/* continue; we might have just removed the 2nd agent */
} else if (conn.getServerSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
conn.getServerSideAgent().getIPAddr().equals(l3.getSourceAddress()) &&
!stats.isClientSideAgent()) {
log.warn("Received termination message from server side agent {} for transfer ID {}", conn.getServerSideAgent().getIPAddr(), stats.getTransferID());
conn.getServerSideAgent().removeTransferId(stats.getTransferID());
if (stats.getSentBytesAvg() != 0) { /* only record valid set of stats; dependent on direction of transfer */
log.info("Setting stats for server side agent {} for transfer ID {}", conn.getServerSideAgent().getIPAddr(), stats.getTransferID());
conn.setTerminationStats(stats);
}
/* continue; we might have just removed the 2nd agent */
} else if (!conn.getServerSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
!conn.getClientSideAgent().getActiveTransfers().contains(stats.getTransferID())) {
log.error("Received termination message for transfer ID {} but both agents were already terminated. Report SOS bug.", stats.getTransferID());
return Command.STOP;
} else {
log.error("SOS in inconsistent state when processing termination message. Report SOS bug. Transfer: {}", conn);
return Command.STOP;
}
/* Not a duplicate check; might have just been notified from the 2nd agent. */
if (!conn.getServerSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
!conn.getClientSideAgent().getActiveTransfers().contains(stats.getTransferID())) {
for (String flowName : conn.getFlowNames()) {
log.trace("Deleting flow {}", flowName);
sfp.deleteFlow(flowName);
}
log.warn("Received reports from all agents of transfer ID {}. Terminating SOS transfer", stats.getTransferID());
conn.setStopTime();
sosConnections.removeConnection(stats.getTransferID());
if (!statistics.removeActiveConnection(conn)) {
log.error("Could not remove connection {} from SOSStatistics object. Report SOS bug", conn);
}
}
return Command.STOP; /* This packet was for our module from an agent */
} else if (agent.getIPAddr().equals(l3.getSourceAddress()) /* FROM known agent */
&& agent.getStatsPort().equals(l4.getDestinationPort())) { /* TO our stats port */
ISOSTransferStats stats = SOSTransferStats.parseFromJson(new String(((Data) l4.getPayload()).getData()));
log.debug("Got transfer stats message from agent {} for UUID {}", agent.getIPAddr(), stats.getTransferID());
SOSConnection conn = sosConnections.getConnection(stats.getTransferID());
if (conn == null) {
log.error("Could not locate UUID {} in connection storage. Report SOS bug", stats.getTransferID());
return Command.STOP; /* This WAS for us, but there was an error; no need to forward */
}
if (conn.getClientSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
conn.getClientSideAgent().getIPAddr().equals(l3.getSourceAddress()) &&
stats.isClientSideAgent()) {
log.info("Setting stats for client side agent {} for transfer ID {}", conn.getClientSideAgent().getIPAddr(), stats.getTransferID());
conn.updateTransferStats(stats);
} else if (conn.getServerSideAgent().getActiveTransfers().contains(stats.getTransferID()) &&
conn.getServerSideAgent().getIPAddr().equals(l3.getSourceAddress()) &&
!stats.isClientSideAgent()) {
log.info("Setting stats for server side agent {} for transfer ID {}", conn.getServerSideAgent().getIPAddr(), stats.getTransferID());
conn.updateTransferStats(stats);
}
return Command.STOP; /* this was for us */
}
} /* END FROM-AGENT LOOKUP */
} /* END IF UDP packet */
} /* END IF IPv4 packet */
return Command.CONTINUE;
} /* END of receive(pkt) */
/**
* Lookup an agent based on the client's current location. Shortest path
* routing is used to determine the closest agent. The route is returned
* inclusive of the SOS agent.
*
* Lookup can be done for either client or server of a TCP connection.
* Supply the IP address of a previously determined agent to select a
* different agent in the event both clients result in the same agent
* being selected.
*
* @param dev, either client or server
* @param agentToAvoid, optional, use IPv4Address.NONE if N/A
* @return
*/
private SOSRoute routeToFriendlyNeighborhoodAgent(SOSDevice dev, SwitchPort[] devAps, IPv4Address agentToAvoid) {
Route shortestPath = null;
SOSAgent closestAgent = null;
/* First, make sure client has a valid attachment point */
if (devAps.length == 0) {
log.error("Client/Server {} was found in the device manager but does not have a valid attachment point. Report SOS bug.");
return null;
}
/* Then, narrow down the APs to the real location where the device is connected */
SwitchPort devTrueAp = findTrueAttachmentPoint(devAps);
if (devTrueAp == null) {
log.error("Could not determine true attachment point for device {}. Report SOS bug.", dev);
return null;
}
for (SOSAgent agent : agents) {
/* Skip agent earmarked for other client */
if (agent.getIPAddr().equals(agentToAvoid)) {
log.debug("Skipping earmarked agent {}", agent);
} else {
/* Find where the agent is attached. Only *ONE* device should be returned here, ever. Assume 0th device is the correct one. */
Iterator<? extends IDevice> i = deviceService.queryDevices(MacAddress.NONE, null, agent.getIPAddr(), IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO);
if (i.hasNext()) {
IDevice d = i.next();
SwitchPort[] agentAps = d.getAttachmentPoints();
if (agentAps.length > 0) {
SwitchPort agentTrueAp = findTrueAttachmentPoint(agentAps);
if (agentTrueAp == null) {
log.error("Could not determine true attachment point for agent {}. Trying next agent. Report SOS bug.", agent);
continue;
}
log.trace("Asking for route from {} to {}", devTrueAp, agentTrueAp);
Route r = routingService.getRoute(devTrueAp.getSwitchDPID(), devTrueAp.getPort(), agentTrueAp.getSwitchDPID(), agentTrueAp.getPort(), U64.ZERO);
if (r != null && shortestPath == null) {
log.debug("Found initial agent {} w/route {}", agent, r);
shortestPath = r;
closestAgent = agent;
closestAgent.setMACAddr(d.getMACAddress()); /* set the MAC while we're here */
} else if (r != null && BEST_AGENT.A2 == selectBestAgent(closestAgent, shortestPath, agent, r)) { /* A2 is 2nd agent, meaning replace if better */
if (log.isDebugEnabled()) { /* Use isDebugEnabled() when we have to create a new object for the log */
log.debug("Found new best agent {} w/route {}", new Object[] { agent, r});
}
shortestPath = r;
closestAgent = agent;
closestAgent.setMACAddr(d.getMACAddress()); /* set the MAC while we're here */
} else {
if (log.isDebugEnabled()) {
log.debug("Retaining current agent {} w/shortest route. Kept route {}; Longer contender {}, {}", new Object[] { closestAgent, shortestPath, agent, r });
}
}
} else {
log.debug("Agent {} was located but did not have any valid attachment points", agent);
}
} else {
log.debug("Query for agents with IP address of {} resulted in no devices. Trying other agents.", agent);
}
}
}
/* If we get here, we should have iterated through all agents for the closest */
if (closestAgent == null) {
log.error("Could not find a path from client/server {} to any agent {}. Report SOS bug.", dev, agents);
return null;
} else {
log.debug("Agent {} was found closest to client/server {}", closestAgent, dev);
}
return new SOSRoute(dev, closestAgent, shortestPath);
}
/*
* Used to more cleanly define a winning agent in the selection method below
*/
private enum BEST_AGENT { A1, A2, NEITHER };
/**
* Based on the latency of the route for each agent and the load of each agent,
* determine which agent should be used. Low latency is preferred over agent load.
*
* @param a1
* @param r1
* @param a2
* @param r2
* @return BEST_AGENT.A1 or BEST_AGENT.A2, whichever wins
*/
private static BEST_AGENT selectBestAgent(SOSAgent a1, Route r1, SOSAgent a2, Route r2) {
if (a1 == null) {
throw new IllegalArgumentException("Agent a1 cannot be null");
} else if (a2 == null) {
throw new IllegalArgumentException("Agent a2 cannot be null");
} else if (r1 == null) {
throw new IllegalArgumentException("Route r1 cannot be null");
} else if (r2 == null) {
throw new IllegalArgumentException("Route r2 cannot be null");
}
long a1_latency = computeLatency(r1);
int a1_load = a1.getNumTransfersServing();
long a2_latency = computeLatency(r2);
int a2_load = a2.getNumTransfersServing();
/*
* How to determine a winner?
*
* An agent is the "best" if that agent is closer to the client/server
* than the other agent. Latency is the primary weight, since we want
* to avoid selecting an agent at the remote site. After latency, we can
* use the load, which will serve to select the closest agent that is
* least heavily loaded. Lastly, hop count could also be considered, but this
* shouldn't manner, since it's included in latency (unless SW switches are
* a part of this hop count).
*/
/* Check if latencies are different enough to imply different geographic locations */
if (Math.abs(a1_latency - a2_latency) <= latencyDifferenceThreshold) {
/* The agents are at the same location (most likely) */
if (log.isDebugEnabled()) {
log.debug("Agents {} and {} with latencies {} and {} are at the same location", new Object[] { a1, a2, a1_latency, a2_latency });
}
/* Pick agent with the least load */
if (a1_load <= a2_load) {
return BEST_AGENT.A1;
} else {
return BEST_AGENT.A2;
}
} else {
/* The agents are at different locations (most likely) */
if (log.isDebugEnabled()) {
log.debug("Agents {} and {} with latencies {} and {} are at different locations", new Object[] { a1, a2, a1_latency, a2_latency });
}
/* Pick the agent with the lowest latency */
if (a1_latency <= a2_latency) {
return BEST_AGENT.A1;
} else {
return BEST_AGENT.A2;
}
}
}
private static long computeLatency(Route r) {
long latency = 0;
for (int i = 0; i < r.getPath().size(); i++) {
if (i % 2 == 1) { /* Only get odd for links [npt0, npt1]---[npt2, npt3]---[npt4, npt5] */
NodePortTuple npt = r.getPath().get(i);
Set<Link> links = linkDiscoveryService.getPortLinks().get(npt);
if (links == null || links.isEmpty()) {
log.warn("Skipping NodePortTuple on network edge (i.e. has no associated links)");
continue;
} else {
for (Link l : links) {
if (l.getSrc().equals(npt.getNodeId()) && l.getSrcPort().equals(npt.getPortId())) {
log.debug("Adding link latency {}", l);
latency = latency + l.getLatency().getValue();
break;
}
}
}
}
}
log.debug("Computed overall latency {}ms for route {}", latency, r);
return latency;
}
/**
* A "true" attachment point is defined as the physical location
* in the network where the device is plugged in.
*
* Each OpenFlow island can have up to exactly one attachment point
* per device. If there are multiple islands and the same device is
* known on each island, then there must be a link between these
* islands (assuming no devices with duplicate MACs exist). If there
* is no link between the islands, then the device cannot be learned
* on each island (again, assuming all devices have unique MACs).
*
* This means if we iterate through the attachment points and find
* one who's switch port is not a member of a link b/t switches/islands,
* then that attachment point is the device's true location. All other
* attachment points are where the device is known on other islands and
* should reside on external/iter-island links.
*
* @param aps
* @return
*/
private SwitchPort findTrueAttachmentPoint(SwitchPort[] aps) {
if (aps != null) {
for (SwitchPort ap : aps) {
Set<OFPort> portsOnLinks = topologyService.getPortsWithLinks(ap.getSwitchDPID());
if (portsOnLinks == null) {
log.error("Error looking up ports with links from topology service for switch {}", ap.getSwitchDPID());
continue;
}
if (!portsOnLinks.contains(ap.getPort())) {
log.debug("Found 'true' attachment point of {}", ap);
return ap;
} else {
log.trace("Attachment point {} was not the 'true' attachment point", ap);
}
}
}
/* This will catch case aps=null, empty, or no-true-ap */
log.error("Could not locate a 'true' attachment point in {}", aps);
return null;
}
/**
* Find the shortest route (by hop-count) between two SOS agents.
* Do not push flows for the route.
* @param src
* @param dst
* @return
*/
private SOSRoute routeBetweenAgents(SOSAgent src, SOSAgent dst) {
/* Find where the agent is attached. Only *ONE* device should be returned here, ever. Assume 0th device is the correct one. */
Iterator<? extends IDevice> si = deviceService.queryDevices(MacAddress.NONE, null, src.getIPAddr(), IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO);
Iterator<? extends IDevice> di = deviceService.queryDevices(MacAddress.NONE, null, dst.getIPAddr(), IPv6Address.NONE, DatapathId.NONE, OFPort.ZERO);
if (si.hasNext() && di.hasNext()) {
IDevice sd = si.next();
IDevice dd = di.next();
SwitchPort sTrueAp = findTrueAttachmentPoint(sd.getAttachmentPoints());
SwitchPort dTrueAp = findTrueAttachmentPoint(dd.getAttachmentPoints());
if (sTrueAp == null) {
log.error("Could not locate true attachment point for client-side agent {}. APs were {}. Report SOS bug.", src, sd.getAttachmentPoints());
return null;
} else if (dTrueAp == null) {
log.error("Could not locate true attachment point for server-side agent {}. APs were {}. Report SOS bug.", dst, dd.getAttachmentPoints());
return null;
}
Route r = routingService.getRoute(sTrueAp.getSwitchDPID(), sTrueAp.getPort(), dTrueAp.getSwitchDPID(), dTrueAp.getPort(), U64.ZERO);
if (r == null) {
log.error("Could not find route between {} at AP {} and {} at AP {}", new Object[] { src, sTrueAp, dst, dTrueAp});
} else {
if (log.isDebugEnabled()) {
log.debug("Between agent {} and agent {}, found route {}", new Object[] {src, dst, r});
}
return new SOSRoute(src, dst, r);
}
} else {
log.debug("Query for agents resulted in no devices. Source iterator: {}; Destination iterator {}", si, di);
}
return null;
}
/**
* Try to force-learn a device that the device manager does not know
* about already. The ARP reply (we hope for) will trigger learning
* the new device, and the next TCP SYN we receive after that will
* result in a successful device lookup in the device manager.
* @param dstIp
* @param srcIp
* @param srcMac
* @param vlan
* @param sw
*/
private void arpForDevice(IPv4Address dstIp, IPv4Address srcIp, MacAddress srcMac, VlanVid vlan, IOFSwitch sw) {
IPacket arpRequest = new Ethernet()
.setSourceMACAddress(srcMac)
.setDestinationMACAddress(MacAddress.BROADCAST)
.setEtherType(EthType.ARP)
.setVlanID(vlan.getVlan())
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REQUEST)
.setSenderHardwareAddress(srcMac)
.setSenderProtocolAddress(srcIp)
.setTargetHardwareAddress(MacAddress.NONE)
.setTargetProtocolAddress(dstIp));
OFPacketOut po = sw.getOFFactory().buildPacketOut()
.setActions(Collections.singletonList((OFAction) sw.getOFFactory().actions().output(OFPort.FLOOD, 0xffFFffFF)))
.setBufferId(OFBufferId.NO_BUFFER)
.setData(arpRequest.serialize())
.setInPort(OFPort.CONTROLLER)
.build();
sw.write(po);
}
/**
* Push flows required for the route provided. If the route is only a single
* hop, we assume the single switch is capable of performing all necessary
* L2, L3, and L4 header rewrites. More importantly, if the route is more
* than two hops, we assume the first hop will perform the redirection of
* TCP packets to/from the agent and rewrite L2 headers, while the last hop
* will rewrite the L3 and L4 headers. This algorithm is chosen to support
* a common configuration where OVS is used as the last hop right before
* an agent to supplement the lack of higher layer header rewrite support
* in prior-hop physical OpenFlow switches.
*
* TODO use table features (OF1.3) to determine what each switch can do.
*
* @param route
*/
private void pushRoute(SOSRoute route, SOSConnection conn) {
ISOSRoutingStrategy rs;
if (route.getRouteType() == SOSRouteType.CLIENT_2_AGENT) {
rs = new SOSRoutingStrategyFirstHopLastHop(true);
rs.pushRoute(route, conn);
} else if (route.getRouteType() == SOSRouteType.AGENT_2_AGENT) {
rs = new SOSRoutingStrategyInterAgent();
rs.pushRoute(route, conn);
} else if (route.getRouteType() == SOSRouteType.SERVER_2_AGENT) {
rs = new SOSRoutingStrategyFirstHopLastHop(true);
rs.pushRoute(route, conn);
} else {
log.error("Received invalid SOSRouteType of {}", route.getRouteType());
}
}
/* **********************************
* IOFSwitchListener implementation *
* **********************************/
@Override
public void switchAdded(DatapathId dpid) {
}
@Override
public void switchRemoved(DatapathId dpid) {
}
@Override
public void switchPortChanged(DatapathId dpid, OFPortDesc portDesc, PortChangeType portChangeType) {
}
@Override
public void switchActivated(DatapathId switchId) {
}
@Override
public void switchChanged(DatapathId switchId) {
}
/* ****************************
* ISOSService implementation *
* ****************************/
@Override
public synchronized SOSReturnCode addAgent(ISOSAgent agent) {
if (agents.contains(agent)) { /* MACs are ignored in devices for equality check, so we should only compare IP and ports here */
log.error("Found pre-existing agent during agent add. Not adding new agent {}", agent);
return SOSReturnCode.ERR_DUPLICATE_AGENT;
} else {
if (agents.add((SOSAgent) agent)) {
log.warn("Agent {} added.", agent);
statistics.addAgent(agent);
} else {
log.error("Error. Agent {} NOT added.", agent);
}
Set<DatapathId> switches = switchService.getAllSwitchDpids();
for (DatapathId sw : switches) {
log.debug("ARPing for agent {} on switch {}", agent, sw);
arpForDevice(
agent.getIPAddr(),
(agent.getIPAddr().and(IPv4Address.of("255.255.255.0"))).or(IPv4Address.of("0.0.0.254")) /* Doesn't matter really; must be same subnet though */,
MacAddress.BROADCAST /* Use broadcast as to not potentially confuse a host's ARP cache */,
VlanVid.ZERO /* Switch will push correct VLAN tag if required */,
switchService.getSwitch(sw)
);
}
if (agentMonitor == null) {
log.warn("Configuring agent ARP monitor thread");
agentMonitor = threadPoolService.getScheduledExecutor().scheduleAtFixedRate(
new SOSAgentMonitor(),
/* initial delay */ 20,
/* interval */ 15,
TimeUnit.SECONDS);
}
return SOSReturnCode.AGENT_ADDED;
}
}
@Override
public synchronized SOSReturnCode removeAgent(ISOSAgent agent) {
if (agents.contains(agent)) { /* MACs are ignored in devices for equality check, so we should only compare IP and ports here */
agents.remove(agent);
statistics.removeAgent(agent);
log.warn("Agent {} removed.", agent);
return SOSReturnCode.AGENT_REMOVED;
} else {
log.error("Could not locate agent {} to remove. Not removing agent.", agent);
return SOSReturnCode.ERR_UNKNOWN_AGENT;
}
}
@Override
public Set<? extends ISOSAgent> getAgents() {
return Collections.unmodifiableSet((Set<? extends ISOSAgent>) agents);
}
@Override
public synchronized SOSReturnCode addWhitelistEntry(ISOSWhitelistEntry entry) {
statistics.addWhitelistEntry(entry);
return sosConnections.addWhitelistEntry(entry);
}
@Override
public synchronized SOSReturnCode removeWhitelistEntry(ISOSWhitelistEntry entry) {
statistics.removeWhitelistEntry(entry);
return sosConnections.removeWhitelistEntry(entry);
}
@Override
public Set<? extends ISOSWhitelistEntry> getWhitelistEntries() {
return sosConnections.getWhitelistEntries(); /* already unmodifiable */
}
@Override
public synchronized SOSReturnCode enable() {
log.warn("Enabling SOS");
enabled = true;
return SOSReturnCode.ENABLED;
}
@Override
public synchronized SOSReturnCode disable() {
log.warn("Disabling SOS");
enabled = false;
return SOSReturnCode.DISABLED;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public ISOSStatistics getStatistics() {
return statistics;
}
@Override
public SOSReturnCode clearStatistics() {
statistics.clear();
return SOSReturnCode.STATS_CLEARED;
}
@Override
public synchronized SOSReturnCode setFlowTimeouts(int hardSeconds, int idleSeconds) {
if (idleSeconds >= 0) {
flowTimeout = (short) idleSeconds;
log.warn("Set idle timeout to {}. Ignoring hard timeout of {}", idleSeconds, hardSeconds);
}
return SOSReturnCode.CONFIG_SET;
}
@Override
public int getFlowIdleTimeout() {
return flowTimeout;
}
@Override
public int getFlowHardTimeout() {
return 0;
}
@Override
public synchronized SOSReturnCode setNumParallelConnections(int num) {
agentNumParallelSockets = num;
log.warn("Set number of parallel connections to {}", num);
return SOSReturnCode.CONFIG_SET;
}
@Override
public int getNumParallelConnections() {
return agentNumParallelSockets;
}
@Override
public synchronized SOSReturnCode setBufferSize(int bytes) {
bufferSize = bytes;
return SOSReturnCode.CONFIG_SET;
}
@Override
public int getBufferSize() {
return bufferSize;
}
@Override
public synchronized SOSReturnCode setQueueCapacity(int packets) {
agentQueueCapacity = packets;
return SOSReturnCode.CONFIG_SET;
}
@Override
public int getQueueCapacity() {
return agentQueueCapacity;
}
@Override
public SOSReturnCode ready() {
int count = 0;
for (ISOSAgent agent : agents) {
/* TODO We assume each agent is only capable of a single transfer. */
if (agent.getActiveTransfers().isEmpty()) {
count++;
}
}
if (count > 1) {
return SOSReturnCode.READY;
} else {
return SOSReturnCode.NOT_READY;
}
}
} |
/**
* log instance is defined in Solution interface
* this is how slf4j will work in this class:
* =============================================
* if (log.isDebugEnabled()) {
* log.debug("a + b = {}", sum);
* }
* =============================================
*/
class Solution2 implements Solution {
@Override
public List<String> generateParenthesis(int n) {
List<String> ret = new ArrayList<>();
backtrack(ret, new StringBuilder(), 0, 0, n);
return ret;
}
private void backtrack(List<String> ret, StringBuilder cur, int open, int close, int max) {
if (cur.length() == max * 2) {
ret.add(cur.toString());
return;
}
if (open < max) {
cur.append("(");
backtrack(ret, cur, open+1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(")");
backtrack(ret, cur, open, close+1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
} |
So are we heading for a Mad Max-style future? I don’t think so. After having lived through Donald Trump we’ll surely just call him Max. Trump is behaving so strangely, we’re probably about a month away from not being allowed to make jokes about him. He’s gone past Charlie Sheen and we’re now entering the bald Britney phase. It’s hard to imagine how America can go back to having a normal president after this. The next president will have to be a car with guns for wheels. After Trump, a Saturday Night Live sketch about Mike Pence would look like something by Samuel Beckett.
Trump is sort of like Father Dougal killed a man, so is wearing Father Jack as a disguise. He looks like the image burned into your retina should you watch a completely normal man burst into flames. Even on an HDTV he looks like a sixth generation VHS recording. A president with the temperament of a wasp that’s spent 40 minutes on musical hold, his Twitter feed reads like he’s building up a credible insanity defence for when he’s finally impeached. It’s not just that he lives on Twitter, he embodies it: digressive, petty, trivial, poisonous and self-aggrandising. He basically speaks like a totally random stream of tweets. One minute he’s on Mexicans, then he’s talking about his shoes, then a threat, then a joke about a cat.
Last week he held a rally in Phoenix, Arizona – possibly because he thought he’d blend in to a state that is orange, desolate and has a cavernous gap in its heart so huge, people travel the world just to gasp and cry. Phoenix is best known for the song By The Time I Get To Phoenix (She’ll Be Rising), in this case referring to Lilitu the she-demon of the apocalypse. Trump delivered one of his random rightwing word collages in front of a crowd who if they were any whiter would have had carrots for noses.
Under investigation by the FBI, Trump is now at war with intelligence in two ways
Imagine standing up in Arizona and talking about preserving white culture: a state so recently colonised that the dry cleaners still offer a smallpox cleansing service. White guys have only been in Arizona for 150 years – that’s not even enough time to fill a Costa loyalty card. He’s literally standing in Apache land, 150 years after their genocide, talking about protecting American culture; standing amid a culture people like him destroyed, talking about building a wall, like Simon Cowell launching the next series of The X Factor in the Cavern Club.
But what else can we expect from Trump – he doesn’t get his history from reading, he gets it from staring at lumps of stone. A statue to Robert E Lee? If they want to look up to a white guy who’s rubbish at attack and can’t remember which side he’s on, we can send James Milner over there to stand on a box. Arizona is on the Mexican border, meaning his shouting the word “WALL” goes down very well, especially since they know they can get better quality drugs through their border with Hollywood. People will still try to jump over whatever makeshift fence he finally manages to put up. All Trump is doing is turning America into a giant Glastonbury; there’s a headliner no one approves of, but you’ll still go for Dolly Parton and the van making smoothies.
Obviously, Trump’s pivot to Afghanistan is depressing. The only comfort to Trump getting in was that he intended to keep his horrific Armageddon packed tightly within his walled up, hermetically sealed Thunderdome America. I suppose this is the kind of consistency we should expect from someone who can’t finish a sentence. Under investigation by the FBI, he is now at war with intelligence in two ways. It’s hard to pick out a single low point of the Trump presidency, but it seems like the KKK now feel relaxed enough to march without their hoods. “Jews will not replace us!”? Looks like if your sister keeps saying no, nobody will mate.
Can we even think of Trump in terms of intent? Aren’t we then like those shamans who used to project anger on to erupting volcanoes? Maybe Trump is a kind of cry for help from the Earth, a human flare. Or perhaps he has been produced by the Earth to destroy mankind, and his personality is actually nature’s critique of humanity. How fitting that life on Earth will be extinguished by a reality TV host, over a mediocre golf-club burger at his nuclear winter White House, a kind of 3-star Black Lodge.
The US has always been balanced on uneasy contradictions. Even the constitution promises both the right to freedom of speech and the freedom to have a gun to shoot people who annoy you. Right at the heart of its contradictions are the twin ideas of liberty and enslavement, its founding principles of “freedom” and “but not for everybody”.
If I had to guess what was at the forefront of the minds of the American right at the moment, I’d say voter suppression. It doesn’t matter that the US has a rhetorical attachment to democracy. Through its actions as a state it has long undermined any connection between its stated ideals and its actions. I think the US will now face a long struggle to avoid a slide into totalitarianism, led of course by people calling themselves libertarians.
Frankie Boyle’s new book Your Guide To Hell (John Murray) is out in October |
Plants grow on houses in the abandoned fishing village of Houtouwan on the island of Shengshan July 26, 2015. Just a handful of people still live in a village on Shengshan Island east of Shanghai that was once home to more than 2,000 fishermen. Every...more
Plants grow on houses in the abandoned fishing village of Houtouwan on the island of Shengshan July 26, 2015. Just a handful of people still live in a village on Shengshan Island east of Shanghai that was once home to more than 2,000 fishermen. Every day hundreds of tourists visit Houtouwan, making their way on narrow footpaths past tumbledown houses overtaken by vegetation. The remote village, on one of more than 400 islands in the Shengsi archipelago, was abandoned in the early 1990s as first wealthy residents then others moved away, aiming to leave problems with education and food delivery behind them. REUTERS/Damir Sagolj
Close |
// HTTPClient is a Client option that sets the http.Client used.
func HTTPClient(client *http.Client) Option {
return func(c *Client) error {
l, err := dns.New(client)
if err != nil {
return err
}
return DNSService(l)(c)
}
} |
package teamroots.embers.block;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyDirection;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import teamroots.embers.RegistryManager;
import teamroots.embers.tileentity.ITileEntityBase;
import teamroots.embers.tileentity.TileEntityEmitter;
import teamroots.embers.tileentity.TileEntityLargeTank;
import teamroots.embers.tileentity.TileEntityPipe;
import teamroots.embers.tileentity.TileEntityTank;
public class BlockStoneEdge extends BlockBase {
public static final PropertyInteger state = PropertyInteger.create("state", 0, 9);
public static final AxisAlignedBB AABB_BASE = new AxisAlignedBB(0,0,0,1,1,1);
public static final AxisAlignedBB AABB_NULL = new AxisAlignedBB(0,0,0,0,0,0);
public static final AxisAlignedBB AABB_XFACE = new AxisAlignedBB(0.25,0,0,0.75,1,1);
public static final AxisAlignedBB AABB_ZFACE = new AxisAlignedBB(0,0,0.25,1,1,0.75);
public static final AxisAlignedBB AABB_POSZ = new AxisAlignedBB(0.25,0,0.25,0.75,1,1);
public static final AxisAlignedBB AABB_NEGZ = new AxisAlignedBB(0.25,0,0,0.75,1,0.75);
public static final AxisAlignedBB AABB_POSX = new AxisAlignedBB(0.25,0,0.25,1,1,0.75);
public static final AxisAlignedBB AABB_NEGX = new AxisAlignedBB(0,0,0.25,0.75,1,0.75);
public static final AxisAlignedBB AABB_PXNZCORNER = new AxisAlignedBB(0,0,0.25,0.75,1,1);
public static final AxisAlignedBB AABB_PXPZCORNER = new AxisAlignedBB(0,0,0,0.75,1,0.75);
public static final AxisAlignedBB AABB_NXPZCORNER = new AxisAlignedBB(0.25,0,0,1,1,0.75);
public static final AxisAlignedBB AABB_NXNZCORNER = new AxisAlignedBB(0.25,0,0.25,1,1,1);
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
if (state.getValue(this.state) == 9 || state.getValue(this.state) == 4){
return AABB_ZFACE;
}
if (state.getValue(this.state) == 2 || state.getValue(this.state) == 6){
return AABB_XFACE;
}
if (state.getValue(this.state) == 1){
return AABB_NXNZCORNER;
}
if (state.getValue(this.state) == 3){
return AABB_NXPZCORNER;
}
if (state.getValue(this.state) == 5){
return AABB_PXPZCORNER;
}
if (state.getValue(this.state) == 7){
return AABB_PXNZCORNER;
}
return AABB_BASE;
}
public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn)
{
if (state.getValue(this.state) == 9 || state.getValue(this.state) == 4){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_ZFACE);
}
if (state.getValue(this.state) == 2 || state.getValue(this.state) == 6){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_XFACE);
}
if (state.getValue(this.state) == 1){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_POSZ);
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_POSX);
}
if (state.getValue(this.state) == 3){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_NEGZ);
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_POSX);
}
if (state.getValue(this.state) == 5){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_NEGZ);
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_NEGX);
}
if (state.getValue(this.state) == 7){
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_POSZ);
addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_NEGX);
}
}
public BlockStoneEdge(Material material, String name, boolean addToTab) {
super(material, name, addToTab);
}
@Override
public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune){
List<ItemStack> list = new ArrayList<ItemStack>();
if (state.getValue(this.state) == 8){
list.add(new ItemStack(this,1));
}
return list;
}
@Override
public BlockStateContainer createBlockState(){
return new BlockStateContainer(this, state);
}
@Override
public int getMetaFromState(IBlockState state){
return state.getValue(this.state);
}
@Override
public IBlockState getStateFromMeta(int meta){
return getDefaultState().withProperty(state,meta);
}
public void breakBlockSafe(World world, BlockPos pos, EntityPlayer player){
if (world.getTileEntity(pos) instanceof ITileEntityBase){
((ITileEntityBase)world.getTileEntity(pos)).breakBlock(world, pos, world.getBlockState(pos), player);
}
if (world.getBlockState(pos).getBlock() == RegistryManager.stoneEdge){
if (world.getBlockState(pos).getValue(this.state) == 8){
boolean foundBlock = false;
for (int i = 1; i < 64 && !foundBlock; i ++){
if (world.getTileEntity(pos.add(0,-i,0)) instanceof TileEntityLargeTank){
((TileEntityLargeTank)world.getTileEntity(pos.add(0,-i,0))).updateCapacity();
foundBlock = true;
}
}
if (!world.isRemote && !player.capabilities.isCreativeMode){
world.spawnEntityInWorld(new EntityItem(world,pos.getX()+0.5,pos.getY()+0.5,pos.getZ()+0.5,new ItemStack(this,1,0)));
}
}
}
world.setBlockToAir(pos);
}
@Override
public void onBlockHarvested(World world, BlockPos pos, IBlockState state, EntityPlayer player){
if (state.getValue(this.state) == 9){
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.south(2),player);
breakBlockSafe(world,pos.east(),player);
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.east().south(),player);
breakBlockSafe(world,pos.west().south(),player);
breakBlockSafe(world,pos.east().south(2),player);
breakBlockSafe(world,pos.west().south(2),player);
}
if (state.getValue(this.state) == 1){
breakBlockSafe(world,pos.east(),player);
breakBlockSafe(world,pos.east(2),player);
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.south(2),player);
breakBlockSafe(world,pos.east().south(),player);
breakBlockSafe(world,pos.east(2).south(),player);
breakBlockSafe(world,pos.east().south(2),player);
breakBlockSafe(world,pos.east(2).south(2),player);
}
if (state.getValue(this.state) == 2){
breakBlockSafe(world,pos.east(),player);
breakBlockSafe(world,pos.east(2),player);
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.north().east(),player);
breakBlockSafe(world,pos.south().east(),player);
breakBlockSafe(world,pos.north().east(2),player);
breakBlockSafe(world,pos.south().east(2),player);
}
if (state.getValue(this.state) == 3){
breakBlockSafe(world,pos.east(),player);
breakBlockSafe(world,pos.east(2),player);
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.north(2),player);
breakBlockSafe(world,pos.east().north(),player);
breakBlockSafe(world,pos.east(2).north(),player);
breakBlockSafe(world,pos.east().north(2),player);
breakBlockSafe(world,pos.east(2).north(2),player);
}
if (state.getValue(this.state) == 4){
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.north(2),player);
breakBlockSafe(world,pos.east(),player);
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.east().north(),player);
breakBlockSafe(world,pos.west().north(),player);
breakBlockSafe(world,pos.east().north(2),player);
breakBlockSafe(world,pos.west().north(2),player);
}
if (state.getValue(this.state) == 5){
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.west(2),player);
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.north(2),player);
breakBlockSafe(world,pos.west().north(),player);
breakBlockSafe(world,pos.west(2).north(),player);
breakBlockSafe(world,pos.west().north(2),player);
breakBlockSafe(world,pos.west(2).north(2),player);
}
if (state.getValue(this.state) == 6){
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.west(2),player);
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.north().west(),player);
breakBlockSafe(world,pos.south().west(),player);
breakBlockSafe(world,pos.north().west(2),player);
breakBlockSafe(world,pos.south().west(2),player);
}
if (state.getValue(this.state) == 7){
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.west(2),player);
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.south(2),player);
breakBlockSafe(world,pos.west().south(),player);
breakBlockSafe(world,pos.west(2).south(),player);
breakBlockSafe(world,pos.west().south(2),player);
breakBlockSafe(world,pos.west(2).south(2),player);
}
if (state.getValue(this.state) == 8){
breakBlockSafe(world,pos.west(),player);
breakBlockSafe(world,pos.south(),player);
breakBlockSafe(world,pos.west().south(),player);
breakBlockSafe(world,pos.west().north(),player);
breakBlockSafe(world,pos.south().east(),player);
breakBlockSafe(world,pos.north().east(),player);
breakBlockSafe(world,pos.north(),player);
breakBlockSafe(world,pos.east(),player);
}
}
@Override
public boolean canPlaceBlockAt(World world, BlockPos pos){
if (world.isAirBlock(pos.east())
&& world.isAirBlock(pos.west())
&& world.isAirBlock(pos.north())
&& world.isAirBlock(pos.south())
&& world.isAirBlock(pos.east().north())
&& world.isAirBlock(pos.east().south())
&& world.isAirBlock(pos.west().north())
&& world.isAirBlock(pos.west().south())){
return true;
}
return false;
}
@Override
public void onBlockAdded(World world, BlockPos pos, IBlockState state){
if (state.getValue(this.state) == 0){
world.setBlockState(pos, RegistryManager.stoneEdge.getStateFromMeta(8));
world.setBlockState(pos.north(), RegistryManager.stoneEdge.getStateFromMeta(9));
world.setBlockState(pos.north().west(), RegistryManager.stoneEdge.getStateFromMeta(1));
world.setBlockState(pos.west(), RegistryManager.stoneEdge.getStateFromMeta(2));
world.setBlockState(pos.south().west(), RegistryManager.stoneEdge.getStateFromMeta(3));
world.setBlockState(pos.south(), RegistryManager.stoneEdge.getStateFromMeta(4));
world.setBlockState(pos.south().east(), RegistryManager.stoneEdge.getStateFromMeta(5));
world.setBlockState(pos.east(), RegistryManager.stoneEdge.getStateFromMeta(6));
world.setBlockState(pos.north().east(), RegistryManager.stoneEdge.getStateFromMeta(7));
}
boolean foundBlock = false;
for (int i = 0; i < 64 && !foundBlock; i ++){
if (world.getTileEntity(pos.add(0,-i,0)) instanceof TileEntityLargeTank){
((TileEntityLargeTank)world.getTileEntity(pos.add(0,-i,0))).updateCapacity();
}
}
}
}
|
/**
* Represents an extension of a Path. Always uses slashes to simplify application development.
*
* Empty segments are accepted but not encouraged which allows parsing of things like S3 keys that might have double
* slashes,
*
* Strange characters are allowed by not encouraged which allows parsing paths that you don't control,
*
* Immutable: appending returns a new SubpathPath with a new array of segments.
*
* When rendered:
* - starts without slash
* - empty segments results in empty string
* - each segment is suffixed with a slash: a/b/c/
*
* A rendered copy of the toString value is calculated on creation because some root directories can be read a lot.
*/
public class Subpath{
private static final String SLASH = "/";
private static final Subpath EMPTY = new Subpath();
private final String[] segments;
private final String rendered;
public Subpath(String... segments){
Scanner.of(segments).forEach(Subpath::validateSegment);
this.segments = segments;
this.rendered = render();
}
public Subpath(List<String> segments){
this(segments.toArray(String[]::new));
}
public Subpath(PathNode pathNode){
this(pathNode.toStringArray());
}
public Subpath append(String segment){
validateSegment(segment);
return Scanner.of(segments)
.append(segment)
.listTo(Subpath::new);
}
public Subpath append(Subpath suffix){
return Scanner.of(segments)
.append(suffix.segments)
.listTo(Subpath::new);
}
public static Subpath join(Collection<Subpath> paths){
return Scanner.of(paths)
.map(path -> path.segments)
.concat(Scanner::of)
.listTo(Subpath::new);
}
public static Subpath empty(){
return EMPTY;
}
/**
* Needs to return the exact format described in the class comments. Tested in SubpathTests
*/
@Override
public String toString(){
return rendered;
}
private static void validateSegment(String segment){
if(segment == null){
throw new IllegalArgumentException("segment cannot be null");
}
if(segment.contains(SLASH)){
throw new IllegalArgumentException("segment cannot contain slash");
}
}
private String render(){
if(segments.length == 0){
return "";
}
return String.join(SLASH, segments) + SLASH;
}
} |
/**
* Creates the Display.
*
* @throws LWJGLException
* If the display couldn't be created.
* @since 14.03.30
*/
public static void createDisplay() throws LWJGLException
{
Display.setTitle( "Voxel Testing" );
Display.setDisplayMode( new DisplayMode( 640, 480 ) );
Display.create();
Mouse.setGrabbed( true );
} |
<filename>front-web/src/Home/index.tsx<gh_stars>0
import React from "react";
import { Link } from "react-router-dom";
import Footer from "../Footer";
import Logo from "./logo.svg";
import GirlImage from "./girl.svg";
import BackImage from "./fundo.svg";
import IconExclamation from "./icon_exclamation.svg";
import IconPofile from "./icon-profile.svg";
import IconSearch from "./icon_search.svg";
import IconInside from "./icon_inside.svg";
import "./style.css";
function Home() {
return (
<>
<img
className="BackImage"
src={BackImage}
alt="imagem to dentro de fundo"
/>
<div className="home-signup-container">
<nav className="header-container">
<img className="header-logo" src={Logo} alt="logo todentro" />
<span className="text-logo">
plataforma para aceleração de oportunidades
</span>
<Link to="/login" className="header-button">
Login
</Link>
</nav>
<div className="home-signup-container-iam">
<p className="home-signup-container-text">
Já pensou em conseguir o primeiro emprego
<br />
da sua carreira sem ao menos sair de casa?
<br />
<strong>Você está dentro do lugar certo pra isso.</strong>
</p>
<div className="home-butons">
<Link to="/cadastro" className="home-butons-type">
Sou uma empresa
</Link>
<Link to="/cadastro" className="home-butons-type">
Sou estudante
</Link>
</div>
</div>
<img
src={GirlImage}
className="imageGirl"
alt="imagem de uma moça com um notebook nas mãos"
width="600"
/>
</div>
<div className="home-operation">
<div className="home-operation-session-one">
<img className="icon-exclamation" src={IconExclamation} alt="icone de exclamação" />
<h1 className="home-operatio-title">
Como Funciona o Tô Dentro
<br />
para o jovem estudante?
</h1>
</div>
<div className="home-operation-session-two">
<div className="home-operation-steps">
<img src={IconPofile} alt="" />
<h3>Crie seu Perfil</h3>
<p>
Aqui é o lugar onde o seu sonho do primeiro emprego começa! Nos
conte mais sobre você e crie um perfil único para que as empresas
possam conhecer a sua personalidade. Com o perfil pronto é só
partir pra busca.
</p>
</div>
<div className="home-operation-steps">
<img src={IconSearch} alt="imagem de uma lupa de pesquisa" />
<h3>Busque</h3>
<p>
Procure por empresas que chamem a sua atenção e veja se são
compatíveis com o seu perfil. Deu match? É só cair pra dentro!
Ainda não tem as qualificações necessárias? Busque um de nossos
cursos para complementar o seu perfil.
</p>
</div>
<div className="home-operation-steps">
<img src={IconInside} alt="icone de um boneco com o braço levantado" />
<h3>Tá dentro!</h3>
<p>
Achou a vaga perfeita, você atende os requisitos, fez a entrevista
online e a empresa está pronta pra te receber? Pronto, você tá
dentro do seu primeiro emprego! .
</p>
</div>
</div>
</div>
<div className="abolt-container">
<h1 className="abolt-title">Sobre nós</h1>
<p className="abolt-text">
A Tô Dentro! nasceu como uma plataforma para aceleração de
oportunidades que busca não <br />
só aproximar candidato e vaga, mas qualificar jovens e servir de
trampolim para sua
<br /> evolução no mercado de trabalho.
<br />
Aqui você cria o seu perfil, faz suas buscas personalizadas, se
qualifica para as empresas que
<br /> têm interesse e tá dentro!
<br />
A Tô Dentro! quer trazer mais agilidade, mais transparência e desafiar
você, jovem, a<br /> construir sua carreira e ajudar você, empresário,
a encontrar a melhor opção de candidato.
<br />
<br />
Cai pra dentro! :)
</p>
</div>
<Footer />
</>
);
}
export default Home;
|
<filename>store.go
package ymsql
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"sync"
"gopkg.in/yaml.v2"
)
type Store interface {
MergeVariables(vals map[string]string) map[string]string
SETEnv(name string, value string)
Load(name string) (Scripting, error)
Store(bytes []byte) error
StoreFromFile(path string) error
StoreFromDirectory(path string) error
StoreResources(res map[string][]byte) error
}
type YMLStore struct {
env sync.Map
scripts sync.Map
}
func NewYMLStore() Store {
return &YMLStore{}
}
func (store *YMLStore) MergeVariables(vals map[string]string) map[string]string {
result := make(map[string]string)
store.env.Range(func(k interface{}, v interface{}) bool {
result[k.(string)] = v.(string)
return true
})
for k, v := range vals {
result[k] = v
}
return result
}
func (store *YMLStore) SETEnv(name string, value string) {
store.env.Store(name, value)
}
func (store *YMLStore) Store(bytes []byte) error {
var m YMLModel
err := yaml.Unmarshal(bytes, &m)
if err != nil {
return err
}
if m.Name == "" {
return fmt.Errorf("section '%s' required", "name")
}
if m.Script == "" {
return fmt.Errorf("section '%s' required", "script")
}
if m.Variables == nil {
m.Variables = make(map[string]string)
}
store.scripts.Store(m.Name, &m)
return nil
}
func (store *YMLStore) Load(name string) (Scripting, error) {
s, ok := store.scripts.Load(name)
if ok == false {
return nil, fmt.Errorf("script %s not found", name)
}
script := &YMLScripting{
s: s.(*YMLModel),
store: store,
variables: store.MergeVariables(s.(*YMLModel).Variables),
}
return script, nil
}
func (store *YMLStore) StoreFromFile(path string) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
err = store.Store(file)
if err != nil {
return err
}
return nil
}
func (store *YMLStore) StoreFromDirectory(path string) error {
dirList, err := ioutil.ReadDir(path)
if err != nil {
return err
}
for _, file := range dirList {
if file.IsDir() == false && strings.HasSuffix(file.Name(), ".yml") {
err = store.StoreFromFile(filepath.Join(path, file.Name()))
if err != nil {
return err
}
}
}
return nil
}
func (store *YMLStore) StoreResources(res map[string][]byte) error {
for _, v := range res {
err := store.Store(v)
if err != nil {
return err
}
}
return nil
}
|
/// Creates a distance in meters.
pub fn meters(value: f64) -> Distance {
if !value.is_finite() {
panic!("Bad Distance {}", value);
}
Distance(trim_f64(value))
} |
package decrypt
import (
"github.com/debba/anticaptcha"
"infoimprese-scraping-tool/settings"
"log"
"os"
"time"
)
func GetCaptcha(autoSetting settings.AutoSetting, url string) (string, error) {
log.Printf("[CHECKING] captcha (url = %s)", url)
log.Printf("[CHECKING] captcha (siteKey = %s, apiKey = %s)", autoSetting.SiteKey, autoSetting.ApiKey)
client := anticaptcha.Client{APIKey: autoSetting.ApiKey}
balance, berr := client.GetBalance()
if berr != nil {
log.Printf("[ERROR] error = %s", berr.Error())
os.Exit(0)
}
if balance < autoSetting.MinimumAmount {
log.Printf("[ERROR] AntiCaptcha balance is too lower (Current: %2f, Minimum requested: %2f)", balance, autoSetting.MinimumAmount)
os.Exit(0)
}
log.Printf("[ANTICAPTCHA BALANCE] Current: %2f", balance)
captcha, err := client.SendRecaptcha(
url,
autoSetting.SiteKey,
10*time.Minute)
if err != nil {
log.Printf("[ERROR] error = %s", err.Error())
os.Exit(0)
}
return captcha, err
}
|
Virginia’s Gubernatorial Race: Where Things Stand with Less Than a Month to Go
It’s no surprise that 2017’s top race is competitive
Geoffrey Skelley, Associate Editor, Sabato's Crystal Ball
The November of the year following a presidential election is always relatively quiet on the electoral front, with only regularly-scheduled statewide races for governor in New Jersey and Virginia. With the Garden State’s contest looking like a safe Democratic pickup and Alabama’s special election for the U.S. Senate not happening until December, coverage of the competitive Virginia race seems to be accelerating as it enters the final month before Election Day. This is only natural: gubernatorial elections in the Old Dominion traditionally ramp up around Labor Day, and now that the election is less than four weeks away, the candidates are beginning to go all-in on television ads, which attracts more notice inside and outside of the commonwealth.
Some of the national discussion regarding the Virginia contest expresses surprise — in Democratic circles, concern — that it appears to be close. After all, President Donald Trump’s approval rating nationally (and in Virginia) is around 40%, and Hillary Clinton carried Virginia by five percentage points in 2016. Surely the margin in a seemingly purple-to-light-blue state should be more comfortable for the Democratic nominee, Lt. Gov. Ralph Northam?
Although all recent public polls show Northam leading Republican nominee Ed Gillespie, the margins vary a great deal, and reports suggest recent campaign surveys have found the race to be inside the margin of error. The reality is, the demographics of the Virginia electorate help explain why a close contest for governor isn’t a surprise. And developments in the campaign have probably helped to make it even more competitive for Gillespie.
The off-year electorate
Virginia elects its governors in off-years, which fundamentally alters the nature of the commonwealth’s electorate compared to presidential cycles. Look at Chart 1 below. Whereas 72% of registered voters in Virginia turned out in the 2012 and 2016 presidential elections, only 43% showed up to vote in the 2013 gubernatorial election. And 2013 had the highest percentage (38%) of the state’s voting-eligible population to show up in a gubernatorial election going back to 1997. It’s hard to say where turnout ends up this year, but obviously it’s going to be far lower than the 2016 presidential contest. That means the gubernatorial electorate will likely be older, whiter, wealthier, and more educated due to the factors that affect individual-level voter turnout — older voters are more regular voters, wealthier and more educated people are more likely to vote, and whites are older, wealthier, and more educated compared to most other racial/ethnic groups.
Chart 1: Voter turnout in Virginia statewide races, by registered voters and voting-eligible population
Notes: Different shapes indicate what race was at the top of the ballot: circles for presidential elections, diamonds for U.S. Senate elections, and squares for gubernatorial elections. The voting-eligible population in gubernatorial years is estimated based on available data for the federal cycles that bookend each gubernatorial cycle (e.g. 2000 and 2002 for the 2001 gubernatorial election).
Sources: Virginia Department of Elections for voter registration figures, United States Election Project for voting-eligible population figures
Based on what we know about voting trends nationally and in Virginia, the first two factors — whiter and older — are good for Gillespie. While exit poll data have their issues, they do show shifts toward a whiter electorate from the presidential to gubernatorial cycles in Virginia. In the 2008 presidential election, the exit poll found 70% of the commonwealth’s electorate was white; in the 2009 gubernatorial election, the figure was 78%. In 2012, the exit poll found Virginia’s presidential electorate was once again 70% white; in the 2013 gubernatorial, the figure was 72% white. Again, exit polls are imperfect: they tend to exaggerate the nonwhite percentage of the electorate and its relative education level (so really, the electorates were probably whiter and less educated). Still, the data show a whiter electorate in Virginia’s off-year elections.
The third shift in the electorate — it will be more educated — is probably good for Democrats. Education has become one of the more important demographic factors in voting, and more highly-educated voters are trending Democratic. However, white voters with a college degree still split fairly evenly in the 2016 election in Virginia (the exit poll found that Trump won such voters 49%-45%), so it’s not like this is a strongly Democratic cohort, and it might be more open to a Republican like Gillespie than one like Trump. Because nonwhite voters are very likely to vote Democratic, the fact that they will likely make up a smaller share of the gubernatorial electorate is a challenge for Democrats.
Essentially, because of the competitive nature of the state and the makeup of Virginia’s off-year electorate, it would be hard for Northam, even if things in the campaign were going swimmingly for him, to truly blow out Gillespie, who is in some respects a “generic Republican.” Remember, while Democrats have won the state in three straight presidential elections, the state is not exactly a leftist redoubt. In recent party primaries, Virginia Democrats voted for Hillary Clinton over Bernie Sanders in 2016 and Northam over ex-Rep. Tom Perriello in 2017. And the Democratic Party of Virginia’s modern history is mostly that of a centrist party, because in order to win it had to be. Only once in the modern era of Virginia two-party politics (from 1969 on) has the Democratic nominee for governor won by more than 10 points — Jerry Baliles (D) won by 10.4 points in 1985. Meanwhile, Republicans have won by more than 10 points four times (1977, 1993, 1997, and 2009). The point is, recent gubernatorial elections in Virginia suggest that a negative environment for a Democratic candidate may be more damaging in electoral margin than a negative environment for a Republican one, and the nature of the off-year electorate is a contributing factor.
The campaign
Importantly for Gillespie, he’s not seen as someone who is Trumpian. The GOP nominee cuts a decidedly non-populist profile, having been a major player in Republican politics for years. This quality could help him in the suburban areas of the state: In an admittedly advantageous environment in the 2014 Senate race, Gillespie did better in Northern Virginia, an increasingly Democratic region, than all other GOP statewide nominees running from 2012 to 2016. While his cool demeanor is far from that of Trump’s, Gillespie has in some ways taken pages out of the same playbook Trump used in 2016. Gillespie is running ads on immigration and law and order, most notably ones focused on the Latino gang MS-13. These spots play to anti-immigrant sentiment among the GOP base and portray Northam as a threat to the health and safety of Virginians. The impetus for the ad was a vote Northam took to break a tie in the state senate — one of the few statutory jobs of the lieutenant governorship — to halt a bill that expressly banned sanctuary cities in Virginia. The vote was orchestrated political theater, but it gave the Gillespie campaign a talking point that has become a critical part of the campaign. For example, when the president weighed in on Gillespie’s behalf on Twitter a few days ago, he specifically referenced MS-13 while attacking Northam. Because of the racial/ethnic overtones of the ads, Democrats have attacked the ads as Willie Horton, part deux. Public polls have found that Democratic unity for Northam is slightly stronger than GOP unity for Gillespie, so the MS-13 ads suggest that his campaign sees the issues of immigration and sanctuary cities as helpful in exciting the Republican base. The ads could also be a tool to bring home some white-collar moderates in the suburbs and exurbs of Northern Virginia, voters who may not like Trump but are also concerned about the activity of MS-13 in that part of the state.
Nonetheless, the two candidates’ level of party unity is not drastically different. In recent polls with party identification crosstabs, Northam is winning among Democrats by an average of 91 points while Gillespie is up 85 points among Republicans. Considering the rancor of the GOP primary contest between Gillespie and Prince William County Board of Supervisors Chairman Corey Stewart, that’s better than some thought would be the case for Gillespie (one could say the same for Northam, who won his primary by more but had to work hard to do so). One aspect of the campaign that may be helping Gillespie is the significant focus on Virginia’s Confederate monuments. The issue appears to have tripped up Northam to some extent because the public is more in favor of keeping such monuments in place than removing them. Northam wants localities to handle such matters but says he’ll be an advocate for removing them, while Gillespie wants the monuments to stay but with more context added. Overall, the relative unity of Republicans on the issue — they overwhelmingly want the monuments to remain — makes this a more straightforward issue for Gillespie compared to the division among Democrats. Moreover, the monuments issue is exactly the sort of catnip for cultural conservatives that could help Gillespie turn out those voters in November despite his lack of outsider credentials. Stewart, whose campaign centered on preserving Confederate monuments, has not formally endorsed Gillespie, but that could change as former White House strategist Steve Bannon and others are encouraging Stewart to do so. It’s hard to say just how much a Stewart endorsement would matter, but more unity on the GOP side can only help Gillespie.
Together, the Confederate monuments and immigration issues could be very useful for Gillespie. Just consider a Gillespie mail piece that claims Northam “wants to tear down history while making life easier for illegal immigrants.” These issues distract from other ones that could be better for Northam, like health care, which tends to be the most or one of the most important issues for Democrats and where the GOP plans in Washington, DC have been horribly unpopular. Additionally, polls have generally shown voters are more likely to support expanding Medicaid, which is a position Northam holds. Gun control has now entered the fray in the aftermath of the Las Vegas massacre, and there may be more potential for Northam than Gillespie on that front: A Quinnipiac poll back in April found that voters are somewhat more likely to support some gun control measures than not. Nonetheless, it’s an issue where the commonwealth is pretty evenly divided.
In terms of television advertising, it seems the Gillespie campaign tried to strike first. Throughout August, Gillespie ad buys were nearly double that of Northam’s in amount spent. Since then, Northam has picked up the pace, but Gillespie used the August ad buys to re-introduce himself to the general electorate with mostly positive spots that focused on, for example, his plans for the Virginia economy and how he worked to pay his way through college. One interesting effect of Northam’s seemingly-stiff Democratic primary challenge from Perriello was that it forced Northam to spend a bunch of money. This meant that Northam had to refill his campaign coffers in July and August, which may have helped Gillespie get the jump on TV ads, with the Republican campaign buying more in that period than the Democratic one. As we get closer to November, Northam may have the overall financial edge. He had $3 million more cash-on-hand than Gillespie at the end of August, and reported having $5.7 million available to spend at the end of September. We don’t yet have Gillespie’s report for September, so we don’t know if Northam has retained his monetary edge. But compared to 2013, Northam’s cash-on-hand total seems formidable: In 2013, now-Gov. Terry McAuliffe — a fundraising maven — had $1.8 million in the bank at the end of September. That means Northam has three times as much at the same point in 2017. This is a surprising development: It seemed reasonable to expect an experienced DC operative like Gillespie to have the connections necessary to outraise Northam — not to mention the well-endowed Republican Governors Association — but now it’s very possible that Northam will have an edge down the stretch, something our Republican sources concede even though they insist this race is anyone’s game. Democrats see Northam with a small lead — considerably smaller than some public polls, from the Washington Post and Quinnipiac, that have Northam leading by 10 or more. We continue to rate the race Leans Democratic, which is where we have had it since the June primary.
Conclusion
Circumstances and Gillespie’s campaign strategy have made this more of a law-and-order election, which has probably hurt Northam. The favorable environment — that is, a fairly unpopular Republican president in the White House and a relatively popular outgoing Democratic governor — is helping to keep the Democrat slightly ahead, but given the tendency in Virginia to vote against the sitting presidential party in gubernatorial elections and Trump’s poor approval rating, Northam should maybe be ahead by a little more.
Still, as discussed above, a blowout was always unlikely. A concern for the Northam campaign has to be the recent history of polling in Virginia and nationally that has missed some conservative voters. For example, the final RealClearPolitics average in 2013 showed McAuliffe leading Ken Cuccinelli (R) 45.6%-38.9%, with Libertarian Robert Sarvis getting 9.6%. Although McAuliffe led by 6.7 points, he only won by 2.5 on Election Day, 47.7%-45.2%. Some of that was Sarvis’ slide to 6.5%, as it’s likely that some Republican voters considering Sarvis came home to the GOP in the end (some of Sarvis’ purported voters probably failed to show on Election Day, too). In 2017, there’s also a Libertarian candidate, Cliff Hyra, though he looks set to win a far smaller share of the vote than Sarvis did. Nevertheless, Cuccinelli’s actual percentage was 6.3 points higher than his polling average while McAuliffe’s was only 2.1 points higher. We’ve seen this phenomenon in recent races, most notably some swing states in the 2016 presidential race, but also in contests like the 2015 Kentucky gubernatorial election. What Northam has to hope for is that with a different party holding the White House, the polls are either on the mark or they underestimate Democrats, not Republicans.
While it’s true that Virginia polls were relatively on the mark in 2016, if Northam isn’t consistently hitting 50% in some polls heading into Election Day 2017, he will have good reason to fear a surprise. |
package io.boodskap.iot.model;
import java.util.Date;
import io.boodskap.iot.dao.BillingInvoiceDAO;
public interface IBillingInvoice extends IDomainObject {
public static BillingInvoiceDAO<IBillingInvoice> dao(){
return BillingInvoiceDAO.get();
}
public static IBillingInvoice create(String domainKey, String targetDomain, String invoiceId) {
return dao().create(domainKey, targetDomain, invoiceId);
}
public static IBillingInvoice find(String domainKey, String targetDomain, String invoiceId) {
return dao().get(domainKey, targetDomain, invoiceId);
}
public static Class<? extends IBillingInvoice> clazz() {
return dao().clazz();
}
public default void save() {
IBillingInvoice.dao().createOrUpdate(this);
}
@Override
public default void copy(Object other) {
IBillingInvoice o = (IBillingInvoice) other;
setTargetDomain(o.getTargetDomain());
setInvoicename(o.getInvoicename());
setInvoiceno(o.getInvoiceno());
setFrequency(o.getFrequency());
setFile(o.getFile());
setGrandtotal(o.getGrandtotal());
setStartdate(o.getStartdate());
setEnddate(o.getEnddate());
setObj(o.getObj());
setInvoicetype(o.getInvoicetype());
IDomainObject.super.copy(other);
}
public String getTargetDomain();
public void setTargetDomain(String targetDomain);
public String getInvoicename();
public void setInvoicename(String invoicename);
public String getInvoiceno();
public void setInvoiceno(String invoiceno);
public String getFrequency();
public void setFrequency(String frequency);
public String getFile();
public void setFile(String file);
public double getGrandtotal();
public void setGrandtotal(double grandtotal);
public Date getStartdate();
public void setStartdate(Date startdate);
public Date getEnddate();
public void setEnddate(Date enddate);
public String getObj();
public void setObj(String obj);
public String getInvoicetype();
public void setInvoicetype(String invoicetype);
}
|
package org.d3ifcool.finpro.dosen.activities.detail;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.d3ifcool.finpro.core.adapters.AnggotaViewAdapter;
import org.d3ifcool.finpro.core.helpers.ViewAdapterHelper;
import org.d3ifcool.finpro.R;
import org.d3ifcool.finpro.core.interfaces.lists.ProyekAkhirListView;
import org.d3ifcool.finpro.core.interfaces.works.JudulWorkView;
import org.d3ifcool.finpro.core.interfaces.works.MahasiswaWorkView;
import org.d3ifcool.finpro.core.interfaces.works.ProyekAkhirWorkView;
import org.d3ifcool.finpro.core.models.Judul;
import org.d3ifcool.finpro.core.models.ProyekAkhir;
import org.d3ifcool.finpro.core.presenters.JudulPresenter;
import org.d3ifcool.finpro.core.presenters.MahasiswaPresenter;
import org.d3ifcool.finpro.core.presenters.ProyekAkhirPresenter;
import java.util.ArrayList;
import java.util.List;
import static org.d3ifcool.finpro.core.helpers.Constant.ObjectConstanta.JUDUL_STATUS_DIGUNAKAN;
import static org.d3ifcool.finpro.core.helpers.Constant.ObjectConstanta.JUDUL_STATUS_DITOLAK;
public class DosenJudulPaSubmahasiswaDetailActivity extends AppCompatActivity implements ProyekAkhirListView,
JudulWorkView, ProyekAkhirWorkView, MahasiswaWorkView {
public static final String EXTRA_JUDUL = "extra_judul";
private static final String PARAM_PROYEK_AKHIR = "proyek_akhir.judul_id";
private ProyekAkhirPresenter proyekAkhirPresenter;
private JudulPresenter judulPresenter;
private MahasiswaPresenter mahasiswaPresenter;
private ProgressDialog progressDialog;
private int extraJudulId;
private ArrayList<ProyekAkhir> arrayListProyekAkhir = new ArrayList<>();
private TextView textViewKelompok;
private ViewAdapterHelper viewAdapterHelper;
private AnggotaViewAdapter anggotaViewAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dosen_judul_pa_submahasiswa_detail);
setTitle(getString(R.string.title_judulpa_detail));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
proyekAkhirPresenter = new ProyekAkhirPresenter(this, this);
judulPresenter = new JudulPresenter(this);
mahasiswaPresenter = new MahasiswaPresenter(this);
proyekAkhirPresenter.initContext(this);
judulPresenter.initContext(this);
mahasiswaPresenter.initContext(this);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.text_progress_dialog));
Judul extraJudul = getIntent().getParcelableExtra(EXTRA_JUDUL);
extraJudulId = extraJudul.getId();
String extraJudulTanggal = extraJudul.getJudul_waktu();
String extraJudulNama = extraJudul.getJudul();
String extraJudulDeskripsi = extraJudul.getDeskripsi();
String extraJudulKategori = extraJudul.getKategori_nama();
TextView textViewTanggal = findViewById(R.id.act_dsn_mhs_judul_tanggal);
TextView textViewJudul = findViewById(R.id.act_dsn_mhs_judul);
TextView textViewDeskripsi = findViewById(R.id.act_dsn_mhs_judul_deskripsi);
TextView textViewKategori = findViewById(R.id.act_dsn_mhs_judul_kategori);
FloatingActionButton floatingActionButtonAccept = findViewById(R.id.act_dsn_mhs_judul_fab_accept);
FloatingActionButton floatingActionButtonDecline = findViewById(R.id.act_dsn_mhs_judul_fab_decline);
FloatingActionButton floatingActionButtonConversation = findViewById(R.id.act_dsn_mhs_judul_fab_conversation);
textViewKelompok = findViewById(R.id.act_dsn_mhs_judul_kelompok);
textViewTanggal.setText(extraJudulTanggal);
textViewJudul.setText(extraJudulNama);
textViewDeskripsi.setText(extraJudulDeskripsi);
textViewKategori.setText(extraJudulKategori);
RecyclerView recyclerView = findViewById(R.id.all_recyclerview_anggota);
anggotaViewAdapter = new AnggotaViewAdapter(this);
viewAdapterHelper = new ViewAdapterHelper(this);
viewAdapterHelper.setRecyclerView(recyclerView);
proyekAkhirPresenter.searchAllProyekAkhirBy(PARAM_PROYEK_AKHIR, String.valueOf(extraJudulId));
floatingActionButtonAccept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog
.Builder(DosenJudulPaSubmahasiswaDetailActivity.this)
.setTitle(getString(R.string.dialog_setuju_title))
.setMessage(getString(R.string.dialog_setuju_text))
.setPositiveButton(R.string.iya, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
judulPresenter.updateStatusJudul(extraJudulId, JUDUL_STATUS_DIGUNAKAN);
}
})
.setNegativeButton(R.string.tidak, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
floatingActionButtonDecline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog
.Builder(DosenJudulPaSubmahasiswaDetailActivity.this)
.setTitle(getString(R.string.dialog_tolak_title))
.setMessage(getString(R.string.dialog_tolak_text))
.setPositiveButton(R.string.iya, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
proyekAkhirPresenter.deleteProyekAkhir(arrayListProyekAkhir.get(0).getProyek_akhir_id());
mahasiswaPresenter.updateMahasiswaJudul(arrayListProyekAkhir.get(0).getMhs_nim(), 0);
if (arrayListProyekAkhir.size() == 2) {
proyekAkhirPresenter.deleteProyekAkhir(arrayListProyekAkhir.get(arrayListProyekAkhir.size()-1).getProyek_akhir_id());
mahasiswaPresenter.updateMahasiswaJudul(arrayListProyekAkhir.get(1).getMhs_nim(), 0);
}
judulPresenter.updateStatusJudul(extraJudulId, JUDUL_STATUS_DITOLAK);
}
})
.setNegativeButton(R.string.tidak, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
floatingActionButtonConversation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void showProgress() {
}
@Override
public void hideProgress() {
}
@Override
public void onSucces() {
}
@Override
public void onSuccesWorkJudul() {
finish();
}
@Override
public void onGetListProyekAkhir(List<ProyekAkhir> proyekAkhirList) {
arrayListProyekAkhir.clear();
arrayListProyekAkhir.addAll(proyekAkhirList);
textViewKelompok.setText(arrayListProyekAkhir.get(0).getNama_tim());
anggotaViewAdapter.addItem(arrayListProyekAkhir);
viewAdapterHelper.setAdapterAnggota(anggotaViewAdapter);
}
@Override
public void isEmptyListProyekAkhir() {
}
@Override
public void onFailed(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
|
// Drop the reference count immediately if the value has no uses.
static LogicalResult dropRefIfNoUses(Value value, unsigned count = 1) {
if (!value.getUses().empty())
return failure();
OpBuilder b(value.getContext());
if (Operation *op = value.getDefiningOp())
b.setInsertionPointAfter(op);
else
b.setInsertionPointToStart(value.getParentBlock());
b.create<RuntimeDropRefOp>(value.getLoc(), value, b.getI64IntegerAttr(1));
return success();
} |
/**
* @author <a href="mailto:[email protected]">Christiaan ten Klooster </a>
* @version $Revision: 1556 $
*/
public class LayoutFactory extends AbstractSwtFactory {
private Class beanClass;
/**
* @param beanClass
*/
public LayoutFactory(Class beanClass) {
this.beanClass = beanClass;
}
public Object newInstance(FactoryBuilderSupport builder, Object name,
Object value, Map attributes) throws InstantiationException,
IllegalAccessException {
Object parent = builder.getCurrent();
Layout layout = (Layout) beanClass.newInstance();
Widget parentComposite = (Widget) SwtUtils.getParentWidget(parent, attributes);
if (parentComposite != null) {
((Composite) parentComposite).setLayout(layout);
}
return layout;
}
} |
/**
* Method to generate the AAI model for a Service or Resource.
*
* @param model
* Java object model representing an AAI {@link Service} or {@link Resource} model
* @return XML representation of the model in String format
* @throws XmlArtifactGenerationException
*/
public String generateModelFor(Model model) throws XmlArtifactGenerationException {
org.onap.aai.babel.xml.generator.xsd.Model aaiModel = createJaxbModel(model);
ModelElement baseWidget = addBaseWidgetRelation(model, aaiModel);
generateWidgetChildren(baseWidget, model.getWidgets());
return getModelAsString(aaiModel);
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.