content
stringlengths 10
4.9M
|
---|
/**
* Assign values to this frame.
* @param values the values
* @return this frame
*/
public Frame assign(Object... values) {
if (stack != null && values != null && values.length > 0) {
Object[] copy = stack.clone();
int ncopy = Math.min(copy.length - curried, values.length);
System.arraycopy(values, 0, copy, curried, ncopy);
return new Frame(scope, copy, curried + ncopy);
}
return this;
} |
def add_regions_to_axis(axis, table_regions):
row_labels = []
row_texts = []
row_colors = []
trend_colors = []
regions = list(table_regions.loc[:, 'region'].tolist())
regions[0] = {'Bangkok Metropolitan Region': 'Bangkok', 'Northeastern': 'Northeast'}.get(regions[0], regions[0])
current_region = regions[0]
append_row(row_labels, row_texts, row_colors, trend_colors, ' ' + current_region + ' Region')
provinces = list(table_regions.index)
values = list(table_regions.loc[:, 'Value'].tolist())
trends = list(table_regions.loc[:, 'Trend'].tolist())
if "Trend_style" in table_regions.columns:
styles = list(table_regions.loc[:, 'Trend_style'].tolist())
else:
styles = None
for row_number, province in enumerate(provinces):
if provinces[row_number] == 'Phra Nakhon Si Ayutthaya':
provinces[row_number] = 'Ayutthaya'
if provinces[row_number] == 'Nakhon Si Thammarat':
provinces[row_number] = 'Nakhon Si Tham.'
if regions[row_number] == 'Bangkok Metropolitan Region':
regions[row_number] = 'Bangkok'
if regions[row_number] == 'Northeastern':
regions[row_number] = 'Northeast'
if not current_region == regions[row_number]:
append_row(row_labels, row_texts, row_colors, trend_colors)
current_region = regions[row_number]
append_row(row_labels, row_texts, row_colors, trend_colors, ' ' + current_region + ' Region')
trend_arrow, trend_color = trend_indicator(trends[row_number], style=styles[row_number] if styles else "green_up")
append_row(row_labels, row_texts, row_colors, trend_colors,
provinces[row_number], [f'{human_format(values[row_number], 0)}', trend_arrow],
[(0, 0, 0, 0), trend_color], trend_color)
axis.set_axis_off()
table = axis.table(cellLoc='right', loc='upper right', colWidths=[0.6, 0.17],
rowLabels=row_labels, cellText=row_texts, cellColours=row_colors)
table.auto_set_column_width((0, 1))
table.auto_set_font_size(False)
table.set_fontsize(15)
table.scale(1.1, 1.42)
for cell in table.get_celld().values():
cell.set_text_props(color=theme_light_text, fontsize=15)
for row_number, color in enumerate(trend_colors):
if row_labels[row_number] in region_colors:
table[(row_number, -1)].set_text_props(color=region_colors[row_labels[row_number]])
table[(row_number, 1)].set_text_props(color='blue')
table[(row_number, 1)].set_color(color)
table[(row_number, -1)].set_color(theme_light_back)
table[(row_number, 0)].set_color(theme_light_back) |
<gh_stars>1-10
package redis
import (
"go.opencensus.io/trace"
)
// TraceOption allows for managing redigo configuration using functional options.
// Copy from https://github.com/opencensus-integrations/ocsql/blob/master/options.go
type TraceOption func(o *TraceOptions)
type TraceOptions struct {
// DefaultAttributes will be set to each span as default.
DefaultAttributes []trace.Attribute
}
// WithDefaultAttributes will be set to each span as default.
func WithDefaultAttributes(attrs ...trace.Attribute) TraceOption {
return func(o *TraceOptions) {
o.DefaultAttributes = attrs
}
}
|
def pkg_manager_init(
self, package_names,
interactive=None,
overwrite=False, merge=False, **kw):
if interactive is None:
interactive = self.interactive
interactive = interactive & check_interactive()
original_json = {}
pkgdef_json = self.pkg_manager_view(package_names, **kw)
pkgdef_path = self.join_cwd(self.pkgdef_filename)
existed = exists(pkgdef_path)
if existed:
try:
with open(pkgdef_path, 'r') as fd:
original_json = json.load(fd)
except ValueError:
logger.warning(
"ignoring existing malformed '%s'", pkgdef_path)
except (IOError, OSError):
logger.error(
"reading of existing '%s' failed; "
"please confirm that it is a file and/or permissions to "
"read and write is permitted before retrying.",
pkgdef_path
)
raise
if merge:
updates = generate_merge_dict(
self.dep_keys, original_json, pkgdef_json,
)
final = {}
final.update(original_json)
final.update(pkgdef_json)
final.update(updates)
pkgdef_json = final
if original_json == pkgdef_json:
return True
if not interactive:
if merge:
overwrite = True
elif interactive:
if not overwrite:
diff = '\n'.join(l for l in (
line.rstrip() for line in difflib.ndiff(
self.dumps(original_json).splitlines(),
self.dumps(pkgdef_json).splitlines(),
))
if l[:1] in '?+-' or l[-1:] in '{}' or l[-2:] == '},')
overwrite = prompt(
"Generated '%(pkgdef_filename)s' differs with "
"'%(pkgdef_path)s'.\n\n"
"The following is a compacted list of changes "
"required:\n"
"%(diff)s\n\n"
"Overwrite '%(pkgdef_path)s'?" % {
'pkgdef_filename': self.pkgdef_filename,
'pkgdef_path': pkgdef_path,
'diff': diff,
},
choices=(
('Yes', True),
('No', False),
),
default_key=1,
)
if not overwrite:
logger.warning("not overwriting existing '%s'", pkgdef_path)
return False
if pkgdef_json:
with open(pkgdef_path, 'w') as fd:
self.dump(pkgdef_json, fd)
logger.info("wrote '%s'", pkgdef_path)
return True |
Congratulations to David Baird for finding and photographing the De’il’s Well, which is probably the traditional site where the Glenluce Devil is alleged to have threatened to cast in a weaver’s daughter called Janet Campbell in 1655.
Campbell’s Croft, Photograph © Copyright David Baird and reproduced by his kind permission.
A couple of months ago, I posted about the Devil of Glenluce, a story recorded by George Sinclair in the 1670s and in his Satan’s Invisible World Discovered of 1685. Almost immediately, David commented that the were local sites near Glenluce which were possibly connected to the story at Campbell’s Croft, see photograph above, or Ghaist Ha’. The original OS map then revealed that the De’il’s Well lay beside Ghaist Ha’ or Hall.
David conducted a great piece of field work to find and photograph the two locations. He describes the locations as follows.
The De’il’s Well looking south. Photograph © Copyright David Baird and reproduced by his kind permission.
Map of De’il’s Well
‘The De’il’s Well was easy to find – it’s more of a spring (with a good flow) rather than a well, and if there was ever any stonework or cover around it then it’s long gone. The original basin of the well has silted up a bit but is still quite obvious, and the farmer has made a bit of a pond of the outflow presumably as a water supply for livestock.’
The De’il’s Well looking north-east. Photograph © Copyright David Baird and reproduced by his kind permission.
According to Sinclair’s story of the Devil:
‘Jennet Campbell going one day to the Well, to bring home some Water, was conveyed, with a shril whistling about her ears, which made her say, I would fain hear thee speake, as well as Whistle. Hereupon it said, after a threatening manner, I’le cast thee Iennet into the Well.’
As David very wisely points out, if you visit the well, DO NOT DRINK THE WATER, as it is highly likely that it is contaminated with animal dung which contains the nasty Cryptosporidium parasite.
Ghaist Ha’ looking south-east. Photograph © Copyright David Baird and reproduced by his kind permission.
Both locations lie to the west of Blackhill near Glenluce. The field pattern had remained relatively unchanged near the sites.
Map of Ghaist Ha’
Ghaist Ha’ is probably the traditional site for the Campbell family home, nearby Campbell’s Croft appears to be a later place name. It was probably at Ghaist Ha’ that the Glenluce Devil is reported to have terrorized the family in 1655 to 1656. Ghaist Ha’ may also be where Jock of Broad Scotland, aka Alexander Agnew a renowned atheist who was executed for blasphemy in 1656, allegedly threatened the Campbell family after he was refused alms.
Ghaist Ha’ looking north-east. Photograph © Copyright David Baird and reproduced by his kind permission.
David records:
‘There is nothing visible at all at the site of Ghaist Ha’ apart perhaps from the ground being a bit more level than the rest of the gently sloping hill. I had a good look around the edges of the field and the dykes for any signs of dressed stone or mortar but with no result, so I assume that if there was a building on this site any rubble has been completely removed and any foundations ploughed out.’
Well done David, an outstanding effort. Thank you for bringing these places back to a wider historical audience.
For other strange events and wonders of the 1680s, see here.
Return to Homepage
Additional Text © Copyright Dr Mark Jardine. All Rights Reserved. Please link to this post on Facebook or retweet it, but do not reblog in FULL without the express permission of the author @drmarkjardine
54.867159 -4.444234
Advertisements
Posted in Covenanters, Galloway, George Sinclair, Glenluce parish, The Devil, Wigtownshire, Wonders
Tags: Dumfries and Galloway, George Sinclair, Glenluce, History, Satan's Invisible World Discovered, Scotland, Walking |
/**
* A sparse grid index that contains lists of objects.
* Be advised that the {@link #get(int, int)} method may return null if no objects
* are queued at that particular spot.
* @param <T> the value type.
* @author Matthew Tropiano
*/
public class SparseQueueGridIndex<T> extends SparseGridIndex<Deque<T>>
{
/** Holds the true size of this grid map. */
private int trueSize;
/**
* Creates a new sparse queue grid of an unspecified width and height.
* @throws IllegalArgumentException if capacity is negative or ratio is 0 or less.
*/
public SparseQueueGridIndex()
{
super();
trueSize = 0;
}
/**
* Enqueues an object at a particular grid coordinate.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param object the object to add.
*/
public void enqueue(int x, int y, T object)
{
if (object != null)
{
getQueue(x, y).add(object);
trueSize++;
}
}
/**
* Dequeues an object at a particular grid coordinate.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @return the first object added at the set of coordinates, null if no objects enqueued.
*/
public T dequeue(int x, int y)
{
T out = getQueue(x, y).pollFirst();
if (out != null)
trueSize--;
return out;
}
/**
* Dequeues an object at a particular grid coordinate.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @param object the object to remove.
* @return the first object added at the set of coordinates, null if no objects enqueued.
*/
public boolean remove(int x, int y, T object)
{
boolean out = getQueue(x, y).remove(object);
if (out)
trueSize--;
return out;
}
/**
* Returns an iterator for a queue at a particular grid coordinate.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @return a resettable iterator for the queue, or null if no queue exists.
*/
public Iterator<T> iterator(int x, int y)
{
return getQueue(x, y).iterator();
}
/**
* Returns a queue for a set of coordinates. If no queue exists, it is created.
* This should NEVER return null.
* @param x the x-coordinate.
* @param y the y-coordinate.
* @return a reference to the queue using the provided coordinates.
*/
protected Deque<T> getQueue(int x, int y)
{
Deque<T> out = get(x, y);
if (out == null)
{
out = new LinkedList<T>();
set(x, y, out);
}
return out;
}
@Override
public void set(int x, int y, Deque<T> queue)
{
Deque<T> oldQueue = get(x, y);
if (oldQueue != null)
trueSize -= oldQueue.size();
super.set(x, y, queue);
if (queue != null)
trueSize += queue.size();
}
@Override
public void clear()
{
super.clear();
trueSize = 0;
}
@Override
public int size()
{
return trueSize;
}
} |
How the budget will affect the Centers for Disease Control and Prevention is less clear. The blueprint asks to reform the CDC through a $500 million block-grant program, that will allow each state to decide how best to use the money. Notably, perhaps, given that epidemics are international in nature, it does not mention anything about funding the CDC’s global work.
In the Department of Energy, nuclear weapons spending gets a boost to the detriment of renewable energy. The budget would eliminate Advanced Research Projects Agency-Energy (ARPA-E), which has given out $1.5 billion to 580 high-risk, high-reward projects in renewable energy and efficiency since 2009. Loan programs for clean energy projects and fuel-efficient cars are also on the chopping block.
In addition, the blueprint cuts $900 million from the Office of Science, which runs ten of the DOE’s seventeen national laboratories. The laboratories carry out a wide range of research, from sequencing for the original Human Genome Project to current fusion energy research.
The Environmental Protection Agency is, unsurprisingly given everything Trump said during the campaign, the biggest target. The blueprint lays out the EPA’s budget as $5.7 billion, effectively a 31 percent cut. It will eliminate the Clean Power Plan, President Obama’s flagship policy for lowering carbon emissions.
But that’s not all. The budget eliminates a full 50 programs the administration deems “lower priority and poorly performing,” including Energy Star (which sets standards for energy-efficient household appliances) and the Endocrine Disruptor Screening Program (which addresses chemicals like BPA). The Superfund program will get 30 percent less funding for cleanup of hazardous waste sites.
Earth science will also lose major funding resources from National Oceanic and Atmospheric Administration and NASA. The plan eliminates $250 million in funding for NOAA, which would cut grants supporting coastal and ocean research. It also cuts $102 million from NASA’s Earth science program and ends four missions that would have observed the Earth from space: PACE, OCO-3, DSCOVR Earth-viewing instruments, and CLARREO Pathfinder.
The Trump administration wants NASA to refocus on space exploration, but first, it wants to kill the Asteroid Redirect Mission, where astronauts would have plucked a rock from space and tugged it into lunar orbit. The mission has never been particularly popular, though the Obama administration sold it as a stepping stone to Mars. What the budget does endorse are the Orion crew vehicle and Space Launch System, which are supposed to eventually take astronauts into Mars and deep space. It also endorses a flyby mission to Europa and a Mars rover. Overall NASA only gets a 0.8 percent budget decrease but it comes with a massive reallocation of resources. |
<filename>bundle/deepracer_simulation_environment/lib/python2.7/dist-packages/mp4_saving/f1_image_editing.py<gh_stars>1-10
"""Image editing class for head to head where there are multiple agents
"""
import datetime
from collections import OrderedDict
import threading
import logging
import rospy
import cv2
import numpy as np
from sensor_msgs.msg import Image as ROSImg
from markov.log_handler.logger import Logger
from markov.log_handler.exception_handler import log_and_exit
from markov.log_handler.constants import (SIMAPP_EVENT_ERROR_CODE_500,
SIMAPP_SIMULATION_SAVE_TO_MP4_EXCEPTION)
from markov.reset.constants import RaceType
from markov.utils import get_racecar_idx
from mp4_saving.top_view_graphics import TopViewGraphics
from mp4_saving.constants import (RaceCarColorToRGB,
RACE_TYPE_TO_VIDEO_TEXT_MAPPING, SCALE_RATIO,
TrackAssetsIconographicPngs, IconographicImageSize,
XYPixelLoc, RACE_COMPLETE_Y_OFFSET,
FrameQueueData)
from mp4_saving import utils
from mp4_saving.image_editing_interface import ImageEditingInterface
LOG = Logger(__name__, logging.INFO).get_logger()
class F1ImageEditing(ImageEditingInterface):
"""Image editing class for F1 grand prix
"""
_lock = threading.Lock()
_finished_lap_time = OrderedDict()
_leader_percentage_completion = list()
_leader_elapsed_time = list()
def __init__(self, racecar_name, racecars_info, race_type):
""" This class is used for head to head racing where there are more than one agent
Args:
racecar_name (str): The agent name with 45degree camera view
racecars_info (dict): All the agents information
race_type (str): The type of race. This is used to know if its race type or evaluation
"""
self.racecar_name = racecar_name
self.racecars_info = racecars_info
racecar_index = get_racecar_idx(racecar_name)
self.racecar_index = racecar_index if racecar_index else 0
self.race_type = race_type
# Store the font which we will use to write the phase with
self.formula1_display_regular_12px = utils.get_font('Formula1-Display-Regular', 12)
self.formula1_display_regular_14px = utils.get_font('Formula1-Display-Regular', 14)
self.formula1_display_regular_16px = utils.get_font('Formula1-Display-Regular', 16)
self.formula1_display_wide_12px = utils.get_font('Formula1-Display-Wide', 12)
self.formula1_display_bold_16px = utils.get_font('Formula1-Display-Bold', 16)
self.total_laps = int(rospy.get_param("NUMBER_OF_TRIALS", 0))
self.is_league_leaderboard = rospy.get_param("LEADERBOARD_TYPE", "") == "LEAGUE"
self.leaderboard_name = rospy.get_param("LEADERBOARD_NAME", "")
# The track image as iconography
self.track_icongraphy_img = utils.get_track_iconography_image()
# Track image offset
self.track_loc_offset = XYPixelLoc.TRACK_IMG_WITHOUT_OFFSET_LOC.value
# Default image of top view
gradient_default_img_path = TrackAssetsIconographicPngs.F1_OVERLAY_DEFAULT_PNG.value
self.gradient_default_img = self._plot_track_on_gradient(gradient_default_img_path)
self.gradient_default_alpha_rgb_mul, self.one_minus_gradient_default_alpha = utils.get_gradient_values(
self.gradient_default_img)
# Midway track gradient
gradient_midway_img_path = TrackAssetsIconographicPngs.F1_OVERLAY_MIDWAY_PNG.value
self.gradient_midway_img = self._plot_track_on_gradient(gradient_midway_img_path)
self.gradient_midway_alpha_rgb_mul, self.one_minus_gradient_midway_alpha = utils.get_gradient_values(
self.gradient_midway_img)
# Finisher track gradient
gradient_finisher_img_path = TrackAssetsIconographicPngs.F1_OVERLAY_FINISHERS_PNG.value
self.gradient_finisher_img = self._plot_track_on_gradient(gradient_finisher_img_path)
self.gradient_finisher_alpha_rgb_mul, self.one_minus_gradient_finisher_alpha = utils.get_gradient_values(
self.gradient_finisher_img)
# Top camera gradient
num_racers = len(self.racecars_info)
if num_racers <= 8:
# TODO: Add one box image and use 1 box image if number of racers are <= 4.
gradient_top_camera_img_path = TrackAssetsIconographicPngs.F1_OVERLAY_TOPVIEW_2BOX_PNG.value
elif num_racers <= 12:
gradient_top_camera_img_path = TrackAssetsIconographicPngs.F1_OVERLAY_TOPVIEW_3BOX_PNG.value
else:
raise Exception("More than 12 racers are not supported for Grand Prix")
gradient_top_camera_img = utils.get_image(gradient_top_camera_img_path,
IconographicImageSize.FULL_IMAGE_SIZE.value)
gradient_top_camera_img = cv2.cvtColor(gradient_top_camera_img, cv2.COLOR_RGBA2BGRA)
self.gradient_top_camera_alpha_rgb_mul, self.one_minus_gradient_top_camera_alpha = utils.get_gradient_values(
gradient_top_camera_img)
# Top camera information
top_camera_info = utils.get_top_camera_info()
self.edited_topview_pub = rospy.Publisher('/deepracer/topview_stream', ROSImg, queue_size=1)
self.top_view_graphics = TopViewGraphics(top_camera_info.horizontal_fov, top_camera_info.padding_pct,
top_camera_info.image_width, top_camera_info.image_height,
racecars_info, race_type)
self.hex_car_colors = [val['racecar_color'].split('_')[-1] for val in racecars_info]
self._racer_color_code_rect_img = list()
self._racer_color_code_slash_img = list()
for car_color in self.hex_car_colors:
# Rectangular png of racers
racer_color_code_rect = "{}_{}".format(TrackAssetsIconographicPngs.F1_AGENTS_RECT_DISPLAY_ICON_PNG.value,
car_color)
self._racer_color_code_rect_img.append(
utils.get_image(racer_color_code_rect, IconographicImageSize.F1_RACER_RECT_DISPLAY_ICON_SIZE.value))
# Slash png of racers
racer_color_code_slash = "{}_{}".format(TrackAssetsIconographicPngs.F1_AGENTS_SLASH_DISPLAY_ICON_PNG.value,
car_color)
racer_color_code_slash_img = utils.get_image(racer_color_code_slash,
IconographicImageSize.F1_RACER_SLASH_DISPLAY_ICON_SIZE.value)
self._racer_color_code_slash_img.append(cv2.cvtColor(racer_color_code_slash_img, cv2.COLOR_RGBA2BGRA))
def _get_racecar_ranking(self, racers_ranking, racer_number):
""" Returns the rank of the racer given the racing number.
This function considers the cars finished and uses the elapsed time for giving the ranking.
Arguments:
racers_ranking (OrderedDict): Sorted ordered dict with racer_number and progress percentage along with lap
racer_number (int): This is the racers number assigned when kinesis video node is spwan
Returns:
(int): The rank of the racer
"""
if racer_number in racers_ranking:
rank = list(racers_ranking.keys()).index(racer_number) + 1
# The difference between self.racecars_info and racers_ranking will give
# the number of racers completed the race at given time frame.
# Relying on self._finished_lap_time for the ranking is a bad idea as given racers_ranking may not
# be from current time (can be from queued frame which is from the past),
# where self._finished_lap_time always contains the latest information.
rank += len(self.racecars_info) - len(racers_ranking)
return rank
else:
# If racer_number is not in racers_ranking then given racer_number racer at the given time frame
# has already completed the race, then it must rely on self._finished_lap_time to
# retrieve its ranking as racers_ranking won't contain the given racer_number and
# self._finished_lap_time is the ONLY source to retrieve its ranking.
return list(self._finished_lap_time.keys()).index(racer_number) + 1
def _get_gap_time(self, racers_ranking, racer_number, racer_metrics_info):
""" Checks if a car has complete the race and considers the difference in the
elapsed time as gap time. If no racers have completed the lap then this function
considers _leader_percentage_completion which tracks all the data points of the
leaders progress to the elapsed time.
Arguments:
racers_ranking (OrderedDict): Sorted ordered dict with racer_number and progress percentage along with lap
racer_number (int): This is the racers number assigned when kinesis video node is spwan
racer_metrics_info (dict): Given racers metric information
"""
if len(racers_ranking) < len(self.racecars_info):
# if size of racers_ranking is smaller than size of self.racecars_info, then
# it means there is at least one racer completed the race.
leader_elapsed_time = list(self._finished_lap_time.items())[0][1]
if racer_number not in racers_ranking:
# If given racer has been also completed the race then the gap time is
# just difference between the race finish times of given racer and leader.
# Otherwise, the gap time needs to be retrieved from interpolation estimation.
return (self._finished_lap_time[racer_number] - leader_elapsed_time) / 1000
# Once leader completed the race, it's unnecessary to update
# self._leader_elapsed_time and self._leader_percentage_completion lists.
# Thus, set race_leader_index to None to avoid updating these static lists.
race_leader_index = None
else:
# If none of the racers completed the race then every progress and time of the leader
# needs to be recorded.
race_leader_index = list(racers_ranking.items())[0][0]
with self._lock:
try:
if race_leader_index is not None:
if len(self._leader_elapsed_time) == 0 or \
(racer_metrics_info.total_evaluation_time > self._leader_elapsed_time[-1] and
racers_ranking[race_leader_index] > self._leader_percentage_completion[-1]):
# ONLY append leader's datapoint when there is an actual latest new datapoint.
self._leader_percentage_completion.append(racers_ranking[race_leader_index])
# Since the total evaluation time is same for all the racers
self._leader_elapsed_time.append(racer_metrics_info.total_evaluation_time)
if racers_ranking[racer_number] < 0.0:
# If the progress of the racer is less than 0 then it means racer hasn't passed the start line yet.
# In such case, the gap time based on leader's elapsed time is meaningless.
# Thus, just return 0.
return 0
leader_elapsed_time = np.interp(racers_ranking[racer_number], self._leader_percentage_completion,
self._leader_elapsed_time)
return (racer_metrics_info.total_evaluation_time - leader_elapsed_time) / 1000
except Exception as ex:
LOG.info("Failed to find race leaders elapsed time: {}".format(ex))
return 0
def _racers_rank_name_gap_time(self, racers_ranking, mp4_video_metrics_info):
""" Gets all the racers information rank, name, gap time. This is used for
showing duirng the halfway mark and finished lap. This is used for the
top view camera editing.
Arguments:
racers_ranking (OrderedDict): Sorted ordered dict with racer_number and progress percentage along with lap
mp4_video_metrics_info (list): All the racers metric information
Returns:
(list): Sorted list based on the ranking along with rank, name, gap time, racer_number
"""
rank_name_gap_time = list()
for i in range(len(self.racecars_info)):
racer_number = int(self.racecars_info[i]['name'].split("_")[1])
rank_name_gap_time.append([
self._get_racecar_ranking(racers_ranking, racer_number),
self.racecars_info[i]['display_name'],
self._get_gap_time(racers_ranking, racer_number, mp4_video_metrics_info[racer_number]),
racer_number
])
return sorted(rank_name_gap_time, key=lambda item: item[0])
def _default_edit(self, major_cv_image):
""" This is used as a default edit.
Arguments:
major_cv_image (Image): Main camera image for the racecar
Returns:
major_cv_image (Image): Edited Main camera image
"""
# Applying gradient to whole major image and then writing text
# F1 logo at the top left
# loc_x, loc_y = XYPixelLoc.F1_LOGO_LOC.value
# f1_logo_image = utils.get_image(TrackAssetsIconographicPngs.F1_LOGO_PNG.value,
# IconographicImageSize.F1_LOGO_IMAGE_SIZE.value)
# major_cv_image = utils.plot_rectangular_image_on_main_image(major_cv_image, f1_logo_image, (loc_x, loc_y))
major_cv_image = utils.apply_gradient(major_cv_image, self.gradient_default_alpha_rgb_mul,
self.one_minus_gradient_default_alpha)
return major_cv_image
def _basic_racer_info_display(self, major_cv_image, racers_ranking, cur_racer_metrics_info, show_racer_name=True):
""" Basic display editting of the main camera following the car.
All the information at the bottom left of the MP4 is edited here.
Arguments:
major_cv_image (Image): Main camera image for the racecar
racers_ranking (OrderedDict): Sorted ordered dict with racer_number and progress percentage along with lap
cur_racer_metrics_info (dict): Given racers metric information
Keyword Arguments:
show_racer_name (bool): All the other states call this. But the finisher state does not have enough
space to show the display name.(default: {True})
Returns:
major_cv_image (Image): Edited Main camera image
"""
if show_racer_name:
# Adding display name to the image
loc_x, loc_y = XYPixelLoc.F1_DISPLAY_NAME_LOC.value
display_name = self.racecars_info[self.racecar_index]['display_name']
display_name_txt = display_name if len(display_name) <= 6 else "{}".format(display_name[:6])
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=display_name_txt,
loc=(loc_x, loc_y), font=self.formula1_display_regular_14px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Racers ranking
loc_x, loc_y = XYPixelLoc.F1_RANKING_LOC.value
cur_rank = self._get_racecar_ranking(racers_ranking, self.racecar_index)
rank_txt = "Rank {}/{}".format(cur_rank, len(self.racecars_info))
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=rank_txt,
loc=(loc_x, loc_y), font=self.formula1_display_regular_16px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Lap Counter|Total eval|gap time
# Lap counter calculation
loc_x, loc_y = XYPixelLoc.F1_LAP_EVAL_GAP_LOC.value
current_lap = min(int(cur_racer_metrics_info.lap_counter) + 1, int(self.total_laps))
lap_counter_text = "Lap {:2d} / {:2d}".format(current_lap, int(self.total_laps))
# Total eval time
if self.racecar_index in self._finished_lap_time:
# If the racer finished the race then lock the total evaluation time to finished lap time.
total_eval_milli_seconds = self._finished_lap_time[self.racecar_index]
else:
total_eval_milli_seconds = cur_racer_metrics_info.total_evaluation_time
time_delta = datetime.timedelta(milliseconds=total_eval_milli_seconds)
total_eval_time_text = "{}".format(utils.milliseconds_to_timeformat(time_delta))
# Writing to the frame (Lap Counter|Total eval|gap time)
lap_elapsed_gap_time = "{} | {} | Gap ".format(lap_counter_text, total_eval_time_text)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=lap_elapsed_gap_time,
loc=(loc_x, loc_y), font=self.formula1_display_regular_16px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Gap (In orange color)
loc_x, loc_y = XYPixelLoc.F1_LAP_EVAL_GAP_VAL_LOC.value
# For the racer ranking 0, we see small floating number for the gap. Hence making it zero
if cur_rank == 1:
gap_time = 0
gap_time = self._get_gap_time(racers_ranking, self.racecar_index, cur_racer_metrics_info)
gap_time_text = "+{:.3f}".format(gap_time)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=gap_time_text,
loc=(loc_x, loc_y), font=self.formula1_display_regular_16px,
font_color=RaceCarColorToRGB.Orange.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Leaderboard name
f1_water_mark_text = "{}".format(self.leaderboard_name)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=f1_water_mark_text,
loc=XYPixelLoc.F1_LEADERBOARD_NAME_LOC.value,
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Do all plotting of images at the end
if show_racer_name:
# Draw racer color code
loc_x, loc_y = XYPixelLoc.F1_DISPLAY_NAME_SLASH_LOC.value
major_cv_image = utils.plot_rectangular_image_on_main_image(
major_cv_image, self._racer_color_code_slash_img[self.racecar_index], (loc_x, loc_y))
major_cv_image = cv2.cvtColor(major_cv_image, cv2.COLOR_RGB2BGRA)
return major_cv_image
def _midway_racers_progress_display(self, major_cv_image, rank_name_gap_time, mp4_video_metrics_info):
""" Half way of the track we show the stats of the racers with there ranks and gap time
Arguments:
major_cv_image (Image): Main camera image for the racecar
rank_name_gap_time (list): Sorted list based on the ranking along with rank, name, gap time, racer_number
mp4_video_metrics_info (list): All the racers metric information
Returns:
major_cv_image (Image): Edited Main camera image
"""
# Applying gradient to whole major image and then writing text
major_cv_image = utils.apply_gradient(major_cv_image, self.gradient_midway_alpha_rgb_mul,
self.one_minus_gradient_midway_alpha)
major_cv_image = cv2.cvtColor(major_cv_image, cv2.COLOR_BGR2RGBA)
# LAP Title
loc_x, loc_y = XYPixelLoc.F1_MIDWAY_LAP_TEXT_LOC.value
lap_txt = "LAP"
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=lap_txt,
loc=(loc_x, loc_y), font=self.formula1_display_wide_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# LAP counter
loc_x, loc_y = XYPixelLoc.F1_MIDWAY_LAP_COUNTER_LOC.value
current_lap = min(int(mp4_video_metrics_info[self.racecar_index].lap_counter) + 1, int(self.total_laps))
lap_counter_text = "{} / {}".format(current_lap, int(self.total_laps))
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=lap_counter_text,
loc=(loc_x, loc_y), font=self.formula1_display_bold_16px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Each racers ranking, name and gap time
rank_loc_x, rank_loc_y = XYPixelLoc.F1_MIDWAY_LEADER_RANK_LOC.value
color_code_loc_x, color_code_loc_y = XYPixelLoc.F1_MIDWAY_LEADER_COLOR_CODE_LOC.value
display_name_loc_x, display_name_loc_y = XYPixelLoc.F1_MIDWAY_LEADER_DISPLAY_NAME_LOC.value
gap_loc_x, gap_loc_y = XYPixelLoc.F1_MIDWAY_LEADER_GAP_LOC.value
# All the other racers name and gap
for i, val in enumerate(rank_name_gap_time):
rank, display_name, gap_time, racer_number = val
# Rank
racer_rank = "{}".format(rank)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=racer_rank,
loc=(rank_loc_x, rank_loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Draw racer color code icon
major_cv_image = utils.plot_rectangular_image_on_main_image(major_cv_image,
self._racer_color_code_rect_img[racer_number],
(color_code_loc_x, color_code_loc_y))
# Adding display name to the table
display_name_txt = display_name if len(display_name) <= 6 else "{}".format(display_name[:6])
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=display_name_txt,
loc=(display_name_loc_x, display_name_loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Adding gap to the table (Do not write gap for leader)
if i:
gap_time_text = "+{:.3f}".format(gap_time)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=gap_time_text,
loc=(gap_loc_x, gap_loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
rank_loc_y += 20
color_code_loc_y += 20
display_name_loc_y += 20
gap_loc_y += 20
return cv2.cvtColor(major_cv_image, cv2.COLOR_RGB2BGRA)
def _race_finish_display(self, major_cv_image, rank_name_gap_time):
""" This displays the stats of all the racers who have finished the lap. When the car
finishes the lap the finisher racers get added into this list.
Arguments:
major_cv_image (Image): Main camera image for the racecar
rank_name_gap_time (list): Sorted list based on the ranking along with rank, name, gap time, racer_number
Returns:
major_cv_image (Image): Edited Main camera image
"""
# Applying gradient to whole major image and then writing text
major_cv_image = utils.apply_gradient(major_cv_image, self.gradient_finisher_alpha_rgb_mul,
self.one_minus_gradient_finisher_alpha)
major_cv_image = cv2.cvtColor(major_cv_image, cv2.COLOR_BGR2RGBA)
# F1 logo
# loc_x, loc_y = XYPixelLoc.F1_LOGO_LOC.value
# f1_logo_image = utils.get_image(TrackAssetsIconographicPngs.F1_LOGO_PNG.value,
# IconographicImageSize.F1_LOGO_IMAGE_SIZE.value,
# is_rgb=True)
# major_cv_image = utils.plot_rectangular_image_on_main_image(major_cv_image, f1_logo_image, (loc_x, loc_y))
# Finish Title
loc_x, loc_y = XYPixelLoc.F1_FINISHED_TITLE_LOC.value
finisher_txt = "Finishers"
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=finisher_txt,
loc=(loc_x, loc_y), font=self.formula1_display_bold_16px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
rank_loc_x, rank_loc_y = XYPixelLoc.F1_FINISHED_RANK_LOC.value
color_code_loc_x, color_code_loc_y = XYPixelLoc.F1_FINISHED_COLOR_CODE_LOC.value
display_name_loc_x, display_name_loc_y = XYPixelLoc.F1_FINISHED_DISPLAY_NAME_LOC.value
for rank, display_name, _, racer_number in rank_name_gap_time:
if racer_number not in self._finished_lap_time:
continue
# All racers name and gap
racer_rank = "{}".format(rank)
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=racer_rank,
loc=(rank_loc_x, rank_loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Draw racer color code icon
major_cv_image = utils.plot_rectangular_image_on_main_image(major_cv_image,
self._racer_color_code_rect_img[racer_number],
(color_code_loc_x, color_code_loc_y))
# Adding display name to the table
display_name_txt = display_name if len(display_name) <= 6 else "{}".format(display_name[:6])
major_cv_image = utils.write_text_on_image(image=major_cv_image, text=display_name_txt,
loc=(display_name_loc_x, display_name_loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
rank_loc_y += 20
color_code_loc_y += 20
display_name_loc_y += 20
return cv2.cvtColor(major_cv_image, cv2.COLOR_RGB2BGRA)
def _get_racers_metric_info(self, mp4_video_metrics_info):
racers_ranking = OrderedDict()
is_finish_lap_time_changed = False
for i in range(len(self.racecars_info)):
racer_number = int(self.racecars_info[i]['name'].split("_")[1])
mp4_video_metrics = mp4_video_metrics_info[racer_number]
if mp4_video_metrics.done and mp4_video_metrics.lap_counter + 1 >= int(self.total_laps):
if racer_number not in self._finished_lap_time:
self._finished_lap_time[racer_number] = mp4_video_metrics.total_evaluation_time
is_finish_lap_time_changed = True
else:
racers_ranking[racer_number] = mp4_video_metrics.completion_percentage / 100.0 +\
mp4_video_metrics.lap_counter
if is_finish_lap_time_changed:
# Re-order the self._finished_lap_time ONLY if there is any information updated.
self._finished_lap_time = OrderedDict(sorted(self._finished_lap_time.items(), key=lambda item: item[1]))
racers_ranking = OrderedDict(sorted(racers_ranking.items(), key=lambda item: item[1], reverse=True))
rank_name_gap_time = self._racers_rank_name_gap_time(racers_ranking, mp4_video_metrics_info)
return racers_ranking, rank_name_gap_time
def _edit_major_cv_image(self, major_cv_image, mp4_video_metrics_info):
""" Apply all the editing for the Major 45degree camera image
Args:
major_cv_image (Image): Image straight from the camera
mp4_video_metrics_info (list): All the racers metric information
Returns:
Image: Edited main camera image
"""
racers_ranking, rank_name_gap_time = self._get_racers_metric_info(mp4_video_metrics_info)
# Check if the done flag is set and set the banner appropriately
cur_racer_metrics_info = mp4_video_metrics_info[self.racecar_index]
current_lap = min(int(cur_racer_metrics_info.lap_counter) + 1, int(self.total_laps))
agent_done = cur_racer_metrics_info.done and (current_lap == int(self.total_laps))
if cur_racer_metrics_info.completion_percentage > 50.0 and cur_racer_metrics_info.completion_percentage < 60.0:
major_cv_image = self._midway_racers_progress_display(major_cv_image, rank_name_gap_time,
mp4_video_metrics_info)
major_cv_image = self._basic_racer_info_display(major_cv_image, racers_ranking, cur_racer_metrics_info)
elif agent_done:
major_cv_image = self._race_finish_display(major_cv_image, rank_name_gap_time)
major_cv_image = self._basic_racer_info_display(major_cv_image, racers_ranking, cur_racer_metrics_info,
show_racer_name=False)
else:
major_cv_image = self._default_edit(major_cv_image)
major_cv_image = self._basic_racer_info_display(major_cv_image, racers_ranking, cur_racer_metrics_info)
return major_cv_image
def _plot_track_on_gradient(self, gradient_img_path):
""" For the given gradient apply the track iconographic image and use this to apply gradient
on each camera frame. Previously this was done on the top camera which changed every frame. But
with the track iconographic image set static, adding the track on gradient is more optimized.
Arguments:
gradient_img_path (str): Gradient image path
Returns:
(Image): Edited gradient image with track image
"""
gradient_img = utils.get_image(gradient_img_path, IconographicImageSize.FULL_IMAGE_SIZE.value)
gradient_img = cv2.cvtColor(gradient_img, cv2.COLOR_RGBA2BGRA)
track_icongraphy_scaled = utils.resize_image(self.track_icongraphy_img, SCALE_RATIO)
track_icongraphy_alpha = track_icongraphy_scaled[:, :, 3] / 255.0
# Track image is placed at the bottom right with some offset (only in leaderboard tracks)
x_min = -(self.track_loc_offset[1] + track_icongraphy_scaled.shape[0])
x_max = gradient_img.shape[0] - self.track_loc_offset[1]
y_min = -(self.track_loc_offset[0] + track_icongraphy_scaled.shape[1])
y_max = gradient_img.shape[1] - self.track_loc_offset[0]
# This is used as the offset for plotting the agent dots
self.track_start_loc = (gradient_img.shape[1] + y_min, gradient_img.shape[0] + x_min)
for channel in range(0, 4):
gradient_img[x_min:x_max, y_min:y_max, channel] =\
(track_icongraphy_alpha * track_icongraphy_scaled[:, :, channel]) + \
(1 - track_icongraphy_alpha) * (gradient_img[x_min:x_max, y_min:y_max, channel])
return gradient_img
def _plot_agents_on_major_cv_image(self, major_cv_image, mp4_video_metrics_info):
""" Add the agents, obstacles on the track.
Arguments:
major_cv_image (Image): Edited image having gradient, text, track
mp4_video_metrics_info (List): List of ROS metric values of each agent
Returns:
Image: Edited image with gradient, text, track and agents with dots
"""
agents_loc = [(metric.x, metric.y) for metric in mp4_video_metrics_info]
objects_loc = []
if mp4_video_metrics_info[0].object_locations:
objects_loc = [(object_loc.x, object_loc.y) for object_loc in mp4_video_metrics_info[0].object_locations]
return self.top_view_graphics.plot_agents_as_circles(
major_cv_image, agents_loc, objects_loc, self.track_start_loc)
def edit_image(self, major_cv_image, metric_info):
mp4_video_metrics_info = metric_info[FrameQueueData.AGENT_METRIC_INFO.value]
# Find max total_evaluation_time from mp4_video_metrics_info
# to synchronize the total evaluation time throughout racers.
max_total_evaluation_time = max([item.total_evaluation_time for item in mp4_video_metrics_info])
for info in mp4_video_metrics_info:
info.total_evaluation_time = max_total_evaluation_time
major_cv_image = self._edit_major_cv_image(major_cv_image, mp4_video_metrics_info)
major_cv_image = self._plot_agents_on_major_cv_image(major_cv_image, mp4_video_metrics_info)
return cv2.cvtColor(major_cv_image, cv2.COLOR_BGRA2RGB)
def _edit_top_camera_image_util(self, top_camera_image, rank_name_gap_time, mp4_video_metrics_info):
""" Showing stats on the top view camera image
Arguments:
major_cv_image (Image): Main camera image for the racecar
rank_name_gap_time (list): Sorted list based on the ranking along with rank, name, gap time, racer_number
mp4_video_metrics_info (list): All the racers metric information
Returns:
major_cv_image (Image): Edited Main camera image
"""
# Applying gradient to whole major image and then writing text
top_camera_image = utils.apply_gradient(top_camera_image, self.gradient_top_camera_alpha_rgb_mul,
self.one_minus_gradient_top_camera_alpha)
top_camera_image = cv2.cvtColor(top_camera_image, cv2.COLOR_BGR2RGBA)
# LAP Title
loc_x, loc_y = XYPixelLoc.F1_TOP_CAMERA_LAP_TEXT_LOC.value
lap_txt = "LAP"
top_camera_image = utils.write_text_on_image(image=top_camera_image, text=lap_txt,
loc=(loc_x, loc_y), font=self.formula1_display_wide_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# LAP counter
loc_x, loc_y = XYPixelLoc.F1_TOP_CAMERA_LAP_COUNTER_LOC.value
# For Top view, lap counter should be based on leader's lap count.
leader_index = rank_name_gap_time[0][3]
current_lap = min(int(mp4_video_metrics_info[leader_index].lap_counter) + 1, int(self.total_laps))
lap_counter_text = "{} / {}".format(current_lap, int(self.total_laps))
top_camera_image = utils.write_text_on_image(image=top_camera_image, text=lap_counter_text,
loc=(loc_x, loc_y), font=self.formula1_display_bold_16px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Each racers ranking, name and gap time
rank_loc_x, rank_loc_y = XYPixelLoc.F1_TOP_CAMERA_LEADER_RANK_LOC.value
color_code_loc_x, color_code_loc_y = XYPixelLoc.F1_TOP_CAMERA_LEADER_COLOR_CODE_LOC.value
display_name_loc_x, display_name_loc_y = XYPixelLoc.F1_TOP_CAMERA_LEADER_DISPLAY_NAME_LOC.value
gap_loc_x, gap_loc_y = XYPixelLoc.F1_TOP_CAMERA_LEADER_GAP_LOC.value
for row in range(4):
for col in range(3):
if (row + 4 * col) >= len(rank_name_gap_time):
continue
rank, display_name, gap_time, racer_number = rank_name_gap_time[row + 4 * col]
# Rank
loc_x, loc_y = rank_loc_x + (col * 185), rank_loc_y + (row * 20)
racer_rank = "{}".format(rank)
top_camera_image = utils.write_text_on_image(image=top_camera_image, text=racer_rank,
loc=(loc_x, loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Draw racer color code icon
loc_x, loc_y = color_code_loc_x + (col * 185), color_code_loc_y + (row * 20)
top_camera_image = utils.plot_rectangular_image_on_main_image(top_camera_image,
self._racer_color_code_rect_img[racer_number],
(loc_x, loc_y))
# Adding display name to the table
loc_x, loc_y = display_name_loc_x + (col * 185), display_name_loc_y + (row * 20)
display_name_txt = display_name if len(display_name) <= 6 else "{}".format(display_name[:6])
top_camera_image = utils.write_text_on_image(image=top_camera_image, text=display_name_txt,
loc=(loc_x, loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
# Adding gap to the table
if row != 0 or col != 0:
loc_x, loc_y = gap_loc_x + (col * 180), gap_loc_y + (row * 20)
# The gradient box images are not equally placed for gaps
if col == 2:
loc_x, loc_y = gap_loc_x + (col * 182), gap_loc_y + (row * 20)
gap_time_text = "+{:.3f}".format(gap_time)
top_camera_image = utils.write_text_on_image(image=top_camera_image, text=gap_time_text,
loc=(loc_x, loc_y),
font=self.formula1_display_regular_12px,
font_color=RaceCarColorToRGB.White.value,
font_shadow_color=RaceCarColorToRGB.Black.value)
return top_camera_image
def edit_top_camera_image(self, top_camera_image, metric_info):
""" Editing the top camera image
Arguments:
top_camera_image (Image): Edited top camera image
"""
mp4_video_metrics_info = metric_info[FrameQueueData.AGENT_METRIC_INFO.value]
_, rank_name_gap_time = self._get_racers_metric_info(mp4_video_metrics_info)
top_camera_image = self._edit_top_camera_image_util(top_camera_image, rank_name_gap_time, mp4_video_metrics_info)
return cv2.cvtColor(top_camera_image, cv2.COLOR_BGRA2RGB)
|
<reponame>VictorGMBraga/clowdr
import type { ChakraColors, ComponentMap } from "./Types";
export function applyComponentColorTheme(
chakraColors: ChakraColors,
componentColors: Partial<ComponentMap>
): ChakraColors {
const result: ChakraColors = {};
for (const key in chakraColors) {
if (key in chakraColors) {
const color = chakraColors[key];
if (typeof color === "string") {
result[key] = color;
} else {
result[key] = { ...color };
}
}
}
for (const componentKey in componentColors) {
if (componentKey in componentColors && componentColors[componentKey]) {
const component = componentColors[componentKey];
const componentOutput: Record<string, string> = (result[componentKey] as Record<string, string>) ?? {};
result[componentKey] = componentOutput;
for (const partKey in component) {
if (partKey in component && component[partKey]) {
const part = component[partKey];
if (typeof part === "string") {
componentOutput[partKey] = determineChakraColor(chakraColors, part);
} else {
componentOutput[partKey + "-light"] = determineChakraColor(chakraColors, part.light);
componentOutput[partKey + "-dark"] = determineChakraColor(chakraColors, part.dark);
}
}
}
}
}
return result;
}
function determineChakraColor(chakraColors: ChakraColors, colorKey: string): string {
if (colorKey.includes(".")) {
const colorKeyParts = colorKey.split(".");
const chakraColorGroup = chakraColors[colorKeyParts[0]];
if (chakraColorGroup) {
if (typeof chakraColorGroup === "string") {
return chakraColorGroup;
} else if (colorKeyParts.length > 1) {
const chakraColor = chakraColorGroup[colorKeyParts[1]];
if (chakraColor) {
return chakraColor;
}
}
}
}
const chakraColorGroup = chakraColors[colorKey];
if (chakraColorGroup) {
if (typeof chakraColorGroup === "string") {
return chakraColorGroup;
}
}
return colorKey;
}
|
import * as core from '@aws-cdk/core';
import * as lambda from '@aws-cdk/aws-lambda';
import * as ssm from '@aws-cdk/aws-ssm';
import * as iam from '@aws-cdk/aws-iam';
export class LambdaStack extends core.Stack {
private functionName: string;
constructor(parent: core.Construct, id: string, distDir: string, props?: core.StackProps, prefix?: string) {
super(parent, id, props);
this.functionName = `${prefix}-blip-request-viewer`;
const override = new lambda.Function(this, this.functionName, {
functionName: this.functionName,
runtime: lambda.Runtime.NODEJS_14_X, // execution environment
code: lambda.Code.fromAsset(`${distDir}/lambda`), // code loaded from "lambda" directory
handler: `cloudfront-${prefix}-blip-request-viewer.handler`, // file is "hello", function is "handler"
role: new iam.Role(this, 'AllowLambdaServiceToAssumeRole', {
assumedBy: new iam.CompositePrincipal(
new iam.ServicePrincipal('lambda.amazonaws.com'),
new iam.ServicePrincipal('edgelambda.amazonaws.com'),
)
})
});
new ssm.StringParameter(this, 'edge-lambda-arn', {
parameterName: `/blip/${prefix}/lambda-edge-arn`,
description: 'CDK parameter stored for cross region Edge Lambda',
stringValue: override.currentVersion.functionArn
})
}
/**
* Get the name of the lambda
*/
public get FunctionName(): string {
return this.functionName;
}
}
|
12.30
Any Lib Dem members who are interested in arranging for the party to adopt a stance in favour of Basic Incomemight be interested in a meeting during the York conference next Saturday (12th March).This, it's to discuss the process of getting something into party policy.The meeting will be at the Waggon and Horses (about 5 min walk from the conference centre),1 - 2 on the Saturday lunchtime. They will be serving food. Room I've booked holds maybe 15-20 at a squeeze.Rough agenda:* Agree timetable for getting motion written, promoted, submitted, and passed* Find individuals (including people with experience in economics and in drafting policy) to take charge of getting a proposal ready for internal discussion and approval.* Identify groups who should be included in the drafting / discussion process* Find individuals to take charge of promoting the motion to help ensure it passesAlso, while I want this to work, I'm keen to avoid steering its direction too much, since I wasn't elected or anything.Also also:; in comments here is fine. |
# -*- coding: utf-8 -*-
"""
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
from math import sqrt
from PyQt5.QtCore import QVariant
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsFeatureSink,
QgsProcessingException,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFeatureSink,
QgsProcessingParameterVectorLayer,
QgsProcessingParameterMultipleLayers,
QgsProcessingParameterNumber,
QgsProcessingParameterBoolean,
QgsProcessingUtils,
QgsFields,
QgsField,
QgsWkbTypes,
QgsUnitTypes,
QgsFeature,
QgsGeometry,
QgsMultiPoint,
QgsPoint,
QgsPointXY)
import processing
def measure_along_line(line_vertices, vertex_idx_before, point_on_line):
"""
"""
distance = 0
# Handles all vertices PRIOR to vertex before point_on_line. Reduction of one is to handle lookahead process. At loop termination, the v2 value will have the vertex before the point.
vertex_idx = 0
while vertex_idx < vertex_idx_before - 1:
v1 = line_vertices[vertex_idx]
v2 = line_vertices[vertex_idx + 1]
vxd = v1.x() - v2.x()
vyd = v1.y() - v2.y()
distance += sqrt(vxd ** 2 + vyd ** 2)
vertex_idx += 1
continue
# Use case if measure is between vertices 0 & 1 (first segment)
if vertex_idx_before < 2:
v2 = line_vertices[0]
#Final distance addition from last vertex before point_on_line to point_on_line
vxd = v2.x() - point_on_line.x()
vyd = v2.y() - point_on_line.y()
distance += sqrt(vxd ** 2 + vyd ** 2)
return distance
def distance_fancy_str(distance, unit, modulo = 100):
first = int(distance / modulo)
second = round(distance % modulo)
return f"{first}+{second}"
def min_max_sort(feature):
distance_on_line = feature.attributes()[5]
return distance_on_line
class LinearReferenceEventsAlgorithm(QgsProcessingAlgorithm):
"""
This is an example algorithm that takes a vector layer and
creates a new identical one.
It is meant to be used as an example of how to create your own
algorithms and explain methods and variables used to do it. An
algorithm like this will be available in all elements, and there
is not need for additional work.
All Processing algorithms should extend the QgsProcessingAlgorithm
class.
"""
# Constants used to refer to parameters and outputs. They will be
# used when calling the algorithm from another algorithm, or when
# calling from the QGIS console.
INPUT = 'INPUT'
EVENTS = 'EVENTS'
EPSILON = 'EPSILON'
CONSOLIDATE = 'CONSOLIDATE'
OUTPUT = 'OUTPUT'
def tr(self, string):
"""
Returns a translatable string with the self.tr() function.
"""
return QCoreApplication.translate('Processing', string)
def createInstance(self):
return LinearReferenceEventsAlgorithm()
def name(self):
"""
Returns the algorithm name, used for identifying the algorithm. This
string should be fixed for the algorithm, and must not be localised.
The name should be unique within each provider. Names should contain
lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'linearreferenceevents'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return self.tr('Linear Reference Events')
def group(self):
"""
Returns the name of the group this algorithm belongs to. This string
should be localised.
"""
return self.tr('klaw-processing')
def groupId(self):
"""
Returns the unique ID of the group this algorithm belongs to. This
string should be fixed for the algorithm, and must not be localised.
The group id should be unique within each provider. Group id should
contain lowercase alphanumeric characters only and no spaces or other
formatting characters.
"""
return 'klaw-processing'
def shortHelpString(self):
"""
Returns a localised short helper string for the algorithm. This string
should provide a basic description about what the algorithm does and the
parameters and outputs associated with it..
"""
return self.tr("Example algorithm short description")
def flags(self):
return QgsProcessingAlgorithm.FlagNoThreading
def initAlgorithm(self, config=None):
"""
Here we define the inputs and output of the algorithm, along
with some other properties.
"""
# We add the input vector features source. It can have any kind of
# geometry.
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input Alignment'),
[QgsProcessing.TypeVectorLine]
)
)
self.addParameter(
QgsProcessingParameterNumber(
self.EPSILON,
self.tr("Epsilon Distance"),
QgsProcessingParameterNumber.Double,
-1
)
)
self.addParameter(
QgsProcessingParameterBoolean(
self.CONSOLIDATE,
self.tr("Consolidate Records"),
True
)
)
self.addParameter(
QgsProcessingParameterMultipleLayers(
self.EVENTS,
self.tr("Event Points")
)
)
# We add a feature sink in which to store our processed features (this
# usually takes the form of a newly created vector layer when the
# algorithm is run in QGIS).
self.addParameter(
QgsProcessingParameterFeatureSink(
self.OUTPUT,
self.tr('Output Record Table')
)
)
def processAlgorithm(self, parameters, context, feedback):
"""
Here is where the processing itself takes place.
"""
# Retrieve the feature source and sink. The 'dest_id' variable is used
# to uniquely identify the feature sink, and must be included in the
# dictionary returned by the processAlgorithm function.
alignment = self.parameterAsSource(
parameters,
self.INPUT,
context
)
if alignment is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
alignment_count = alignment.featureCount()
alignment_wkb = alignment.wkbType()
alignment_crs = alignment.sourceCrs()
alignment_units = QgsUnitTypes.toString(alignment_crs.mapUnits())
feedback.pushInfo('CRS is {0}, Units are {1}'.format(alignment_crs.authid(), alignment_units))
if alignment_count != 1:
raise QgsProcessingException("Alignment has more than one feature. Only one singlepart feature is allowed.")
if QgsWkbTypes.isMultiType(alignment_wkb):
raise QgsProcessingException("Alignment has multipart geometry. Convert LAYER to single parts.")
if alignment_crs.isGeographic():
raise QgsProcessingException("Alignment has geographic coordinate system. Convert to planar system with units in feet.")
if alignment_units != "feet":
raise QgsProcessingException("Alignment has projection in other units than feet. Convert to planar system with units in feet.")
alignment_feature = alignment.getFeatures().__next__()
alignment_geometry = alignment_feature.geometry()
alignment_shape = alignment_geometry.get()
alignment_vertices = [i for i in alignment_shape.vertices()]
epsilon = self.parameterAsDouble(
parameters,
self.EPSILON,
context
)
consolidate = self.parameterAsBool(
parameters,
self.CONSOLIDATE,
context
)
event_layers = self.parameterAsLayerList(
parameters,
self.EVENTS,
context
)
if event_layers is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.EVENTS))
total_event_features = 0
mod_event_layers = []
for event_layer in event_layers:
event_name = event_layer.name()
event_count = event_layer.featureCount()
event_wkb = event_layer.wkbType()
event_geom = QgsWkbTypes.geometryType(event_wkb)
event_multi = QgsWkbTypes.isMultiType(event_wkb)
event_crs = event_layer.sourceCrs()
event_units = QgsUnitTypes.toString(event_crs.mapUnits())
if event_count < 1:
feedback.pushInfo("Event Layer {0} is empty. Skipping...".format(event_name))
continue
if event_crs != alignment_crs:
raise QgsProcessingException("Alignment CRS mismatch with Event Layer {0} CRS!".format(event_name))
if event_multi:
event_layer = processing.run("native:multiparttosingleparts", {
"INPUT": event_layer,
"OUTPUT": "memory:"
}, context = context, feedback = feedback)["OUTPUT"]
if event_geom > 1:
if False:
event_layer = processing.run("qgis:densifygeometriesgivenaninterval", {
"INPUT": event_layer,
"INTERVAL": 10,
"OUTPUT": "memory:"
}, context = context, feedback = feedback)["OUTPUT"]
event_layer = processing.run("native:extractvertices", {
"INPUT": event_layer,
"OUTPUT": "memory:"
}, context = context, feedback = feedback)["OUTPUT"]
event_layer.setName(event_name)
total_event_features += event_count
mod_event_layers.append(event_layer)
continue
OUTPUTFIELDS = QgsFields()
OUTPUTFIELDS.append(QgsField("fid", QVariant.LongLong, "int"))
OUTPUTFIELDS.append(QgsField("event_id", QVariant.String, "string", 255))
OUTPUTFIELDS.append(QgsField("event_layer", QVariant.String, "string", 255))
OUTPUTFIELDS.append(QgsField("event_comment", QVariant.String, "string"))
OUTPUTFIELDS.append(QgsField("distance_away", QVariant.Double, "double"))
OUTPUTFIELDS.append(QgsField("distance_line", QVariant.Double, "double"))
OUTPUTFIELDS.append(QgsField("distance_line_str", QVariant.String, "string", 255))
OUTPUTFIELDS.append(QgsField("side_of_line", QVariant.String, "string", 255))
OUTPUTFIELDS.append(QgsField("line_x", QVariant.Double, "double"))
OUTPUTFIELDS.append(QgsField("line_y", QVariant.Double, "double"))
OUTPUTFIELDS.append(QgsField("event_type", QVariant.String, "string", 255))
(sink, dest_id) = self.parameterAsSink(
parameters,
self.OUTPUT,
context,
OUTPUTFIELDS,
QgsWkbTypes.MultiPoint,
alignment_crs
)
if sink is None:
raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
feedback.setProgress(0)
output_fid = 1
for event_layer in mod_event_layers:
# Stop the algorithm if cancel button has been clicked
if feedback.isCanceled():
break
event_name = event_layer.name()
event_fields = event_layer.fields()
event_idx = event_fields.indexOf("GUID")
comment_idx = event_fields.indexOf("comment")
events = event_layer.getFeatures()
for event in events:
egeom = event.geometry()
eshape = egeom.constGet()
epoint = QgsPointXY(eshape.x(), eshape.y())
epoint = QgsPoint(epoint)
if event_idx > -1:
eid = event.attributes()[event_idx]
else:
eid = "-"
if comment_idx > -1:
comment = event.attributes()[comment_idx]
else:
comment = ""
results = alignment_shape.closestSegment(eshape)
distance_away = sqrt(results[0])
point_on_line = results[1]
vertex_idx_after = results[2].vertex
side_of_line = results[3]
if distance_away > epsilon and epsilon != -1:
continue
if side_of_line == -1:
side_of_line = "Left"
elif side_of_line == 1:
side_of_line = "Right"
else:
side_of_line = "Unknown / On Line"
distance_on_line = measure_along_line(alignment_vertices, vertex_idx_after - 1, point_on_line)
point_on_line = QgsPointXY(point_on_line.x(), point_on_line.y())
point_on_line = QgsPoint(point_on_line)
record = QgsFeature()
record.setFields(OUTPUTFIELDS)
record.setAttribute(0, output_fid)
record.setAttribute(1, str(eid))
record.setAttribute(2, event_name)
record.setAttribute(3, comment)
record.setAttribute(4, distance_away)
record.setAttribute(5, distance_on_line)
record.setAttribute(6, distance_fancy_str(distance_on_line, alignment_units))
record.setAttribute(7, side_of_line)
record.setAttribute(8, point_on_line.x())
record.setAttribute(9, point_on_line.y())
record.setAttribute(10, "Unitary")
if output_fid % 1000 == 0 and False:
feedback.pushDebugInfo(str(repr(epoint) + " " + repr(point_on_line)))
record_shape = QgsMultiPoint()
record_shape.addGeometry(epoint)
record_shape.addGeometry(point_on_line)
record_geometry = QgsGeometry(record_shape)
record.setGeometry(record_geometry)
if output_fid % 1000 == 0 and True:
feedback.pushDebugInfo("Record Successfully Generated!")
sink.addFeature(record)
output_fid += 1
feedback.setProgress(int(output_fid / total_event_features))
continue
sink.flushBuffer()
continue
sink = QgsProcessingUtils.mapLayerFromString(dest_id, context)
if consolidate:
output_unique = list(sink.uniqueValues(1))
for unique in output_unique:
if unique == "-":
continue
sink.selectByExpression(""""event_id" = '{0}'""".format(unique))
unique_count = sink.selectedFeatureCount()
if unique_count == 1:
continue
sink.startEditing()
feedback.pushDebugInfo("Clearing middle points for {0}".format(unique))
features = [i for i in sink.getSelectedFeatures()]
features.sort(key = min_max_sort)
min_fid = features[0].attributes()[0]
max_fid = features[-1].attributes()[0]
dispose_fids = [str(i.attributes()[0]) for i in features[1:-1]]
dispose_fids_sql = '(' + ",".join(dispose_fids) + ')'
sink.removeSelection()
sink.selectByExpression(""""fid" IN {0}""".format(dispose_fids_sql))
count = sink.deleteSelectedFeatures()
sink.removeSelection()
sink.changeAttributeValue(min_fid, 10, "Start")
sink.changeAttributeValue(max_fid, 10, "End")
feedback.pushDebugInfo("Features deleted: {0}".format(str(count)))
sink.commitChanges()
continue
# Return the results of the algorithm. In this case our only result is
# the feature sink which contains the processed features, but some
# algorithms may return multiple feature sinks, calculated numeric
# statistics, etc. These should all be included in the returned
# dictionary, with keys matching the feature corresponding parameter
# or output names.
return {self.OUTPUT: dest_id}
|
<filename>src/tools/codeeditor/projectsearch.cpp
#include "projectsearch.hpp"
#include <eepp/system/filesystem.hpp>
#include <eepp/system/luapattern.hpp>
static int countNewLines( const std::string& text, const size_t& start, const size_t& end ) {
const char* startPtr = text.c_str() + start;
const char* endPtr = text.c_str() + end;
size_t count = 0;
if ( startPtr != endPtr ) {
count = *startPtr == '\n' ? 1 : 0;
while ( ++startPtr && startPtr != endPtr ) {
if ( '\n' == *startPtr )
count++;
};
}
return count;
}
static String textLine( const std::string& fileText, const size_t& fromPos, size_t& relCol ) {
size_t start = 0;
size_t end = 0;
const char* stringStartPtr = fileText.c_str();
const char* startPtr = fileText.c_str() + fromPos;
const char* ptr = startPtr;
const char* nlStartPtr = stringStartPtr;
if ( stringStartPtr != ptr ) {
while ( stringStartPtr != ptr && *--ptr != '\n' ) {
}
nlStartPtr = ptr + 1;
start = ptr - stringStartPtr + 1;
}
ptr = startPtr;
while ( ++ptr && *ptr != '\0' && *ptr != '\n' ) {
}
end = ptr - stringStartPtr;
relCol = String( fileText.substr( start, startPtr - nlStartPtr ) ).size();
return fileText.substr( start, end - start );
}
static std::vector<ProjectSearch::ResultData::Result>
searchInFileHorspool( const std::string& file, const std::string& text, const bool& caseSensitive,
const bool& wholeWord, const String::BMH::OccTable& occ ) {
std::vector<ProjectSearch::ResultData::Result> res;
std::string fileText;
Int64 lSearchRes = 0;
Int64 searchRes = 0;
size_t totNl = 0;
FileSystem::fileGet( file, fileText );
if ( !caseSensitive ) {
std::string fileTextOriginal( fileText );
String::toLowerInPlace( fileText );
do {
searchRes = String::BMH::find( fileText, text, searchRes, occ );
if ( searchRes != -1 ) {
if ( wholeWord && !String::isWholeWord( fileText, text, searchRes ) ) {
lSearchRes = searchRes;
searchRes += text.size();
continue;
}
size_t relCol;
totNl += countNewLines( fileText, lSearchRes, searchRes );
String str( textLine( fileTextOriginal, searchRes, relCol ) );
res.push_back( { str,
{ { (Int64)totNl, (Int64)relCol },
{ (Int64)totNl, (Int64)( relCol + text.size() ) } } } );
lSearchRes = searchRes;
searchRes += text.size();
}
} while ( searchRes != -1 );
} else {
do {
searchRes = String::BMH::find( fileText, text, searchRes, occ );
if ( searchRes != -1 ) {
if ( wholeWord && !String::isWholeWord( fileText, text, searchRes ) ) {
lSearchRes = searchRes;
searchRes += text.size();
continue;
}
size_t relCol;
totNl += countNewLines( fileText, lSearchRes, searchRes );
String str( textLine( fileText, searchRes, relCol ) );
res.push_back( { str,
{ { (Int64)totNl, (Int64)relCol },
{ (Int64)totNl, (Int64)( relCol + text.size() ) } } } );
lSearchRes = searchRes;
searchRes += text.size();
}
} while ( searchRes != -1 );
}
return res;
}
static std::vector<ProjectSearch::ResultData::Result>
searchInFileLuaPattern( const std::string& file, const std::string& text, const bool& caseSensitive,
const bool& wholeWord ) {
std::string fileText;
FileSystem::fileGet( file, fileText );
LuaPattern pattern( text );
std::vector<ProjectSearch::ResultData::Result> res;
size_t totNl = 0;
bool matched = false;
Int64 searchRes = 0;
if ( !caseSensitive ) {
std::string fileTextOriginal( fileText );
String::toLowerInPlace( fileText );
do {
int start, end = 0;
if ( ( matched = pattern.find( fileText, start, end, searchRes ) ) ) {
if ( wholeWord && !String::isWholeWord(
fileText, fileText.substr( start, end - start ), start ) ) {
searchRes = end;
continue;
}
size_t relCol;
totNl += countNewLines( fileText, searchRes, end );
String str( textLine( fileTextOriginal, start, relCol ) );
int len = end - start;
res.push_back( { str,
{ { (Int64)totNl, (Int64)relCol },
{ (Int64)totNl, (Int64)( relCol + len ) } } } );
searchRes = end;
}
} while ( matched );
} else {
do {
int start, end = 0;
if ( ( matched = pattern.find( fileText, start, end, searchRes ) ) ) {
if ( wholeWord && !String::isWholeWord(
fileText, fileText.substr( start, end - start ), start ) ) {
searchRes = end;
continue;
}
size_t relCol;
totNl += countNewLines( fileText, searchRes, end );
String str( textLine( fileText, start, relCol ) );
int len = end - start;
res.push_back( { str,
{ { (Int64)totNl, (Int64)relCol },
{ (Int64)totNl, (Int64)( relCol + len ) } } } );
searchRes = end;
}
} while ( matched );
}
return res;
}
void ProjectSearch::find( const std::vector<std::string> files, const std::string& string,
ResultCb result, bool caseSensitive, bool wholeWord,
const TextDocument::FindReplaceType& type ) {
Result res;
const auto occ =
type == TextDocument::FindReplaceType::Normal
? String::BMH::createOccTable( (const unsigned char*)string.c_str(), string.size() )
: std::vector<size_t>();
for ( auto& file : files ) {
auto fileRes = type == TextDocument::FindReplaceType::Normal
? searchInFileHorspool( file, string, caseSensitive, wholeWord, occ )
: searchInFileLuaPattern( file, string, caseSensitive, wholeWord );
if ( !fileRes.empty() )
res.push_back( { file, fileRes } );
}
result( res );
}
struct FindData {
Mutex resMutex;
Mutex countMutex;
int resCount{ 0 };
ProjectSearch::Result res;
};
void ProjectSearch::find( const std::vector<std::string> files, std::string string,
std::shared_ptr<ThreadPool> pool, ResultCb result, bool caseSensitive,
bool wholeWord, const TextDocument::FindReplaceType& type ) {
if ( files.empty() )
result( {} );
FindData* findData = eeNew( FindData, () );
findData->resCount = files.size();
if ( !caseSensitive )
String::toLowerInPlace( string );
const auto occ =
type == TextDocument::FindReplaceType::Normal
? String::BMH::createOccTable( (const unsigned char*)string.c_str(), string.size() )
: std::vector<size_t>();
for ( auto& file : files ) {
pool->run(
[findData, file, string, caseSensitive, wholeWord, occ, type] {
auto fileRes =
type == TextDocument::FindReplaceType::Normal
? searchInFileHorspool( file, string, caseSensitive, wholeWord, occ )
: searchInFileLuaPattern( file, string, caseSensitive, wholeWord );
if ( !fileRes.empty() ) {
Lock l( findData->resMutex );
findData->res.push_back( { file, fileRes } );
}
},
[result, findData] {
int count;
{
Lock l( findData->countMutex );
findData->resCount--;
count = findData->resCount;
}
if ( count == 0 ) {
result( findData->res );
eeDelete( findData );
}
} );
}
}
|
CHICAGO – Once upon a time, “reality” television was exactly that. While the genre now seems to feature as much scripted drama as actual reality, UFC President Dana White said one chilling incident proves that his new series doesn’t follow those lines.
“The guy was going to be a star on the show, was going to be one of the guys, and I’ve known this guy for 25 years,” White explained. “He’s an absolute character. He came out of Cus D’Amato’s camp. He trained with those guys and everything else. He had his own gym. He put on his own fights.
“The night before we’re starting to shoot, he stabbed a guy. He’s off the show. See you later.”
White and “The Ultimate Fighter” producer Craig Piligian are behind the boxing-focused series “The Fighters,” which documents a series of up-and-coming fighters in South Boston. The two executives and longtime boxing instructor Peter Welch shared the story at a media screening of the debut episode.
According to an official release, the eight-part series “documents the daily struggles, personal relationships and epic training sessions as the fighters prepare for the fight of their lives – where only one will overcome the odds and emerge victorious. Every week, these three rounds will help decide not only their fates, but also the fate of boxing in Southie.”
The show debuts tonight at 9 p.m. ET on Discovery Channel.
Meanwhile, White returns to his primary role as UFC boss at Saturday’s UFC on FOX 10 event, which takes place at Chicago’s United Center.
To see the full, 26-minute Q&A with White, Piligian and Welch, see Video: Dana White, Craig Piligian, Peter Welch preview ‘The Fighters’ |
def save_config(self, filename=None, heading='DEFAULT'):
self._conf.save(filename = filename,
heading = heading,
tags = self.active_tags,
logbooks = self.active_logbooks,
username = self._auth[0],
url = self._url) |
// Or adds additional error types to the handled errors of the policy
func (it *builder) Or(errorObj interface{}) ErrorBuilder {
pred := it.handlePredicate
return &builder{
handlePredicate: func(err error) bool {
if reflect.TypeOf(err) == reflect.TypeOf(errorObj) {
return true
}
return pred(err)
},
}
} |
/**
* Created by clay d
*/
public class ItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements ItemTouchHelperAdapter {
private List<Destination> mDestinationList;
OnItemClickListener mItemClickListener;
private static final int TYPE_ITEM = 0;
private final LayoutInflater mInflater;
private final OnStartDragListener mDragStartListener;
private Context mContext;
private int selected;
public ItemAdapter(Context context, List<Destination> list, OnStartDragListener dragListner) {
this.mDestinationList = list;
this.mInflater = LayoutInflater.from(context);
mDragStartListener = dragListner;
mContext = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
if (viewType == TYPE_ITEM) {
//inflate your layout and pass it to view holder
View v = mInflater.inflate(R.layout.person_item, viewGroup, false);
return new VHItem(v);
}
throw new RuntimeException("there is no type that matches the type " + viewType + " + make sure your using types correctly");
}
@Override
public int getItemViewType(int position) {
return TYPE_ITEM;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int i) {
if (viewHolder instanceof VHItem) {
final VHItem holder= (VHItem)viewHolder;
holder.container.setBackgroundColor(Color.LTGRAY);
if (i == selected - 1) {
holder.container.setBackgroundColor(Color.argb(255,40,40,40));
}
((VHItem) viewHolder).setWaypoint(mDestinationList.get(i));
((VHItem) viewHolder).waypoint.setText(mDestinationList.get(i).getID());
((VHItem) viewHolder).type.setText(mDestinationList.get(i).getType());
((VHItem) viewHolder).distance.setText(String.valueOf(mDestinationList.get(i).getDistance()));
((VHItem) viewHolder).time.setText(mDestinationList.get(i).getEte());
((VHItem) viewHolder).course.setText(mDestinationList.get(i).getCourse());
((VHItem) viewHolder).heading.setText("");
((VHItem) viewHolder).wind.setText(mDestinationList.get(i).getWinds());
((VHItem) viewHolder).fuel.setText(mDestinationList.get(i).getFuel());
((VHItem) viewHolder).image_menu.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mDragStartListener.onStartDrag(holder);
}
return false;
}
});
((VHItem) viewHolder).image_select.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
//enter code here to select as next destination
((PlanActivity) mContext).newDestination(mDestinationList.get(i));
selected = holder.getAdapterPosition() + 1;
updateList(mDestinationList);
}
return false;
}
});
((VHItem) viewHolder).holo.setOnTouchListener(new OnSwipeTouchListener(mContext) {
//add functionality to select
/*
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mDragStartListener.onStartDrag(holder);
}
return false;
}
*/
//add functionality to delete
public void onSwipeLeft() {
mDestinationList.remove(i);
updateList(mDestinationList);
Toast.makeText(mContext, "Waypoint Deleted", Toast.LENGTH_SHORT).show();
((PlanActivity) mContext).delete();
}
});
}
}
@Override
public int getItemCount() {
if (mDestinationList == null) return 0;
return mDestinationList.size();
}
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public class VHItem extends RecyclerView.ViewHolder implements View.OnClickListener ,ItemTouchHelperViewHolder{
private ImageView image_menu; //set this to whatever u want to use to drag
private ImageView image_select;
public TextView waypoint;
public TextView type;
public TextView distance;
public TextView time;
public TextView course;
public TextView heading;
public TextView wind;
public TextView fuel;
public View container;
private ImageView holo;
private Destination data;
public VHItem(View itemView) {
super(itemView);
data = null;
container = (View) itemView.findViewById(R.id.container);
image_menu = (ImageView) itemView.findViewById(R.id.image_menu);
image_select = (ImageView) itemView.findViewById(R.id.image_Select);
holo = (ImageView) itemView.findViewById(R.id.holo);
waypoint = (TextView) itemView.findViewById(R.id.waypoint);
type = (TextView) itemView.findViewById(R.id.type);
distance = (TextView) itemView.findViewById(R.id.distance);
time = (TextView) itemView.findViewById(R.id.time);
course = (TextView) itemView.findViewById(R.id.course);
heading = (TextView) itemView.findViewById(R.id.heading);
wind = (TextView) itemView.findViewById(R.id.wind);
fuel = (TextView) itemView.findViewById(R.id.fuel);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
@Override
public void onItemSelected() {
itemView.setBackgroundColor(Color.LTGRAY);
}
@Override
public void onItemClear() {
itemView.setBackgroundColor(0);
}
public Destination getWaypoint() {
return data;
}
public void setWaypoint(Destination wayPo) {
data = wayPo;
}
}
@Override
public void onItemDismiss(int position) {
mDestinationList.remove(position);
notifyItemRemoved(position);
}
@Override
public boolean onItemMove(int fromPosition, int toPosition) {
//Log.v("", "Log position" + fromPosition + " " + toPosition);
if (fromPosition < mDestinationList.size() && toPosition < mDestinationList.size()) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mDestinationList, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mDestinationList, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
}
return true;
}
public void updateList(List<Destination> list) {
mDestinationList = list;
notifyDataSetChanged();
}
public List<Destination> getDestinationList() {
return mDestinationList;
}
} |
// teamsForOrg queries the GitHub API for team membership within a specific organization.
//
// The HTTP passed client is expected to be constructed by the golang.org/x/oauth2 package,
// which inserts a bearer token as part of the request.
func (c *githubConnector) teamsForOrg(ctx context.Context, client *http.Client, orgName string) ([]string, error) {
apiURL, groups := c.apiURL+"/user/teams", []string{}
for {
var (
teams []team
err error
)
if apiURL, err = get(ctx, client, apiURL, &teams); err != nil {
return nil, fmt.Errorf("github: get teams: %v", err)
}
for _, t := range teams {
if t.Org.Login == orgName {
groups = append(groups, c.teamGroupClaims(t)...)
}
}
if apiURL == "" {
break
}
}
return groups, nil
} |
Constable Shane Greville on the job in 2013. He has pleaded guilty to a charge of careless driving causing injury.
A police officer who smashed into the back of another car while driving at 91kmh in a 50kmh zone said he had been showing off.
Hawke's Bay constable Shane Greville was off duty and had been drinking with friends on the evening of September 27, 2013, before driving his recently purchased 1967 Chevrolet Camaro along Napier Road.
He accelerated out of a roundabout and overtook another vehicle.
As he did so a woman drove out of her driveway and began travelling in the same direction as Greville.
Greville slammed on his brakes and his car skidded 50 metres before slamming into the rear of the woman's car and shunting it onto the footpath.
The 74-year-old woman, who was not wearing a seatbelt, suffered heavy bruising to her face and ribs and spent a night in hospital.
Police investigators estimated Greville's car was travelling at 91kmh when it hit the woman's car.
When spoken to by police Greville said he was extremely remorseful and had been "showing off".
Residents told police they had heard a extremely loud vehicle travelling at excessive speed.
The woman's car was written off.
Greville pleaded guilty to a charge of careless driving causing injury in the Hastings District Court on Tuesday.
Police prosecutor Neil Coker advised Judge Gerald Lynch the charge had been amended from one of dangerous driving causing injury.
Greville's lawyer Jonathan Krebs said he had an exemplary record as a police officer.
He said Greville had made arrangements to provide the victim with a car until she had replaced hers.
It is understood Greville had bought the rare car for $89,000 a few weeks prior to the crash.
Greville has been on restricted police duties since the crash.
He was convicted and will be sentenced in September.
An internal code of conduct inquiry will occur after sentencing to determine whether he can remain a police officer and if any further action will be taken. |
/**
* Created by LiYouGui on 2017/6/6.
*/
public class KnowledgeInfo implements Serializable {
private String title;
private String keywords;
private String content;
private String kntype;
public String getKntype() {
return kntype;
}
public void setKntype(String kntype) {
this.kntype = kntype;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
} |
a, b = input().split()
a, b = int(a), int(b)
m = a + b
serv = {}
for i in range(a):
name, ip = input().split()
ip = ip + ";"
serv[ip] = name
for i in range(b):
mn, ip = input().split()
print(mn, ip, "#"+serv[ip]) |
/**
* Author :zhx
* Create at 2016/12/12
* Description:
*/
public class MovieDetailModelImpl implements IMovieDetailModel{
private static final MovieDetailModelImpl movieModel = new MovieDetailModelImpl();
public static MovieDetailModelImpl getInstance() {
return movieModel;
}
@Override
public Observable<JsonObject> getMovieStory(String id) {
return OneHttp.getServiceInstance().getMovieStory(id);
}
@Override
public Observable<MovieDetailEntity> getMovieDetail(String id) {
return OneHttp.getServiceInstance().getMovieDetail(id);
}
@Override
public Observable<JsonObject> getMovieComment(String type, String id) {
return OneHttp.getServiceInstance().getComment(type,id);
}
} |
// elementTypeFor returns the type into which data with this marker should be
// decoded, falling back to interface{} in the general case.
func elementTypeFor(m Marker) reflect.Type {
switch m {
case TrueMarker, FalseMarker:
return boolType
case UInt8Marker:
return uint8Type
case Int8Marker:
return int8Type
case Int16Marker:
return int16Type
case Int32Marker:
return int32Type
case Int64Marker:
return int64Type
case Float32Marker:
return float32Type
case Float64Marker:
return float64Type
case StringMarker:
return stringType
case CharMarker:
return charType
case HighPrecNumMarker:
return highPrecNumType
}
return ifaceType
} |
<filename>app/src/main/java/com/tanguy/rssfeed/service/RecyclerViewClickListener.java
package com.tanguy.rssfeed.service;
import android.view.View;
public interface RecyclerViewClickListener {
void recyclerViewListClicked(View v, int position);
} |
PADUCAH, KY—Throughout his life, 22-year-old Matthew Leske has been a devout Christian, attending services three times a week at Holy Christ Almighty Lutheran Church in his hometown of Paducah, regularly participating in Bible-study devotionals with his mother and four sisters, and faithfully adhering to the dictums of his strict fundamentalist Christian upbringing.
Throughout his post-pubescent life, Leske has also, like all male humans, been gripped by an intense, all-consuming desire to ejaculate sperm, but has been unable to do so out of fear of incurring the wrath of God and suffering an eternity of agonizing punishment in the afterlife.
Advertisement
A part-time prep-cook and odd-job yardwork handyman when not volunteering as a Bible witness to local shut-ins and nursing-home residents, the young Leske has never had much time for socializing with members of the opposite sex. Nevertheless, last week, Leske announced his intention to marry fellow Christian Luann Ruth Perkins, also a member of Holy Christ Almighty, whom he met on a church-sponsored Luther League hayride two months ago.
Leske cited his irresistible desire to achieve sexual climax and ejaculate sperm without having to go to hell as the number one factor in his decision to propose marriage.
"I really want to discharge semen," he said. "I mean I really, really, really want to really bad."
Advertisement
Living his 22 years inviolate under strict fundamentalist doctrine, Leske has never ejaculated, for to do so outside the holy bonds of sacramental matrimony would mean non-negotiable, eternal punishment upon death.
"I don't want to go to hell," said Leske, explaining his decision not to engage in premarital ejaculation. "I am absolutely terrified of the burning and scorching of my impure, unclean flesh in the Lake of Fire; the prodding and stabbing by pitchforks wielded by demons; and, in particular, the unending, eternal torment in pits of boiling pitch as Satan the Deceiver laughs in sadistic glee."
Burning with a desire to ejaculate so overwhelming that it has threatened to dwarf even his love for Christ, Leske has, ever since puberty, researched the subject at length, discovering "five score and seventeen" different methods by which males can achieve ejaculation. Unfortunately, Leske said, not one of them is permissible under fundamentalist-Christian law.
Advertisement
"Homosexuality, masturbation, oral-genital contact, frottage, shoe fetishes, barnyard animals, leaning up against a washing machine on spin cycle—I could go on and on," Leske said. "I would have gladly tried any one of these, because, like I said, I really, really want to ejaculate. Regrettably, though, they are all punishable by eternal torment in the demon pits, so it was pretty much either get married or give up on ejaculating completely."
While Leske is greatly looking forward to marriage and the sweet release of sperm it will bring, he noted that even in holy wedlock, fundamentalist Christian doctrine limits permissible ejaculation to just one circumstance: sexual congress for the purpose of procreation.
"I'm going to want to start a family pretty much immediately," he said. "If I can get a raise and a second job, I figure I might be able to eventually support a family of as many as six or seven offspring. That means I should hopefully get to ejaculate seven times before I die. I know, you're thinking, 'That's not much.' But believe me, it will sure beat the heck out of what I'm doing now, which is not ejaculating at all."
Advertisement
Leske does admit to harboring some doubts about his upcoming nuptials. "What if Luann, never having seen a naked man before, is so frightened that she refuses to allow me to ejaculate?" he said. "Divorce would be out of the question, and I'd be trapped forever in a non-ejaculatory marriage. It will probably work out okay, though: Once she becomes my wife, I should be able to command her to do whatever I say, and, even if it's against her wishes, it will be her Christian duty to obey me."
No date has been set for the wedding, but Leske said he would like it to take place "as soon as humanly possible."
"I have opened my heart and mind to Jesus Christ, the Son of God the Father, my Lord and Savior in Heaven, who died on the cross for my sins, that I might be born again in His blood. And I yearn for the righteous power of the Holy Spirit to fill me with holy inspiration. But I also yearn—desperately yearn, yearn with indescribable longing, I mean really, really yearn—to ejaculate. If it were up to me I would prefer to ejaculate right now. This minute. No lie." |
/// Creates a *reference hash* for an event.
///
/// Returns the hash as a Base64-encoded string, using the standard character set, without padding.
///
/// The reference hash of an event covers the essential fields of an event, including content
/// hashes. It is used to generate event identifiers and is described in the Matrix server-server
/// specification.
///
/// # Parameters
///
/// object: A JSON object to generate a reference hash for.
///
/// # Errors
///
/// Returns an error if the event is too large or redaction fails.
pub fn reference_hash(
value: &CanonicalJsonObject,
version: &RoomVersionId,
) -> Result<String, Error> {
let redacted_value = redact(value, version)?;
let json =
canonical_json_with_fields_to_remove(&redacted_value, REFERENCE_HASH_FIELDS_TO_REMOVE)?;
if json.len() > MAX_PDU_BYTES {
return Err(Error::PduSize);
}
let hash = Sha256::digest(json.as_bytes());
Ok(encode_config(
&hash,
match version {
RoomVersionId::Version1 | RoomVersionId::Version2 | RoomVersionId::Version3 => {
STANDARD_NO_PAD
}
// Room versions higher than version 3 are url safe base64 encoded
_ => URL_SAFE_NO_PAD,
},
))
} |
/** The context exposed for executing {@link com.facebook.buck.step.Step}s */
@BuckStyleValueWithBuilder
@SuppressWarnings(
"immutables:from") // Suppress warning for event bus being different type in superclass
public abstract class StepExecutionContext extends IsolatedExecutionContext {
/**
* Creates {@link StepExecutionContext} from {@link ExecutionContext}, {@code ruleCellRoot} and
* {@code actionId}
*/
public static StepExecutionContext from(
ExecutionContext executionContext,
AbsPath ruleCellRoot,
ActionId actionId,
Optional<BuildTarget> target) {
return StepExecutionContext.builder()
.setConsole(executionContext.getConsole())
.setBuckEventBus(executionContext.getBuckEventBus())
.setPlatform(executionContext.getPlatform())
.setEnvironment(executionContext.getEnvironment())
.setProcessExecutor(executionContext.getProcessExecutor())
.setAndroidDevicesHelper(executionContext.getAndroidDevicesHelper())
.setPersistentWorkerPools(executionContext.getPersistentWorkerPools())
.setBuildCellRootPath(executionContext.getBuildCellRootPath())
.setProjectFilesystemFactory(executionContext.getProjectFilesystemFactory())
.setClassLoaderCache(executionContext.getClassLoaderCache())
.setShouldReportAbsolutePaths(executionContext.shouldReportAbsolutePaths())
.setRuleKeyDiagnosticsMode(executionContext.getRuleKeyDiagnosticsMode())
.setTruncateFailingCommandEnabled(executionContext.isTruncateFailingCommandEnabled())
.setWorkerProcessPools(executionContext.getWorkerProcessPools())
.setRuleCellRoot(ruleCellRoot)
.setActionId(actionId)
.setClock(executionContext.getClock())
.setWorkerToolPools(executionContext.getWorkerToolPools())
.setBuildTarget(target)
.build();
}
public abstract BuckEventBus getBuckEventBus();
public abstract Optional<AndroidDevicesHelper> getAndroidDevicesHelper();
/**
* Worker process pools that are persisted across buck invocations inside buck daemon. If buck is
* running without daemon, there will be no persisted pools.
*/
public abstract Optional<ConcurrentMap<String, WorkerProcessPool<DefaultWorkerProcess>>>
getPersistentWorkerPools();
/**
* The absolute path to the cell where this build was invoked.
*
* <p>For example, consider two cells: cell1 and cell2. If a build like "buck build cell2//:bar"
* was invoked from cell1, this method would return cell1's path.
*
* <p>See {@link com.facebook.buck.core.build.context.BuildContext#getBuildCellRootPath}.
*/
public abstract Path getBuildCellRootPath();
public abstract ProjectFilesystemFactory getProjectFilesystemFactory();
/**
* The build target associated with the steps that we will execute with this context, if one
* exists.
*/
public abstract Optional<BuildTarget> getBuildTarget();
@Value.Default
public boolean shouldReportAbsolutePaths() {
return false;
}
@Value.Default
public RuleKeyDiagnosticsMode getRuleKeyDiagnosticsMode() {
return RuleKeyDiagnosticsMode.NEVER;
}
@Value.Default
public boolean isTruncateFailingCommandEnabled() {
return true;
}
/**
* Worker process pools that you can populate as needed. These will be destroyed as soon as buck
* invocation finishes, thus, these pools are not persisted across buck invocations.
*/
@Value.Default
public ConcurrentMap<String, WorkerProcessPool<DefaultWorkerProcess>> getWorkerProcessPools() {
return new ConcurrentHashMap<>();
}
@Override
@Value.Default
public IsolatedEventBus getIsolatedEventBus() {
return getBuckEventBus().isolated();
}
@Override
protected void registerCloseables(Closer closer) {
super.registerCloseables(closer);
getAndroidDevicesHelper().ifPresent(closer::register);
// The closer closes in reverse order, so do the clear first.
closer.register(getWorkerProcessPools()::clear);
getWorkerProcessPools().values().forEach(closer::register);
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends ImmutableStepExecutionContext.Builder {}
} |
/* Return route type string for VTY output. */
const char *
route_type_str (u_char type)
{
switch (type)
{
case ZEBRA_ROUTE_SYSTEM:
return "system";
case ZEBRA_ROUTE_KERNEL:
return "kernel";
case ZEBRA_ROUTE_CONNECT:
return "connected";
case ZEBRA_ROUTE_STATIC:
return "static";
case ZEBRA_ROUTE_RIP:
return "rip";
case ZEBRA_ROUTE_RIPNG:
return "rip";
case ZEBRA_ROUTE_OSPF:
return "ospf";
case ZEBRA_ROUTE_OSPF6:
return "ospf";
case ZEBRA_ROUTE_BGP:
return "bgp";
default:
return "unknown";
}
} |
class Preprocessor:
"""Dummy-encode categoricals, standardize reals."""
def __init__(self, interactions=False):
self.interactions = interactions
self.design_info_ = None
def fit(self, df):
dmat = self.do_encoding(df)
self.design_info_ = dmat.design_info
return self
def do_encoding(self, df):
patsy_formula = build_patsy_formula(df, self.interactions)
return patsy.dmatrix(patsy_formula, df)
def transform(self, df):
return patsy.build_design_matrices([self.design_info_], df)[0]
def fit_transform(self, df):
dmat = self.do_encoding(df)
self.design_info_ = dmat.design_info
return dmat |
//: See if we can find the format from an example
// Returns false if fail.
bool DPFileSequenceBaseBodyC::ProbeExample(FilenameC rootFn) {
ONDEBUG(cerr << "DPFileSequenceBaseBodyC::ProbeExample('" << rootFn << "') \n");
if(forLoad) {
if(!rootFn.Exists())
return false;
}
int i;
bool digits_set = false;
if(digits == -1)
digits_set = true;
for(i = rootFn.length()-1;i >= 0;i--) {
if(isdigit(rootFn[i]))
break;
}
if(i < 0) {
ONDEBUG(cerr << "No digits found. Not an example. \n");
return false;
}
int lastd = i;
for(;i >= 0;i--) {
if(!isdigit(rootFn[i]))
break;
}
i++;
if(rootFn[i] == '0' && (lastd != i))
digits = (lastd - i)+1;
else
digits = 0;
IntT tmpStart = atoi(rootFn.at(i,digits).chars());
if(start == ((UIntT) -1))
start = tmpStart;
if(no == ((UIntT) -1))
no = tmpStart;
templateFile = rootFn.before(i) + "%d" + rootFn.after(lastd);
if(forLoad) {
if(!Filename(digits,no+1).Exists()) {
if(digits_set)
digits = -1;
ONDEBUG(cerr << "Failed to load example. Rejecting. \n");
return false;
}
}
ONDEBUG(cerr << "DPFileSequenceBaseBodyC::ProbeExample(), File Sequence found for '" << rootFn << "'. Template='" << templateFile << "' Digits=" << digits << " \n");
if(start == ((UIntT) -1)) {
if(!forLoad || !Filename(digits,no-1).Exists())
start = no;
}
ONDEBUG(cerr << "DPFileSequenceBaseBodyC::ProbeExample(), Found. \n");
return true;
} |
<filename>src/Recursion_Level_1/Get_Keypad_Combinations.java
// Here, in this question, we're given a keypad code and its reference and
// we've to return all the keypad combinations that are possible
// using the given keypad code in an arraylist.
package Recursion_Level_1;
import java.util.*;
public class Get_Keypad_Combinations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the keypad code:- ");
String str = sc.nextLine();
System.out.println("The keypad combinations possible are:- ");
System.out.println(getKeypadCombinations(str));
}
static String[] codes = {".;", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tu", "vwx", "yz"};
private static ArrayList<String> getKeypadCombinations(String str) {
if (str.length() == 0) { // Base case, if length of str becomes 0
ArrayList<String> baseResult = new ArrayList<>(); // create a new arraylist
baseResult.add(""); // add an empty string to the arraylist
return baseResult; // return the arraylist
}
char ch = str.charAt(0); // Take out the first character from the main string
String ros = str.substring(1); // Take out the rest of string from the main string
String codeforch = codes[ch - '0']; // Take out the corresponding codes for the char
ArrayList<String> recResult = getKeypadCombinations(ros); // Make the call for ros
ArrayList<String> myResult = new ArrayList<>(); // create a new arraylist
for (int i = 0; i < codeforch.length(); i++) { // iterate over codeforch.length()
char chcode = codeforch.charAt(i); // Take out the ith character from codeforch
for (String rstr : recResult) { // iterate over the recResult arraylist
myResult.add(chcode + rstr); // add the stored char to all the elements
}
}
return myResult; // return the resultant list
}
} |
// GeneticAlgorithmSimulation.cpp - This is a program that demonstrates genetic algorithms using simulated robots
// <NAME> - 12/11/2017
// CISP 400
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <list>
#include <vector>
//#pragma warning(disable:4996)
using namespace std;
// Object class - General class for map objects
class Object {
protected:
char name; // 0 = Nothing, 1 = Battery, 2 = Robot, 9 = Wall
public:
char getName() { return name; } // Returns ID of object
};
// Robot class - Implements genetic learning algorithms
class Robot : public Object {
private:
Object*** world; // 2D array of object pointers
char genes[24][9]; // 24 genes with 9 chromosomes each
char direction = 'N'; // Direction robot is facing
int row = 0; // Row location
int col = 0; // Column location
int fitness = 0; // Determined by number of batteries collected
int energy = 10; // Changes based on movement and battery collection
public:
Robot(); // Default class constructor for robot
Robot(Robot*, Robot*); // Class constructor used for breeding a new robot
~Robot() { world[row][col] = 0; } // Automatically removes pointer in 2D array
char* getGene(int g) { return genes[g]; } // Returns specified gene in robot
int getFitness() { return fitness; } // Returns fitness of robot
void takeAction(); // Make the robot do something
bool checkMove(int, int); // Check if move is legal, change fitness and energy accordingly
void setWorld(Object***, int, int); // Set 2D array and position of robot
void printGenes(); // Used for debugging
};
// Default class constructor for robot
Robot::Robot() {
// Robot ID
name = '2';
// Generate initial genes of robot
for (int i = 0; i < 24; i++) {
// First 4 chromosomes
for (int j = 0; j < 4; j++) {
int k = rand() % 4;
switch (k) {
case 0:
genes[i][j] = '0';
break;
case 1:
genes[i][j] = '1';
break;
case 2:
genes[i][j] = '2';
break;
default:
genes[i][j] = '9';
break;
}
}
// Middle 1 chromosome
int k = rand() % 4;
switch (k) {
case 0:
genes[i][4] = 'N';
break;
case 1:
genes[i][4] = 'E';
break;
case 2:
genes[i][4] = 'S';
break;
default:
genes[i][4] = 'W';
break;
}
// Last 4 chromosomes
for (int j = 5; j < 9; j++) {
int k = rand() % 4;
switch (k) {
case 0:
genes[i][j] = 'M';
break;
case 1:
genes[i][j] = 'L';
break;
case 2:
genes[i][j] = 'R';
break;
default:
genes[i][j] = 'X';
break;
}
}
}
}
// Class constructor used for breeding a new robot
Robot::Robot(Robot* r1, Robot* r2) {
// Robot ID
name = '2';
// Breed new genes using first half of r1's genes
for (int i = 0; i < 12; i++) {
strncpy(genes[i], r1->getGene(i), 9);
// 5% chance for mutation
if (rand() % 100 < 5) {
// Chromosome to overwrite
int j = rand() % 9;
// Value used for overwriting
int k = rand() % 4;
// First 4 chromosomes
if (j < 4) {
switch (k) {
case 0:
genes[i][j] = '0';
break;
case 1:
genes[i][j] = '1';
break;
case 2:
genes[i][j] = '2';
break;
default:
genes[i][j] = '9';
break;
}
}
// Middle 1 chromosome
else if (j == 4) {
switch (k) {
case 0:
genes[i][4] = 'N';
break;
case 1:
genes[i][4] = 'E';
break;
case 2:
genes[i][4] = 'S';
break;
default:
genes[i][4] = 'W';
break;
}
}
// Last 4 chromosomes
else {
switch (k) {
case 0:
genes[i][j] = 'M';
break;
case 1:
genes[i][j] = 'L';
break;
case 2:
genes[i][j] = 'R';
break;
default:
genes[i][j] = 'X';
break;
}
}
}
}
// Breed new genes using second half of r2's genes
for (int i = 12; i < 24; i++) {
strncpy(genes[i], r2->getGene(i), 9);
// 5% chance for mutation
if (rand() % 100 < 5) {
// Chromosome to overwrite
int j = rand() % 9;
// Value used for overwriting
int k = rand() % 4;
// First 4 chromosomes
if (j < 4) {
switch (k) {
case 0:
genes[i][j] = '0';
break;
case 1:
genes[i][j] = '1';
break;
case 2:
genes[i][j] = '2';
break;
default:
genes[i][j] = '9';
break;
}
}
// Middle 1 chromosome
else if (j == 4) {
switch (k) {
case 0:
genes[i][4] = 'N';
break;
case 1:
genes[i][4] = 'E';
break;
case 2:
genes[i][4] = 'S';
break;
default:
genes[i][4] = 'W';
break;
}
}
// Last 4 chromosomes
else {
switch (k) {
case 0:
genes[i][j] = 'M';
break;
case 1:
genes[i][j] = 'L';
break;
case 2:
genes[i][j] = 'R';
break;
default:
genes[i][j] = 'X';
break;
}
}
}
}
}
// Make the robot do something
void Robot::takeAction() {
int bestIndex = 0; // Best matching gene
int bestMatch = 0; // Number of matches for best gene
// Initialize sensor data, use '0' if no objects detected around robot
char sensors[5] = {
world[row + 1][col] ? world[row + 1][col]->getName() : '0',
world[row][col + 1] ? world[row][col + 1]->getName() : '0',
world[row - 1][col] ? world[row - 1][col]->getName() : '0',
world[row][col - 1] ? world[row][col - 1]->getName() : '0',
direction
};
// Find best matching gene
for (int i = 0; i < 24; i++) {
int currMatch = 0;
for (int j = 0; j < 5; j++) {
if (sensors[j] == genes[i][j]) {
currMatch++;
}
}
if (currMatch > bestMatch) {
bestIndex = i;
bestMatch = currMatch;
}
}
// Apply action using best matching gene
for (int j = 5; j < 9; j++) {
int rAdd = 0; // Used for row movement
int cAdd = 0; // Used for col movement
// Check behaviors
switch (genes[bestIndex][j]) {
// Move
case 'M':
switch (direction) {
case 'N':
rAdd++;
break;
case 'E':
cAdd++;
break;
case 'S':
rAdd--;
break;
case 'W':
cAdd--;
break;
}
// If valid move, move robot and adjust pointers inside 2D array
if (checkMove(rAdd, cAdd)) {
world[row][col] = 0;
row += rAdd;
col += cAdd;
world[row][col] = this;
}
break;
// Rotate left
case 'L':
switch (direction) {
case 'N':
direction = 'W';
break;
case 'E':
direction = 'N';
break;
case 'S':
direction = 'E';
break;
case 'W':
direction = 'S';
break;
}
break;
// Rotate right
case 'R':
switch (direction) {
case 'N':
direction = 'E';
break;
case 'E':
direction = 'S';
break;
case 'S':
direction = 'W';
break;
case 'W':
direction = 'N';
break;
}
break;
// Do nothing
case 'X':
break;
}
}
}
// Check if move is legal, change fitness and energy accordingly
bool Robot::checkMove(int rAdd, int cAdd) {
// Return false immediately if energy is zero
if (!energy) {
return false;
}
// Decrement energy, check row and col for valid move
energy--;
rAdd += row;
cAdd += col;
// If object exists
if (world[rAdd][cAdd]) {
// If valid battery object ID, return true
if (world[rAdd][cAdd]->getName() == '1') {
// Automatically delete and clear pointer
delete world[rAdd][cAdd];
world[rAdd][cAdd] = 0;
energy += 5; // Add 5 energy
fitness++; // Add 1 fitness
return true;
}
// Else return false
else {
return false;
}
}
// Else return true
else {
return true;
}
}
// Set 2D array and position of robot
void Robot::setWorld(Object*** w, int r, int c) {
// If 2D array is set, remove current pointer inside 2D array
if (world) {
world[row][col] = 0;
}
world = w; // Set 2D array
row = r; // Set row
col = c; // Set col
// Set random direction
int k = rand() % 4;
switch (k) {
case 0:
direction = 'N';
break;
case 1:
direction = 'E';
break;
case 2:
direction = 'S';
break;
default:
direction = 'W';
break;
}
energy = 10; // Set energy to 10
fitness = 0; // Set fitness to 0
// Adjust pointer inside 2D array
world[row][col] = this;
}
// Used for debugging
void Robot::printGenes() {
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 9; j++) {
printf("%c", genes[i][j]);
}
printf("\t");
for (int j = 0; j < 9; j++) {
printf("%c", genes[i + 12][j]);
}
printf("\n");
}
printf("\n");
}
// Battery class - Collected by robot
class Battery : public Object {
public:
Battery() { name = '1'; } // Battery ID
};
// Wall class - Obstacle for robot
class Wall : public Object {
public:
Wall() { name = '9'; } // Wall ID
};
// Main
int main() {
// Vector containing surviving/newly bred robots
vector<Robot*> myRobots;
vector<float> firstLastFitness;
// Manually construct 2D array of pointers, initialized to zero
Object*** world = new Object**[14];
for (int i = 0; i < 14; i++) {
world[i] = new Object*[14]();
}
// Total number of robots created
int count = 0;
// Program Greeting
printf("This is a program that demonstrates genetic algorithms using simulated robots.\nThe end-of-round robot positions are displayed. Total population: 20000\n");
printf(" 0 - Nothing (not shown)\n");
printf(" 1 - Battery\n");
printf(" 2 - Robot\n");
printf(" 9 - Wall\n\n");
printf("Press any key to continue...\n");
getchar();
//system("pause");
printf("\n");
// Build the walls (Can be optimized)
for (int i = 0; i < 14; i++) {
for (int j = 0; j < 14; j++) {
if (i == 0 || i == 13 || j == 0 || j == 13) {
world[i][j] = new Wall;
}
}
}
// Initial population size 10
while (count < 10) {
// Within bounds of walls
int row = rand() % 12 + 1;
int col = rand() % 12 + 1;
// Check for valid random location
if (!world[row][col]) {
Robot* temp;
temp = new Robot;
// Push robot pointer to vector
myRobots.push_back(temp);
// Set 2D array of robot
temp->setWorld(world, row, col);
// Increment robot count
count++;
}
}
// Repeat until 20000 robots have been created
while (count <= 20000) {
// 58 batteries = 40% of squares within bounds of walls
int battCount = 0;
while (battCount < 58) {
// Within bounds of walls
int row = rand() % 12 + 1;
int col = rand() % 12 + 1;
// Check for valid random location
if (!world[row][col]) {
// Set pointer inside 2D array
world[row][col] = new Battery;
// Increment battery count
battCount++;
}
}
// 25 moves per robot
for (int i = 0; i < 25; i++) {
// 10 robots
for (int j = 0; j < 10; j++) {
myRobots[j]->takeAction();
}
}
// Print all squares using object IDs
for (int i = 0; i < 14; i++) {
for (int j = 0; j < 14; j++) {
if (world[i][j]) {
printf("%c ", world[i][j]->getName());
}
else {
printf(" ");
}
}
printf("\n");
}
// Sort robots in vector by fitness and print average fitness
float avgFitness = 0;
sort(myRobots.begin(), myRobots.end(), [](Robot* a, Robot* b) { return a->getFitness() > b->getFitness(); });
for (unsigned int i = 0; i < myRobots.size(); i++) {
avgFitness += myRobots[i]->getFitness();
}
avgFitness /= 10;
printf("Average Fitness: %.1f\n\n", avgFitness);
if (firstLastFitness.size() == 2) {
firstLastFitness.pop_back();
firstLastFitness.push_back(avgFitness);
}
else {
firstLastFitness.push_back(avgFitness);
}
// Delete all batteries and clear battery pointers in 2D array
for (int i = 0; i < 14; i++) {
for (int j = 0; j < 14; j++) {
if (world[i][j] && world[i][j]->getName() == '1') {
delete world[i][j];
world[i][j] = 0;
}
}
}
// Kill off 5 weakest robots
// 1 breeds with 2, 2 breeds with 3, 3 breeds with 4
// 4 breeds with 5, 5 breeds with 1, totals 5 newly created robots
for (int i = 0; i < 5; i++) {
delete myRobots[i + 5];
myRobots[i + 5] = new Robot(myRobots[i], myRobots[(i + 1) % 5]);
}
// Repeat until 10 robot pointers have been set inside 2D array
int turnCount = 0;
while (turnCount < 10) {
// Within bounds of walls
int row = rand() % 12 + 1;
int col = rand() % 12 + 1;
// Check for valid random location
if (!world[row][col]) {
// Set 2D array of robot
myRobots[turnCount]->setWorld(world, row, col);
// Increment count for newly created robots
turnCount++;
}
}
// Add 5 to total number of robots created
count += 5;
}
// Bonus - Print final genes of robot
printf("Final genes:\n");
myRobots[0]->printGenes();
// Bonus - Compare first and last generation average fitness
float lastFitness = firstLastFitness.back();
firstLastFitness.pop_back();
printf("First Generation Average Fitness: %.1f\nLast Generation Average Fitness: %.1f\n\n", firstLastFitness.back(), lastFitness);
printf("Press any key to continue...\n");
getchar();
//system("pause");
return 0;
}
|
def rays(year, teams):
if year >= 2008:
teams.append('TBR')
elif year >= 1998:
teams.append('TBD') |
from sys import stdin
import math
n = int(stdin.readline().rstrip())
li = [list(stdin.readline().rstrip().split()) for _ in range(n)]
s = stdin.readline().rstrip()
time = 0
flag = 0
for i in li:
if s == i[0]:
flag = 1
continue
if flag == 1:
time += int(i[1])
print(time)
|
/**
*
* This method ignores the provided id field
* in the parameter. Instead using only the class'
* internal static counter to generate ids at the DB level
*
* @param newURL
* @return
*/
@Override
public Optional<Integer> add(ShortURL newURL) {
String url = newURL.getLongFormatURL();
String key = Integer.toString(counter);
try (Jedis jedis = new Jedis(hostname)) {
switchDb(jedis);
jedis.set(key, url);
}
counter++;
return Optional.of(counter-1);
} |
Top Google Glass Apps of 2014
Usually at the end of every month I gather up the best apps released during that month. But, since it’s about to be 2015, this time I’m making a small list of the best apps released in 2014.
Down below you will find some of the most unique, helpful, and interesting apps that came to Google Glass in 2014. If you come across an app that you’ve never heard of, then give it a try. There’s a pretty good chance that you will enjoy using it! Anyway, continue reading to see some of the top Google Glass apps from 2014.
Almost everyone knows what Pandora Internet Radio is so this glassware doesn’t need much explaining. Overall, it’s nice to be able to listen to music on Google Glass occasionally. With that being said, you’re going to need the Google Glass earbuds to truly enjoy this application.
Official Description:
Great music discovery is effortless and free with Pandora® Internet Radio. Just start with the name of one of your favorite artists, songs, composers or existing stations and we will do the rest. It’s easy to create and listen to personalized stations that play the music you’ll love.
Color Detector is an application that identifies the colors of the objects that you are looking at. Using the application, you can look at an object and the application will give you the color hex code of the object. Really, Color Detector isn’t that useful of an application unless you’re color blind or a designer. Still, it’s fun to mess with.
Official Description:
Simple Glassware that shows you the color of what’s in front of you. It shows the name of the color and its hex code, and if you want to pause just tap the touchpad.
Evercam is an application that helps you identify nearby CCTV cameras. Upon request, the application will show you a snapshot of the nearest CCTV camera. I thought this was a pretty neat little application and one that privacy-conscious people might enjoy.
Official Description:
An Evercam integration that help you explore CCTV cameras nearby. It will show a snapshot of the nearest camera when requested.
If you’re a person who likes to chill back and have a nice alcoholic beverage occasionally, then this is an application that you want to install. Let’s Drink is a cocktail application for Google Glass. It has a ton of drink recipes and it’ll teach you how to mix them all. So, if you want to try a new tasty beverage, then give this app a try.
This is currently the best Reddit application for Google Glass. Using this application you can browse your Reddit front page, visit links, and upvote content. I love Reddit, so I had to give this application a shoutout.
Official Description:
Browse your Reddit frontpage right on Google Glass with Monocle. Read self posts inline, visit story links, vote on articles, and get notified of new comment replies and messages (coming soon).
Zombies, Run! is a small little fitness game for Google Glass where your job is to save humanity by running. The application turns running into a game by giving you tasks as you run and by telling you a story. It’s a definitely worth playing at least once.
Official Description:
Zombies, Run! is a thrilling running game and audio adventure, co-created with award-winning novelist Naomi Alderman. We deliver the story straight to your headphones through orders and voice recordings – and it’s your job to save the last remnants of humanity by running in the real world.
ViewTube is currently the best Youtube app for Google Glass. It allows you to look up videos, and even let’s you run them in the background while you multitask. The battery in Google Glass sucks, but it’s still cool to be able to watch a video on the device and play something in the background occasionally. If you want to watch Youtube videos on Google Glass, then go with this application.
Official Description:
Search for YouTube content and view it directly on Google Glass as well as listen to content while multitasking with other Glassware. With ViewTube, you can continue listening to content in the background while interacting with other Glassware by simply swiping away from ViewTube. The seamless experience allows one to return from listening to viewing content by moving back to ViewTube at anytime. Other features supported in ViewTube are controls for fast forward, rewind and pause.
BestParking is a glassware that directs you towards the cheapest parking garages that are near you. The application works in over 105 cities, so it’ll work for a decent amount of you. If you live in a city where it is hard to find parking and parking is expensive, then you should give this app a shot.
Official Description:
BestParking steers you toward the cheapest and most convenient parking garages and lots in 105 cities & 115 airports throughout North America. Save hundreds of dollars!
Preview for Google Glass is a pretty cool, but simple application. Using the application, you can look at a movie poster and the trailer for the movie will automatically start playing. While most of us don’t generally go around looking at random movie posters this is still a pretty neat little application.
Official Description:
Enhance your movie-going experience with Preview for Google Glass. Simply look at a movie poster and say, “ok, glass recognize this”. Focus on the poster image and the film’s trailer will begin automatically.
LynxFit is a pretty popular fitness application for Google Glass. The application includes a bunch of different fitness programs and challenges that you can subscribe to and try out. There are running programs, prenatal fitness programs, and more. LynxFit even has a social aspect to it where you can share your progress with friends. If you’re looking to get in shape, then definitely give this application a try.
Official Description:
Start your 30 day program or challenge by saying “ok glass, start a workout.” Choose from various fitness content partners and subscribe to a workout challenge, schedule and track your activity with Glass. Share your P.I.E. (pace, intensity and endurance) progress with your friends.
Tesco Groceries for Google Glass allows you to browse items, view nutritional information of items, and shop for items at Tesco stores. It’s one of the more feature packed shopping applications for Google Glass, so I thought it deserved to be on this list. If you live near a Tesco Grocery and wouldn’t mind ordering some food hands-free, then give this application a little try.
Official Description:
Tesco grocery Glassware lets you browse, view nutritional information, and add items to your shopping basket hands-free. A great companion to the Tesco mobile applications that you use for all your grocery shopping.
Released in August, Trackendo is a cool little tracking glassware. Google Glass already has a small tool that you can use to track Google Glass, but Trackendo is a bit better because it allows you to track multiple locations and it provides way better location information than the “standard” tracking tool. If you’re scared you might someday lose your Google Glass, then get this app.
Official Description:
Don’t be afraid of losing your Google Glass™ anymore. With Trackendo you’ll be able to know the last locations your Glass was and when it was there, so that you can easily keep track of it.
If you struggle with speeches, then this is an application for you. Users can upload speeches to the application, and view different slides from their speech as they go through their presentation. Using this application you will never slip up and will always know where you are in your speech. Overall, a very handy app for people who get nervous during presentations and speeches.
Official Description:
Speech Helper provides the user with an effective way to deliver a seamless speech. Users can upload speeches and view slide notes on Glass while delivering a presentation. Begin a new hands-free and paperless speech experience right now!
Captioning on Google Glass is an application that was designed to help deaf and hearing-impaired people communicate properly with others. The Google Glass application connects to an application that is installed on a phone. Once the application on Google Glass is connected to a phone, a person can talk into the phone and whatever is said is captioned and displayed to the person wearing Google Glass. Not an application that the average person will use regularly, but one that is pretty cool and one that can definitely help hearing-impaired people.
Official Description:
Captioning on Google Glass provides real-time closed captioning, allowing the deaf or hard of hearing to converse with others. It requires an Android smartphone paired with Google Glass to function. Just say “ok glass, recognize this” to start captioning. Your conversational partner speaks into the phone and the speech is converted to text and displayed on your Google Glass instantly. Android device with companion app required. You will be directed to install the app while installing the Glassware.
Star Chart is pretty popular among Explorers, because it’s a darn awesome augmented reality application. Using the application, you can look up into the sky and it’ll teach you about all the different constellations and stars that you are looking it. Star Chart has audio descriptions for all the planets in our solar system and for many of the stars near us. Star Chart is an educational application at heart, but it’s so cool that it doesn’t seem like one. If you haven’t tried Star Chart yet, then you should. It’s THE best augmented reality application on Google Glass right now.
Official Description:
The world’s top astronomy app – Star Chart – comes to Google Glass. Star Chart for Google Glass lets you explore the wonders of our universe via the seamless experience of augmented reality. Simply look up at the sky to discover the stars, planets and constellations above you. Star Chart’s features include:
– All the visible stars of the northern and southern hemispheres.
– All the planets of the solar system, the Moon, the Sun and Pluto.
– All 88 constellations, with imagery based on the beautiful artwork of 17th century astronomer Johannes Hevelius.
– Audio descriptions of all the planets and many of the brightest stars.
The Escapist Games Team hopes you enjoy Star Chart. Send your feedback and feature requests to: [email protected].
So, those are what I consider to be the top Google Glass applications of 2014. You may not agree with some of my choices, but that’s okay. Feel free to create your own list of top apps and share it with us in the comments section down below! |
Verizon is pushing out an update to the Galaxy Note 4 today, with the update available through only Kies at the moment. According to users who are getting update, the build is still Android 5.0.1 (build number N910VVRU2BOF1) and there don’t seem to be any notable changes. The Kies version of the update is 2GB in size – that’s quite large, but remember that Kies downloads the entire firmware so you get a large file no matter how big the actual update is.
Verizon hasn’t posted a changelog yet, though that should change once the over-the-air (OTA) version of the update starts rolling out to devices. Head into the Settings » About device » Software updates menu and hit the Check now button if you don’t want to download the 2GB file through Kies, or just wait till a notification for the OTA pops up on your Note 4’s status bar.
Oh, and if you don’t have a Galaxy Note 4 but are looking to buy a nice new phablet at a discounted price, you can take advantage of Samsung’s Notable Savings deal, which is offering the device at a $200 rebate discount till July 26th. This deal is only for the GSM variant though, so you are out of luck if Verizon or Sprint are your carriers of choice.
Via
Image credits: Android Authority |
<gh_stars>0
package com.greyturtle.silencer.service;
import com.greyturtle.silencer.di.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.zeroturnaround.exec.InvalidExitValueException;
import org.zeroturnaround.exec.ProcessExecutor;
@Slf4j
public class SilencerService implements Service {
private final String binPath = "play";
public void silence() {
final String messageFile = "silence-1.mp3";
final List<String> cmd = new ArrayList<>();
cmd.add(binPath);
cmd.add(messageFile);
try {
new ProcessExecutor().command(cmd.toArray(new String[cmd.size()])).timeout(10, TimeUnit.SECONDS)
.execute();
} catch (InvalidExitValueException | IOException | InterruptedException | TimeoutException e) {
e.printStackTrace();
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
#define max_n 200008
#define oo 1000000000
#define in insert
#define eps 1e-11
#define l_b lower_bound
#define fr(i,n) for(int i=0;i<n;i++)
#define LSOne(S) (S & (-S))
typedef vector<int >vi;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> ii;
typedef vector<ii> vii;
int n;
ii x[max_n];
int sol[max_n];
int main(){
// freopen("in.in","rt",stdin);
cin>>n;
for(int i=1;i<=n;i++){
cin>>x[i].first>>x[i].second;
}
x[0]=ii(-3000000,0);
sort(x,x+n+1);
for(int i=1;i<=n;i++){
int pos=l_b(x,x+n+1,ii(x[i].first-x[i].second,-1))-x;
int poss=l_b(x,x+n+1,ii(x[i].first,-1))-x;
int dif=poss-pos;
sol[i]=sol[i-dif-1]+dif;
}
int ans=oo;
for(int i=n;i>=1;i--){
ans=min(ans,n-i+sol[i]);
}
cout<<ans;
} |
use barrel::types;
use expect_test::expect;
use indoc::indoc;
use introspection_engine_tests::test_api::*;
use quaint::prelude::Queryable;
use test_macros::test_connector;
#[test_connector(tags(Postgres), exclude(CockroachDb))]
async fn kanjis(api: &TestApi) -> TestResult {
let migration = indoc! {r#"
CREATE TABLE "A"
(
id int primary key,
b患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患 int not null
);
CREATE TABLE "B"
(
a者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者 int primary key
);
ALTER TABLE "A" ADD CONSTRAINT "患者ID" FOREIGN KEY (b患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患患) REFERENCES "B"(a者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者者) ON DELETE RESTRICT ON UPDATE CASCADE;
"#};
api.database().raw_cmd(migration).await?;
let expected = expect![[r#"
model A {
id Int @id
b____________________ Int @map("b患患患患患患患患患患患患患患患患患患患患")
B B @relation(fields: [b____________________], references: [a____________________], map: "患者ID")
}
model B {
a____________________ Int @id @map("a者者者者者者者者者者者者者者者者者者者者")
A A[]
}
"#]];
expected.assert_eq(&api.introspect_dml().await?);
Ok(())
}
#[test_connector(tags(Postgres), exclude(CockroachDb))]
// Cockroach can return either order for multiple foreign keys. This is hard to deterministically
// test, so disable for now. See: https://github.com/cockroachdb/cockroach/issues/71098.
async fn multiple_foreign_key_constraints_are_taken_always_in_the_same_order(api: &TestApi) -> TestResult {
let migration = indoc! {r#"
CREATE TABLE "A"
(
id int primary key,
foo int not null
);
CREATE TABLE "B"
(
id int primary key
);
ALTER TABLE "A" ADD CONSTRAINT "fk_1" FOREIGN KEY (foo) REFERENCES "B"(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "A" ADD CONSTRAINT "fk_2" FOREIGN KEY (foo) REFERENCES "B"(id) ON DELETE RESTRICT ON UPDATE RESTRICT;
"#};
api.database().raw_cmd(migration).await?;
let expected = expect![[r#"
model A {
id Int @id
foo Int
B B @relation(fields: [foo], references: [id], onDelete: Cascade, map: "fk_1")
}
model B {
id Int @id
A A[]
}
"#]];
for _ in 0..10 {
expected.assert_eq(&api.introspect_dml().await?);
}
Ok(())
}
#[test_connector(tags(Postgres), exclude(CockroachDb))]
async fn relations_should_avoid_name_clashes_2(api: &TestApi) -> TestResult {
api.barrel()
.execute(move |migration| {
migration.create_table("x", move |t| {
t.add_column("id", types::primary());
t.add_column("y", types::integer().nullable(false));
t.add_index("unique_y_id", types::index(vec!["id", "y"]).unique(true));
});
migration.create_table("y", move |t| {
t.add_column("id", types::primary());
t.add_column("x", types::integer().nullable(false));
t.add_column("fk_x_1", types::integer().nullable(false));
t.add_column("fk_x_2", types::integer().nullable(false));
});
migration.change_table("x", |t| {
t.add_foreign_key(&["y"], "y", &["id"]);
});
migration.change_table("y", |t| {
t.add_constraint(
"y_fkey",
types::foreign_constraint(&["fk_x_1", "fk_x_2"], "x", &["id", "y"], None, None),
);
});
})
.await?;
let expected = expect![[r#"
model x {
id Int @id @default(autoincrement())
y Int
y_x_yToy y @relation("x_yToy", fields: [y], references: [id], onDelete: NoAction, onUpdate: NoAction)
y_xToy_fk_x_1_fk_x_2 y[] @relation("xToy_fk_x_1_fk_x_2")
@@unique([id, y], map: "unique_y_id")
}
model y {
id Int @id @default(autoincrement())
x Int
fk_x_1 Int
fk_x_2 Int
x_xToy_fk_x_1_fk_x_2 x @relation("xToy_fk_x_1_fk_x_2", fields: [fk_x_1, fk_x_2], references: [id, y], onDelete: NoAction, onUpdate: NoAction, map: "y_fkey")
x_x_yToy x[] @relation("x_yToy")
}
"#]];
expected.assert_eq(&api.introspect_dml().await?);
Ok(())
}
#[test_connector(tags(Postgres), exclude(CockroachDb))]
async fn default_values_on_relations(api: &TestApi) -> TestResult {
api.barrel()
.execute(|migration| {
migration.create_table("User", |t| {
t.add_column("id", types::primary());
});
migration.create_table("Post", |t| {
t.add_column("id", types::primary());
t.inject_custom("user_id INTEGER REFERENCES \"User\"(\"id\") Default 0");
});
})
.await?;
let expected = expect![[r#"
model Post {
id Int @id @default(autoincrement())
user_id Int? @default(0)
User User? @relation(fields: [user_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
}
model User {
id Int @id @default(autoincrement())
Post Post[]
}
"#]];
expected.assert_eq(&api.introspect_dml().await?);
Ok(())
}
|
Dentin tubule occluding ability of dentin desensitizers.
PURPOSE
To compare the dentin tubule-occluding ability of fluoroaluminocalciumsilicate-based (Nanoseal), calcium phosphate-based (Teethmate Desensitizer), resin-containing oxalate (MS Coat ONE) and diamine silver fluoride (Saforide) dentin desensitizers using artificially demineralized bovine dentin.
METHODS
Simulated hypersensitive dentin was created using cervical dentin sections derived from bovine incisors using phosphoric acid etching followed by polishing with a paste containing hydroxyapatite. The test desensitizers were applied in one, two, or three cycles, where each cycle involved desensitizer application, brushing, and immersion in artificial saliva (n= 5 each). The dentin surfaces were examined with scanning electron microscopy, and the dentin tubule occlusion rate was calculated. The elemental composition of the deposits was analyzed with electron probe microanalysis. Data were analyzed by one-way ANOVA and the Tukey honestly significant different test.
RESULTS
Marked deposit formation was observed on the specimens treated with Nanoseal or Teethmate Desensitizer, and tags were detected in the specimens' dentin tubules. These findings became more prominent as the number of application cycles increased. The major elemental components of the tags were Ca, F, and Al (Nanoseal) and Ca and P (Teethmate Desensitizer). The tubule occlusion rates of MS Coat ONE and Saforide were significantly lower than those of Nanoseal and Teethmate Desensitizer (P< 0.05). |
pub trait PartialEquivalenceRelation<A: ?Sized> {
fn equal(&self, &A, &A) -> bool;
#[inline]
fn inequal(&self, x: &A, y: &A) -> bool { !self.equal(x, y) }
}
pub trait EquivalenceRelation<A: ?Sized> : PartialEquivalenceRelation<A> {}
impl<A: ?Sized + PartialEq> PartialEquivalenceRelation<A> for ::Core {
fn equal(&self, x: &A, y: &A) -> bool { x == y }
fn inequal(&self, x: &A, y: &A) -> bool { x != y }
}
impl<A: ?Sized + Eq> EquivalenceRelation<A> for ::Core {}
|
#include <assert.h>
#include <limits.h>
struct TestS {
long x, y, q, r;
};
static struct TestS test_s[] = {
{ 4, 2, 2, 0 }, /* normal cases */
{ 9, 7, 1, 2 },
{ 0, 0, -1, 0 }, /* div by zero cases */
{ 9, 0, -1, 9 },
{ LONG_MIN, -1, LONG_MIN, 0 }, /* overflow case */
};
struct TestU {
unsigned long x, y, q, r;
};
static struct TestU test_u[] = {
{ 4, 2, 2, 0 }, /* normal cases */
{ 9, 7, 1, 2 },
{ 0, 0, ULONG_MAX, 0 }, /* div by zero cases */
{ 9, 0, ULONG_MAX, 9 },
};
#define ARRAY_SIZE(X) (sizeof(X) / sizeof(*(X)))
int main (void)
{
int i;
for (i = 0; i < ARRAY_SIZE(test_s); i++) {
long q, r;
asm("div %0, %2, %3\n\t"
"rem %1, %2, %3"
: "=&r" (q), "=r" (r)
: "r" (test_s[i].x), "r" (test_s[i].y));
assert(q == test_s[i].q);
assert(r == test_s[i].r);
}
for (i = 0; i < ARRAY_SIZE(test_u); i++) {
unsigned long q, r;
asm("divu %0, %2, %3\n\t"
"remu %1, %2, %3"
: "=&r" (q), "=r" (r)
: "r" (test_u[i].x), "r" (test_u[i].y));
assert(q == test_u[i].q);
assert(r == test_u[i].r);
}
return 0;
}
|
//! Module level comment describing the example ...
//!
//! Delete the comments below from final versions.
//!
//! Please ensure that concepts which a previous example have not introduced are
//! well commented inline. Have a look at other examples to get a feeling for what we mean here.
//!
//! The goal is that someone who has not come across the functionality you're providing an example
//! for previously comes away with a solid understanding which they can directly implement or
//! further enhance by reading through specific Gotham web framework API docs.
//!
//! Minimal examples necessary to describe a specific piece of functionality work out better. There
//! is no need to create a collection of 10 items for example where 1 will do perfectly well.
//!
//! Many examples use the theme of a "web store" to help explain concepts which is something we'd
//! like to continue encouraging for unity purposes.
//!
//! Finally please ships tests for the specific functionality your example is exploring, there is no
//! need however to show tests for Gotham web framework functionality that is outside of the scope
//! of your specific example i.e. That a 404 is correctly returned for a missing endpoint when
//! you're writing an example for setting Cookies.
extern crate gotham;
extern crate hyper;
extern crate mime;
use gotham::helpers::http::response::create_response;
use gotham::router::builder::*;
use gotham::router::Router;
use gotham::state::State;
use hyper::{Response, StatusCode};
/// Create a `Handler` that ...
pub fn well_named_function(state: State) -> (State, Response) {
let res = create_response(&state, StatusCode::Ok, None);
(state, res)
}
/// Create a `Router`
fn router() -> Router {
build_simple_router(|route| {
route.get("/").to(well_named_function);
})
}
/// Start a server and use a `Router` to dispatch requests
pub fn main() {
let addr = "127.0.0.1:7878";
println!("Listening for requests at http://{}", addr);
gotham::start(addr, router())
}
#[cfg(test)]
mod tests {
use super::*;
use gotham::test::TestServer;
#[test]
fn well_named_test() {
let test_server = TestServer::new(router()).unwrap();
let response = test_server
.client()
.get("http://localhost")
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::Ok);
}
}
|
<filename>helospark-core-ui/src/app/login-form/login-form.component.ts<gh_stars>0
import { AuthenticationStoreService } from './../common/authentication-store/authentication-store.service';
import { LoginService } from './../common/login/login.service';
import { LoginData } from './../common/login-dialog/login-data';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-login-form',
templateUrl: './login-form.component.html',
styleUrls: ['./login-form.component.css']
})
export class LoginFormComponent implements OnInit {
private loginData:LoginData;
constructor(private loginService:LoginService, private authStore:AuthenticationStoreService) { }
ngOnInit() {
this.loginData = new LoginData();
}
onSubmit() {
this.loginService.doLogin(this.loginData)
.subscribe(tokens => this.authStore.setTokens(tokens),
error => console.log(error));
}
}
|
#include <bits/stdc++.h>
using namespace std;
void Solve(){
long long n;
string s;
cin>>n>>s;
string pre = "", suf = "";
int i = 0;
while(i < s.size()){
while(i < s.size() && s[i] != '.'){
pre += s[i];
i++;
}
i++;
while(i < s.size()){
suf += s[i];
i++;
}
}
int pree = stoi(pre);
int suff = stoi(suf);
long long res = n * pree;
res += n * suff / 100;
cout<<res<<'\n';
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
Solve();
}
|
<reponame>BurgosNY/nutrinews
from flask import Flask, render_template, flash, redirect, url_for, request
from flask_pymongo import PyMongo
from pymongo import DESCENDING, ASCENDING
from link_analysis import link_check
import settings
from flask_wtf import FlaskForm
# Initialize app:
app = Flask(__name__)
app.config["MONGO_URI"] = settings.MONGODB_URI
mongo = PyMongo(app)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
result = request.form
url = result['url']
print(url)
data = link_check(url)
print(data)
return render_template('index.html', **data)
else:
return render_template('home.html')
if __name__ == '__main__':
app.run(port=5000, debug=True)
|
// Host provides the net.IP of the Internet Host.
func (a *Address) Host() net.IP {
switch a.Network() {
case "tcp", "tcp4", "tcp6":
addr, _ := net.ResolveTCPAddr(a.Network(), a.String())
return addr.IP
case "udp", "udp4", "udp6":
addr, _ := net.ResolveUDPAddr(a.Network(), a.String())
return addr.IP
case "ip", "ip4", "ip6":
addr, _ := net.ResolveIPAddr(a.Network(), a.String())
return addr.IP
default:
return net.IP{}
}
} |
/// Returns the number of rows that are available in the buffers defined for the query. If no
/// rows are currently available in the buffers, an internal fetch takes place in order to
/// populate them, if rows are available. If the statement does not refer to a query an error
/// is returned. All columns that have not been defined prior to this call are implicitly
/// defined using the metadata made available when the statement was executed.
///
/// * `max_rows` - the maximum number of rows to fetch. If the number of rows available exceeds
/// this value only this number will be fetched.
///
/// Returns a tuple representing (row_index, num_rows_fetched, more_rows).
pub fn fetch_rows(&self, max_rows: u32) -> Result<(u32, u32, bool)> {
let mut buffer_row_index = 0;
let mut num_rows_fetched = 0;
let mut more_rows = 0;
try_dpi!(
externs::dpiStmt_fetchRows(
self.inner,
max_rows,
&mut buffer_row_index,
&mut num_rows_fetched,
&mut more_rows
),
Ok((buffer_row_index, num_rows_fetched, more_rows == 1)),
ErrorKind::Statement("dpiStmt_fetchRows".to_string())
)
} |
import {FunctionalComponent, h} from "preact";
import {ComponentViewProps} from "./ComponentsConfig";
import {Transform2D_Data} from "@highduck/core";
import {Vec2Field} from "../fields/Vec2Field";
import {NumberField} from "../fields/NumberField";
import {RectField} from "../fields/RectField";
import {Color4Field} from "../fields/Color4Field";
export const Transform2DEditor: FunctionalComponent<ComponentViewProps> = (props: ComponentViewProps) => {
const data = props.data as Transform2D_Data;
return <div>
<Vec2Field label="Position" target={data} field="position"/>
<Vec2Field label="Scale" target={data} field="scale"/>
<Vec2Field label="Skew" target={data} field="skew"/>
<NumberField label="Rotation" target={data} field="rotation"/>
<Vec2Field label="Origin" target={data} field="origin"/>
<Vec2Field label="Pivot" target={data} field="pivot"/>
<RectField label="Canvas" target={data} field="rect"/>
<NumberField label="Alpha" target={data.colorMultiplier} field="a" min={0} max={1}/>
<Color4Field label="Color Multip" target={data} field="colorMultiplier"/>
<NumberField label="Additive" target={data.colorOffset} field="a" min={0} max={1}/>
<Color4Field label="Color Offset" target={data} field="colorOffset"/>
</div>
}; |
import imp
import inspect
import os
import sys
import uuid
from conans.client.generators import _save_generator
from conans.errors import ConanException, NotFoundException
from conans.model.conan_file import ConanFile
from conans.model.conan_generator import Generator
from conans.util.config_parser import ConfigParser
from conans.util.files import rmdir
from conans.tools import chdir
def load_conanfile_class(conanfile_path):
loaded, filename = _parse_file(conanfile_path)
try:
return _parse_module(loaded, filename)
except Exception as e: # re-raise with file name
raise ConanException("%s: %s" % (conanfile_path, str(e)))
def _parse_module(conanfile_module, filename):
""" Parses a python in-memory module, to extract the classes, mainly the main
class defining the Recipe, but also process possible existing generators
@param conanfile_module: the module to be processed
@param consumer: if this is a root node in the hierarchy, the consumer project
@return: the main ConanFile class from the module
"""
result = None
for name, attr in conanfile_module.__dict__.items():
if name[0] == "_":
continue
if (inspect.isclass(attr) and issubclass(attr, ConanFile) and attr != ConanFile and
attr.__dict__["__module__"] == filename):
if result is None:
result = attr
else:
raise ConanException("More than 1 conanfile in the file")
if (inspect.isclass(attr) and issubclass(attr, Generator) and attr != Generator and
attr.__dict__["__module__"] == filename):
_save_generator(attr.__name__, attr)
if result is None:
raise ConanException("No subclass of ConanFile")
return result
def _parse_file(conan_file_path):
""" From a given path, obtain the in memory python import module
"""
# Check if precompiled exist, delete it
if os.path.exists(conan_file_path + "c"):
os.unlink(conan_file_path + "c")
# Python 3
pycache = os.path.join(os.path.dirname(conan_file_path), "__pycache__")
if os.path.exists(pycache):
rmdir(pycache)
if not os.path.exists(conan_file_path):
raise NotFoundException("%s not found!" % conan_file_path)
filename = os.path.splitext(os.path.basename(conan_file_path))[0]
try:
current_dir = os.path.dirname(conan_file_path)
sys.path.append(current_dir)
old_modules = list(sys.modules.keys())
with chdir(current_dir):
loaded = imp.load_source(filename, conan_file_path)
# Put all imported files under a new package name
module_id = uuid.uuid1()
added_modules = set(sys.modules).difference(old_modules)
for added in added_modules:
module = sys.modules[added]
if module:
folder = os.path.dirname(module.__file__)
if folder.startswith(current_dir):
module = sys.modules.pop(added)
sys.modules["%s.%s" % (module_id, added)] = module
except Exception:
import traceback
trace = traceback.format_exc().split('\n')
raise ConanException("Unable to load conanfile in %s\n%s" % (conan_file_path,
'\n'.join(trace[3:])))
finally:
sys.path.pop()
return loaded, filename
class ConanFileTextLoader(object):
"""Parse a conanfile.txt file"""
def __init__(self, input_text):
# Prefer composition over inheritance, the __getattr__ was breaking things
self._config_parser = ConfigParser(input_text, ["requires", "generators", "options",
"imports"], parse_lines=True)
@property
def requirements(self):
"""returns a list of requires
EX: "OpenCV/2.4.10@phil/stable"
"""
return [r.strip() for r in self._config_parser.requires.splitlines()]
@property
def options(self):
return self._config_parser.options
@property
def _import_parameters(self):
def _parse_args(param_string):
root_package, ignore_case, folder, excludes = None, False, False, None
params = param_string.split(",")
params = [p.split("=") for p in params if p]
for (var, value) in params:
var = var.strip()
value = value.strip()
if var == "root_package":
root_package = value
elif var == "ignore_case":
ignore_case = (value.lower() == "true")
elif var == "folder":
folder = (value.lower() == "true")
elif var == "excludes":
excludes = value.split()
else:
raise Exception("Invalid imports. Unknown argument %s" % var)
return root_package, ignore_case, folder, excludes
def _parse_import(line):
pair = line.split("->")
source = pair[0].strip().split(',', 1)
dest = pair[1].strip()
src, pattern = source[0].strip(), source[1].strip()
return pattern, dest, src
ret = []
local_install_text = self._config_parser.imports
for line in local_install_text.splitlines():
# discard blanks, comments, and discard trailing comments
line = line.strip()
if not line or line.startswith("#"):
continue
line = line.split("#", 1)[0]
invalid_line_msg = "Invalid imports line: %s\nEX: OpenCV/lib, * -> ./lib" % line
if line.startswith("/") or line.startswith(".."):
raise ConanException("%s\n%s" % (invalid_line_msg,
"Import's paths can't begin with '/' or '..'"))
try:
tokens = line.split("@", 1)
if len(tokens) > 1:
line = tokens[0]
params = tokens[1]
else:
params = ""
root_package, ignore_case, folder, excludes = _parse_args(params)
pattern, dest, src = _parse_import(line)
ret.append((pattern, dest, src, root_package, folder, ignore_case, excludes))
except Exception as e:
raise ConanException("%s\n%s" % (invalid_line_msg, str(e)))
return ret
@property
def generators(self):
return self._config_parser.generators.splitlines()
def imports_method(self, conan_file):
parameters = self._import_parameters
def imports():
for import_params in parameters:
conan_file.copy(*import_params)
return imports
|
<reponame>amit212316/master
# yomamabot/fb_yomamabot/urls.py
from django.conf.urls import include, url
from .views import YoMamaBotView
urlpatterns = [
url(r'^66d2b8f4a09cd35cb23076a1da5d51529136a3373fd570b122/?$', YoMamaBotView.as_view())
] |
// convert the database tablespace query result to internal structure
func NewTablespaces(tuples TablespaceTuples) Tablespaces {
clusterTablespaceMap := make(Tablespaces)
for _, t := range tuples {
tablespaceInfo := TablespaceInfo{Location: t.Location, UserDefined: t.UserDefined}
if segTablespaceMap, ok := clusterTablespaceMap[t.DbId]; ok {
segTablespaceMap[t.Oid] = tablespaceInfo
clusterTablespaceMap[t.DbId] = segTablespaceMap
} else {
segTablespaceMap := make(SegmentTablespaces)
segTablespaceMap[t.Oid] = tablespaceInfo
clusterTablespaceMap[t.DbId] = segTablespaceMap
}
}
return clusterTablespaceMap
} |
#include <stdio.h>
#define MAX 100
struct longnumber {
char dig[MAX];
};
typedef struct longnumber longnumber;
longnumber add(longnumber a, longnumber b) {
longnumber c;
int i=0, f=0;
for(i=0; i<MAX; i++) {
int z=a.dig[i]+b.dig[i]+f;
c.dig[i]=z % 10;
f = z/10;
}
return c;
}
longnumber mul(longnumber *a, int x, int shift) {
longnumber c;
int i=0, f=0;
for(i=0; i<MAX; i++) {
int z=(i-shift>=0) ? a->dig[i-shift]*x+f : 0;
c.dig[i]=z % 10;
f = z/10;
}
return c;
}
longnumber mult(longnumber *a, int x) {
longnumber c;
longnumber sum;
int s=0;
while (x) {
int p=x % 10;
c= mul(a, p, s);
sum=(s) ? add(sum, c) : c;
x/=10;
s++;
}
return sum;
}
void print(longnumber b) {
int i;
for(i=MAX-1; b.dig[i]==0 ; i--) ;
int z=0;
for( ; i>=0; i--) {
z++;
printf("%c", b.dig[i]+'0');
}
// printf("\n(%d digits)\n\n",z);
}
int main() {
int m,n,a;
int x,y,i;
scanf("%d%d%d", &m, &n, &a);
x=(m % a==0) ? m/a: m/a+1;
y=(n % a ==0)? n/a: n/a+1;
longnumber xl;
for(i=0; i<MAX; i++) xl.dig[i]=0;
i=0;
while (x) {
xl.dig[i++]= x % 10;
x /=10;
}
// print(xl);
longnumber z=mult(&xl,y);
print(z);
return 0;
}
|
// computeValidationMetricsCompleted updates the internal state of the sequencer to account for a
// completed COMPUTE_VALIDATION_METRICS worklaod.
func (s *trialWorkloadSequencer) computeValidationMetricsCompleted(
msg workload.CompletedMessage, isBestValFunc func() bool,
) (op *searcher.ValidateAfter, err error) {
if msg.ValidationMetrics == nil {
return nil, errors.New("missing validation metrics")
}
hadSearcherValidation := s.hasSearcherValidation()
s.BatchesSinceLastVal = 0
if s.NeedInitialValidation {
s.NeedInitialValidation = false
}
if s.BatchesSinceLastCkpt != 0 {
switch s.checkpointPolicy {
case model.AllCheckpointPolicy:
s.NeedPostValidationCkpt = true
case model.BestCheckpointPolicy:
if isBestValFunc() {
s.NeedPostValidationCkpt = true
}
}
}
if s.BatchesSinceLastCkpt == 0 {
s.snapshotState()
}
if hadSearcherValidation {
return &s.ops[s.CurOpIdx-1], nil
}
return nil, nil
} |
Comparative Analyses of Universal Extraction Buffers for Assay of Stress Related Biochemical and Physiological Parameters
Comparative efficiency of three extraction solutions, including the universal sodium phosphate buffer (USPB), the Tris-HCl buffer (UTHB), and the specific buffers, were compared for assays of soluble protein, free proline, superoxide radical (), hydrogen peroxide (H2O2), and the antioxidant enzymes such as superoxide dismutase (SOD), catalase (CAT), guaiacol peroxidase (POD), ascorbate peroxidase (APX), glutathione peroxidase (GPX), and glutathione reductase (GR) in Populus deltoide. Significant differences for protein extraction were detected via sodium dodecyl sulfate polyacrylamide gel electrophoresis (SDS-PAGE) and two-dimensional electrophoresis (2-DE). Between the two universal extraction buffers, the USPB showed higher efficiency for extraction of soluble protein, CAT, GR, , GPX, SOD, and free proline, while the UTHB had higher efficiency for extraction of APX, POD, and H2O2. When compared with the specific buffers, the USPB showed higher extraction efficiency for measurement of soluble protein, CAT, GR, and , parallel extraction efficiency for GPX, SOD, free proline, and H2O2, and lower extraction efficiency for APX and POD, whereas the UTHB had higher extraction efficiency for measurement of POD and H2O2. Further comparisons proved that 100 mM USPB buffer showed the highest extraction efficiencies. These results indicated that USPB would be suitable and efficient for extraction of soluble protein, CAT, GR, GPX, SOD, H2O2, , and free proline. |
/**
* Utility pojo which will be used to examining the
*/
public class SchemaReferenceInfo {
@JsonDeserialize(as = SchemaReferenceImpl.class)
private SchemaReference schema;
/**
* Return the schema reference.
*
* @return Schema reference
*/
public SchemaReference getSchema() {
return schema;
}
/**
* Set the schema reference.
*
* @param schema
* Schema reference
* @return Fluent API
*/
public SchemaReferenceInfo setSchema(SchemaReference schema) {
this.schema = schema;
return this;
}
} |
HONG KONG (Reuters) - Simon Murray, adventurer and outspoken chairman of commodity trader Glencore (GLEN.L), is back in the spotlight, this time over his role as a director of Sino-Forest TRE.TO, whose shares have been hit by accusations of fraud.
Simon Murray is seen at Alliance Airport in Fort Worth, Texas, in this May 23, 2007 file photo. REUTERS/Mike Stone/Files
The company denies allegations made last week by a short seller and research group, Muddy Waters. Sino-Forest has said it may take defamation action and has hired a consultant and an independent committee to investigate the matter.
But shares in what was until recently one of the largest forestry companies on the Toronto exchange are down nearly 70 percent since Muddy Waters called the business model a ‘ponzi scheme’ that had exaggerated the value of its assets.
Whether or not the allegations prove to be true, the saga has put Murray back in the headlines, just weeks after his less-than-smooth appointment to the Glencore job and subsequent comments to a British paper about asylum seekers and women, which brought the commodities giant unwelcome attention.
Should there be any truth in Muddy Waters’ allegations, which include a claim that Sino-Forest overstated its Yunnan timber investments by $900 million, the finger pointing would aim at not just founder and Chairman Allen Chan, but the company’s board as well, which includes Murray.
“We have to wait to see who is shown to be correct but if Muddy Waters is proved right then it does raise questions about the board’s oversight,” said Jamie Allen, Secretary General of the Asian Corporate Governance Association.
Murray joined Sino-Forest in 1999, becoming an independent director. He is also a non-executive director and major shareholder in its subsidiary Greenheart Group (0094.HK), through his private equity fund GEMS (General Enterprise Management Services International).
“I first got to know him in 1995 when he was chairman of the Asia-Pacific branch of Deutsche Bank,” Chan was quoted as saying by the Globe & Mail newspaper.
“We were very small and we had a short-term loan facility with Deutsche Bank in Hong Kong. Simon was there at the signing ceremony when we signed for a very small loan. He was a very nice guy to support such a small company.”
A forestry official in Yunnan province indicated that Sino-Forest was a substantial player, though she did not clarify the size of the investment there.
“It’s not just one plot of land, they have many,” said an employee surnamed Chen at the Gengma autonomous region forestry administration office in Yunnan, near the border with Myanmar.
“They (the plantations) have been developed step by step, they acquired (the land) bit by bit,” she told Reuters by phone.
Sino Forest’s 2009 annual report cites Murray as one of the parties involved in a “significant” business transaction to acquire 60.3 percent of equity interests in Greenheart in 2007, with an option to acquire the remaining equity interests within 18 months after that.
There is no indication that Murray, as a director, was privy to any potentially sensitive business decisions. Chan told the Globe & Mail that Murray’s close support was vital to help Sino-Forest drum up credibility and investor interest.
“We became friends and when he set up his own fund he called me and said he would interested in investing in our company as a support. I think that was 1999,” Chan was quoted as saying.
Murray, a former Foreign Legionnaire and a close associate of Hong Kong tycoon Li Ka-shing, did not respond to attempts to reach him by email and telephone.
Glencore, which irked some investors by not confirming its appointment of Murray as chairman until eight hours after filing its intention to float, said it had confidence in its choice.
“We are happy with Simon Murray as our chairman,” a Glencore spokesman said. He declined to comment further on the saga, which comes just weeks after the giant commodities trading and mining group became a listed blue chip company in London and Hong Kong.
Murray’s credentials have already been questioned by some investors, and he is likely to face direct questioning at Glencore’s first quarter results next week, their first earnings release since the listing.
Chan, 58, a Hong Kong newspaper columnist and entrepreneur, started the company in the mid-1990s. The company is accused by Muddy Waters of widespread fraud including siphoning off funds and massively exaggerating assets including forestry investments in Yunnan by over $800 million.
Sino Forest dismissed the claims as “inaccurate, spurious and defamatory” while stressing its finances had been “thoroughly scrutinized” by auditor, Ernst & Young ERNY.UL.
Murray, a seasoned Asia hand, was paid HK$575,000 ($73,900) last year by Sino Forest to act as an independent director.
Sino-Forest counts some major North American funds as its investors, including one run by legendary hedge fund investor John Paulson.
($1 = 7.779 Hong Kong Dollars) |
#include "FWCore/Framework/interface/global/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DataFormats/SiStripCluster/interface/SiStripClusterTools.h"
#include "DataFormats/TrackerRecHit2D/interface/SiStripRecHit2DCollection.h"
#include "Geometry/Records/interface/TrackerTopologyRcd.h"
#include "TrackingTools/Records/interface/TransientRecHitRecord.h"
#include "RecoTracker/MkFit/interface/MkFitHitWrapper.h"
#include "RecoTracker/MkFit/interface/MkFitClusterIndexToHit.h"
#include "RecoTracker/MkFit/interface/MkFitGeometry.h"
#include "RecoTracker/Record/interface/TrackerRecoGeometryRecord.h"
#include "convertHits.h"
namespace {
class ConvertHitTraits {
public:
ConvertHitTraits(float minCharge) : minGoodStripCharge_(minCharge) {}
static constexpr bool applyCCC() { return true; }
static float clusterCharge(const SiStripRecHit2D& hit, DetId hitId) {
return siStripClusterTools::chargePerCM(hitId, hit.firstClusterRef().stripCluster());
}
bool passCCC(float charge) const { return charge > minGoodStripCharge_; }
static void setDetails(mkfit::Hit& mhit, const SiStripCluster& cluster, int shortId, float charge) {
mhit.setupAsStrip(shortId, charge, cluster.amplitudes().size());
}
private:
const float minGoodStripCharge_;
};
} // namespace
class MkFitSiStripHitConverter : public edm::global::EDProducer<> {
public:
explicit MkFitSiStripHitConverter(edm::ParameterSet const& iConfig);
~MkFitSiStripHitConverter() override = default;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void produce(edm::StreamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const override;
const edm::EDGetTokenT<SiStripRecHit2DCollection> stripRphiRecHitToken_;
const edm::EDGetTokenT<SiStripRecHit2DCollection> stripStereoRecHitToken_;
const edm::ESGetToken<TransientTrackingRecHitBuilder, TransientRecHitRecord> ttrhBuilderToken_;
const edm::ESGetToken<TrackerTopology, TrackerTopologyRcd> ttopoToken_;
const edm::ESGetToken<MkFitGeometry, TrackerRecoGeometryRecord> mkFitGeomToken_;
const edm::EDPutTokenT<MkFitHitWrapper> wrapperPutToken_;
const edm::EDPutTokenT<MkFitClusterIndexToHit> clusterIndexPutToken_;
const edm::EDPutTokenT<std::vector<float>> clusterChargePutToken_;
const ConvertHitTraits convertTraits_;
};
MkFitSiStripHitConverter::MkFitSiStripHitConverter(edm::ParameterSet const& iConfig)
: stripRphiRecHitToken_{consumes<SiStripRecHit2DCollection>(iConfig.getParameter<edm::InputTag>("rphiHits"))},
stripStereoRecHitToken_{consumes<SiStripRecHit2DCollection>(iConfig.getParameter<edm::InputTag>("stereoHits"))},
ttrhBuilderToken_{esConsumes<TransientTrackingRecHitBuilder, TransientRecHitRecord>(
iConfig.getParameter<edm::ESInputTag>("ttrhBuilder"))},
ttopoToken_{esConsumes<TrackerTopology, TrackerTopologyRcd>()},
mkFitGeomToken_{esConsumes<MkFitGeometry, TrackerRecoGeometryRecord>()},
wrapperPutToken_{produces<MkFitHitWrapper>()},
clusterIndexPutToken_{produces<MkFitClusterIndexToHit>()},
clusterChargePutToken_{produces<std::vector<float>>()},
convertTraits_{static_cast<float>(
iConfig.getParameter<edm::ParameterSet>("minGoodStripCharge").getParameter<double>("value"))} {}
void MkFitSiStripHitConverter::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.add("rphiHits", edm::InputTag{"siStripMatchedRecHits", "rphiRecHit"});
desc.add("stereoHits", edm::InputTag{"siStripMatchedRecHits", "stereoRecHit"});
desc.add("ttrhBuilder", edm::ESInputTag{"", "WithTrackAngle"});
edm::ParameterSetDescription descCCC;
descCCC.add<double>("value");
desc.add("minGoodStripCharge", descCCC);
descriptions.add("mkFitSiStripHitConverterDefault", desc);
}
void MkFitSiStripHitConverter::produce(edm::StreamID iID, edm::Event& iEvent, const edm::EventSetup& iSetup) const {
const auto& ttrhBuilder = iSetup.getData(ttrhBuilderToken_);
const auto& ttopo = iSetup.getData(ttopoToken_);
const auto& mkFitGeom = iSetup.getData(mkFitGeomToken_);
MkFitHitWrapper hitWrapper;
MkFitClusterIndexToHit clusterIndexToHit;
std::vector<float> clusterCharge;
auto convert = [&](auto& hits) {
return mkfit::convertHits(
convertTraits_, hits, hitWrapper.hits(), clusterIndexToHit.hits(), clusterCharge, ttopo, ttrhBuilder, mkFitGeom);
};
edm::ProductID stripClusterID;
const auto& stripRphiHits = iEvent.get(stripRphiRecHitToken_);
const auto& stripStereoHits = iEvent.get(stripStereoRecHitToken_);
if (not stripRphiHits.empty()) {
stripClusterID = convert(stripRphiHits);
}
if (not stripStereoHits.empty()) {
auto stripStereoClusterID = convert(stripStereoHits);
if (stripRphiHits.empty()) {
stripClusterID = stripStereoClusterID;
} else if (stripClusterID != stripStereoClusterID) {
throw cms::Exception("LogicError") << "Encountered different cluster ProductIDs for strip RPhi hits ("
<< stripClusterID << ") and stereo (" << stripStereoClusterID << ")";
}
}
hitWrapper.setClustersID(stripClusterID);
iEvent.emplace(wrapperPutToken_, std::move(hitWrapper));
iEvent.emplace(clusterIndexPutToken_, std::move(clusterIndexToHit));
iEvent.emplace(clusterChargePutToken_, std::move(clusterCharge));
}
DEFINE_FWK_MODULE(MkFitSiStripHitConverter);
|
Developmental Immaturity of Siglec Receptor Expression on Neonatal Alveolar Macrophages Predisposes to Severe Group B Streptococcal Infection
Summary Streptococcus agalactiae (Group B Streptococcus, GBS) is the most common neonatal pathogen. However, the cellular and molecular mechanisms for neonatal susceptibility to GBS pneumonia and sepsis are incompletely understood. Here we optimized a mouse model of GBS pneumonia to test the role of alveolar macrophage (ΑΜΦ) maturation in host vulnerability to disease. Compared with juvenile and adult mice, neonatal mice infected with GBS had increased mortality and persistence of lung injury. In addition, neonatal mice were defective in GBS phagocytosis and killing. ΑΜΦ depletion and disruption of ΑΜΦ differentiation in Csf2−/− mice both impaired GBS clearance. AMΦ engage the heavily sialylated GBS capsule via the cell surface Siglec receptors Sn and Siglec-E. Although both newborn and adult ΑΜΦ expressed Siglec-E, newborn ΑΜΦ expressed significantly lower levels of Sn. We propose that a developmental delay in Sn expression on ΑΜΦ may prevent effective killing and clearing of GBS from the newborn lung.
INTRODUCTION
The encapsulated gram-positive bacterium Streptococcus agalactiae (group B Streptococcus, GBS) remains a potentially devastating neonatal pathogen. Globally, GBS colonizes the vaginal or rectal epithelium of an estimated 21.7 million pregnant women . The leading infectious cause of neonatal mortality, GBS, is estimated to cause 150,000 newborn deaths worldwide each year Seale et al., 2017). Infants are exposed to GBS during passage through the birth canal or via ascending infection through the amniotic membranes. GBS neonatal disease is commonly classified as early-onset (<7 days of age) or late-onset disease (7 days-6 months of age) (Baker and Barrett, 1973;Franciosi et al., 1973;Horn et al., 1974;Randis et al., 2017). In the majority of cases of early-onset disease, newborns aspirate contaminated amniotic or vaginal fluid, developing clinical signs of pneumonia, lung injury, and sepsis within the first few hours of life. In contrast, lateonset GBS infections tend to present days later with bacteremia and a high risk of meningitis (Raabe and Shane, 2019). Serious GBS infections in otherwise healthy older children and adults are rare, although non-pulmonary invasive disease is increasingly reported in individuals with lowered immunity such as the elderly, pregnant women, and those with diabetes or cancer (Pitts et al., 2018;Skoff et al., 2009).
In this study, we sought a mechanistic understanding of the unique susceptibility of the newborn infant to severe invasive GBS infection initiated through the lung portal of entry. Normally, multiple cell populations serve to protect the lung from infection and injury. Epithelial cells secrete surfactant and antimicrobial peptides capable of killing and/or inactivating inhaled microbes (Weitnauer et al., 2016;Whitsett and Alenghat, 2015). In addition, mucociliary clearance captures and removes particulates and infectious agents (Fliegauf et al., 2013). The major resident immune cells protecting the lung from inhaled pathogens are alveolar macrophages (AMFs). Present throughout life, AMFs can phagocytose and kill microbes, release inflammatory mediators, recruit additional immune cells including neutrophils, and participate in tissue repair following injury (Allard et al., 2018;Byrne et al., 2015;Kopf et al., 2015). AMF differentiation in the postnatal lung is
Increased Mortality and Persistence of Lung Injury in Neonatal GBS Infection
Despite being the most common cause of neonatal pneumonia, the molecular and cellular mechanisms responsible for the unique susceptibility of newborns to GBS remain unclear. To investigate key host-pathogen interactions in the newborn period, we developed and employed a murine model of GBS neonatal pneumonia (see Transparent Methods). Newborn C57BL/6 mice were lightly anesthetized and intranasally inoculated with 28,000 CFU/g of wild-type (WT) GBS (serotype III strain COH1). Control mice were similarly anesthetized and received an identical volume of sterile, endotoxin-free saline. For comparison, we also infected juvenile (PND7) and adult (8-week-old) mice with a comparable weight-based GBS inoculum. Adult and juvenile mice universally survived infection ( Figure 1A). However, in neonatal mice, over 20% of GBS-infected animals died within 2 days. We did not observe additional deaths in any group between days 2 and 7.
We cultured GBS from infected lungs to compare bacterial clearance between neonatal, juvenile, and adult mice ( Figure 1B). Adult mice did have viable GBS bacterial CFUs in their lungs 1 day after infection but no GBS when measured at day 3. Two adult mice did have rare detectable GBS on day 7 after infection. Juvenile and neonatal mouse lungs contained viable GBS when measured both 1 and 3 days after infection. We next measured temporal changes in lung pathology following GBS infection. All ages of mice infected with GBS developed histological signs of significant acute lung injury 1 day following infection (Figures 1C and 1D). However, adult mice infected with GBS showed rapid histological improvement by day 3 and complete resolution by day 7. By comparison, abnormal pathology in GBS-infected juvenile mice persisted to day 3 with resolution by day 7. Pathology in GBS-infected neonatal mice was even more persistent, with no improvement as late as 7 days post infection. Our GBS infection model therefore replicates the clinical scenario of early-onset GBS disease, which includes severe pneumonia, lung injury, and death specifically in neonates. In addition, these initial experiments suggest neonates have defects related to clearance of GBS and resolution of lung injury.
Delayed Kinetics of Lung Inflammation and GBS Clearance by Alveolar Macrophages in Neonatal GBS Pneumonia
The very distinct differences in GBS clearance and resolution of lung pathology between newborn and adult mice suggested potential differences in the lung immune response and inflammatory signaling. To initially test the innate immune response to GBS, we measured expression of pro-inflammatory mediators Il1b, Il6, and Cxcl1 in the first 24 h following GBS infection. Adult mice had elevated levels of each inflammatory mediator during the 2-to 12-h time window following GBS infection; however, expression levels of the factors fell back to baseline by 24 h (Figure 2A). By contrast in neonatal mice, expression of Il1b, Il6, and Cxcl1 did not increase until 24 h after GBS infection ( Figure 2B), revealing a delayed inflammatory response in neonatal mouse lungs compared with adults. Adult lungs had a rapid influx of additional CD68+ macrophages and monocytes into the lung 12-24 h after GBS inoculation; however, neonatal lungs did not show such an accumulation of CD68+ cells 24 h after infection ( Figure 2C). This finding corresponded to the delay in the upregulation of key inflammatory mediators and chemoattractants. Thus the neonatal lung immune All mice were given 28,000 CFU/g body weight of GBS. Neonatal mice (red) were infected within 24 h of delivery, juvenile mice (blue) were infected on day 7 of life, adult mice (black) were 6-8 weeks of age at infection. GBS-infected animals are shown with solid lines. Controls (dashed lines) were given identical anesthesia but intranasal sterile saline. ***p < 0.005 using the Mantel-Cox test (n = 15-29).
(C) Representative H&E-stained sections obtained from mouse lungs 1, 3, and 7 days after GBS infection demonstrates initial lung injury and inflammation in all mice, with differential resolution by day 7. Scale bar, 100 mm.
(D) Neonatal mice displayed persistence of lung pathology following GBS infection. Lung pathology scoring was performed by three independent, blinded reviewers. Each experimental group included four to six animals with three representative images taken in a systematic method from each animal for a total of 12-18 images per group. The box is bound by the 25 th and 75 th percentile; the middle line represents the median value. The whiskers represent the minimum and maximum values. *p < 0.05, **p < 0.01, ***p < 0.005, ****p < 0.001 using one-way ANOVA. iScience Article response to GBS pneumonia is delayed, both in terms of inflammatory mediator production and the accumulation of CD68+ myeloid cells.
We next tested if the delayed inflammatory response in neonates impaired GBS clearance by measuring viable GBS throughout the first 24 h following infection ( Figure 2D). In adult lungs, the number of GBS CFU recovered fell steadily over the first 24 h. Juveniles had less dramatic but still significant reductions in CFU by 24 h. However, neonatal mice were not able to reduce GBS CFU counts during the first 24 h following infection, consistent with an inherent defect in killing GBS during the newborn transition. These findings suggested that early in the disease process in vivo, neonatal AMF lacked the ability to phagocytose and kill GBS. As juvenile mice achieved partial GBS clearance to prevent persistent lung pathology, we more closely examined how long the window of susceptibility to GBS persisted in newborn mice. For these experiments, mice were infected with a higher inoculum of intranasal GBS on days 1, 2, or 3 of life ( Figure 2E). Survival depended on day of infection, and 50% of mice infected on day 1 died within the first 24 h. Mice infected on day 2 survived the initial acute period but suffered late mortality between days 11 and 14. In contrast, all mice infected on day 3 of life survived for at least 21 days. When survivors were sacrificed 21 days following infection, we detected significant intrapulmonary GBS only in mice infected on day 1. In subsets of mice infected on day 1 but surviving until day 21, GBS had also spread to the spleen. These findings suggested that mice infected with GBS within the first day of life have reduced survival and lack the ability to adequately clear GBS in the lung and prevent systemic dissemination of the pathogen. Newborn mice apparently acquire the ability to control GBS and protect against devastating infection within the first several days of life.
Confocal microscopy identified potential differences in cellular interactions following GBS infection (Figure 2F). In adult lungs, CD68+ AMF localized to the sites of GBS infection within the first 2 h. By 12-24 h, the majority of GBS visualized in adult lungs were inside CD68+ macrophages, consistent with active phagocytosis. These data correlated with CFU kinetics, where the vast majority of viable GBS were cleared from adult lungs within 24 h after infection. In juvenile lungs, AMFs accumulated around the sites of GBS infection within the first few hours, and some AMFs were seen to phagocytose GBS. However, by 24 h after infection, substantial quantities of noninternalized GBS were still observed throughout the lung parenchyma, even in areas of AMF accumulation. We documented a very different pattern in neonatal lungs. GBS were distributed throughout the lung but also occasionally accumulated in small masses within the airways. AMF in these regions surrounded the GBS, but with very little evidence of phagocytic uptake. These data were consistent with CFU data showing lack of significant GBS clearance in neonatal lungs over the first 24 h following infection.
Mature AMFs Are Required for Rapid GBS Clearance
In the lung, AMFs provide the major initial response to inhaled or aspirated microbial pathogens. In adults, inflammatory stimuli or lung injury increase expression of CD11b on fully differentiated, Siglec-F+ AMFs (Duan et al., 2012(Duan et al., , 2016. We measured a similar increase in CD11b expression on adult Siglec-F+ AMF beginning on the first day after GBS infection with return to baseline levels by day 7 (Figures 3A and S1). Juvenile AMF also increased CD11b on day 3 after GBS infection. However, AMF in GBS-infected neonatal mice, which did not express Siglec-F until day 3 of life, also did not show a measurable increase in CD11b expression. Therefore, although GBS infection did not interfere with AMF acquisition of Siglec-F expression, immature AMF within the neonatal lung did not display the same changes in differentiation marker expression as adult cells.
We hypothesized that AMF maturity determined either protection against GBS in adults or susceptibility to GBS in neonates. To initially test the requirement of mature AMF, we depleted AMF from adult mice using liposomal clodronate prior to GBS infection. Intranasal administration of clodronate liposomes reduced the number CD11c+Siglec-F+ AMF ( Figures 3B and S2). We then infected both clodronate-treated adult mice and controls treated with empty liposomes. By 24 h after GBS infection, confocal imaging of clodronate-treated mice infected with GBS did demonstrate small, CD68lo monocytic cells in the lung after GBS infection, but these cells were not efficient at phagocytosing bacteria ( Figure 3C). Clodronate-treated iScience Article adults had significantly higher GBS CFU recovered from the lungs compared with control adults ( Figure 3D). Consistent with the requirement of AMF maturation, newborn Csf2À/À mice, which lack fully differentiated AMF (Guilliams et al., 2013;Shibata et al., 2001), had higher levels of GBS within their lungs 24 h after infection ( Figures 3E and 3F).
Developmental Maturation of Lung Myeloid Siglec Expression
The heavily sialylated capsule of GBS contributes to bacterial virulence. In hosts, the sialic acid-binding immunoglobulin-type lectins Siglec-1 (sialoadhesin, Sn) and Siglec-E both bind GBS sialic acid moieties (Chang et al., 2014a(Chang et al., , 2014b. GBS sialic acid binding to Siglec-E reduces the proinflammatory innate immune response to GBS (Chang et al., 2014a). In adult mice, Sn mediates GBS phagocytosis and killing (Chang et al., 2014b). Given the dramatic defects we measured in neonatal mouse lung macrophages, we next examined the developmental dynamics of Siglec-E and Sn expression in lung myeloid populations by FACS (Figure 4; Table S1). In adult lungs, Sn expression was detected in AMF (both CD11b hi and CD11b lo ) and in recently described CD11c neg nerve and airway-associated macrophages (NAMFs ; Figures 4A and S3). Adult neutrophils (PMNs) and interstitial macrophage/monocyte and dendritic cell populations (IM and IM/DC) were Sn-negative. Siglec-E expression was slightly more widespread in adults, being expressed in AMFs, NAMFs, neutrophils, and to a lower level in CD11c + IM/DC cells. Sn and Siglec-E expression in juvenile lung myeloid cells closely resembled the patterns observed in adults ( Figure 4B). The neonatal lung contains PMN, IM, and developing AMF populations ( Figure 4C). Sn expression was only detected in AMF, whereas Siglec-E was measured in all populations. Overlaying FACS detection of Sn and Siglec-E in all CD45 + cells ( Figures 4D and 4E) and all F4/80 + CD11b + macrophages ( Figures 4F and 4G) illustrated the reduced Sn expression in the neonatal lung compared with juveniles and adults. However, expression of the inhibitory Siglec-E was similar across all three timepoints tested.
Developmental Immaturity of AMF Siglec-Sialic Acid Detection Contributes to Neonatal GBS Susceptibility
We further investigated the potential contribution of developmental immaturity of Sia receptor expression in neonatal lungs to the inability to rapidly clear GBS. Real-time PCR and immunostaining demonstrated consistently lower Sn expression in newborn mouse lungs ( Figures 5A and 5B). We then leveraged a recently completed study examining gene expression in preterm infant tracheal aspirate macrophages to test the dynamics of Sn expression in humans. Samples obtained on the first day of life had lower hSI-GLEC1 (Sn) compared with samples obtained on day 7 ( Figure 5C). Expression of SIGLEC9 (the human paralog of Siglec-E) was similar at these two timepoints. We next tested if deletion of the inhibitory Siglec-E could remove a potential defect in GBS killing. In adult mice (which express high levels of Sn), Siglec-E deletion had no effect on GBS killing ( Figures 5D and 5E). However, newborn SigE À/À mice showed improved GBS killing compared with WT controls with fewer colonies of bacteria isolated from the lungs 24 h after infection ( Figure 5F). Confocal microscopy identified increased GBS phagocytosis in newborn SigE À/À lungs compared with controls ( Figure 5G). Therefore, removal of the inhibitory Siglec-E improved GBS phagocytosis and killing by neonatal AMF even in the setting low Sn expression. In Csf2 À/À mice that iScience Article lack normal AMF differentiation, we detected even lower neonatal Sn expression on lung macrophages compared with WT neonatal mice ( Figure 5H). Adult Csf2 À/À AMF lacked Siglec-E expression, whereas expression in neonates was similar ( Figure 5I). Therefore, in both mice and humans, immature newborn AMF have adult levels of the inhibitory receptor Siglec-E but lack expression of Sn. Alterations of the (F and G) GBS killing is increased in neonatal SigE À/À mice. (F) Compared with WT controls, neonatal SigE À/À mice had reduced CFU recovered from lung 24 h after GBS infection. Data are represented as mean G SEM. **p < 0.005 using Mann-Whitney U test (n = 10 for WT, n = 24 for SigE À/À ). (G) Confocal immunofluorescent micrographs demonstrated reduced GBS overall (red) and increased GBS phagocytosis by CD68 + cells in SigE À/À neonatal mouse lungs 24 h after infection. Images are representative of three independent experimental replicates. Scale bar, 25 mm. iScience Article GBS capsule to eliminate sialic acid also improved clearance in the neonatal lung. We infected mice with GBS strains bearing mutations in genes critical for either sialic acid modification (DneuA) or capsule formation (DcpsD). Although clearance in adults was similar to WT GBS ( Figures 5J and 5K), newborn mice showed improved phagocytosis and killing of both DneuA and DcpsD strains ( Figures 5L and 5M), confirming that the sialic acid-rich GBS capsule is a key virulence factor in the neonatal lung.
DISCUSSION
We corroborated the unique susceptibility of newborns to GBS pneumonia using a novel murine model. Similar to the pathogenesis of GBS pneumonia in human newborns, infected neonatal mice fail to clear intrapulmonary GBS, develop persistent lung injury, and suffer increased mortality compared with older mice and adults. The window of susceptibility appears restricted to the newborn period, since even 2-to 3-day-old mice have much better outcomes compared with mice infected on the first day of life. As in humans, adult mice are resistant to GBS lung infection, quickly clearing bacteria within the lung and completely resolving any signs of lung injury or pathology. Interestingly, the primary immune defect in newborn mice may lie in the inability of AMFs to effectively phagocytose and kill GBS within the lung. GBS persisted in a subpopulation of animals infected at birth, leading to bacteremia, and spread to the central nervous system. Neonatal mice did, however, mount an inflammatory immune response to GBS, albeit with altered kinetics compared with juvenile and adult animals. In addition to a delayed initiation of lung inflammation, neonatal mice had persistent lung injury up to 1 week after infection. Although many functional aspects of the lung immune system may be underdeveloped at birth, our data point to immaturity of lung AMFs as particularly important in rendering the newborn susceptible to disease.
Like many human pathogens, GBS expresses a variety of virulence factors to subvert host immune detection and killing and/or promote cellular damage (Bebien et al., 2012;Doran et al., 2002). However, the same GBS strains that asymptomatically colonize adults can cause devastating disease in newborns. We hypothesized that the neonatal window of susceptibility is primarily due to defective maturation of host pulmonary innate immunity. In addition to AMF function, lung immunity includes antimicrobial peptides, surfactant, mechanical mucus clearance, resident lymphocyte and dendritic cell function, and neutrophil influx (Evans et al., 2010;Lambert and Culley, 2017;Nicod, 2005). Although our data here do not discount important contributions of these or any other mechanisms, rapid GBS clearance was impaired in mice depleted of AMFs and in Csf2 À/À mice that lack mature AMFs. Our data also clearly demonstrated that neonatal AMFs lack sufficient expression of Sn for effective detection, phagocytosis, and killing of sialylated GBS. We propose that this neonatal immaturity might allow persistent GBS lung infection in some newborns, significantly increasing the risk of systemic spread to produce bacteremia, sepsis, and meningitis.
Multiple immune cell populations within the lung respond to serious bacterial infection and likely contribute to the subsequent repair process. Developmental immaturity of these cell populations therefore contributes to infectious disease risk and pathogenesis in newborns. Our data reinforce the paradigm of incomplete lung myeloid cell differentiation at birth with identification of key contributing lectin-glycan interactions and associated receptor signaling pathways. Sn-expressing NAMF populations were present at low numbers in juvenile mice and not detected in newborns. Different populations of IM and DC were also difficult to identify in newborn mouse lungs, potentially owing to their incomplete differentiation. Although we conclude that neonatal GBS susceptibility is significantly impacted by AMF immaturity, additional immune development defects also make the newborn particularly vulnerable.
Our findings suggest potential new opportunities for protecting newborns from infection. In addition to antimicrobial treatment of both mothers and newborns at risk of serious infection (Boyer and Gotoff, 1986), strategies aimed at improving or accelerating AMF maturation could provide protection against GBS. Specifically, identifying ways to improve GBS killing by the immature AMFs found in the newborn lung could mitigate against both early-onset pneumonia and the risk of late-onset sepsis and meningitis. The inflammatory response in adult and newborn lungs also appears to follow a very different time course after GBS infection. AMFs detect GBS via multiple pattern recognition receptors, including the TLR family members TLR2, TLR6, TLR7, TLR8/13, and TLR9 (Henneke et al., 2001(Henneke et al., , 2002Talati et al., 2008). Importantly, both neonatal and adult AMFs expressed Siglec-E, which engages the repeated a2-3 sialic acid motif of the GBS capsule and attenuates innate immune signaling via SHP-1/2-mediated TBK1 inhibition (Chang et al., 2014a). Therefore, neonatal Siglec-E expression may suppress GBS-mediated immune signaling and cytokine production until other pathways are engaged or Sn expression increases. As pro-inflammatory signals are also required for initiating an anti-inflammatory host response, additional experimental ll OPEN ACCESS iScience 23, 101207, June 26, 2020 iScience Article studies will be required to determine if targeting specific components of immune signaling will prove beneficial or harmful in the setting of neonatal GBS infection. Murine experimental models like the one developed here may therefore prove invaluable for testing potential therapeutic strategies and interventions.
Limitations of the Study
In humans, newborns first encounter GBS either through ascending infection following amniotic membrane rupture or aspiration of GBS during the birth process. Although GBS colonization of the maternal urinary tract and vaginal canal have been modeled in mice (Andrade et al., 2018), direct inoculation of mice with defined and consistent numbers of GBS allowed us to test the relative impact of infection on the first day of life and during the postnatal period. We expected some variability in any pneumonia model, especially when using a noninvasive approach to infect newborn mice. However, our data support the use of this model in reliably and reproducibly modeling neonatal infection. Given these potential caveats, our data strongly support the primary role of AMFs in providing immunity against GBS in adult lungs and demonstrate how AMF immaturity leads to defects in GBS clearance.
Resource Availability Lead Contact
Further information and requests for resources and reagents should be directed to and will be fulfilled by the Lead Contact, Lawrence S. Prince ([email protected]).
Materials Availability
Mouse strains used in this study are available from Jackson Laboratories and Envigo. Unique bacterial strains and reagents used in this study are available from the Lead Contact and may require a Materials Transfer Agreement.
Data and Code Availability
The human preterm infant lung macrophage dataset included in Figure 5 is available through the Gene Expression Omnibus (GSE149490).
METHODS
All methods can be found in the accompanying Transparent Methods supplemental file.
DECLARATION OF INTERESTS
The authors declare no competing interests with the results of this study. |
import { HttpClient } from '@angular/common/http';
import { EventEmitter, Injectable } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { Observable } from 'rxjs';
import { AdminInterno } from 'src/app/shared/model/adminInterno';
import { CustomFilter } from 'src/app/shared/model/support/custom-filter';
import { CustomRepository } from 'src/app/shared/repository/custom-repository';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class AdminInternoService implements CustomRepository<AdminInterno, number> {
url = environment.API;
findValueParam = new EventEmitter<string>();
onChangeContextTitle = new EventEmitter<string>();
findValueParamFromServer = new EventEmitter<CustomFilter>();
findValueParams = new EventEmitter<CustomFilter>();
onChangeContext = new EventEmitter<boolean>();
emitOnDetalheButtonCliked = new EventEmitter<number>();
emitOnEditButtonCliked = new EventEmitter<number>();
emitOnDeleteButtonCliked = new EventEmitter<number>();
AdminInternoTable: MatTableDataSource<AdminInterno[]>;
constructor(private http: HttpClient) {
}
getById(id: number): Observable<AdminInterno> {
return this.http.get<AdminInterno>(`${this.url}/admin/adminInterno/${id}`);
}
list(): Observable<AdminInterno[]> {
return this.http.get<AdminInterno[]>(`${this.url}/admin/adminInterno`);
}
filterByNomeSexo(filterParam: CustomFilter): Observable<AdminInterno[]> {
filterParam = this.filterResolve(filterParam);
return this.http
.get<AdminInterno[]>(`${this.url}/admin/adminInterno?nome=${filterParam.nome}&sexo=${filterParam.sexo}`);
}
filterBySexoAndEspecialidade(filterParam: CustomFilter): Observable<AdminInterno[]> {
filterParam = this.filterResolve(filterParam);
return this.http
.get<AdminInterno[]>(`${this.url}/admin/adminInterno?sexo=${filterParam.sexo}`);
}
save(t: AdminInterno): Observable<AdminInterno> {
if (t.id) {
return this.http.put<AdminInterno>(`${this.url}/admin/adminInterno`, t);
}
return this.http.post<AdminInterno>(`${this.url}/admin/adminInterno`, t);
}
deleteById(id: number): Observable<void> {
return this.http.delete<void>(`${this.url}/admin/adminInterno/${id}`);
}
filterResolve(filterParam: CustomFilter): CustomFilter {
filterParam.nome = filterParam.nome === undefined ? '' : filterParam.nome;
filterParam.sexo = filterParam.sexo === undefined ? '' : filterParam.sexo;
filterParam.descricao = filterParam.descricao === undefined ? '' : filterParam.descricao;
return filterParam;
}
}
|
/*---------------------------------------------------------------------*
* Tinyusb FatFs module reads image file data
*---------------------------------------------------------------------
*/
bool file_system_mount(uint8_t dev_addr)
{
char *filename;
char logic_drv_num[10] = {0};
uint8_t phy_disk = dev_addr - 1;
UINT cnt = 0;
disk_initialize(phy_disk);
if (disk_is_ready(phy_disk)){
sprintf(logic_drv_num, "%d", phy_disk);
if (f_mount(&fatfs[phy_disk], _T(logic_drv_num), 0) != FR_OK){
printf("FatFs mount failed!\n");
return false;
}
else{
printf("FatFs mount succeeded!\n");
}
f_chdrive(logic_drv_num);
f_chdir("/");
#if defined DECOMPRESS_MODE
filename = f_scan("/");
if (f_open(&file, filename, FA_OPEN_ALWAYS | FA_READ) == FR_OK){
printf("The %s is open.\n", filename);
f_read(&file, filebuff, FILEBUFFLEN, &cnt);
f_close(&file);
jpg_size= cnt;
usbtask = true;
}
#elif defined COMPRESS_MODE
f_scan("/");
filename = "Camera.jpg";
if (f_open(&file, filename, FA_OPEN_ALWAYS | FA_WRITE) == FR_OK){
printf("The %s is open.\n", filename);
for (int32_t fl = 0; fl < jpg_size; fl++){
f_write(&file, (uint8_t *)(filebuff + fl), 1, &cnt);
}
f_scan("/");
f_close(&file);
jpg_size = 0;
usbtask = true;
}
#endif
else{
printf("Can't Open the %s file!\n", filename);
}
}
return true;
} |
/**
* Checks if a given CC specifier file can be used to produce an instance of CC. Returns
* <code>true</code>, if a CC can be instantiated, <code>false</code> otherwise.
*
* @param specifier
* the resource specifier
* @param resource_manager
* a new resource_manager
* @param status
* the place where to put the results
*
* @throws IOException
* If an I/O exception occurred while creating <code>XMLInputSource</code>.
* @throws InvalidXMLException
* If the XML parser failed to parse the given input file.
* @throws ResourceInitializationException
* If the specified CC cannot be instantiated.
*/
private void testCasConsumer(ResourceSpecifier specifier, ResourceManager resource_manager,
TestStatus status)
throws IOException, InvalidXMLException, ResourceInitializationException {
CasConsumer cc = UIMAFramework.produceCasConsumer(specifier, resource_manager, null);
if (cc != null) {
status.setRetCode(TestStatus.TEST_SUCCESSFUL);
} else {
status.setRetCode(TestStatus.TEST_NOT_SUCCESSFUL);
status.setMessage(I18nUtil.localizeMessage(PEAR_MESSAGE_RESOURCE_BUNDLE,
"installation_verification_cc_not_created",
new Object[] { this.pkgBrowser.getInstallationDescriptor().getMainComponentId() },
null));
}
} |
/**
* Check if a given number is a prime number.
* This means that for a number {@code n},
* there does not exist a number {@code a} such that
* {@code a < n} and {@code n % a = 0}, except for {@code a = 1}.
*
* @name Is Prime
* @type CONDITION
* @pattern %numbers% (is|are)[ not|n't] [a] prime [number[s]]
* @since ALPHA
* @author Mwexim
*/
public class CondExprIsPrime extends PropertyConditional<Number> {
static {
Parser.getMainRegistration().newPropertyConditional(CondExprIsPrime.class, "numbers", ConditionalType.BE, "[a] prime [number[s]]")
.addData(PROPERTY_IDENTIFIER, "prime")
.register();
}
@Override
public boolean check(Number performer) {
var bd = BigDecimalMath.getBigDecimal(performer);
return bd.signum() != -1
&& BigDecimalMath.isIntValue(bd)
&& NumberMath.isPrime(BigDecimalMath.getBigInteger(bd));
}
} |
package internal
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"net"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/prestonvanloon/go-recaptcha"
faucetpb "github.com/rauljordan/eth-faucet/proto/faucet"
gateway "github.com/rauljordan/minimal-grpc-gateway"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var (
log = logrus.WithField("prefix", "server")
)
// Config for the faucet server.
type Config struct {
GrpcPort int `mapstructure:"grpc-port"`
GrpcHost string `mapstructure:"grpc-host"`
HttpPort int `mapstructure:"http-port"`
HttpHost string `mapstructure:"http-host"`
AllowedOrigins []string `mapstructure:"allowed-origins"`
CaptchaHost string `mapstructure:"captcha-host"`
CaptchaSecret string `mapstructure:"captcha-secret"`
CaptchaMinScore float64 `mapstructure:"captcha-min-score"`
Web3Provider string `mapstructure:"web3-provider"`
PrivateKey string `mapstructure:"private-key"`
FundingAmount string `mapstructure:"funding-amount"`
GasLimit uint64 `mapstructure:"gas-limit"`
IpLimitPerAddress int `mapstructure:"ip-limit-per-address"`
ChainId int64 `mapstructure:"chain-id"`
}
// Server capable of funding requests for faucet ETH via gRPC and REST HTTP.
type Server struct {
faucetpb.UnimplementedFaucetServer
cfg *Config
captcha recaptcha.Recaptcha
client *ethclient.Client
funder common.Address
pk *ecdsa.PrivateKey
fundingAmount *big.Int
rateLimiter rateLimiter
}
// NewServer initializes the server from configuration values.
func NewServer(cfg *Config) (*Server, error) {
privKeyHex := cfg.PrivateKey
if strings.HasPrefix(privKeyHex, "0x") {
privKeyHex = privKeyHex[2:]
}
pk, err := crypto.HexToECDSA(privKeyHex)
if err != nil {
return nil, fmt.Errorf("could not parse funder private key: %v", err)
}
fundingAmount, ok := new(big.Int).SetString(cfg.FundingAmount, 10)
if !ok {
return nil, errors.New("could not set funding amount")
}
client, err := ethclient.DialContext(context.Background(), cfg.Web3Provider)
if err != nil {
return nil, fmt.Errorf("could not dial %s: %w", cfg.Web3Provider, err)
}
funder := crypto.PubkeyToAddress(pk.PublicKey)
return &Server{
cfg: cfg,
client: client,
funder: funder,
captcha: recaptcha.Recaptcha{RecaptchaPrivateKey: cfg.CaptchaSecret},
pk: pk,
fundingAmount: fundingAmount,
rateLimiter: newSimpleRateLimiter(cfg.IpLimitPerAddress),
}, nil
}
// Start a faucet server by serving a gRPC connection, an http JSON server, and a rate limiter.
func (s *Server) Start() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
runtime.GOMAXPROCS(runtime.NumCPU())
log.WithFields(logrus.Fields{
"chainID": s.cfg.ChainId,
}).Info("Initializing faucet server")
// Query the funds left in the funder's account.
s.queryFundsLeft(ctx)
// Initialize and register gRPC handlers.
grpcServer := s.initializeGRPCServer()
grpcAddress := fmt.Sprintf("%s:%d", s.cfg.GrpcHost, s.cfg.GrpcPort)
// Start a gRPC server.
go func() {
log.Infof("Starting gRPC server %s", grpcAddress)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", s.cfg.GrpcPort))
if err != nil {
log.WithError(err).Fatalf("Could not listen on port %d", s.cfg.GrpcPort)
}
if err := grpcServer.Serve(lis); err != nil {
log.WithError(err).Fatal("Stopped server")
}
}()
// Check IP addresses and reset their max request count over time.
go s.rateLimiter.refreshLimits(ctx)
// Start a gRPC Gateway to serve http JSON requests.
gatewayAddress := fmt.Sprintf("%s:%d", s.cfg.HttpHost, s.cfg.HttpPort)
gatewaySrv := gateway.New(ctx, &gateway.Config{
GatewayAddress: gatewayAddress,
RemoteAddress: grpcAddress,
AllowedOrigins: s.cfg.AllowedOrigins,
EndpointsToRegister: []gateway.RegistrationFunc{faucetpb.RegisterFaucetHandlerFromEndpoint},
})
log.Infof("Starting JSON http server %s", gatewayAddress)
gatewaySrv.Start()
// Listen for any process interrupts.
stop := make(chan struct{})
go func() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigc)
<-sigc
logrus.Info("Got interrupt, shutting down...")
grpcServer.GracefulStop()
stop <- struct{}{}
}()
// Wait for stop channel to be closed.
<-stop
}
// Query the funds left in the faucet account and log them to the uer.
func (s *Server) queryFundsLeft(ctx context.Context) {
bal, err := s.client.BalanceAt(ctx, s.funder, nil)
if err != nil {
log.WithError(err).Fatalf("Could not retrieve funder's current balance")
}
log.WithFields(logrus.Fields{
"fundsInWei": bal,
"publicKey": s.funder.Hex(),
}).Info("Funder account details")
}
// Initialize a gRPC server and register handlers.
func (s *Server) initializeGRPCServer() *grpc.Server {
grpcServer := grpc.NewServer()
faucetpb.RegisterFaucetServer(grpcServer, s)
reflection.Register(grpcServer)
return grpcServer
}
|
#pragma once
#include "D3D9VTable.h"
#include "CUpscaler.h"
#include "Win32Ex.h"
#define SIMULATE_LOST_DEVICE 0
#define LOST_DEVICE_TEST 0
#define NO_DEVICE_HOOK 0
extern CRITICAL_SECTION d3d9CriticalSection;
class CriticalSectionLock
{
LPCRITICAL_SECTION criticalSection;
public:
CriticalSectionLock(LPCRITICAL_SECTION criticalSection)
{
this->criticalSection = criticalSection;
EnterCriticalSection(criticalSection);
}
~CriticalSectionLock()
{
LeaveCriticalSection(criticalSection);
}
};
class D3D9Context2;
class D3D9DeviceContext;
class D3D9SwapChainContext;
extern D3D9Context2* GetD3D9Context(IDirect3D9* key, bool allocate = false);
extern D3D9Context2* GetD3D9Context();
extern void RemoveD3D9Context(IDirect3D9* key);
extern D3D9DeviceContext* GetD3D9DeviceContext(IDirect3DDevice9* key, bool allocate = false);
extern D3D9DeviceContext* GetD3D9DeviceContext();
extern void RemoveD3D9DeviceContext(IDirect3DDevice9* key);
extern D3D9SwapChainContext* GetD3D9SwapChainContext(IDirect3DSwapChain9* key, bool allocate = false);
extern D3D9SwapChainContext* GetD3D9SwapChainContext();
extern void RemoveD3D9SwapChainContext(IDirect3DSwapChain9* key);
bool SwapChainContextExists(IDirect3DSwapChain9* key);
void RemoveD3D9DisposedObjects();
extern IDirect3D9ExVtbl* GetOriginalVTable(IDirect3D9* d3d9, bool allocate = false);
extern IDirect3DDevice9ExVtbl* GetOriginalVTable(IDirect3DDevice9* device, bool allocate = false);
extern IDirect3DSwapChain9ExVtbl* GetOriginalVTable(IDirect3DSwapChain9* swapChain, bool allocate = false);
//extern IDirect3D9ExVtbl* GetNewVTable(IDirect3D9* d3d9);
//extern IDirect3DDevice9ExVtbl* GetNewVTable(IDirect3DDevice9* device);
//extern IDirect3DSwapChain9ExVtbl* GetNewVTable(IDirect3DSwapChain9* swapChain);
//extern void AssignVTable(IDirect3D9* d3d9, IDirect3D9ExVtbl* vTable);
//extern void AssignVTable(IDirect3DDevice9* d3d9, IDirect3DDevice9ExVtbl* vTable);
//extern void AssignVTable(IDirect3DSwapChain9* d3d9, IDirect3DSwapChain9ExVtbl* vTable);
extern bool GetIsEx(IDirect3D9* d3d9);
extern bool GetIsEx(IDirect3DDevice9* device);
extern bool GetIsEx(IDirect3DSwapChain9* swapChain);
IDirect3D9* CreateAndOverrideDirect3D9();
IDirect3D9Ex* CreateAndOverrideDirect3D9Ex();
class D3D9Context2
{
public:
int internalRefCount = 0;
IDirect3D9Ex* d3d9 = NULL;
IDirect3D9ExVtbl* originalVTable = NULL;
IDirect3D9ExVtbl* myVTable = NULL;
bool IsEx = false;
public:
D3D9Context2(IDirect3D9* d3d9);
D3D9Context2();
void Init(IDirect3D9* d3d9);
~D3D9Context2();
void Dispose();
HRESULT CreateDeviceReal(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface);
HRESULT CreateDeviceExReal(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode, IDirect3DDevice9Ex** ppReturnedDeviceInterface);
ULONG ReleaseReal();
static void GetPresentParameters(D3DPRESENT_PARAMETERS& presentParameters, HWND hwnd, bool vsync);
HRESULT CreateDevice_(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface);
HRESULT CreateDeviceEx_(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode, IDirect3DDevice9Ex** ppReturnedDeviceInterface);
ULONG Release_();
static HRESULT __stdcall CreateDevice(IDirect3D9Ex* This, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DDevice9** ppReturnedDeviceInterface);
static HRESULT __stdcall CreateDeviceEx(IDirect3D9Ex* This, UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode, IDirect3DDevice9Ex** ppReturnedDeviceInterface);
static ULONG __stdcall Release(IDirect3D9Ex* This);
};
class D3D9DeviceContext
{
friend D3D9Context2;
public:
IDirect3DDevice9Ex* device = NULL;
IDirect3DDevice9ExVtbl* originalVTable = NULL;
IDirect3DDevice9ExVtbl* myVTable = NULL;
D3D9Context2* parent = NULL;
D3D9SwapChainContext* childSwapChainContext = NULL;
IDirect3DSwapChain9* realSwapChain = NULL;
//IDirect3DSurface9* initialRenderTarget = NULL;
//IDirect3DSurface9* initialDepthStencilSurface = NULL;
bool forceReal = false;
int simulateLostDevice = 0;
bool IsEx = false;
int internalRefCount = 0;
int refCountFirstCapture = 0;
int refCountTrackerCount = 0;
bool disposing = false;
D3DDEVICE_CREATION_PARAMETERS originalDeviceCreationParameters = {};
public:
D3D9DeviceContext(IDirect3DDevice9* device);
D3D9DeviceContext();
static void SetVTable(IDirect3DDevice9ExVtbl* myVTable);
void SetVTable();
void Init(IDirect3DDevice9* device);
~D3D9DeviceContext();
void Dispose();
void DisposeExcludingDevice();
int GetRefCount() const;
int BeginTrackingRefCount();
int EndTrackingRefCount();
HRESULT CreateVirtualDevice(HWND hwnd, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters);
ULONG Release_();
HRESULT GetCreationParameters_(D3DDEVICE_CREATION_PARAMETERS* pParameters);
HRESULT CreateAdditionalSwapChain_(D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain);
//HRESULT GetSwapChain_(UINT iSwapChain, IDirect3DSwapChain9** pSwapChain);
//UINT GetNumberOfSwapChains_();
HRESULT Reset_(D3DPRESENT_PARAMETERS* pPresentationParameters);
HRESULT Present_(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion);
HRESULT GetBackBuffer_(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
HRESULT GetFrontBufferData_(UINT iSwapChain, IDirect3DSurface9* pDestSurface);
HRESULT BeginStateBlock_();
HRESULT PresentEx_(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
HRESULT ResetEx_(D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode);
HRESULT TestCooperativeLevel_();
ULONG ReleaseReal();
HRESULT GetCreationParametersReal(D3DDEVICE_CREATION_PARAMETERS* pParameters);
HRESULT CreateAdditionalSwapChainReal(D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain);
//HRESULT GetSwapChainReal(UINT iSwapChain, IDirect3DSwapChain9** pSwapChain);
//UINT GetNumberOfSwapChainsReal();
HRESULT ResetReal(D3DPRESENT_PARAMETERS* pPresentationParameters);
HRESULT PresentReal(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion);
HRESULT GetBackBufferReal(UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
HRESULT GetFrontBufferDataReal(UINT iSwapChain, IDirect3DSurface9* pDestSurface);
HRESULT BeginStateBlockReal();
HRESULT PresentExReal(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
HRESULT ResetExReal(D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode);
static ULONG __stdcall Release(IDirect3DDevice9Ex* This);
static HRESULT __stdcall GetCreationParameters(IDirect3DDevice9Ex* This, D3DDEVICE_CREATION_PARAMETERS* pParameters);
static HRESULT __stdcall CreateAdditionalSwapChain(IDirect3DDevice9Ex* This, D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain);
//static HRESULT __stdcall GetSwapChain(IDirect3DDevice9Ex* This, UINT iSwapChain, IDirect3DSwapChain9** pSwapChain);
//static UINT __stdcall GetNumberOfSwapChains(IDirect3DDevice9Ex* This);
static HRESULT __stdcall Reset(IDirect3DDevice9Ex* This, D3DPRESENT_PARAMETERS* pPresentationParameters);
static HRESULT __stdcall Present(IDirect3DDevice9Ex* This, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion);
static HRESULT __stdcall GetBackBuffer(IDirect3DDevice9Ex* This, UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
static HRESULT __stdcall GetFrontBufferData(IDirect3DDevice9Ex* This, UINT iSwapChain, IDirect3DSurface9* pDestSurface);
static HRESULT __stdcall BeginStateBlock(IDirect3DDevice9Ex* This);
static HRESULT __stdcall PresentEx(IDirect3DDevice9Ex* This, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
static HRESULT __stdcall ResetEx(IDirect3DDevice9Ex* This, D3DPRESENT_PARAMETERS* pPresentationParameters, D3DDISPLAYMODEEX* pFullscreenDisplayMode);
static HRESULT __stdcall TestCooperativeLevel(IDirect3DDevice9Ex* This);
};
class D3D9SwapChainContext
{
friend D3D9DeviceContext;
public:
IDirect3DSwapChain9Ex* realSwapChain = NULL;
IDirect3DSurface9* realBackBuffer = NULL;
IDirect3DSurface9* realDepthStencilSurface = NULL;
IDirect3DTexture9* virtualBackBufferTexture = NULL;
IDirect3DSurface9* virtualBackBuffer = NULL;
IDirect3DSurface9* virtualBackBufferMultisampled = NULL;
IDirect3DSurface9* virtualDepthStencilSurface = NULL;
CUpscaler upscaler;
D3DSWAPEFFECT swapEffect = D3DSWAPEFFECT_COPY;
IDirect3DSwapChain9ExVtbl* originalVTable = NULL;
IDirect3DSwapChain9ExVtbl* myVTable = NULL;
IDirect3DDevice9* device = NULL;
D3D9DeviceContext* parent = NULL;
bool IsEx = false;
bool isDestroying = false;
bool insidePresent = false;
bool forceReal = false;
int width, height;
D3DPRESENT_PARAMETERS presentParameters = {};
public:
D3D9SwapChainContext(IDirect3DSwapChain9* swapChain);
D3D9SwapChainContext();
void SetVTable();
void Init(IDirect3DSwapChain9* swapChain);
~D3D9SwapChainContext();
void Dispose();
HRESULT CreateVirtualDevice(HWND hwnd, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS* pPresentationParameters);
HRESULT Present_(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
HRESULT GetFrontBufferData_(IDirect3DSurface9* pDestSurface);
HRESULT GetBackBuffer_(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
HRESULT GetPresentParameters_(D3DPRESENT_PARAMETERS* pPresentationParameters);
HRESULT PresentReal(const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
HRESULT GetFrontBufferDataReal(IDirect3DSurface9* pDestSurface);
HRESULT GetBackBufferReal(UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
HRESULT GetPresentParametersReal(D3DPRESENT_PARAMETERS* pPresentationParameters);
static HRESULT __stdcall Present(IDirect3DSwapChain9Ex* This, const RECT* pSourceRect, const RECT* pDestRect, HWND hDestWindowOverride, const RGNDATA* pDirtyRegion, DWORD dwFlags);
static HRESULT __stdcall GetFrontBufferData(IDirect3DSwapChain9Ex* This, IDirect3DSurface9* pDestSurface);
static HRESULT __stdcall GetBackBuffer(IDirect3DSwapChain9Ex* This, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer);
static HRESULT __stdcall GetPresentParameters(IDirect3DSwapChain9Ex* This, D3DPRESENT_PARAMETERS* pPresentationParameters);
};
|
Desperate messages are being shared on social media claiming that some fathers in Eastern Aleppo are asking religious scholars whether it is permissible to kill their daughters before they are captured and raped by Assad regime forces, Hezbollah, or Iranian militias.
Syrian regime forces and sectarian militias carried out nearly 200 executions in Aleppo on Monday, which included women and children, according to eyewitnesses from within the city, Al Arabiya News Channel reported.
Activists on the ground say Hezbollah carried out most of the mass executions in the war-torn city. Sources confirmed to Al Arabiya that militias loyal to the regime killed nine children and four women, by burning them to death.
Muhammad Al-Yaqoubi, a prominent Syrian Islamic scholar and religious leader who fled Syria tweeted on Tuesday that he was receiving questions from Aleppo, including whether “a man can kill his wife or sister to avoid rape by Assad regime forces.”
We are receiving from Aleppo questions like this one, can a man kill his wife or sister before she is raped by Assad Forces in front of him? — Muhammad Al-Yaqoubi (@Shaykhabulhuda) December 13, 2016
Another Facebook message, posted by a Syrian activist relaying the message from a girl in Aleppo, read:
“To all the religious leaders and scholars of the world. To all those who are supposedly carrying the burden on their shoulder. I am one of Aleppo's girls who awaits rape within a few hours. There are no men nor arms to stand between us and the monster whom are called the Syrian army”.
I don’t want anything from you, not even prayers. I am still able to talk and I believe my prayers are more sincere then yours. All what I am asking for is don’t take God’s place and judge me when I kill myself. I am going to kill myself and I don’t care if you doom me to hell.
I am committing suicide because I didn’t survive all those time in my father’s home for nothing!! My father who died from sorrow and fear for who he left behind. I am committing suicide so my body isn’t any sort of pleasure for those who couldn't even dare to mention Aleppo’s name a few days ago.
“I am committing suicide in Aleppo because the day of judgment just happened and I don't think hell is worse then what we are living.”
“I will kill myself and I know you are going to unite over judging my destiny to hell. I know the only thing that will unite you all is a girl committing suicide. I am not your mom or your sister or wife. I am just a girl you don’t care about.”
“I am going to finish my statement with saying your fatwa doesn’t mean anything to me and doesn’t interest me anymore. Keep it for your family. I am killing myself and when u read this you should know I just died pure and untouched in spite of you all.”
Residents of Aleppo are either being forced to flee to governement held areas, or fearfully await the Syrian army’s arrival.
Al Arabiya cannot confirm or validate the information given.
Last Update: Wednesday, 14 December 2016 KSA 19:51 - GMT 16:51 |
// Log sends log messages to elasticsearch
func (e *Elasticsearch) Log(ctx context.Context, index, tzpe string, msg interface{}) error {
if _, err := e.Client.Index().Index(index).Type(tzpe).BodyJson(msg).Do(); err != nil {
return err
}
return nil
} |
<reponame>polinwei/jwt<gh_stars>0
package com.spring.jwt.db.maria.model.authentication;
// Generated Jul 12, 2018 3:28:17 PM by Hibernate Tools 5.2.11.Final
import javax.persistence.Column;
import javax.persistence.Embeddable;
/**
* UserAuthorityId generated by hbm2java
*/
@Embeddable
public class UserAuthorityId implements java.io.Serializable {
private long userId;
private long authorityId;
public UserAuthorityId() {
}
public UserAuthorityId(long userId, long authorityId) {
this.userId = userId;
this.authorityId = authorityId;
}
@Column(name = "user_id", nullable = false)
public long getUserId() {
return this.userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
@Column(name = "authority_id", nullable = false)
public long getAuthorityId() {
return this.authorityId;
}
public void setAuthorityId(long authorityId) {
this.authorityId = authorityId;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof UserAuthorityId))
return false;
UserAuthorityId castOther = (UserAuthorityId) other;
return (this.getUserId() == castOther.getUserId()) && (this.getAuthorityId() == castOther.getAuthorityId());
}
public int hashCode() {
int result = 17;
result = 37 * result + (int) this.getUserId();
result = 37 * result + (int) this.getAuthorityId();
return result;
}
}
|
<gh_stars>0
import { IOperation } from './interface'
import * as inquirer from 'inquirer'
import RootStore from '../store'
import { setScaleDeployment } from '../api/k8s/resources'
import { selector } from '../helpers/prompts'
const Scaler: IOperation = {
execute: async () => {
const deployments = (await selector('deployments', 'checkbox-plus'))
.selection as string[]
await inquirer
.prompt({
type: 'number',
name: 'scale',
})
.then(async (answer: { scale: number }) => {
await Promise.all(
deployments.map(async (deployment: string) => {
const res = await setScaleDeployment(
deployment,
RootStore.currentNamespace,
answer.scale
)
console.log(`Scaled ${deployment} to ${answer.scale} pods`)
return res
})
)
})
},
label: 'Scaler',
}
export default Scaler
|
/**
* Modifies the given DependencyCollection so that it is identical to the
* cached copy based on a previous call to putIntoCache() and returns
* {@code true}.
* If the cache is disabled or there is no existing cache for the given
* resource, returns {@code false}.
*/
private boolean populateFromCache(ResourceReference ref,
DependencyCollection scripts)
{
if(null == ref) return false;
CacheEntry ce = this.cache.get(ref);
if(ce != null && ce.isActive())
{
ce.populate(scripts);
return true;
}
return false;
} |
def sliding_window2d_backend(x, kernel_size, padding, stride):
padded_x = np.pad(x, [[0, 0],
[int(np.floor(padding[0] / 2)), int(np.ceil(padding[0] / 2))],
[int(np.floor(padding[1] / 2)), int(np.ceil(padding[1] / 2))],
[0, 0]], mode='constant', constant_values=(0.0,))
return np.ndarray([x.shape[0],
calc_size_backend(x.shape[1], kernel_size[0], padding[0], stride[0]),
calc_size_backend(x.shape[2], kernel_size[1], padding[1], stride[1]),
kernel_size[0], kernel_size[1], x.shape[3]],
dtype=padded_x.dtype, buffer=padded_x.data, offset=bytes_offset_backend(padded_x),
strides=[x.strides[0], stride[0] * x.strides[1], stride[1] * x.strides[2],
x.strides[1], x.strides[2], x.strides[3]]) |
<reponame>chaixiaoxue/dlink
import React, {useEffect, useState} from 'react';
import {Form, Button, Input, Modal, Select,Divider,Space,Switch} from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import {ClusterConfigurationTableListItem} from "@/pages/ClusterConfiguration/data";
import {getConfig, getConfigFormValues} from "@/pages/ClusterConfiguration/function";
import {FLINK_CONFIG_LIST, HADOOP_CONFIG_LIST} from "@/pages/ClusterConfiguration/conf";
import type {Config} from "@/pages/ClusterConfiguration/conf";
export type ClusterConfigurationFormProps = {
onCancel: (flag?: boolean) => void;
onSubmit: (values: Partial<ClusterConfigurationTableListItem>) => void;
modalVisible: boolean;
values: Partial<ClusterConfigurationTableListItem>;
};
const Option = Select.Option;
const formLayout = {
labelCol: {span: 7},
wrapperCol: {span: 13},
};
const ClusterConfigurationForm: React.FC<ClusterConfigurationFormProps> = (props) => {
const [form] = Form.useForm();
const [formVals, setFormVals] = useState<Partial<ClusterConfigurationTableListItem>>({
id: props.values.id,
name: props.values.name,
alias: props.values.alias,
type: props.values.type?props.values.type:"Yarn",
configJson: props.values.configJson,
note: props.values.note,
enabled: props.values.enabled,
});
const {
onSubmit: handleSubmit,
onCancel: handleModalVisible,
modalVisible,
} = props;
const buildConfig = (config:Config[]) =>{
let itemList = [];
for(let i in config){
itemList.push(<Form.Item
name={config[i].name}
label={config[i].lable}
>
<Input placeholder={config[i].placeholder}/>
</Form.Item>)
}
return itemList;
};
const submitForm = async () => {
const fieldsValue = await form.validateFields();
let formValues = {
id:formVals.id,
name:fieldsValue.name,
alias:fieldsValue.alias,
type:fieldsValue.type,
note:fieldsValue.note,
enabled:fieldsValue.enabled,
configJson:JSON.stringify(getConfig(fieldsValue)),
};
setFormVals({...formVals, ...formValues});
handleSubmit({...formVals, ...formValues});
};
const renderContent = (formVals) => {
return (
<>
<Form.Item
name="type"
label="类型"
>
<Select defaultValue="Yarn" value="Yarn">
<Option value="Yarn">Flink On Yarn</Option>
</Select>
</Form.Item>
<Divider>Hadoop 配置</Divider>
<Form.Item
name="hadoopConfigPath"
label="配置文件路径"
help="可指定配置文件路径(末尾无/),需要包含以下文件:core-site.xml,hdfs-site.xml,yarn-site.xml"
>
<Input placeholder="值如 /usr/local/dlink/conf"/>
</Form.Item>
<Divider orientation="left" plain>自定义配置(高优先级)</Divider>
{buildConfig(HADOOP_CONFIG_LIST)}
<Form.Item
label="其他配置"
>
<Form.List name="hadoopConfigList">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, fieldKey, ...restField }) => (
<Space key={key} style={{ display: 'flex' }} align="baseline">
<Form.Item
{...restField}
name={[name, 'name']}
fieldKey={[fieldKey, 'name']}
>
<Input placeholder="name" />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'value']}
fieldKey={[fieldKey, 'value']}
>
<Input placeholder="value" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
添加一个自定义项
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form.Item>
<Divider>Flink 配置</Divider>
<Form.Item
name="flinkLibPath"
label="lib 路径"
rules={[{required: true, message: '请输入 lib 路径!'}]}
help="必须指定 lib 的 hdfs 路径(末尾无/),需要包含 Flink 运行时的依赖"
>
<Input placeholder="值如 hdfs:///flink/lib"/>
</Form.Item>
<Form.Item
name="flinkConfigPath"
label="配置文件路径"
help="可指定配置文件 flink-conf.yaml 的具体路径"
>
<Input placeholder="值如 /usr/local/dlink/conf/flink-conf.yaml"/>
</Form.Item>
<Divider orientation="left" plain>自定义配置(高优先级)</Divider>
{buildConfig(FLINK_CONFIG_LIST)}
<Form.Item
label="其他配置"
>
<Form.List name="flinkConfigList">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, fieldKey, ...restField }) => (
<Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<Form.Item
{...restField}
name={[name, 'name']}
fieldKey={[fieldKey, 'name']}
>
<Input placeholder="name" />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'value']}
fieldKey={[fieldKey, 'value']}
>
<Input placeholder="value" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
添加一个自定义项
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form.Item>
<Divider>基本配置</Divider>
<Form.Item
name="name"
label="标识"
rules={[{required: true, message: '请输入名称!'}]}>
<Input placeholder="请输入唯一英文标识"/>
</Form.Item>
<Form.Item
name="alias"
label="名称"
>
<Input placeholder="请输入名称"/>
</Form.Item>
<Form.Item
name="note"
label="注释"
>
<Input.TextArea placeholder="请输入文本注释" allowClear
autoSize={{minRows: 3, maxRows: 10}}/>
</Form.Item>
<Form.Item
name="enabled"
label="是否启用">
<Switch checkedChildren="启用" unCheckedChildren="禁用"
defaultChecked={formVals.enabled}/>
</Form.Item>
</>
);
};
const renderFooter = () => {
return (
<>
<Button onClick={() => handleModalVisible(false)}>取消</Button>
<Button type="primary" onClick={() => submitForm()}>
完成
</Button>
</>
);
};
return (
<Modal
width={1200}
bodyStyle={{padding: '32px 40px 48px'}}
destroyOnClose
title={formVals.id?"维护集群配置":"创建集群配置"}
visible={modalVisible}
footer={renderFooter()}
onCancel={() => handleModalVisible()}
>
<Form
{...formLayout}
form={form}
initialValues={getConfigFormValues(formVals)}
>
{renderContent(formVals)}
</Form>
</Modal>
);
};
export default ClusterConfigurationForm;
|
package com.simonstuck.vignelli.refactoring.step.impl;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiAssignmentExpression;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiReferenceExpression;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.refactoring.introduceField.IntroduceFieldHandler;
import com.simonstuck.vignelli.psi.PsiContainsChecker;
import com.simonstuck.vignelli.psi.util.EditorUtil;
import com.simonstuck.vignelli.refactoring.step.RefactoringStep;
import com.simonstuck.vignelli.refactoring.step.RefactoringStepDelegate;
import com.simonstuck.vignelli.refactoring.step.RefactoringStepGoalChecker;
import com.simonstuck.vignelli.refactoring.step.RefactoringStepResult;
import com.simonstuck.vignelli.refactoring.step.RefactoringStepVisitor;
import com.simonstuck.vignelli.ui.description.HTMLFileTemplate;
import com.simonstuck.vignelli.ui.description.Template;
import com.simonstuck.vignelli.util.IOUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class ConvertToConstructorAssignedFieldRefactoringStep implements RefactoringStep {
private static final String STEP_NAME = "Convert Expression to Constructor-Initialised Field";
private static final String TEMPLATE_PATH = "descriptionTemplates/convertToConstructorAssignedFieldDescription.html";
private final Project project;
private final PsiExpression expression;
private final RefactoringStepGoalChecker refactoringStepGoalChecker;
private final Application application;
@NotNull
private final RefactoringStepDelegate delegate;
public ConvertToConstructorAssignedFieldRefactoringStep(
@NotNull PsiExpression expression,
@NotNull Project project,
@NotNull Application application,
@NotNull RefactoringStepDelegate delegate
) {
this.expression = expression;
this.project = project;
this.application = application;
this.delegate = delegate;
refactoringStepGoalChecker = new ExpressionMovedToConstructorChecker();
}
@Override
public void start() {
application.addApplicationListener(refactoringStepGoalChecker);
EditorUtil.navigateToElement(expression);
}
@Override
public void end() {
application.removeApplicationListener(refactoringStepGoalChecker);
}
@Override
public void process() {
PsiElement[] elements = new PsiElement[] { expression };
IntroduceFieldHandler handler = new IntroduceFieldHandler();
handler.invoke(project, elements, null);
}
@Override
public void describeStep(Map<String, Object> templateValues) {
templateValues.put(STEP_NAME_TEMPLATE_KEY, STEP_NAME);
templateValues.put(STEP_DESCRIPTION_TEMPLATE_KEY, getDescription());
}
@Override
public void accept(RefactoringStepVisitor refactoringStepVisitor) {
refactoringStepVisitor.visitElement(this);
}
private String getDescription() {
Template template = new HTMLFileTemplate(IOUtil.tryReadFile(TEMPLATE_PATH));
HashMap<String, Object> contentMap = new HashMap<String, Object>();
PsiClass thisClass = PsiTreeUtil.getParentOfType(expression, PsiClass.class);
if (thisClass != null) {
contentMap.put("thisClass", thisClass.getName());
}
final PsiClass expressionClass = PsiTypesUtil.getPsiClass(expression.getType());
if (expressionClass != null) {
contentMap.put("expressionClass", expressionClass.getName());
}
contentMap.put("expression", expression.getText());
return template.render(contentMap);
}
public static final class Result implements RefactoringStepResult {
HashSet<PsiExpression> constructorExpressions;
public Result(HashSet<PsiExpression> constructorExpressions) {
this.constructorExpressions = constructorExpressions;
}
public HashSet<PsiExpression> getConstructorExpressions() {
return constructorExpressions;
}
@Override
public boolean isSuccess() {
return true;
}
}
/**
* This checker checks whether the original expression has been moved to the constructor
*
* <p>This works as follows:</p>
* <ol>
* <li>Record all assignments to fields in all constructors before we begin.</li>
* <li>
* <span>Then, for every change:</span>
* <ol>
* <li>Check for field assignments in the constructor that have been added since recording the originals</li>
* <li>For every new assignment expression, check if the original expression is within the RHS</li>
* <li>If so, check if the field is used in the code block that we originally removed it from.</li>
* <li>Check if the original expression is invalid</li>
* </ol>
* </li>
* </ol>
*/
private class ExpressionMovedToConstructorChecker extends RefactoringStepGoalChecker {
private Set<PsiAssignmentExpression> originalConstructorFieldAssignments = new HashSet<PsiAssignmentExpression>();
private final PsiClass clazz;
private final PsiMethod originalExpressionMethod;
public ExpressionMovedToConstructorChecker() {
super(ConvertToConstructorAssignedFieldRefactoringStep.this, delegate);
clazz = PsiTreeUtil.getParentOfType(expression, PsiClass.class);
setUpOriginalConstructorAssignmentExpressions();
originalExpressionMethod = PsiTreeUtil.getParentOfType(expression, PsiMethod.class);
}
private void setUpOriginalConstructorAssignmentExpressions() {
originalConstructorFieldAssignments.addAll(getAllConstructorFieldAssignmentExpressions());
}
private Set<PsiAssignmentExpression> getAllConstructorFieldAssignmentExpressions() {
Set<PsiAssignmentExpression> result = new HashSet<PsiAssignmentExpression>();
if (clazz != null) {
Set<PsiMethod> methods = getDefinedMethods(clazz);
for (PsiMethod method : methods) {
result.addAll(getFieldAssignmentsIfConstructor(method));
}
}
return result;
}
private Set<PsiAssignmentExpression> getFieldAssignmentsIfConstructor(PsiMethod method) {
Set<PsiAssignmentExpression> result = new HashSet<PsiAssignmentExpression>();
if (method.isValid() && method.isConstructor()) {
@SuppressWarnings("unchecked")
Collection<PsiAssignmentExpression> assignmentExpressions = PsiTreeUtil.collectElementsOfType(method, PsiAssignmentExpression.class);
for (PsiAssignmentExpression assignmentExpression : assignmentExpressions) {
PsiExpression lExpression = assignmentExpression.getLExpression();
if (lExpression instanceof PsiReferenceExpression && ((PsiReferenceExpression) lExpression).resolve() instanceof PsiField) {
result.add(assignmentExpression);
}
}
}
return result;
}
@Override
public RefactoringStepResult computeResult() {
Set<PsiAssignmentExpression> newAssignments = getAllConstructorFieldAssignmentExpressions();
newAssignments.removeAll(originalConstructorFieldAssignments);
final Map<PsiMethod, PsiExpression> constructorAssignmentExpressions = new HashMap<PsiMethod, PsiExpression>();
for (PsiAssignmentExpression newAssignment : newAssignments) {
PsiExpression constructorExpression = (PsiExpression) new PsiContainsChecker().findEquivalent(newAssignment, expression);
PsiExpression lExpression = newAssignment.getLExpression();
if (constructorExpression != null && lExpression instanceof PsiReferenceExpression) {
PsiElement lResolved = ((PsiReferenceExpression) lExpression).resolve();
if (lResolved instanceof PsiField) {
PsiField assignee = (PsiField) lResolved;
if (containsReferencesToField(originalExpressionMethod, assignee)) {
PsiMethod constructor = PsiTreeUtil.getParentOfType(constructorExpression, PsiMethod.class);
if (constructor != null) {
constructorAssignmentExpressions.put(constructor, constructorExpression);
}
}
}
}
}
if (constructorAssignmentExpressions.size() >= clazz.getConstructors().length && clazz.getConstructors().length > 0) {
return new Result(new HashSet<PsiExpression>(constructorAssignmentExpressions.values()));
}
return null;
}
/**
* Checks whether the given method contains references to the given field.
* @param method The method to check.
* @param field The field for which to find references.
* @return True iff the method contains references to the field.
*/
private boolean containsReferencesToField(PsiMethod method, PsiField field) {
@SuppressWarnings("unchecked")
Collection<PsiReferenceExpression> referencesInOriginalMethod = PsiTreeUtil.collectElementsOfType(method, PsiReferenceExpression.class);
for (PsiReference referenceInOriginalMethod : referencesInOriginalMethod) {
PsiElement resolvedReference = referenceInOriginalMethod.resolve();
if (resolvedReference != null && resolvedReference.equals(field) && !expression.isValid()) {
return true;
}
}
return false;
}
}
}
|
package gst
/*
#include <gst/gst.h>
*/
import "C"
import "github.com/s-urbaniak/glib"
type Device struct {
GstObj
}
func (d *Device) g() *C.GstDevice {
return (*C.GstDevice)(d.GetPtr())
}
func (d *Device) GetCaps() *Caps {
return (*Caps)(C.gst_device_get_caps(d.g()))
}
func (d *Device) GetDisplayName() string {
return C.GoString((*C.char)(C.gst_device_get_display_name(d.g())))
}
func (d *Device) GetDeviceClass() string {
return C.GoString((*C.char)(C.gst_device_get_device_class(d.g())))
}
func (d *Device) GetProperties() (string, glib.Params) {
s := C.gst_device_get_properties(d.g())
defer C.gst_structure_free(s)
return parseGstStructure(s)
}
|
/*
TODO: Measure::getAverage()
This function calculates the average/mean value for all the values.
@return
The average value for all the years, or 0 if it cannot be calculated
*/
double Measure::getAverage() const{
double sum = 0;
int size = this->values.size();
for(auto it = this->values.begin(); it != this->values.end(); it++){
sum += it->second;
}
return sum/size;
} |
/**
* Creates a new time slice which stores the information specified. This essentially stores
* the bike's left/right wheel positions and their rotation at `currentTime + msPassed`
* moment of time.
*/
public void createSlice(float msPassed, VectorF leftWheelPos, VectorF rightWheelPos,
float leftRotation, float rightRotation) {
if (!currentRun.isFinished()) {
currentRun.createSlice(msPassed, leftWheelPos, rightWheelPos, leftRotation,
rightRotation);
}
if (prevRun != null && prevRun.hasSlices()) {
GhostInfo.TimeSlice slice = prevRun.getSlice(msPassed);
leftWheel.setPos(slice.leftWheelPos.x, slice.leftWheelPos.y);
rightWheel.setPos(slice.rightWheelPos.x, slice.rightWheelPos.y);
leftWheel.setRotation(slice.leftWheelRotation);
rightWheel.setRotation(slice.rightWheelRotation);
}
} |
#pragma once
#include "poolstd.hpp"
using namespace std;
namespace pool {
class POOL_PUBLIC Natives {
public:
virtual bool add(const string &name, const shared_ptr<Object> &value) = 0;
virtual bool addFun(const string &name, const vector<Function::Param> ¶meters, const NativeFunction::method_t &code) = 0;
virtual shared_ptr<Object> find(const string &name) = 0;
static Natives &get();
};
} |
def check_integrity(self):
if self.left and self.right:
return self.left.check_integrity() and \
self.right.check_integrity() and \
self.hash_value == hash_string(self.left.hash_value + self.right.hash_value)
else:
assert self.left is None and self.right is None
return self.hash_value == hash_string(self.layer_weights_hash + self.layer_key) |
// TestValidateGroupName tests for an invalid group name
func TestAppProject_ValidateGroupName(t *testing.T) {
p := newTestProject()
err := p.ValidateProject()
assert.NoError(t, err)
p.Spec.Roles[0].Groups = []string{"mygroup"}
err = p.ValidateProject()
assert.NoError(t, err)
badGroupNames := []string{
"",
" ",
"my, group",
"my,group",
"my\ngroup",
"my\rgroup",
}
for _, badName := range badGroupNames {
p.Spec.Roles[0].Groups = []string{badName}
err = p.ValidateProject()
assert.Error(t, err)
}
goodGroupNames := []string{
"my:group",
}
for _, goodName := range goodGroupNames {
p.Spec.Roles[0].Groups = []string{goodName}
err = p.ValidateProject()
assert.NoError(t, err)
}
} |
Former chief minister BS Yeddyurappa, who has been appointed the head of the BJP in Karnataka, did not even fire his first salvo, and the Congress in the state is already facing factionalism with three groups formed within the Karnataka Pradesh Congress Committee (KPCC).
The Congress is aware of Yeddyurappa's clout and power, as the undisputed leader of the largest community (Lingayats) in Karnataka. He single-handedly brought the party to power and went on to become the CM in 2008.
No Congress leader enjoys the Lingayat community backing as that of Yeddyurappa. Consequently, they want the Congress to appoint a Vokkaliga (second largest community) as the KPCC president to take on Yeddyurappa.
A day after the BJP announced Yeddyurappa as the new leader of the party in Karnataka, state's Animal Husbandry Minister A Manju (Vokkaliga) and several other community leaders formed a group and proposed the name of Energy Minister DK Shivakumar for the post of the KPCC president. Last month, there was some movement to appoint Shivakumar as the KPCC head, but it was delayed in view of the charges against him. Now, Manju and over 15 MLAs in the Congress are rallying behind Shivakumar for the KPCC president's post.
Another faction led by MLA ST Somashekar has openly rebelled against Siddaramaiah. Somashekar and another 20+ ministerial aspirants want Siddaramaiah to undertake a Cabinet reshuffle and appoint new faces as ministers. According to them, some of the ministers have not performed well and it could affect the Congress' prospects in the next Assembly elections due in two years.
"It has been 3 years since we came to power in Karnataka. All of us are equally responsible for decimating the BJP in the last elections. Siddaramaiah should drop 25 ministers from the Council of Cabinet and accommodate youngsters like us. There are several of us waiting to prove the mettle. This way we can counter the BJP's game-plan," said Somashekar, who is leading a delegation to New Delhi to meet the party High Command. Former ministers Dr. A B Maalakaraddy, K B Koliwada, Maalikkayya V Guttedar, R V Devaraj, and MLAs K N Rajanna, M Krishnappa, and Shivananada Patil are among those backing this faction.
But the Siddaramaiah camp is opposed to both the factions - one seeking appointment of a Vokkaliga as the KPCC president and the other demanding Cabinet reshuffle. The supporters of Siddaramaiah are of the view that both demands are undermining the capabilities of Siddaramaiah. "Our leader (Siddaramaiah) is capable of leading the party in the next elections. We do not want any parallel power centre. Yeddyurappa's appointment should not evoke such knee-jerk reaction in the Congress," Siddaramaiah's aides contended.
It is known to all that Siddaramaiah's popularity as a CM is declining day-by-day. Political analysts are of the view that Siddaramaiah is handing over Karnataka on a platter to the BJP by ignoring administration that should have been people-friendly and development-oriented.
"If Yeddyurappa's appointment as the BJP head in Karnataka can create so much unrest in the Congress, one can understand the predicament once the former CM hits the road. The Congress will have to get its strategy right from now on. Otherwise it will be too late for the Congress in Karnataka," remarked political analyst and historian Dr. A Veerappa.
Also Read:
BS Yeddyurappa is the new BJP head in Karnataka
Yeddyurappa says he will bring down Congress government |
<filename>tests/test_configuration.py<gh_stars>1-10
#pylint: skip-file
import mock
import re
from util import VigilanceTestCase
class ConfigurationParserTest(VigilanceTestCase):
def setUp(self):
super(ConfigurationParserTest, self).setUp()
global ConfigurationParsingError
from vigilance.error import ConfigurationParsingError
from vigilance.configuration import ConfigurationParser, ConfigurationStanza
from vigilance.constraint import ConstraintSuite
self.mockSuite = mock.MagicMock(spec=ConstraintSuite, **{'group_constraints.side_effect': lambda c: c})
self.globalMock = mock.MagicMock(spec=ConfigurationStanza)
self.filteredMock = mock.MagicMock(spec=ConfigurationStanza, **{'parse.return_value': ['asdf']})
self.parser = ConfigurationParser({'nicetype': self.filteredMock, 'global': self.globalMock}, self.mockSuite)
def test_parse_with_unknown_stanza_type_should_skip_and_log_warning(self):
constraintSet = self.parser.parse([{"type": "weirdo"}])
self.assertEqual([], constraintSet.globalConstraints)
self.assertEqual([], constraintSet.filteredConstraints)
self.log.warning.assert_called_once_with('Skipping malformed constraint stanza; unknown type "%s"', 'weirdo')
def test_parse_should_parse_stanzas(self):
constraintSet = self.parser.parse([{"type": "global"}, {"type": "nicetype"}, {"type": "global"}])
self.assertEqual(self.globalMock.parse.return_value, constraintSet.globalConstraints)
self.assertEqual(['asdf'], constraintSet.filteredConstraints)
self.log.warning.assert_called_once_with('Skipping duplicate global configuration stanza')
|
/**
* Represents the WAF logging stack outputs.
*/
public class WafLoggingOutputs {
private String kinesisFirehoseDeliveryStreamARN;
private String kinesisFirehoseDeliveryStreamName;
public String getKinesisFirehoseDeliveryStreamName() {
return kinesisFirehoseDeliveryStreamName;
}
public void setKinesisFirehoseDeliveryStreamName(String kinesisFirehoseDeliveryStreamName) {
this.kinesisFirehoseDeliveryStreamName = kinesisFirehoseDeliveryStreamName;
}
public String getKinesisFirehoseDeliveryStreamARN() {
return kinesisFirehoseDeliveryStreamARN;
}
public void setKinesisFirehoseDeliveryStreamARN(String kinesisFirehoseDeliveryStreamARN) {
this.kinesisFirehoseDeliveryStreamARN = kinesisFirehoseDeliveryStreamARN;
}
} |
//////////////////////////////////////////////////////////////////////////////
//
// Class:
// COAConcurrentGroup
//
// Method:
// COAConcurrentGroup constructor
//
// Description:
// Constructor.
//
// Input:
// CMetricsDevice * device - parent metrics device
// const char * name - concurrent group name
// const char * description - concurrent group description
// uint32_t measurementTypeMask -
//
//////////////////////////////////////////////////////////////////////////////
COAConcurrentGroup::COAConcurrentGroup( CMetricsDevice* device, const char* name, const char* description, uint32_t measurementTypeMask )
: CConcurrentGroup( device, name, description, measurementTypeMask )
{
m_processId = 0;
m_contextTagsEnabled = false;
m_ioMetricSet = NULL;
m_streamEventHandle = NULL;
m_streamType = STREAM_TYPE_OA;
m_ioMeasurementInfoVector = new( std::nothrow ) Vector<CInformation*>( EXCEPTIONS_VECTOR_INCREASE );
m_ioGpuContextInfoVector = new( std::nothrow ) Vector<CInformation*>( GPU_CONTEXTS_VECTOR_INCREASE );
AddIoMeasurementInfoPredefined();
} |
/** Clears the value of the 'split' field */
public StartupConfiguration.Builder clearSplit() {
split = null;
fieldSetFlags()[0] = false;
return this;
} |
/**
* Attempts to redeem this kit, saving it beforehand.
*
* @param uuid The {@link UUID} of the player to redeem the kit for
* @return The result
*/
default KitRedeemResult redeem(final UUID uuid) {
this.save();
final NucleusKitService kitService = NucleusAPI.getKitService().orElseThrow(() -> new IllegalStateException("No Kit module"));
return kitService.redeemKit(this, uuid, true);
} |
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
package org.apache.james.blob.objectstorage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import org.apache.commons.io.IOUtils;
import org.apache.james.blob.objectstorage.crypto.CryptoConfig;
import org.jclouds.io.Payloads;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import com.google.crypto.tink.subtle.Hex;
class AESPayloadCodecTest implements PayloadCodecContract {
private static final byte[] ENCRYPTED_BYTES = Hex.decode("0d5321372dae79366a2cc4ca7f52a9acd9bb6408e50a6bcb7b0008d0b10c90db46");
@Override
public PayloadCodec codec() {
return new AESPayloadCodec(
new CryptoConfig(
"c603a7327ee3dcbc031d8d34b1096c605feca5e1",
"foobar".toCharArray()));
}
@Test
void aesCodecShouldEncryptPayloadContentWhenWriting() throws Exception {
Payload payload = codec().write(expected());
byte[] bytes = IOUtils.toByteArray(payload.getPayload().openStream());
// authenticated encryption uses a random salt for the authentication
// header all we can say for sure is that the output is not the same as
// the input.
assertThat(bytes).isNotEqualTo(SOME_BYTES);
}
@Test
void aesCodecShouldDecryptPayloadContentWhenReading() throws Exception {
Payload payload = new Payload(Payloads.newInputStreamPayload(new ByteArrayInputStream(ENCRYPTED_BYTES)), Optional.empty());
InputStream actual = codec().read(payload);
assertThat(actual).hasSameContentAs(expected());
}
@Test
void aesCodecShouldRaiseExceptionWhenUnderliyingInputStreamFails() throws Exception {
Payload payload =
new Payload(Payloads.newInputStreamPayload(new FilterInputStream(new ByteArrayInputStream(ENCRYPTED_BYTES)) {
private int readCount = 0;
@Override
public int read(@NotNull byte[] b, int off, int len) throws IOException {
if (readCount >= ENCRYPTED_BYTES.length / 2) {
throw new IOException();
} else {
readCount += len;
return super.read(b, off, len);
}
}
}),
Optional.empty());
assertThatThrownBy(() -> codec().read(payload)).isInstanceOf(IOException.class);
}
}
|
<reponame>wolfv6/keybrd
#include "Code_Sc.h"
void Code_Sc::press()
{
Keyboard.press(scancode);
}
void Code_Sc::release()
{
Keyboard.release(scancode);
}
|
<reponame>VineethReddy02/timescale-prometheus
package pgmodel
import (
"fmt"
"math"
"sort"
"github.com/jackc/pgtype"
"github.com/jackc/pgx/v4"
"github.com/prometheus/prometheus/pkg/labels"
"github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc"
)
const (
// Postgres time zero is Sat Jan 01 00:00:00 2000 UTC.
// This is the offset of the Unix epoch in milliseconds from the Postgres zero.
PostgresUnixEpoch = -946684800000
)
var (
errInvalidData = fmt.Errorf("invalid row data")
)
// pgxSeriesSet implements storage.SeriesSet.
type pgxSeriesSet struct {
rowIdx int
rows []pgx.Rows
err error
}
// Next forwards the internal cursor to next storage.Series
func (p *pgxSeriesSet) Next() bool {
if p.rowIdx >= len(p.rows) {
return false
}
for !p.rows[p.rowIdx].Next() {
p.rows[p.rowIdx].Close()
p.rowIdx++
if p.rowIdx >= len(p.rows) {
return false
}
}
return true
}
// At returns the current storage.Series. It expects to get rows to contain
// four arrays in binary format which it attempts to deserialize into specific types.
// It also expects that the first two and second two arrays are the same length.
func (p *pgxSeriesSet) At() storage.Series {
if p.rowIdx >= len(p.rows) {
return nil
}
// Setting invalid data until we confirm that all data is valid.
p.err = errInvalidData
ps := &pgxSeries{}
if err := p.rows[p.rowIdx].Scan(&ps.labelNames, &ps.labelValues, &ps.times, &ps.values); err != nil {
return nil
}
if len(ps.labelNames.Elements) != len(ps.labelValues.Elements) {
return nil
}
if len(ps.times.Elements) != len(ps.values.Elements) {
return nil
}
p.err = nil
return ps
}
// Err implements storage.SeriesSet.
func (p *pgxSeriesSet) Err() error {
return p.err
}
// pgxSeries implements storage.Series.
type pgxSeries struct {
labelNames pgtype.TextArray
labelValues pgtype.TextArray
times pgtype.TimestamptzArray
values pgtype.Float8Array
}
// Labels returns the label names and values for the series.
func (p *pgxSeries) Labels() labels.Labels {
ll := make(labels.Labels, len(p.labelNames.Elements))
for i := range ll {
ll[i].Name = p.labelNames.Elements[i].String
ll[i].Value = p.labelValues.Elements[i].String
}
sort.Sort(ll)
return ll
}
// Iterator returns a chunkenc.Iterator for iterating over series data.
func (p *pgxSeries) Iterator() chunkenc.Iterator {
return newIterator(p.times, p.values)
}
// pgxSeriesIterator implements storage.SeriesIterator.
type pgxSeriesIterator struct {
cur int
totalSamples int
times pgtype.TimestamptzArray
values pgtype.Float8Array
}
// newIterator returns an iterator over the samples. It expects times and values to be the same length.
func newIterator(times pgtype.TimestamptzArray, values pgtype.Float8Array) *pgxSeriesIterator {
return &pgxSeriesIterator{
cur: -1,
totalSamples: len(times.Elements),
times: times,
values: values,
}
}
// Seek implements storage.SeriesIterator.
func (p *pgxSeriesIterator) Seek(t int64) bool {
p.cur = -1
for p.Next() {
if p.getTs() >= t {
return true
}
}
return false
}
// getTs returns a Unix timestamp in milliseconds.
func (p *pgxSeriesIterator) getTs() int64 {
v := p.times.Elements[p.cur]
switch v.InfinityModifier {
case pgtype.NegativeInfinity:
return math.MinInt64
case pgtype.Infinity:
return math.MaxInt64
default:
return v.Time.UnixNano() / 1e6
}
}
func (p *pgxSeriesIterator) getVal() float64 {
return p.values.Elements[p.cur].Float
}
// At returns a Unix timestamp in milliseconds and value of the sample.
func (p *pgxSeriesIterator) At() (t int64, v float64) {
if p.cur >= p.totalSamples || p.cur < 0 {
return 0, 0
}
return p.getTs(), p.getVal()
}
// Next implements storage.SeriesIterator.
func (p *pgxSeriesIterator) Next() bool {
for {
p.cur++
if p.cur >= p.totalSamples {
return false
}
if p.times.Elements[p.cur].Status == pgtype.Present &&
p.values.Elements[p.cur].Status == pgtype.Present {
return true
}
}
}
// Err implements storage.SeriesIterator.
func (p *pgxSeriesIterator) Err() error {
return nil
}
|
<filename>beaconing/index.d.ts
import { IonicNativePlugin } from '@ionic-native/core';
export declare class BeaconingOriginal extends IonicNativePlugin {
/**
* Your plugin plugin functions go here.
* Function names should match the ones in your .swift & .js files.
* Otherwise you won't be able to execute them.
*/
rangeBeaconIdListener(): Promise<any>;
monitorBeaconIdListener(): Promise<any>;
enteredRegionIdListener(): Promise<any>;
leftRegionIdListener(): Promise<any>;
rangeBeacons(options: string): Promise<any>;
stopRangeBeacons(options: string): Promise<any>;
monitorBeacons(options: string): Promise<any>;
stopMonitorBeacons(options: string): Promise<any>;
}
export declare const Beaconing: BeaconingOriginal; |
# Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
'''Defines various tools related to temporary files.'''
from __future__ import generator_stop
import tempfile
import shutil
import pathlib
from python_toolbox import context_management
@context_management.ContextManagerType
def create_temp_folder(*, prefix=tempfile.template, suffix='',
parent_folder=None, chmod=None):
'''
Context manager that creates a temporary folder and deletes it after usage.
After the suite finishes, the temporary folder and all its files and
subfolders will be deleted.
Example:
with create_temp_folder() as temp_folder:
# We have a temporary folder!
assert temp_folder.is_dir()
# We can create files in it:
(temp_folder / 'my_file').open('w')
# The suite is finished, now it's all cleaned:
assert not temp_folder.exists()
Use the `prefix` and `suffix` string arguments to dictate a prefix and/or a
suffix to the temporary folder's name in the filesystem.
If you'd like to set the permissions of the temporary folder, pass them to
the optional `chmod` argument, like this:
create_temp_folder(chmod=0o550)
'''
temp_folder = pathlib.Path(tempfile.mkdtemp(prefix=prefix, suffix=suffix,
dir=parent_folder))
try:
if chmod is not None:
temp_folder.chmod(chmod)
yield temp_folder
finally:
shutil.rmtree(str(temp_folder)) |
by Brett Stevens on July 27, 2013
Symbolism occurs when a small part of some thing comes to represent the whole. We see a flag, and we think of a nation, even though the nation despite containing many flags does not resemble a flag, nor is solely made of flags.
When we are an undifferentiated mass like the commercial hordes of modern liberal democracy, we have no way to think of ourselves outside of political symbols. The crowd cannot be summarized because it has nothing in common but commerce and ideology.
As a result, we tend to look toward those that aggregate ideas. We like our politicians to seem to represent our “camp,” so we choose them by their more dramatic acts. We like media because we identify with the characters. And we pick social elites who seem to agree with us.
The trap here is that these people symbolize what we think we want, and not how we live or our actual interests. They are cheerleaders for a symbolic “statement” or stand made for the things we fear or desire, but outside of that, have nothing in common with us.
Thus people get promoted to the elites for supporting legal abortion, outspoken civil rights activity or even simply being funny or witty. We know nothing else about them.
A problem occurs because we then poll these elites to see what we should be thinking.
These elites take many forms. They can be impoverished civil rights activists, wealthy media figures, or even those who inhabit an online community like Twitter or Metafilter.
This is the same problem that we encounter with surveys, which measure the thoughts of the people who can answer ten questions via their home phone number on a Tuesday morning at 10:30 AM.
Our media thrives on false elites because it makes for an easy story. Look at a small group, see what they think, and report it as reality. Although it is misleading, it makes for better symbolism than trying to get into the depth of a story.
Depth introduces complexity and potential conflicts. It requires unpacking many issues and their multiple consequences. This doesn’t make for good news. Cartoonish battles between two over-the-top primary forces brings drama and advertising dollars. Much like political campaigns.
In addition to these customer elites, formed of those who use products and therefore are presumed to be hip and wise, we have permanent elites based on industries. There’s the film industry in Hollywood, the government elites in D.C., and the digital elites in NoCal.
Each of these groups has two salient characteristics: first, they are chosen to represent more than themselves; second, by having been chosen, they are cut off from normal life and immersed in a specialized community shaped by the interests it serves.
The result is a total disconnect from reality. This is one of the many layers of disconnect. First, socialization is based on what we wish were true, not what is. Next, democracy is based on an aggregation of lowest common impulses. Finally, elites summarize this in symbols.
It is no surprise that elites are thus both Ivory Tower types and people who indulge in false humility and the pretense of defending the common man, the poor, the under-represented, etc. They need to justify their Ivory Tower, so they pick symbols of victimhood to defend.
The result however is that the people who are actually making life work the old fashioned way, which is by adapting to it, have zero representation, and most representation instead comes from the Ivory Tower types and the sample audiences they choose.
As a result, we have a pluralistic society where people are encouraged to believe in any ideal or lifestyle they choose, while the elites who endorse this philosophy have a non-pluralistic view because they are shaped by the demands of being elites.
It is no surprise then that we have a loss of sacred things, of heroes, and of values in common. We have ceded our values to elites who symbolically represent us, but don’t know us, and don’t care to.
Tags: crowdism, democracy, elites, pluralism
Please enable JavaScript to view the comments powered by Disqus. |
package main
import (
"flag"
"fmt"
"net/http"
"os"
"github.com/Nextdoor/conductor/core"
"github.com/Nextdoor/conductor/shared/datadog"
)
func main() {
flag.Parse()
core.Preload()
endpoints := core.Endpoints()
server := core.NewServer(endpoints)
address := ":8400"
datadog.Info("Starting the Conductor server on %s ...", address)
if e := http.ListenAndServe(address, server); e != nil {
err := fmt.Errorf("Failed to start server on %s: %v", address, e)
datadog.Error("Shutting down: %v", err)
os.Exit(1)
}
}
|
#import sys
#import numpy as np
#import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions import gcd
#input=sys.stdin.readline
a,b=map(int,input().split())
if a==b:
print(a)
exit()
if a==0:
i=0
resb=0
while True:
if i==0:
if ((b+1)//2)%2==1:
resb+=1
i+=1
continue
if 2**i>b+1:
break
if ((b+1)%(2**i))%2==1 and ((b+1)//(2**i))%2==1:
resb+=2**i
i+=1
print(resb)
exit()
n_b=b.bit_length()
n_a=(a-1).bit_length()
i=0
res=0
while True:
if i==0:
if (a//2)%2==1:
res+=1
i+=1
continue
if 2**i>a:
break
if (a%(2**i))%2==1 and (a//(2**i))%2==1:
res+=2**i
i+=1
i=0
resb=0
while True:
if i==0:
if ((b+1)//2)%2==1:
resb+=1
i+=1
continue
if 2**i>b+1:
break
if ((b+1)%(2**i))%2==1 and ((b+1)//(2**i))%2==1:
resb+=2**i
i+=1
print(res^resb) |
<gh_stars>1-10
# -*- coding:utf8 -*-
from fabric.api import task, local, run, sudo, env
from oozappa.config import get_config, procure_common_functions
_settings = get_config()
procure_common_functions()
# your own task below
@task
def set_env_app_type_a():
u'''eg. search app server type a instance via api or hard-coding and set fabric env.'''
print('set_env_app_type_a')
@task
def set_env_app_type_b():
u'''eg. search app server type b instance via api or hard-coding and set fabric env.'''
print('set_env_app_type_b')
@task
def deploy_application_type_a():
u'''grab application from somewhere and deploy app_type_a'''
print('deploy_application_type_a')
@task
def deploy_application_type_b():
u'''grab application from somewhere and deploy app_type_b'''
print('deploy_application_type_b')
@task
def create_image_from_app_type_a():
u'''eg. search app_type_a instance and create image.'''
print('create_image_from_app_type_a')
|
ES Lifestyle Newsletter Enter your email address Please enter an email address Email address is invalid Fill out this field Email address is invalid You already have an account. Please log in or register with your social account
The average British woman’s body in 1957 looked quite different to the average woman’s body of today.
As you can see in the photo above, time brings about change, and in this case, time brought has brought on inches — everywhere.
The latest study by international lingerie brand Bluebella found that 60 years ago the average British woman was 5ft 2ins, weighed 9st 10lbs and had a dress size 12.
Fast forward to 2017, and she is 5ft 5ins, weighs 11st and has a dress size 16.
Her bra size has shot up more than any other part of her anatomy to a 36DD and her waistline has increased by six inches, from 28 to 34 inches.
The study analysed data on changing body shapes from government figures, and its findings revealed a shift in lifestyle as well. Women's life expecancy has gone up ten years from 73 to 83.
Bluebella chief executive Emily Bendell said that 2017's “Miss Average” was far more body-conscious than her 1957 equivalent.
"She is likely to exercise at least twice a week - consuming 2,300 calories a day compared to 1,800 calories back then,” she said. "She is much healthier than her fifties counterpart and devotes around 30 per cent more of her income to her wardrobe.”
The scale of that spending is also reflected in women’s lingerie collections. According to the study, the average woman today has twice the amount of bras compared to women in the fifties.
Higher spending was a result of higher income and changes in women’s social status.
Sixty years ago, most women were given one career option: to get married and raise children. It was uncommon for them to enter the professional field. However, today, women have a much wider choice as to what occupation they want to go into.
Miss Average in 1957, according to the study, earned just £10 a week. Flash forward 60 years, she is earning an average of £530 a week.
The changes women have gone through physically and socially in six decades show how just a few generations can affect our society.
Looking at how far women have come raises the questions: what changes can we expect in the next 60 years? |
package raylib
/*
#include "../lib/raylib/src/rglfw.c"
#cgo darwin LDFLAGS: -framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo
#cgo darwin CFLAGS: -x objective-c -mmacosx-version-min=10.9 -I../lib/raylib/src/external/glfw/include -DPLATFORM_DESKTOP
#cgo linux LDFLAGS: -lGL -lm -pthread -ldl -lrt -lX11
#cgo linux CFLAGS: -I../lib/raylib/src/external/glfw/include -Wno-unused-result -DPLATFORM_DESKTOP
#cgo windows LDFLAGS: -lopengl32 -lgdi32 -lwinmm -lole32
#cgo windows CFLAGS: -I../lib/raylib/src/external/glfw/include -I../lib/raylib/src/external/glfw/deps/mingw -DPLATFORM_DESKTOP
*/
import "C"
|
def _get_router_info_list_for_tenant(self, routers, tenant_id):
router_ids = [
router['id']
for router in routers
if router['tenant_id'] == tenant_id]
router_info_list = []
for rid in router_ids:
if rid not in self.router_info:
continue
router_info_list.append(self.router_info[rid])
return router_info_list |
class TokenActions:
"""
Collection of token actions.
.. note::
This is just a class rather than an enum because enums cannot be
extended at runtime which would limit the number of token actions
to the ones implemented by FlaskBB itself and block extension of
tokens by plugins.
"""
RESET_PASSWORD = 'reset_password'
ACTIVATE_ACCOUNT = 'activate_account' |
#include <bits/stdc++.h>
using namespace std;
#define long long long
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define REP(i, n) for(int i = 0; i < n; ++i)
const int MAX = 200100;
vector<int> g[MAX];
long n, a[MAX], xorsum[MAX], ans, CS[22][2], AS[22][2], curRoot;
namespace centroid {
// empty mom[] before use, sz no need
vector<int> sz(MAX), mom(MAX);
auto &g = ::g; // outer access
int dfs(int i, int s, int p) {
sz[i] = 1;
int child = 0, ans = -1;
for (int j: g[i]) {
if (j != p && mom[j] == 0) {
int res = dfs(j, s, i);
if (res != -1) ans = res;
child = max(child, sz[j]);
sz[i] += sz[j];
}
}
// must be '<=', not '<' or will get MLE
return max(child,s-sz[i])*2 <= s ? i : ans;
}
// ================================
int dfs_xorsum(int i, int p) {
xorsum[i] ^= a[i];
ans += xorsum[i];
long withoutRoot = xorsum[i] ^ a[curRoot];
REP(b, 20) {
CS[b][(xorsum[i] >> b) & 1] += 1;
ans += (1LL << b) * AS[b][((withoutRoot >> b) & 1)^1];
}
for (int j: g[i]) {
if (mom[j] == 0 && j != p) {
xorsum[j] = xorsum[i];
dfs_xorsum(j, i);
}
}
}
// ================================
// n independent of 0- or 1-indexed
// root: any, p: previous centroid,
void run(int root, int n, int p) {
int i = dfs(root, n, -1);
if (i != -1) {
if (i != root) dfs(i, n, -1);
// ======================
curRoot = i;
memset(AS, 0, sizeof AS);
for (int j: g[i]) {
memset(CS, 0, sizeof CS);
if (mom[j] == 0) {
xorsum[j] = a[i];
dfs_xorsum(j, i);
}
REP(b, 20) {
AS[b][0] += CS[b][0];
AS[b][1] += CS[b][1];
}
}
// ======================
mom[i] = p;
for (int j: g[i]) {
if (mom[j] == 0) run(j, sz[j], i);
}
}
}
}
void body() {
cin >> n;
REP(i, n) {
cin >> a[i + 1];
ans += a[i + 1];
}
int u, v;
REP(i, n - 1) {
cin >> u >> v;
g[u].emplace_back(v);
g[v].emplace_back(u);
}
centroid::run(1, n, -1);
cout << ans << "\n";
}
int main() {
// freopen("main.in", "r", stdin);
// ios::sync_with_stdio(false);
body();
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.