content
stringlengths
10
4.9M
<gh_stars>10-100 package party.detection.unknown.util; /** * Utility for generating and getting data from integer colors. * * @author GenericSkid * @since 1/3/2018 */ public class Colors { public static int getColor(int red, int green, int blue) { return getColor(red, green, blue, 255); } /** * Encode given colors into a single integer. * * @param red * Inclusive value between 0-255. * @param green * Inclusive value between 0-255. * @param blue * Inclusive value between 0-255. * @param alpha * Inclusive value between 0-255. * @return Encoded color integer. */ public static int getColor(int red, int green, int blue, int alpha) { int color = 0; color |= alpha << 24; color |= red << 16; color |= green << 8; color |= blue; return color; } /** * Extracts the alpha value from the given color integer. * * @param color * Encoded color integer. * @return Alpha <i>(transparency)</i>. */ public static double getAlpha(int color) { return ((double) ((color >> 24 & 0xff) / 255F)); } /** * Extracts the red value from the given color integer. * * @param color * Encoded color integer. * @return Red. */ public static double getRed(int color) { return ((double) ((color >> 16 & 0xff) / 255F)); } /** * Extracts the green value from the given color integer. * * @param color * Encoded color integer. * @return Green. */ public static double getGreen(int color) { return ((double) ((color >> 8 & 0xff) / 255F)); } /** * Extracts the blue value from the given color integer. * * @param color * Encoded color integer. * @return Blue. */ public static double getBlue(int color) { return ((double) ((color & 0xff) / 255F)); } }
<filename>tests/unit/test_charm.py # Copyright 2020 Canonical Ltd. # See LICENSE file for licensing details. import hashlib import json import re import unittest import yaml from ops.testing import Harness from charm import CONFIG_PATH, DATASOURCES_PATH, PROVISIONING_PATH, GrafanaCharm MINIMAL_CONFIG = {"grafana-image-path": "grafana/grafana", "port": 3000} MINIMAL_DATASOURCES_CONFIG = { "apiVersion": 1, "datasources": [], "deleteDatasources": [], } BASIC_DATASOURCES = [ { "access": "proxy", "isDefault": "false", "name": "juju_test-model_abcdef_prometheus_0", "orgId": "1", "type": "prometheus", "url": "http://1.2.3.4:1234", } ] SOURCE_DATA = { "model": "test-model", "model_uuid": "abcdef", "application": "prometheus", "type": "prometheus", } DASHBOARD_CONFIG = { "apiVersion": 1, "providers": [ { "name": "Default", "type": "file", "options": {"path": "/etc/grafana/provisioning/dashboards"}, } ], } DB_CONFIG = { "type": "mysql", "host": "1.1.1.1:3306", "name": "mysqldb", "user": "grafana", "password": "<PASSWORD>", } DATABASE_CONFIG_INI = """[database] type = mysql host = 1.1.1.1:3306 name = mysqldb user = grafana password = <PASSWORD> url = mysql://grafana:[email protected]:3306/mysqldb """ def datasource_config(config): config_dict = yaml.safe_load(config) return config_dict def dashboard_config(config): config_dict = yaml.safe_load(config) return config_dict def global_config(config): config_dict = yaml.safe_load(config) return config_dict["global"] def cli_arg(plan, cli_opt): plan_dict = plan.to_dict() args = plan_dict["services"]["grafana"]["command"].split() for arg in args: opt_list = arg.split("=") if len(opt_list) == 2 and opt_list[0] == cli_opt: return opt_list[1] if len(opt_list) == 1 and opt_list[0] == cli_opt: return opt_list[0] return None class TestCharm(unittest.TestCase): def setUp(self): self.harness = Harness(GrafanaCharm) self.addCleanup(self.harness.cleanup) self.harness.begin() self.minimal_datasource_hash = hashlib.sha256( str(yaml.dump(MINIMAL_DATASOURCES_CONFIG)).encode("utf-8") ).hexdigest() def test_datasource_config_is_updated_by_raw_grafana_source_relation(self): self.harness.set_leader(True) # check datasource config is updated when a grafana-source joins rel_id = self.harness.add_relation("grafana-source", "prometheus") self.harness.update_relation_data( rel_id, "prometheus", {"grafana_source_data": json.dumps(SOURCE_DATA)} ) self.harness.add_relation_unit(rel_id, "prometheus/0") self.harness.update_relation_data( rel_id, "prometheus/0", {"grafana_source_host": "1.2.3.4:1234"} ) config = self.harness.charm.container.pull(DATASOURCES_PATH) self.assertEqual(yaml.safe_load(config).get("datasources"), BASIC_DATASOURCES) def test_datasource_config_is_updated_by_grafana_source_removal(self): self.harness.set_leader(True) rel_id = self.harness.add_relation("grafana-source", "prometheus") self.harness.update_relation_data( rel_id, "prometheus", {"grafana_source_data": json.dumps(SOURCE_DATA)} ) self.harness.add_relation_unit(rel_id, "prometheus/0") self.harness.update_relation_data( rel_id, "prometheus/0", {"grafana_source_host": "1.2.3.4:1234"} ) config = self.harness.charm.container.pull(DATASOURCES_PATH) self.assertEqual(yaml.safe_load(config).get("datasources"), BASIC_DATASOURCES) rel = self.harness.charm.framework.model.get_relation("grafana-source", rel_id) # type: ignore self.harness.charm.on["grafana-source"].relation_departed.emit(rel) config = yaml.safe_load(self.harness.charm.container.pull(DATASOURCES_PATH)) self.assertEqual(config.get("datasources"), []) self.assertEqual( config.get("deleteDatasources"), [{"name": "juju_test-model_abcdef_prometheus_0", "orgId": 1}], ) def test_config_is_updated_with_database_relation(self): self.harness.set_leader(True) rel_id = self.harness.add_relation("database", "mysql") self.harness.add_relation_unit(rel_id, "mysql/0") self.harness.update_relation_data( rel_id, "mysql", DB_CONFIG, ) config = self.harness.charm.container.pull(CONFIG_PATH) self.assertEqual(config.read(), DATABASE_CONFIG_INI) def test_dashboard_path_is_initialized(self): self.harness.set_leader(True) self.harness.charm.init_dashboard_provisioning(PROVISIONING_PATH + "/dashboards") dashboards_dir_path = PROVISIONING_PATH + "/dashboards/default.yaml" config = self.harness.charm.container.pull(dashboards_dir_path) self.assertEqual(yaml.safe_load(config), DASHBOARD_CONFIG) def can_get_password(self): self.harness.set_leader(True) # Harness doesn't quite support actions yet... self.assertTrue(re.match(r"[A-Za-z0-9]{12}", self.harness.charm._get_admin_password())) def test_config_is_updated_with_subpath(self): self.harness.set_leader(True) self.harness.update_config({"web_external_url": "/grafana"}) services = self.harness.charm.container.get_plan().services["grafana"].to_dict() self.assertIn("GF_SERVER_SERVE_FROM_SUB_PATH", services["environment"].keys()) self.assertTrue(services["environment"]["GF_SERVER_ROOT_URL"].endswith("/grafana"))
def deltalogp_spline(Flux, Variance, params_transitions, r): spline = func.prepare_shape(r) params_transitions = func.planet_fit(params_transitions, Time, Flux, Variance, spline, r) flux_planets = func.profile_with_spline(Time, *params_transitions, spline, r) logp = func.negative_2loglikelihood(Flux, Variance, func.distribution_parameters) - func.negative_2loglikelihood(Flux - flux_planets, Variance, func.distribution_parameters) print(np.sqrt(logp))
After years of promoting the theory that President Barack Obama was born in a foreign country -- one that has been consistently debunked by fact-checkers -- Donald Trump reversed course on Sept. 16, 2016, and said Obama was born in the United States. "President Barack Obama was born in the United States. Period," Trump said while briefly addressing the subject at the end of a campaign event at his newly built hotel in Washington. We’ve separately ruled this a Full Flop. But Trump’s other remarks on the so-called "birther" controversy have inspired fact-checks of their own. Trump prefaced his statement about Obama’s birthplace by saying, "Hillary Clinton and her campaign of 2008 started the birther controversy. I finished it. I finished it. You know what I mean." We rated the first part of that claim that "Hillary Clinton and her campaign of 2008 started the birther controversy" False. Here, we’ll fact-check the assertion that Trump "finished it." We didn’t hear back from the Trump campaign, but the evening before Trump’s announcement in Washington, Jason Miller, a senior communications adviser with the campaign, sent out a news release saying in part, "In 2011, Mr. Trump was finally able to bring this ugly incident to its conclusion by successfully compelling President Obama to release his birth certificate. Mr. Trump did a great service to the President and the country by bringing closure to the issue that Hillary Clinton and her team first raised." So it appears that the campaign’s argument is that Trump pushed for Obama to release the long form of his Hawaii birth certificate on April 27, 2011, several years after the birther controversy bubbled up. Previously, a shorter version of the document had been available, but skeptics had been calling for the full document to be released. Trump himself had made this case as early as Aug. 22, 2013, when he tweeted, "Why are people upset w/ me over Pres Obama’s birth certificate? I got him to release it, or whatever it was, when nobody else could!" But for Trump’s argument to hold water, we see two conditions that have to be met. First, did Trump "finish" advocating for the birther viewpoint once Obama released the long-form birth certificate? And second, did Obama’s release of the long-form certificate "finish" the idea among American voters that Obama was born outside the United States? In both cases, the answer is no. Trump’s continued birther tweets Slate has produced a comprehensive index to the tweets by Trump -- all made after Obama’s document release in 2011 -- in which the real-estate magnate either openly advocated birtherism or promoted skepticism about the official story of Obama’s birth. The list includes about three dozen examples between November 2011 and November 2014. Here’s a sampling: July 17, 2012: "I wonder what the answer is on @BarackObama's college application to the question: place of birth? Maybe the same as his book cover? Release your records, Mr. President!" July 20, 2012: "With @BarackObama listing himself as "Born in Kenya" in 1999 http://bit.ly/JaHQW0 HI laws allowed him to produce a fake certificate. #SCAM" Aug. 6, 2012: "An 'extremely credible source' has called my office and told me that @BarackObama's birth certificate is a fraud." Aug. 27, 2012: "Why do the Republicans keep apologizing on the so called "birther" issue? No more apologies--take the offensive!" Sept. 13, 2012: "Wake Up America! See article: "Israeli Science: Obama Birth Certificate is a Fake" http://bit.ly/UIfG7B." June 29, 2014: "Always remember, I was the one who got Obama to release his birth certificate, or whatever that was! Hilary couldn't, McCain couldn't." Sept. 6, 2014: "Attention all hackers: You are hacking everything else so please hack Obama's college records (destroyed?) and check ‘place of birth’" Public opinion about Obama’s birthplace The birther controversy never actually ended, either, judging by the polls. For starters, the birth certificate release itself didn't eliminate skepticism within the public about Obama’s birthplace -- not even close. At least two surveys looked at the question shortly before and shortly after Obama’s document release. Gallup asked whether respondents would say Obama was "probably or definitely born in another country" and found that the number dropped from 24 percent before the release in April 2011 to 13 percent after the release in May 2011. And YouGov asked whether "Barack Obama was born in the United States." Before the release, 15 percent of respondent said "false," a number that dropped to 13 percent after the release. Thirteen percent is not a trivial number of people in a nation of more than 300 million people. As time went on, polls by YouGov actually found rising numbers of respondents answering "false" "Barack Obama was born in the United States" -- 17 percent in January 2012 and 20 percent in July 2012. And as recently as September 2015, a CNN/Opinion Research Corp. poll found 13 percent answering "another country" when asked, "Where was Barack Obama born, as far as you know?" That poll was taken more than four years after Obama released his long-form birth certificate. Our ruling Trump said of the birther controversy, "I finished it." In no credible sense is this true. Trump didn’t "finish" fanning the flames of birther conspiracies once Obama released his long-form birth certificate in April 2011 -- he kept tweeting about it for at least another three and a half years. And a core group of Americans hasn’t "finished" expressing birther sentiments. As recently as a year ago, various polls have found that 13 percent of Americans supported the viewpoint. We rate Trump’s claim Pants on Fire. https://www.sharethefacts.co/share/f8a8c00a-de79-480b-8444-2e5f66aab040
// InitFlags creates logging flags which update the given variables. The passed mutex is // locked while the boolean variables are accessed during flag updates. func InitFlags( mu sync.Locker, toStderr *bool, logDir flag.Value, nocolor *bool, verbosity, vmodule, traceLocation flag.Value, ) { *toStderr = true flag.Var(&atomicBool{Locker: mu, b: toStderr}, LogToStderrName, "log to standard error instead of files") flag.BoolVar(nocolor, NoColorName, *nocolor, "disable standard error log colorization") flag.Var(verbosity, VerbosityName, "log level for V logs") flag.Var(vmodule, VModuleName, "comma-separated list of pattern=N settings for file-filtered logging") flag.Var(traceLocation, LogBacktraceAtName, "when logging hits line file:N, emit a stack trace") flag.Var(logDir, LogDirName, "if non-empty, write log files in this directory") }
Book reviews : Dunne, T. and Leopold, L .B. 1978: Water in environmental planning. San Francisco: W. H.| Freeman. xxvii + 818 pp. £17.40 A is misquoted in which the log of the x-terms should be summed, not the log of the mean of the x-terms. This is a very readable book, well illustrated and well referenced. Most of the diagrams have been taken directly from other published work, often without redrawing, and sometimes without any conversion of the non-metric units (especially in chapter 9), while a heavy reliance on the diagrams of A. N. Strahler is recognized in the preface. There are some 567 references quoted in the bibliography, but partly because of the date of publication, only 37 of those referred to were published after 1970, which slightly dates the work. Despite the occasional blemish and the rather staid view of climatology, it is sure to appear on reading lists for many ’applied climatology’ courses.
/** * This class is exposed to SpEL parsing through the variable <code>#{@value SPEL_PREFIX}</code>. Use the attributes * in your SpEL expressions: {@link #selectEntity}, {@link #fields}, {@link #bucket} and {@link #filter}. */ public static final class N1qlSpelValues { /** * <code>#{{@value SPEL_SELECT_FROM_CLAUSE}. * selectEntity</code> will be replaced by the SELECT-FROM clause corresponding to the entity. Use once at the * beginning. */ public final String selectEntity; /** * <code>#{{@value SPEL_ENTITY}. * fields</code> will be replaced by the list of N1QL fields allowing to reconstruct the entity. */ public final String fields; /** * <code>#{{@value SPEL_BUCKET}. * bucket</code> will be replaced by (escaped) bucket name in which the entity is stored. */ public final String bucket; /** * <code>#{{@value SPEL_FILTER}}. * filter</code> will be replaced by an expression allowing to select only entries matching the entity in a WHERE * clause. */ public final String filter; /** * <code>#{{@value SPEL_DELETE}}. * delete</code> will be replaced by a delete expression. */ public final String delete; /** * <code>#{{@value SPEL_RETURNING}}. * returning</code> will be replaced by a returning expression allowing to return the entity and meta information on * deletes. */ public final String returning; public N1qlSpelValues(String selectClause, String entityFields, String bucket, String filter, String delete, String returning) { this.selectEntity = selectClause; this.fields = entityFields; this.bucket = bucket; this.filter = filter; this.delete = delete; this.returning = returning; } }
class WorkflowInfo: """Workflow info adapter""" def __init__(self, context): self.context = context self.wf = get_utility(IWorkflow, name=self.name) # pylint: disable=invalid-name @property def parent(self): """Workflow managed content getter""" return get_parent(self.context, IWorkflowManagedContent) @property def name(self): """Workflow name getter""" return self.parent.workflow_name def fire_transition(self, transition_id, comment=None, side_effect=None, check_security=True, principal=None, request=None): # pylint: disable=too-many-arguments """Fire transition with given ID""" versions = IWorkflowVersions(self.parent) state = IWorkflowState(self.context) if request is None: request = check_request() # this raises InvalidTransitionError if id is invalid for current state transition = self.wf.get_transition(state.state, transition_id) # check whether we may execute this workflow transition if check_security and transition.permission: if not request.has_permission(transition.permission, context=self.context): raise HTTPUnauthorized() # now make sure transition can still work in this context if not transition.condition(self, self.context): raise ConditionFailedError() # perform action, return any result as new version if principal is None: principal = request.principal result = transition.action(self, self.context) if result is not None: # stamp it with version versions.add_version(result, transition.destination, principal) # execute any side effect: if side_effect is not None: side_effect(result) event = WorkflowVersionTransitionEvent(result, self.wf, principal, self.context, transition.source, transition.destination, transition, comment) else: versions.set_state(state.version_id, transition.destination, principal) # execute any side effect if side_effect is not None: side_effect(self.context) event = WorkflowTransitionEvent(self.context, self.wf, principal, transition.source, transition.destination, transition, comment) # change state of context or new object registry = request.registry registry.notify(event) # send modified event for original or new object if result is None: registry.notify(ObjectModifiedEvent(self.context)) else: registry.notify(ObjectModifiedEvent(result)) return result def fire_transition_toward(self, state, comment=None, side_effect=None, check_security=True, principal=None, request=None): # pylint: disable=too-many-arguments """Fire transition(s) to given state""" current_state = IWorkflowState(self.context) if state == current_state.state: # unchanged state return None transition_ids = self.get_fireable_transition_ids_toward(state, check_security) if not transition_ids: raise NoTransitionAvailableError(current_state.state, state) if len(transition_ids) != 1: raise AmbiguousTransitionError(current_state.state, state) return self.fire_transition(transition_ids[0], comment, side_effect, check_security, principal, request) def fire_transition_for_versions(self, state, transition_id, comment=None, principal=None, request=None): # pylint: disable=too-many-arguments """Fire transition for all versions in given state""" versions = IWorkflowVersions(self.parent) for version in versions.get_versions(state): IWorkflowInfo(version).fire_transition(transition_id, comment, principal=principal, request=request) def fire_automatic(self): """Fire automatic transitions""" for transition_id in self.get_automatic_transition_ids(): try: self.fire_transition(transition_id) except ConditionFailedError: # if condition failed, that's fine, then we weren't # ready to fire yet pass else: # if we actually managed to fire a transition, # we're done with this one now. return def has_version(self, state): """Test for existing versions in given state""" wf_versions = IWorkflowVersions(self.parent) return wf_versions.has_version(state) def get_manual_transition_ids(self, check_security=True): """Getter for available transitions IDs""" if check_security: request = check_request() permission_checker = request.has_permission else: permission_checker = granted_permission return [ transition.transition_id for transition in sorted(self._get_transitions(MANUAL_TRANSITION), key=lambda x: x.user_data.get('order', 999)) if transition.condition(self, self.context) and permission_checker( transition.permission, context=self.context) ] def get_system_transition_ids(self): """Getter for system transitions IDs, ignoring permissions checks. """ return [ transition.transition_id for transition in sorted(self._get_transitions(SYSTEM_TRANSITION), key=lambda x: x.user_data.get('order', 999)) if transition.condition(self, self.context) ] def get_fireable_transition_ids(self, check_security=True): """Get IDs of transitions which can be fired""" return (self.get_manual_transition_ids(check_security) + self.get_system_transition_ids()) def get_fireable_transition_ids_toward(self, state, check_security=True): """Get IDs of transitions which can be fired to access given state""" result = [] for transition_id in self.get_fireable_transition_ids(check_security): transition = self.wf.get_transition_by_id(transition_id) if transition.destination == state: result.append( transition_id) return result def get_automatic_transition_ids(self): """Get IDs of automatic transitions""" return [ transition.transition_id for transition in self._get_transitions(AUTOMATIC_TRANSITION) ] def has_automatic_transitions(self): """Text existing automatic transitions""" return bool(self.get_automatic_transition_ids()) def _get_transitions(self, trigger): """Retrieve all possible transitions from workflow utility""" state = IWorkflowState(self.context) transitions = self.wf.get_transitions(state.state) # now filter these transitions to retrieve all possible # transitions in this context, and return their ids return [transition for transition in transitions if transition.trigger == trigger]
UFC 164's fight card isn't quite above reproach, but it is very, very good. The key consideration, though, is not whether it's good or bad. Rather, it's whether FOX exposure leads to increased pay-per-view sales. UFC CEO Lorenzo Fertitta famously told the press before the first FOX fight if the seven-year deal resulted in just 100,000 more UFC pay-per-view subscribers, the entire partnership would've been worth it. In the coming days, we may find out how close to that mark the UFC truly is. There are essentially two competing theories about FOX and pay-per-view as it relates to the UFC. The first is the free content on the major network is often so good that it entices viewers to watch, but does little in the way of producing pay-per-view subscribers. After all, these fights are good, the fighters are excellent, but none are Anderson Silva or Georges St-Pierre stars. They're getting there, but aren't there, at least not yet. So why bother paying for them? The theory suggests casual viewers will tune in on FOX, but won't make the leap behind the paywall. The other theory, the more prominent of the two, suggests over time FOX exposure will lead viewers to pay-per-view buys where fans will want to follow who they've watched for free. As these fighters, particularly like champion Benson Henderson, advance their career fight after fight, their star power builds. Once they've reached a certain tipping point, enough fans will have watched them win to want to them pay to see them at this elevated stage of their career. Where is Henderson on that continuum? We don't know, but anecdotal evidence (which is admittedly very flawed and imprecise) suggests this pay-per-view will sell ok, but not great. What does that mean for FOX and pay-per-view? It may mean it's either not the vehicle to create more pay-per-view subscribers or that Henderson, should he keep winning, will take an inordinately long time to turn into an attraction fans will pay money to see, if he converts into one at all. The UFC will get the results from tonight's weather balloon very soon and what the data reads could be hugely indicative of which theory about FOX and pay-per-view is actually true. Neither situation is any sort of doomsday scenario for the UFC. Great ratings are great ratings, and pay-per-view sells well enough. But if FOX exposure only leads to FOX ratings, the UFC might be facing new pressure as it looks at its business model for the next 10 years. If rights fees can generate huge dollars and pay-per-view can't be buoyed by television, is an all rights-fee model in the organization's future? It's not an idle question. Benson Henderson vs. Anthony Pettis At stake: belts, bragging rights and bounty. What needs to be said about this bout that hasn't already been uttered, explained and exclaimed a thousand times already? The lightweight title is on the line, which brings with it untold fortunes and favors. This is also a rematch and just a hint of competitive bad blood, which makes winning the second one even more important. What I focus more on is the chance of the division to rebuild itself a touch in the absence of B.J. Penn. I don't mean from a competitive standpoint as the talent hasn't slipped at all. I mean as a promotional powerhouse. Pettis seems much more star-friendly than Henderson, but that's neither here nor there. What catches my eye is what a potential rivalry between the two could do for the division. Henderson and Edgar or Edgar and everyone else he faced (including Gray Maynard) never had quite the back story these two do. They never had quite the contrast in styles and neither had the potent finishing skills of Pettis. There is something particularly interesting about their rivalry and one wonders if there's enough there to lift the division back up (or at least tonight's winner) into more of a promotional juggernaut moving forward. Frank Mir vs. Josh Barnett At stake: a resume highlight. There's more to any fight than I can describe in the pity space of two or three words. This is one such occasion where that is particularly true. This fight feels like the winner, depending on how they win, could bounce themselves into all sorts of opportunities that otherwise wouldn't exist. The fact is beating Frank Mir or stopping Josh Barnett, even in 2013, is a real achievement. If nothing else, a win here is a huge moment of success. When we further place into context the reality there's a dearth of contenders at heavyweight, it's not inconceivable - especially for the matriculating Barnett - title shot talk could emerge. This one is an old fashioned grudge match between two veterans who've proven a lot and still have the ability to wreak havoc on the right night in the right moment. Here's to hoping one of them seizes the day. Chad Mendes vs. Clay Guida At stake: Jose Aldo title shot sweepstakes. Chad Mendes may have fallen short against Jose Aldo the first time they met (dramatically so), but he's on the cusp of another title shot. Sure, beating Cody McKenzie doesn't mean much, but stopping Darren Elkins does. And if he can look dominant against Clay Guida, despite the Greg Jackson-trained fighter's recent problems, he can do wonders for advancing his cause as the division's top contender behind Ricardo Lamas. As for Guida, he needs to right the ship. He squeaked past Hatsu Hioki after laying an egg at lightweight. If you've ever seen Guida fight at a UFC event, there are few non-title holders who generate greater fan enthusiasm. One wonders, though, if that's starting to wane. Guida's go for broke style has given way to patience, extreme caution and ultra reactionary offense. I'm not suggesting he fight anyway other than what he feels is best, but the quickest way to turn fans sour is to fight like he has been and lose. Guida needs this fight to get back on course in the division and with the faithful who've chanted his name. Ben Rothwell vs. Brandon Vera At stake: UFC employment. It's been a long time since Brandon Vera has won a bout while looking impressive. Even his most recent win, a decision victory over Elliot Marshall at UFC 137, came after he was nearly submitted via armbar. I don't know if going back to heavyweight is the answer for what ails him, but it at least provides an opportunity to claim reinvention. Weight class change can often provide cover for at least one loss, so Vera has time to find some cause for continued employment. Rothwell, by contrast, is a .500 heavyweight in the UFC. That may or may not be enough to keep him in the majors, but it's probably more precarious than he'd like. A win over Vera doesn't mean a ton, but it's enough to get back on the winning track after losing badly to Gabriel Gonzaga. Right now, that's the most important thing. Erik Koch vs. Dustin Poirier At stake: a place in the pecking order. Both Koch and Poirier are coming off of bad losses. Koch's was especially violent. If there was ever a time for them to prove they're more than what we last saw of them, it's right now. Unlike Koch, who has a stoppage win over Raphael Assuncao, Poirier still lacks a signature win in the division. He can chew up and spit out those just below the elite level with aplomb, but hasn't really been able to break through as a guy among the top contenders who can consistently threaten. Defeating Koch would change that for him. Koch is still in the rebuilding stage after having his title shot slip through his fingers. Beating Poirier doesn't really put him in the front of the line, but it's a solid building block on the path back.
<filename>src/container/HomeContainer/actions.tsx export function listIsLoading(bool: boolean) { return { type: "LIST_IS_LOADING", isLoading: bool, }; } export function fetchListSuccess(list: Object) { return { type: "FETCH_LIST_SUCCESS", list, }; } export function checkLogout(bool: boolean) { return { type: "LOGOUT", isLogout: bool, } } export function fetchList(url) { return dispatch => { dispatch(fetchListSuccess(url)); dispatch(listIsLoading(false)); }; } export function logout() { return dispatch=>{ dispatch(checkLogout(true)) //ban đầu truyền vào isLogout=true cho action } }
<reponame>TheSilverEcho/ZeroPointAPI<filename>src/main/java/me/thesilverecho/zeropoint/api/module/ClientModule.java package me.thesilverecho.zeropoint.api.module; import org.lwjgl.glfw.GLFW; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ClientModule { /** * @return name of the module */ String name(); /** * @return description of the module */ String description() default "No description provided"; /** * @return if the module should be drawn in the array list */ boolean shouldDraw() default true; /** * @return if renderer notification must be sent when the module is toggled */ boolean showToggleMsg() default false; /** * @return if the module is active by default */ boolean active() default false; /** * @return the keybinding for the module */ int keyBinding() default GLFW.GLFW_KEY_UNKNOWN; }
<gh_stars>1-10 export enum ProfileRole { Admin = 'ADMIN', Coordinator = 'COORDINATOR', Crew = 'CREW', FleetManager = 'FLEET MANAGER', Member = 'MEMBER', Skipper = 'SKIPPER', None = 'NONE' }
/* * is_present - returns TRUE if tag is already present on the stack. */ int html_text::is_present (HTML_TAG t) { tag_definition *p=stackptr; while (p != NULL) { if (t == p->type) return TRUE; p = p->next; } return FALSE; }
<filename>ferrite-session/src/internal/session/channel/receive.rs use tokio::{ task, try_join, }; use crate::internal::{ base::{ once_channel, unsafe_create_session, unsafe_run_session, AppendContext, Context, ContextLens, Empty, PartialSession, Protocol, }, functional::Nat, protocol::ReceiveChannel, }; pub fn receive_channel<C1, C2, N, A, B>( cont: impl FnOnce(N) -> PartialSession<C2, B> ) -> PartialSession<C1, ReceiveChannel<A, B>> where N: Nat, A: Protocol, B: Protocol, C1: Context<Length = N>, C2: Context, C1: AppendContext<(A, ()), Appended = C2>, { let cont2 = cont(N::nat()); unsafe_create_session(move |ctx1, sender| async move { let (sender1, receiver1) = once_channel(); sender.send(ReceiveChannel(sender1)).unwrap(); let (receiver2, sender2) = receiver1.recv().await.unwrap(); let ctx2 = C1::append_context(ctx1, (receiver2, ())); unsafe_run_session(cont2, ctx2, sender2).await; }) } pub fn receive_channel_slot<I, P, Q, N>( _: N, cont: PartialSession<N::Target, Q>, ) -> PartialSession<I, ReceiveChannel<P, Q>> where P: Protocol, Q: Protocol, I: Context, N: ContextLens<I, Empty, P>, { unsafe_create_session(move |ctx1, sender| async move { let ((), ctx2) = N::extract_source(ctx1); let (sender1, receiver1) = once_channel(); let child1 = task::spawn(async move { sender.send(ReceiveChannel(sender1)).unwrap(); }); let child2 = task::spawn(async move { let (receiver2, sender2) = receiver1.recv().await.unwrap(); let ctx3 = <N as ContextLens<I, Empty, P>>::insert_target(receiver2, ctx2); unsafe_run_session(cont, ctx3, sender2).await; }); try_join!(child1, child2).unwrap(); }) } pub fn send_channel_to<N, M, C1, C2, C3, A1, A2, B>( _n: N, _m: M, cont: PartialSession<C3, B>, ) -> PartialSession<C1, B> where C1: Context, C2: Context, C3: Context, A1: Protocol, A2: Protocol, B: Protocol, N: ContextLens<C2, ReceiveChannel<A1, A2>, A2, Target = C3>, M: ContextLens<C1, A1, Empty, Target = C2>, { unsafe_create_session(move |ctx1, sender1| async move { let (receiver1, ctx2) = M::extract_source(ctx1); let ctx3 = M::insert_target((), ctx2); let (receiver2, ctx4) = N::extract_source(ctx3); let ReceiveChannel(sender2) = receiver2.recv().await.unwrap(); let (sender3, receiver3) = once_channel(); let child1 = task::spawn(async move { sender2.send((receiver1, sender3)).unwrap(); }); let ctx5 = N::insert_target(receiver3, ctx4); let child2 = task::spawn(async move { unsafe_run_session(cont, ctx5, sender1).await; }); try_join!(child1, child2).unwrap(); }) }
/** * Add a new Meme * * @param meme Meme object contains name, url, caption * @return created Meme id */ @ApiOperation(value="Add a Meme post", notes="returns the id") @PostMapping public ResponseEntity<Object> AddMeme(@Valid @RequestBody Meme meme) { if (memeService.alreadyExist(meme)) { return ResponseEntity.status(409).body("content already exists"); } int id = memeService.addMeme(meme); System.out.println(meme); return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("id", id)); }
Signal/Noise and Sensitometry Limitations in Chest Radiography: Implications of Regional Exposure Control The field of medical imaging has experienced many significant advances in recent years with the evolution of a host of computer assisted imaging methods. This growth has also been evident in the areas of more conventional radiography through improved resolution and sensitivity in screen/film technologies. However, in spite of these improvements the fundamental principles of radiographic projection imaging have not significantly changed since its earliest demonstration. A case in point is the nature of the irradiation technique itself which routinely uses a field. of radiation of spatially uniform intensity. These uniform fields can result in large variations in transmitted exposure when used in radio graphy of the chest, head and neck. These wide exposure variations often exceed the useful exposure range of conventional radiographic film/screen combinations and result in large portions of the image being rendered with suboptimal contrast. In chest radiography this is particularly evident, resulting in images where the thick mediastinal, diaphragmatic and heart regions are rendered with negligible contrast when the thinner lung zones are properly. exposed.
import { Component, Input } from '@angular/core'; import { InvoiceService } from '../../invoice.service'; import { PrintService } from '../../../../services/print.service'; import { OrganizationService } from '../../../organization/organization.service'; import 'rxjs/add/operator/take'; @Component({ selector: ' suspended-invoice-print', templateUrl: './print.html' }) export class SuspendedInvoicePrint { amount = 0; totalAmount = 0.0; totalWeight = 0.0; otherAmount = 0.0; xAddress: any = null; xLoadingPlanItemList = []; @Input() set id(id: number) { if (this.id !== 0) { this.service.get(+id).take(1).subscribe(data => { if (data === null) return; this.invoice = data; this.totalAmount = 0.0; this.totalWeight = 0.0; this.xAddress = null; this.xLoadingPlanItemList = []; for (let i = 0; i < this.invoice.dispatchNoteList.length; i++) { let dispatchNote = this.invoice.dispatchNoteList[i]; if (dispatchNote === undefined) return; let xLoadingPlanList = dispatchNote.loadingPlanList; for (let ii = 0; ii < xLoadingPlanList.length; ii++) { let xLoadingPlan = xLoadingPlanList[ii]; if (this.xAddress === null) { this.xAddress = xLoadingPlan.address; } } } for (let i = 0; i < this.invoice.dispatchNoteList.length; i++) { let yLoadingPlanList = this.invoice.dispatchNoteList[i].loadingPlanList; for (let ii = 0; ii < yLoadingPlanList.length; ii++) { let yLoadingPlanItemList = yLoadingPlanList[ii].loadingPlanItemList; for (let iii = 0; iii < yLoadingPlanItemList.length; iii++) { let yLoadingPlanItem = yLoadingPlanItemList[iii]; let yItemId = yLoadingPlanItem.dispatchSchedule.job.item.id; let ySalesOrderId = yLoadingPlanItem.dispatchSchedule.salesOrderItem.salesOrder.id; let found = false; for (let iiii = 0; iiii < this.xLoadingPlanItemList.length; iiii++) { let xLoadingPlanItem = this.xLoadingPlanItemList[iiii]; let xItemId = xLoadingPlanItem.dispatchSchedule.job.item.id; let xSalesOrderId = xLoadingPlanItem.dispatchSchedule.salesOrderItem.salesOrder.id; if (yItemId === xItemId && ySalesOrderId === xSalesOrderId){ if (yLoadingPlanItem.unitPrice === null || yLoadingPlanItem.unitPrice === undefined){ yLoadingPlanItem.unitPrice = yLoadingPlanItem.dispatchSchedule.salesOrderItem.unitPrice; } this.totalAmount += yLoadingPlanItem.invoiceQuantity * yLoadingPlanItem.unitPrice; xLoadingPlanItem.invoiceQuantity += yLoadingPlanItem.invoiceQuantity; xLoadingPlanItem.amount += yLoadingPlanItem.invoiceQuantity * yLoadingPlanItem.unitPrice; xLoadingPlanItem.weight = yLoadingPlanItem.invoiceQuantity * yLoadingPlanItem.dispatchSchedule.job.item.weight; this.totalWeight += xLoadingPlanItem.weight; found = true; break; } } if (!found){ if (yLoadingPlanItem.unitPrice === null || yLoadingPlanItem.unitPrice === undefined){ yLoadingPlanItem.unitPrice = yLoadingPlanItem.dispatchSchedule.salesOrderItem.unitPrice; } yLoadingPlanItem.amount = yLoadingPlanItem.invoiceQuantity * yLoadingPlanItem.unitPrice; this.totalAmount += yLoadingPlanItem.amount; yLoadingPlanItem.weight = yLoadingPlanItem.invoiceQuantity * yLoadingPlanItem.dispatchSchedule.job.item.weight; this.totalWeight += yLoadingPlanItem.weight; this.xLoadingPlanItemList.push(yLoadingPlanItem); } } } } setTimeout(() => { let element = document.getElementById('suspendedInvoicePrint'); if (element != null) { this.printService.printA4(element.innerHTML); } }, 100); }); } } organization: any; invoice: any; constructor( private service: InvoiceService, private printService: PrintService, private organizationService: OrganizationService) { this.getOrganization(); } getOrganization() { this.organizationService.getAll().subscribe((data: any) => { this.organization = data[0]; }); } }
/** * A Graph-wrapper to use as base in a {@link #getWorkModel() working model}. * <p> * Created by @ssz on 01.03.2019. */ public static class TrackedGraph extends WrappedGraph { public TrackedGraph(Graph base) { super(Objects.requireNonNull(base)); } @Override public void add(Triple t) { if (base.contains(t)) return; super.add(t); } @Override public void delete(Triple t) { if (!base.contains(t)) return; super.delete(t); } }
Better policing, extra help for single mothers and incentives for companies to recruit from poor districts are among Macron's plans for tackling stubborn deprivation away from the bright lights in the centre of big cities. "I want the face of our neighbourhoods to have changed by the end of my term," the French leader said, expressing regret that gritty suburbs had become synonymous with crime and violence. The major speech in one of France's poorest towns -- Tourcoing, on the Belgian border -- comes as the former investment banker has faced repeated criticism for seeming out of touch. He acknowledged that France's industrial belt -- where voters backed his far-right rival Marine Le Pen in droves at this year's presidential election -- had been hard hit by globalisation. Jobs, opportunities and safe surroundings should not be "reserved for the luckiest," the 39-year-old centrist said. And he said government failures were partly to blame for Islamic radicalisation in depressed immigrant suburbs which has resulted in hundreds of young men setting off to join jihadists in Syria and Iraq. "In these neighbourhoods we have closed schools, cut aid for the oldest and youngest, and other groups have arrived touting solutions for all of that," he said, pointing to ultra-conservative Muslim associations. "I cannot ask a young person to believe in the republic when the republic isn't up to it," he added, promising more than a dozen anti-radicalisationschemes by the start of 2018. Tax cuts Set out at a carefully chosen location -- a former industrial centre renovated as a hub for tech firms -- Macron's plans include tax benefits for companies hiring workers from deprived neighbourhoods. The pilot scheme will from January exempt companies hiring people from target areas -- including Marseille and the Paris suburbs -- from thousands of euros of payroll taxes per employee. Poor neighbourhoods will also be first in line for the 10,000 new police Macron has vowed to hire, as well as investment in transport links and trial schemes to combat discrimination. The speech followed a similar trip Monday to Clichy-sous-Bois -- the north Paris suburb where nationwide riots first flared in 2005 -- with Macron facing scepticism from the left over his commitment to helping the working class. "How you can you give a speech on urban policy when you're hitting social housing and subsidised jobs?" said Martine Aubry, the Socialist mayor of Lille which counts Tourcoing as a suburb. Macron has come under fire from critics labelling him a "president of the rich" for slashing wealth taxes while cutting housing benefits and axing thousands of job contracts subsidised by the government. A series of offhand comments -- dismissing critics of his business-friendly labour reforms as "slackers", for instance -- have also landed him in hot water. Macron insists his wider programme of tax cuts will benefit poor and middle-income families. "I don't know what that means, 'having a policy for the rich'," he hit back Tuesday. "All I know is that when there is not an economy that moves everyone forward, neighbourhoods in difficulty do not do well." Macron's ratings have plummeted since he stormed to power in May at the head of new centrist party En Marche (On The Move). Some 40 percent had a positive opinion of him in October, according to a survey published by the Liberation newspaper Monday, down 13 points from June. Two thirds consider themselves to be losers from his policies, according to the poll. Two major trade unions, the CGT and FO, have called demonstrations Thursdayagainst his reforms, which include an overhaul of France's famously complicated labour code.
/* * Set a default IPv6 address for a 6to4 tunnel interface 2002:<tsrc>::1/16 */ static void ipif_set6to4addr(ipif_t *ipif) { ill_t *ill = ipif->ipif_ill; struct in_addr v4phys; ASSERT(ill->ill_mactype == DL_6TO4); ASSERT(ill->ill_phys_addr_length == sizeof (struct in_addr)); ASSERT(ipif->ipif_isv6); if (ipif->ipif_flags & IPIF_UP) return; (void) ip_plen_to_mask_v6(16, &ipif->ipif_v6net_mask); bcopy(ill->ill_phys_addr, &v4phys, sizeof (struct in_addr)); IN6_V4ADDR_TO_6TO4(&v4phys, &ipif->ipif_v6lcl_addr); V6_MASK_COPY(ipif->ipif_v6lcl_addr, ipif->ipif_v6net_mask, ipif->ipif_v6subnet); }
<reponame>afizsavage/Mide-Ice-Cream-SIte import React, { useState, useEffect, useRef } from "react" import { Nav } from "react-bootstrap" import { Link } from "gatsby" interface Iprops { lists: Array<string> path: string name: string } interface IListItemProps { LinkName: string key: number } const ListItem = ({ LinkName }: IListItemProps) => { return ( <li> <Link to="flavours/milo" className="text-decoration-none"> <span>{LinkName}</span> </Link> </li> ) } const DDownNavs = ({ lists, path, name }: Iprops) => { // Create a ref that we add to the element for which we want to detect outside clicks const ref = useRef() //const [hovered, setHovered] = useState(false) const [isOpen, setisOpen] = useState(false) const DDownStatus = event => { setisOpen(true) console.log(`${lists}`) } useOnClickOutside(ref, () => setisOpen(false)) //const toggleHover = () => {setHovered(!hovered)} const contentItems = lists.map((list, index) => { return <ListItem key={index} LinkName={list} /> }) return ( <li ref={ref} className={isOpen ? "dd-sm-show-below dd-sm-show" : ""} onMouseEnter={DDownStatus} //onMouseLeave={toggleHover} > <Link to={path} className="navlink text-decoration-none"> {name} </Link> <ul className="dropdown-content dd-submenu list-unstyled"> {contentItems} </ul> </li> ) } const Navlinks = () => { return ( <Nav className="ml-auto mr-auto pl-5"> <ul className="list-group list-group-horizontal-md list-unstyled"> <DDownNavs lists={["<NAME>"]} path="/page-2" name="FLAVOURS" /> <DDownNavs lists={["<NAME>"]} path="/page-2" name="SHOPS &amp; CATERING" /> <DDownNavs lists={["<NAME>"]} path="/page-2" name="VALUES" /> <DDownNavs lists={["<NAME>", "<NAME>"]} path="/page-2" name="ABOUT US" /> </ul> </Nav> ) } function useOnClickOutside(ref, handler) { useEffect( () => { const listener = event => { // Do nothing if clicking ref's element or descendent elements if (!ref.current || ref.current.contains(event.target)) { return } handler(event) } document.addEventListener("mousedown", listener) document.addEventListener("touchstart", listener) return () => { document.removeEventListener("mousedown", listener) document.removeEventListener("touchstart", listener) } }, // Add ref and handler to effect dependencies // It's worth noting that because passed in handler is a new ... // ... function on every render that will cause this effect ... // ... callback/cleanup to run every render. It's not a big deal ... // ... but to optimize you can wrap handler in useCallback before ... // ... passing it into this hook. [ref, handler] ) } export default Navlinks
<filename>angular-libs/projects/angular-reactive-message/src/lib/angular-reactive-message.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; export enum MessageType { warning = 'warning', info = 'info', error = 'danger' } @Injectable() export class AngularReactiveMessageService { private messageSubject = new BehaviorSubject<{ message: string, type: string }>(null); message$ = this.messageSubject.asObservable(); constructor() { } showMessage(message: string, type: MessageType) { this.messageSubject.next({ message, type }); } }
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "CommonCorePch.h" #include "Core/BinaryFeatureControl.h" //For making direct call in release binaries. #if !defined(DELAYLOAD_SET_CFG_TARGET) extern "C" WINBASEAPI BOOL WINAPI GetProcessMitigationPolicy( __in HANDLE hProcess, __in PROCESS_MITIGATION_POLICY MitigationPolicy, __out_bcount(nLength) PVOID lpBuffer, __in SIZE_T nLength ); #endif // ENABLE_DEBUG_CONFIG_OPTIONS bool BinaryFeatureControl::RecyclerTest() { #ifdef RECYCLER_TEST return true; #else return false; #endif } BOOL BinaryFeatureControl::GetMitigationPolicyForProcess(__in HANDLE hProcess, __in PROCESS_MITIGATION_POLICY MitigationPolicy, __out_bcount(nLength) PVOID lpBuffer, __in SIZE_T nLength) { #if !defined(DELAYLOAD_SET_CFG_TARGET) return GetProcessMitigationPolicy(hProcess, MitigationPolicy, lpBuffer, nLength); #else return FALSE; #endif }
/** * If the model is not fit this classifier, it will be error. * <p>CreateTime : 2014-11-19 * @author xiaoxiao * */ public class ModelException extends Exception{ public ModelException(){} public ModelException(String msg){ super(msg); } }
Translating lifestyle intervention to practice in obese patients with type 2 diabetes: Improving Control with Activity and Nutrition (ICAN) study. OBJECTIVE To assess the efficacy of a lifestyle intervention program that can be readily translated into clinical practice for obese patients with type 2 diabetes. RESEARCH DESIGN AND METHODS The study consisted of a 12-month randomized controlled trial of 147 health plan members with type 2 diabetes and obesity (BMI >or=27 kg/m(2)). Participants were randomized to lifestyle case management or usual care. Case management entailed individual and group education, support, and referral by registered dietitians; intervention cost was US dollars 350 per person. Individuals treated with usual care received educational material. Both groups received ongoing primary care. Outcomes were difference between groups for change in weight (kilograms), waist circumference (centimeters), HbA(1c), fasting lipid levels, use of prescription medications, and health-related quality of life. RESULTS Case management resulted in greater weight loss (P < 0.001), reduced waist circumference (P < 0.001), reduced HbA(1c) level (P = 0.02), less use of prescription medications (P = 0.03), and improved health-related quality of life (P < 0.001) compared with usual care. The 12-month group difference in weight loss and waist circumference was 3.0 kg (95% CI -5.4 to -0.6) and -4.2 cm (-6.8 to -1.6). HbA(1c) differences were greatest at 4 months (-0.59%, P = 0.006) but not significant by 12 months (-0.19%, P = 0.45). Participants in the case management group lowered their use of medications, primarily diabetes medications, by 0.8 medications per day more than participants treated with usual care (P = 0.03). In seven of nine quality-of-life domains, the case management group improved compared with usual care (P < 0.05). CONCLUSIONS Moderate-cost dietitian-led lifestyle case management may improve diverse health indicators among obese patients with type 2 diabetes.
def cmu_mocap(subject, train_motions, test_motions=[], sample_every=4, data_set='cmu_mocap'): subject_dir = os.path.join(data_path, data_set) all_motions = train_motions + test_motions resource = cmu_urls_files(([subject], [all_motions])) data_resources[data_set] = data_resources['cmu_mocap_full'].copy() data_resources[data_set]['files'] = resource['files'] data_resources[data_set]['urls'] = resource['urls'] if resource['urls']: download_data(data_set) skel = GPy.util.mocap.acclaim_skeleton(os.path.join(subject_dir, subject + '.asf')) exlbls = np.eye(len(train_motions)) tot_length = 0 temp_Y = [] temp_lbls = [] for i in range(len(train_motions)): temp_chan = skel.load_channels(os.path.join(subject_dir, subject + '_' + train_motions[i] + '.amc')) temp_Y.append(temp_chan[::sample_every, :]) temp_lbls.append(np.tile(exlbls[i, :], (temp_Y[i].shape[0], 1))) tot_length += temp_Y[i].shape[0] Y = np.zeros((tot_length, temp_Y[0].shape[1])) lbls = np.zeros((tot_length, temp_lbls[0].shape[1])) end_ind = 0 for i in range(len(temp_Y)): start_ind = end_ind end_ind += temp_Y[i].shape[0] Y[start_ind:end_ind, :] = temp_Y[i] lbls[start_ind:end_ind, :] = temp_lbls[i] if len(test_motions) > 0: temp_Ytest = [] temp_lblstest = [] testexlbls = np.eye(len(test_motions)) tot_test_length = 0 for i in range(len(test_motions)): temp_chan = skel.load_channels(os.path.join(subject_dir, subject + '_' + test_motions[i] + '.amc')) temp_Ytest.append(temp_chan[::sample_every, :]) temp_lblstest.append(np.tile(testexlbls[i, :], (temp_Ytest[i].shape[0], 1))) tot_test_length += temp_Ytest[i].shape[0] Ytest = np.zeros((tot_test_length, temp_Ytest[0].shape[1])) lblstest = np.zeros((tot_test_length, temp_lblstest[0].shape[1])) end_ind = 0 for i in range(len(temp_Ytest)): start_ind = end_ind end_ind += temp_Ytest[i].shape[0] Ytest[start_ind:end_ind, :] = temp_Ytest[i] lblstest[start_ind:end_ind, :] = temp_lblstest[i] else: Ytest = None lblstest = None info = 'Subject: ' + subject + '. Training motions: ' for motion in train_motions: info += motion + ', ' info = info[:-2] if len(test_motions) > 0: info += '. Test motions: ' for motion in test_motions: info += motion + ', ' info = info[:-2] + '.' else: info += '.' if sample_every != 1: info += ' Data is sub-sampled to every ' + str(sample_every) + ' frames.' return data_details_return({'Y': Y, 'lbls' : lbls, 'Ytest': Ytest, 'lblstest' : lblstest, 'info': info, 'skel': skel}, data_set)
// UnmarshalBytes implements marshal.Marshallable.UnmarshalBytes. func (s *Sembuf) UnmarshalBytes(src []byte) { s.SemNum = uint16(hostarch.ByteOrder.Uint16(src[:2])) src = src[2:] s.SemOp = int16(hostarch.ByteOrder.Uint16(src[:2])) src = src[2:] s.SemFlg = int16(hostarch.ByteOrder.Uint16(src[:2])) src = src[2:] }
<reponame>IBM/FHIR /* * (C) Copyright IBM Corp. 2021 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.fhir.operation.cpg; import static com.ibm.fhir.cql.helpers.ModelHelper.fhircode; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.mockito.Mockito.*; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.testng.annotations.Test; import org.mockito.MockedStatic; import com.ibm.fhir.cql.helpers.LibraryHelper; import com.ibm.fhir.model.resource.Library; import com.ibm.fhir.model.type.Attachment; import com.ibm.fhir.model.type.Canonical; import com.ibm.fhir.model.type.CodeableConcept; import com.ibm.fhir.model.type.Coding; import com.ibm.fhir.model.type.RelatedArtifact; import com.ibm.fhir.model.type.Uri; import com.ibm.fhir.model.type.code.RelatedArtifactType; import com.ibm.fhir.registry.FHIRRegistry; public class LibraryHelperTest { @Test public void testDeserializeElmAttachment() throws Exception { Library library = TestHelper.getTestLibraryResource("library-EXM104-8.2.000.json"); List<org.cqframework.cql.elm.execution.Library> cqlLibrary = LibraryHelper.loadLibrary(null, library); assertNotNull(cqlLibrary); } @Test public void testLoadLibrariesIgnoreNonLogic() throws Exception { try (MockedStatic<FHIRRegistry> staticRegistry = mockStatic(FHIRRegistry.class)) { FHIRRegistry mockRegistry = mock(FHIRRegistry.class); staticRegistry.when(FHIRRegistry::getInstance).thenReturn(mockRegistry); Library template = TestHelper.getTestLibraryResource("library-EXM104-8.2.000.json"); CodeableConcept valid = LibraryHelper.getLogicLibraryConcept(); // valid type, valid content Library l1 = TestHelper.buildBasicLibrary("1", "http://localhost/fhir/Library/first", "first", "1.0.0").type(valid).content(template.getContent()).build(); when(mockRegistry.getResource(l1.getUrl().getValue(), Library.class)).thenReturn(l1); CodeableConcept irrelevant = getIrrelevantConcept(); // irrelevant type, valid content Library l2 = TestHelper.buildBasicLibrary("2", "http://localhost/fhir/Library/second", "second", "1.0.0").type(irrelevant).content(template.getContent()).build(); when(mockRegistry.getResource(l2.getUrl().getValue(), Library.class)).thenReturn(l2); // all of the above plus a ValueSet Collection<RelatedArtifact> related = Arrays.asList(l1.getUrl(), l2.getUrl(), Uri.of("http://localhost/fhir/ValueSet/1.2.3")).stream().map(url -> RelatedArtifact.builder().type(RelatedArtifactType.DEPENDS_ON).resource(Canonical.of(url.getValue())).build()).collect(Collectors.toList()); // add in an irrelevant link type for completeness RelatedArtifact otherRelationType = RelatedArtifact.builder().type(RelatedArtifactType.CITATION).resource(Canonical.of("http://docs.org")).build(); related.add(otherRelationType); Library parent = TestHelper.buildBasicLibrary("parent", "http://localhost/fhir/Library/parent", "parent", "1.0.1").type(valid).relatedArtifact(related).content(template.getContent()).build(); List<Library> actual = LibraryHelper.loadLibraries(parent); assertEquals(actual.size(), 2); } } @Test(expectedExceptions = IllegalArgumentException.class) public void testUnsupportedContent() { Library library = TestHelper.buildBasicLibrary("3", "http://localhost/fhir/Library/FHIR-Model", "FHIR-Model", "4.0.1").type(LibraryHelper.getLogicLibraryConcept()).content(Attachment.builder().contentType(fhircode("text/xml")).build()).build(); LibraryHelper.loadLibrary(null, library); } private CodeableConcept getIrrelevantConcept() { CodeableConcept irrelevant = CodeableConcept.builder().coding(Coding.builder().system(Uri.of("http://nothing")).code(fhircode("ignore-me")).build()).build(); return irrelevant; } }
// Give an example of Switch case statement in JAVA Program. public class switcheg { public static void main (String[] args){ char ch = 'o'; switch (ch){ case 'a': System.out.println ("Vowel"); break; case 'e': System.out.println ("Vowel"); break; case 'i': System.out.println ("Vowel"); break; case 'o': System.out.println ("Vowel"); break; case 'u': System.out.println ("Vowel"); break; default: System.out.println ("Consonant"); break; } } }
//------------------------------------------------- // view_notify - handle notification of updates // to cursor changes //------------------------------------------------- void debug_view_disasm::view_notify(debug_view_notification type) { if((type == VIEW_NOTIFY_CURSOR_CHANGED) && (m_cursor_visible == true)) adjust_visible_y_for_cursor(); else if(type == VIEW_NOTIFY_SOURCE_CHANGED) { const debug_view_disasm_source &source = downcast<const debug_view_disasm_source &>(*m_source); m_expression.set_context(&source.device()->debug()->symtable()); m_expression.set_default_base(source.space().is_octal() ? 8 : 16); } }
Method and system for microfluidic imaging and analysis In this specification, the sample, using the image from a device such as a consumer's cell phone, the method and device for assessing the presence of disease or organism are disclosed. A method for creating a sample data, a i) a series of photons from a light source, a step of releasing in a short burst, the burst is over 5 seconds to about 1 second to about 1,000,000 minute sustained, at least some of the photons, the method comprising contacting the sample, ii) at least one photon was collected by the image sensor, a step of creating the sample data, photons are the recovered the steps a photon in contact with the sample, iii) processing the sample data, the steps leading to binary quantification of nucleic acid in the sample, iv) analyzing the binary quantification of nucleic acids, said method comprising the steps of creating a conclusion according associated with the sample.
#!/usr/bin/env python n, k = list(map(int, input().split(' '))) nums = list(map(int, input().split(' '))) pebbles = [[] for i in range(len(nums))] smallest = min(nums) prefix = smallest * [1] nums = list(map(lambda x: x - smallest, nums)) for c in range(1, k+1): for i, e in enumerate(nums): if e != 0: pebbles[i].append(c) nums[i] -= 1 if any(map(lambda x: x > 0, nums)): print("NO") else: print("YES") prefix = ' '.join(map(str, prefix)) for p in pebbles: print(prefix + ' ' + ' '.join(map(str, p)))
/** * {@link EventHandlers} is a component that allows to register custom event handlers for {@link Requester} specific events. */ public class EventHandlers<T> { private BiConsumer<Acknowledge, MessageContext> onAcknowledge = (acknowledge, msgContext) -> {}; private BiConsumer<T, MessageContext> onResponse = (acknowledge, msgContext) -> {}; private BiConsumer<Message, MessageContext> onRawResponse = (acknowledge, msgContext) -> {}; private Callback<Void> onEnd = messages -> {}; private BiConsumer<Exception, Message> onError; /** * Return callback registered for Acknowledge event. * * @return acknowledge callback */ public BiConsumer<Acknowledge, MessageContext> onAcknowledge() { return onAcknowledge; } /** * Registered callback for Acknowledge event. * * @param onAcknowledge callback * @return EventHandlers */ public EventHandlers onAcknowledge(BiConsumer<Acknowledge, MessageContext> onAcknowledge) { this.onAcknowledge = onAcknowledge; return this; } /** * Return callback registered for Response event. * * @return response callback * @return EventHandlers */ public BiConsumer<T, MessageContext> onResponse() { return onResponse; } /** * Registered callback for Response event. * * @param onResponse callback * @return EventHandlers */ public EventHandlers onResponse(BiConsumer<T, MessageContext> onResponse) { this.onResponse = onResponse; return this; } /** * Return callback registered for Response event. * * @return response callback * @return EventHandlers */ public BiConsumer<Message, MessageContext> onRawResponse() { return onRawResponse; } /** * Registered callback for Response event. * * @param onRawResponse callback * @return EventHandlers */ public EventHandlers onRawResponse(BiConsumer<Message, MessageContext> onRawResponse) { this.onRawResponse = onRawResponse; return this; } /** * Return callback registered for End event. * * @return end event callback */ public Callback<Void> onEnd() { return onEnd; } /** * Registered callback for End event. * * @param onEnd callback * @return EventHandlers */ public EventHandlers onEnd(Callback<Void> onEnd) { this.onEnd = onEnd; return this; } /** * Registered callback for Error event. * * @param onError callback * @return EventHandlers */ public EventHandlers onError(BiConsumer<Exception, Message> onError) { this.onError = onError; return this; } /** * Return callback registered for Error event. * * @return error callback */ public BiConsumer<Exception, Message> onError() { return onError; } }
import { Component, OnInit } from '@angular/core'; import { AuthenticationService, RegionService, LanguageService, ProfileService, GameService } from '../../_services'; import { FormGroup, FormBuilder, Validators, AbstractControl } from '@angular/forms'; import { PublicUser } from 'src/app/data_objects/publicuser'; import { Language } from 'src/app/data_objects/language'; import { Region } from 'src/app/data_objects/region'; import { ControlsMap } from 'src/app/_interface/controls-map'; import { Router } from '@angular/router'; import { GameSelectStatus } from '../../_classes/game-select-status'; import { gameValidator } from 'src/app/_shared/game-validator.directive'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-profile-update', templateUrl: './profile-update.component.html', styleUrls: ['./profile-update.component.scss'] }) export class ProfileUpdateComponent implements OnInit { // RegExp public strongRegex: RegExp = new RegExp('^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})'); public mediumRegex: RegExp = new RegExp('^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})'); public profileUpdateForm: FormGroup; public gamer: PublicUser; public loading: boolean = false; public hidePo: boolean = true; public hidePn: boolean = true; public lang: string; public regionList: Array<Region> = []; public langList: Array<Language> = []; private regionSelected: number; private languageSelected: Array<number> = []; public constructor( private formBuilder: FormBuilder, private authenticationService: AuthenticationService, private profileService: ProfileService, private regionService: RegionService, private languageService: LanguageService, private gameService: GameService, private router: Router, private toastrService: ToastrService, ) { } public ngOnInit(): void { this.authenticationService.currentGamer.subscribe(gamer => this.gamer = gamer); this.lang = this.getLanguages(this.gamer.languages); this.regionSelected = this.gamer.region.region_id; this.languageSelected = this.getSelectedLanguages(this.gamer.languages); this.regionService.getRegions() .subscribe(r => this.regionList = r); this.languageService.getLanguage() .subscribe(l => this.langList = l); this.createForm(); this.gameService.setCompState(GameSelectStatus.COMP_PROFILE); this.gameService.setFormState(GameSelectStatus.FORM_PROFILE); } public createForm(): void { this.profileUpdateForm = this.formBuilder.group({ region: [this.regionSelected, Validators.required], lang: [this.languageSelected, Validators.required], oPassword: [''], nPassword: ['', Validators.minLength(6)], biography: [this.gamer.biography, Validators.maxLength(100)], game: ['', gameValidator()], }); } public hasError = (controlName: string, errorName: string) => { return this.profileUpdateForm.controls[controlName].hasError(errorName); } public hidePwO(event: any): void { // without type info @https://angular.io/guide/user-input this.hidePo = !this.hidePo; event.preventDefault(); } public hidePwN(event: any): void { // without type info @https://angular.io/guide/user-input this.hidePn = !this.hidePn; event.preventDefault(); } public isStrong(controlName: string): number { let strenght = -1; const pw = this.profileUpdateForm.controls[controlName].value; if (this.strongRegex.test(pw)) { strenght = 2; } else if (this.mediumRegex.test(pw)) { strenght = 1; } else if (pw !== '') { strenght = 0; } return strenght; } public getLanguages(arr: Language[]): string { let langString: string = ''; for (let i = 0; i < arr.length; i++) { langString += arr[i].name; if (i < arr.length - 1) { langString += ', '; } } return langString; } public getSelectedLanguages(arr: Array<Language>): Array<number> { for (let i = 0; i < arr.length; i++) { this.languageSelected[i] = arr[i].language_id; } return this.languageSelected; } private get profileUpdateValue(): ControlsMap<AbstractControl> { return this.profileUpdateForm.controls; } public onProfileUpdateSubmit(): void { this.loading = true; this.profileService.updateProfile(this.profileUpdateValue).subscribe( (data) => { this.router.navigate(['/profile']); this.loading = false; this.toastrService.success('Your profile was successful changed'); }, (error) => { this.loading = false; console.log(error.error.error); this.toastrService.error(error.error.error, 'Editing failed'); } ); } public onProfileDelete(): void { this.profileService.deleteProfile().subscribe( (data) => { this.authenticationService.logout(); this.router.navigate(['']); this.toastrService.success('User with the discord tag' + data.publicUser.discord_tag + ' was deleted'); }, (error) => { console.log(error.error.error); this.toastrService.error(error.error.error, 'Deletion failed'); } ); } }
import { Injectable } from '@nestjs/common'; import { ElasticsearchService } from '@nestjs/elasticsearch'; const axios = require('axios'); @Injectable() export class SearchService { constructor(private readonly elasticsearchService: ElasticsearchService) {} async search(queryBuilder) { console.log("queryBuilder ", queryBuilder) const { body } = await this.elasticsearchService.search({ index: 'strapi_jobs_2', body:queryBuilder }) const hits = body.hits; // return hits.map((item) => item._source); return hits; } }
Isolation of Mesophyll Protoplast and Establishment of Gene Transient Expression System in Cotton This paper aimed to set up a stable and efficient transient expression system based on cotton mesophyll protoplasts produced from cotyledon. We analyzed the key factors related to isolating effectively cotton mesophyll protoplasts and used it as a vehicle to express transfected genes for functional studies. The optimized techniques are as follows:(1) the healthy 12-day-old cotyledon grown naturally was selected to isolate cotton protoplasts;(2) the digestion system contained 1.5% cellulose, 0.4% macerozyme, 0.5 mol L–1 mannitol, 20 mmol L–1 KCl, 20 mmol L–1 MES, 0.1 mol L–1 CaCl2, and 1.0 g L–1 BSA; and(3) the digestion was conducted in the dark under 28 for 8 h with gentle shaking. The protoplast yield was higher than 1.0 × 10℃6 mL–1. Using this system, we integrated a cotton zinc finger protein gene(GhZFP2) into pJIT166-GFP plasmid vector and constructed the GhZFP2:GFP fusion vector. The target gene was then transformed into purified cotton mesophyll protoplast mediated with 40% PEG-4000. As a result, cotton mesophyll protoplast with high transformation frequency was obtained. The transient expression assay showed that the GhZFP2 protein was clearly located in the cell nucleus of cotton.
// New returns a new K-D tree built using the given nodes. // Building a new tree with nodes that are already members of // K-D trees invalidates those trees. func New(nodes []*T) *T { if len(nodes) == 0 { return nil } return buildTree(0, preSort(nodes)) }
<gh_stars>1-10 # pylint: disable=no-self-use,redefined-outer-name from io import StringIO import sys import pytest from mock import patch from flashback.debugging import caller @pytest.fixture def output(): return StringIO() class TestCaller: def test_execution(self, output): caller_instance = caller(output=output) captured = output.getvalue() assert caller_instance.__name__ == "pytest_pyfunc_call" assert len(captured.splitlines()) == 12 def test_execution_with_depth(self, output): caller_instance = caller(depth=30, output=output) captured = output.getvalue() assert caller_instance.__name__ == "main" # Prior to python 3.8, the lineno for multiline calls is wrong if sys.version_info >= (3, 8): assert len(captured.splitlines()) == 14 else: assert len(captured.splitlines()) == 12 def test_execution_with_context(self, output): caller_instance = caller(context=10, output=output) captured = output.getvalue() assert caller_instance.__name__ == "pytest_pyfunc_call" assert len(captured.splitlines()) == 22 @patch("inspect.currentframe") def test_no_frame(self, mocked_currentframe, output): mocked_currentframe.side_effect = [None] caller_instance = caller(output=output) captured = output.getvalue() assert caller_instance is None assert len(captured.splitlines()) == 2 assert "No code context found" in captured @patch("inspect.findsource") def test_no_context(self, mocked_findsource, output): mocked_findsource.side_effect = OSError("could not get source code") caller_instance = caller(depth=3, output=output) # depth=3 because we have a decorator captured = output.getvalue() assert caller_instance.__name__ == "pytest_pyfunc_call" assert len(captured.splitlines()) == 2 @patch("flashback.debugging.get_callable") def test_no_callable(self, mocked_get_callable, output): mocked_get_callable.side_effect = [None] caller_instance = caller(output=output) captured = output.getvalue() assert caller_instance is None assert len(captured.splitlines()) == 12
def nb_to_html_cells(nb) -> list: html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_notebook_node(nb) return BeautifulSoup(body, 'html.parser').findAll('div', class_='cell')
/** * @author monty * * * Concerns: * - Manages Sectors and Players in those sectors * - Game events management */ public class GameEngine implements Runnable { private GameWorld world; private int timeStep; private GameEngineListener listener; private GameDelegate delegate; private GameAudioManager audioManager; /** * */ private volatile boolean running = true; private boolean updating; /** * */ public static boolean loaded = false; /** * */ public GameEngine(GameWorld world, GameEngineListener listener) { this.world = world; this.listener = listener; audioManager = GameAudioManager.getInstance(); } // ------------------------------------------------------------------------------------------------------------ /** * * @param actor * @param sectorId */ public void placeActor(AndroidGameActor actor, int sectorId) { GameSector sector = (GameSector) world.getSector(sectorId); actor.moveTo(sector.getCenter()); actor.setCurrentSector(sectorId); sector.onSectorEnteredBy(actor); } public void setTimeStep(int timeStep) { this.timeStep = timeStep; } // ------------------------------------------------------------------------------------------------------------ private void doGravity(AndroidGameActor actor) { GameSector sector = (GameSector) world.getSector(actor .getCurrentSector()); GameSector candidate = sector; GameSector groundSector = sector; while (groundSector != null && (groundSector.cachedNeighBours[ Constants.FACE_FLOOR ] != null )) { candidate = groundSector.cachedNeighBours[ Constants.FACE_FLOOR ]; if (candidate.isMaster()) { continue; } groundSector = candidate; } while ((groundSector.getY0() + actor.getDY()) > (actor .getPosition().y)) { actor.consume(ActorConstants.MOVE_UP); } while ((groundSector.getY0() + actor.getDY()) < (actor .getPosition().y)) { actor.consume(ActorConstants.MOVE_DOWN); } } // ------------------------------------------------------------------------------------------------------------ /** * */ @Override public void run() { ArrayList<AndroidGameActor> toBeAdded = new ArrayList<AndroidGameActor>(); Actor sons; boolean actorHasChangedSector; boolean needsToRefreshLightning = false; GameSector originalSector; AndroidGameActor actor; actorHasChangedSector = true; while (running && loaded ) { updating = true; needsToRefreshLightning = false; try { Thread.sleep(timeStep); audioManager.update(); world.checkpointActors(); if ( listener != null ) listener.beforeTick(); if (delegate != null) delegate.update(world); toBeAdded.clear(); int count = world.getTotalActors(); for ( Actor baseActor: world.getActorList() ) { actor = (AndroidGameActor) baseActor; if (!actor.isAlive()) continue; actor.tick(); originalSector = (GameSector) world.getSector(actor.currentSector); if (actor.isPlayable()) { doGravity(actor); } findBestFitForActorFromSector(actor, originalSector); if (originalSector != world.getSector(actor.currentSector)) { actorHasChangedSector = true; if ( actor.getEmissiveLightningIntensity() > 0 ) needsToRefreshLightning = true; } sons = actor.checkGenerated(); if (sons != null) { toBeAdded.add( (AndroidGameActor)sons); } } int newId = 0; for ( AndroidGameActor spawn : toBeAdded ) { spawn.setId(count + newId++ ); try { spawn.getPosition().index = (-2); } catch (Exception e) { } actorHasChangedSector = true; world.addActor( spawn ); listener.onActorAdded( spawn ); } if (actorHasChangedSector) { listener.needsToRefreshWindow( false ); } if ( needsToRefreshLightning ) { listener.needsToRefreshLightning(); } actorHasChangedSector = false; } catch (Exception e) { } updating = false; } if ( world != null ) { for ( Actor toBeKilled : world.getActorList() ) { if (!toBeKilled.isAlive()) continue; toBeKilled.setAlive( false ); } } } //this would belong to World, wasn't for the dynamics of collision between entities private void findBestFitForActorFromSector(AndroidGameActor actor, GameSector originalSector) { int[] neighbours; GameSector sector = originalSector; if (!originalSector.contains(actor.getPosition())) { neighbours = originalSector.getNeighbours(); for (int d = 0; d < neighbours.length; ++d) { sector = (GameSector) world.getSector(neighbours[d]); if (sector.isMaster()) { continue; } if (neighbours[d] != 0 && sector.contains(actor.getPosition())) break; sector = null; } if (sector == null) { int size = world.getTotalSectors(); for (int d = 1; d < size; ++d) { sector = (GameSector) world.getSector(d); if (sector.isMaster()) continue; if (sector.contains(actor.getPosition())) break; sector = null; } } if (sector == null || sector.isMaster()) { originalSector.onSectorLeftBy(actor); actor.setCurrentSector(originalSector.getId()); actor.hit( originalSector ); } else { originalSector.onSectorLeftBy(actor); sector.onSectorEnteredBy(actor); if ( sector.getDoorCount() > 0 ) { listener.needsToRefreshWindow( false ); } if ( delegate != null && sector != originalSector ) { delegate.onSectorEntered(world, actor, sector); } actor.setCurrentSector(sector.getId()); } } } public void stop() { this.running = false; loaded = false; } public void pause() { loaded = false; } public void resume() { loaded = true; } public void setDelegate(GameDelegate delegate) { this.delegate = delegate; delegate.setGameEngine( this ); for ( Actor actor : world.getActorList() ) { ( ( AndroidGameActor ) actor ).setGameDelegate( delegate ); } for ( Sector sector : world ) { GameSector s = ( ( GameSector) sector ); for ( int c = 0; c < 6; ++c ) { if ( s.getDoor( c ) != null ) { s.getDoor( c ).setDelegate( delegate ); } } } } public void requestMapChange(String mapName) { listener.requestMapChange(mapName); } public void start() { running = true; } public void showStory(int index ) { listener.showHistory( index ); } public void destroy() { while ( updating ) { try { Thread.sleep( 10 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } world.destroy(); } public void restoreState() throws FileNotFoundException, IOException { world.loadSnapshotAt( PlayGameActivity.getInstance().openFileInput( "state" ) ); } public GameWorld getWorld() { return world; } public GameEngineListener getListener() { return listener; } public void showInformation(String information ) { listener.needsToDisplayMessage( information ); } public void needRefreshVisibity() { listener.needsToRefreshWindow( false ); } public void showScreen( String screenClass ) { listener.showScreen( screenClass ); } }
Comedian and television host Chelsea Handler tends not to sugarcoat things. As Jenny McCarthy once told the New York Times, “If you’re going to get your lip injected 12 times, Chelsea Handler is going to be the first person to point it out.” I need auto correct for my mouth. — Chelsea Handler (@chelseahandler) November 28, 2013 The host of the E! late-night show “Chelsea Lately” alighted last night on the soon-to-be-over CNN show “Piers Morgan Live,” and some ribbing ensued. In her chat with Morgan, Handler expressed some indignation at the host’s conduct during a commercial break. Turns out he was tweeting. “In the middle of the commercial break, I want your viewers to know. I mean, they must know because they’re probably following you on Twitter. I mean, you can’t even pay attention for 60 seconds. You’re a terrible interviewer,” Handler ripped away. At this point, Morgan could have apologized for ignoring his guest while he hovered over some Twitter interface. But he didn’t: “Well, you just weren’t keeping my attention. It’s more an issue for you than me.” After Morgan continued protesting that his company wasn’t interesting enough, Handler said, “Well, maybe that’s why your job is coming to an end.” Nailed it! As the Erik Wemple Blog argued a while back, relying on the Chelsea Handlers of the world to keep your cable ratings competitive isn’t a workable model — not for Morgan and not for Larry King in the final years of his tenure in the same slot. And one other thing: Morgan has 4 million followers on Twitter, the product of 45,000 (often nasty) little messages. Think he builds such a franchise by just sitting around during breaks? (Handler has a Twitter crowd, too).
def down(self, argv): res = self._dbg.go_down() if res: self._print(res) self._reset_namespace()
<reponame>JacobAlbus/songster<filename>scripts/pull_data.py # Imports import lyricsgenius import json import argparse from pathlib import Path import os # Constants DATA_DIR = Path('../data/') SECRETS = Path('./secrets.json') """ This script downloads song data corresponding to the passed parameters Example usage (in scripts directory): python pull_data.py --genre "Hip Hop" """ def download_genre(genius, genre, song_count_limit): """Download the data for a given genre, and save to the project's data directory Args: genre (str): genre to pull song data for song_count_limit (int): limits # of songs being pulled """ page = 1 all_lyrics = {} while len(all_lyrics) < song_count_limit and page: response = genius.tag(genre, page=page) for hit in response['hits']: lyrics = genius.lyrics(song_url=hit['url']) all_lyrics[hit['title']] = clean_lyrics(lyrics) page = response['next_page'] write_dict_to_file(genre, all_lyrics) return all_lyrics def download_artist(genius, artist, song_count_limit): """Download the data for a given artist, and save to the project's data directory Args: genius (obj): genius API object artist (str): artist to pull song data for song_count_limit (int): limits # of songs being pulled Returns: (str): name of artist (dict): dictionary containing song titles and lyrics """ genius_artist = genius.search_artist(artist, max_songs=1, include_features=True) page = 1 all_lyrics = {} while len(all_lyrics) < song_count_limit and page: request = genius.artist_songs(genius_artist.id, sort='popularity', per_page=10, page=page) for song in request['songs']: title = song['title'] try: lyrics = genius.search_song(title, genius_artist.name).lyrics try: all_lyrics[title] = clean_lyrics(lyrics) except IndexError: continue except AttributeError: continue page = request['next_page'] write_dict_to_file(genius_artist.name, all_lyrics) return genius_artist.name, all_lyrics def clean_lyrics(lyrics): """ Removes bracketed sections (eg. [Chorus 1: John]) and removes line breaks Args: lyrics (str): lyrics to be cleaned Returns: (str): cleaned up lyrics """ lyrics = lyrics.replace("\n", " ").replace("\r", " ") lyrics_index = 0 while lyrics_index < len(lyrics): if lyrics[lyrics_index] == '[': sub_index = lyrics_index while lyrics[sub_index] != ']': sub_index += 1 lyrics = lyrics[: lyrics_index] + lyrics[sub_index + 1:] lyrics_index += 1 # removes all non-unicode characters return ''.join([i if ord(i) < 128 else ' ' for i in lyrics]) def write_dict_to_file(artist_name, lyric_dict): """ Writes passed dictionary to a file in the data folder, creates data folder if it doesn't already exist Args: artist_name (str): name of the artist or genre lyric_dict (dict): dictionary with song name as keys and lyrics as value """ formatted_artist_name = "" for name in artist_name.split(" "): formatted_artist_name += name + "_" file_name = formatted_artist_name + "lyrics.txt" file_path = str(Path().resolve().parent) + "/data/" if not os.path.exists(file_path): os.makedirs(file_path) data = str(lyric_dict) file_writer = open(file_path + file_name, 'w+', encoding="utf-8", errors="ignore") file_writer.write(data) def main(args): """Validates the arguments passed, launches data download Args: args (object): command line arguments passed to the script """ with open(SECRETS) as secrets_f: secrets = json.load(secrets_f) genius = lyricsgenius.Genius(secrets['keys']['genius']) print('Key: {}\n'.format(secrets['keys']['genius'])) print('*****Passed Arguments*****\nGenre: {}\nArtist: ' '{}\nLimit: {}'.format(args.genre, args.artist, args.limit)) print('This is the data directory: {}'.format(DATA_DIR)) song_count_limit = args.limit if args.artist is not None: download_artist(genius, args.artist, song_count_limit) if args.genre is not None: download_genre(genius, args.genre, song_count_limit) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Songster data ') parser.add_argument('--genre', dest='genre', type=str, default=None, help='download music from the passed genre') parser.add_argument('--artist', dest='artist', type=str, default=None, help='download music from the passed artist') parser.add_argument('--limit', dest='limit', type=int, default=20, help='limits number of downloaded songs') args = parser.parse_args() main(args)
#!/usr/bin/env python # encoding: utf-8 # package ''' @author: yuxiqian @license: MIT @contact: <EMAIL> @software: electsys-api @file: electsysApi/interface/__init__.py @time: 2019/1/9 ''' from .interface import * __all__ = ['ElectCourse', 'PersonalCourse', 'PersonalExam', 'PersonalScore']
The attorney representing the family of Ernesto Duenez has presented a graphic video of the police officer shooting him 11 times, just one day after the said officer was cleared of wrongdoing. Duenez was wanted for a domestic violence incident and several police officers in patrol cars were waiting for him to come home so they could arrest him. The video from one of the patrol car cameras shows Duenez parking his pickup truck and officer James Moody approaching him with a drawn gun. He suspected that Duenez had a knife and shouted at him to drop it and put his hands up. As Duenez was exiting the vehicle over the passenger seat, he tripped and turned around which provoked the officer to fire 13 shots in just 4.2 seconds. Duenez was shot once in the head, eight times in the body and two times in the extremities and died from wounds to his chest and abdomen. After hearing the gunshots, his wife Whitney Duenez ran out of the house screaming and ignored officer’s warning to stand back, rushing to hug her dying husband. < It was later discovered that Duenez had his foot stuck in the seat belt which is probably why he had turned around, trying to set his foot loose. Attorney John Burris wants officer Moody prosecuted for murder, saying that he should be “held accountable just like anyone else would be held accountable when they engage in this kind of barbaric conduct.”
// Test 6 - CreateTrafficQueues-Upstream FIXED_QUEUE failure case TEST_F(TestCreateTrafficQueues, CreateUpstreamFixedQueueFailure) { traffic_queues->set_uni_id(0); traffic_queues->set_port_no(16); traffic_queue_1->set_direction(tech_profile::Direction::UPSTREAM); bcmos_errno olt_cfg_set_res = BCM_ERR_INTERNAL; ON_CALL(balMock, bcmolt_cfg_set(_, _)).WillByDefault(Return(olt_cfg_set_res)); Status status = CreateTrafficQueues_(traffic_queues); ASSERT_TRUE( status.error_message() != Status::OK.error_message() ); }
//Takes the data from the old hash table and inserts it into the new hash table public void rehash(String[] oldTable, String[] newTable) { for (int i = 0; i < oldTable.length; i++) { if (oldTable[i] != null) { int hashVal = hash(oldTable[i], newTable.length); if (newTable[hashVal] == null) newTable[hashVal] = oldTable[i]; else { while (newTable[hashVal] != null) { if (hashVal > getCapacity()) hashVal = 0; hashVal++; } newTable[hashVal] = oldTable[i]; } } } }
/** * The class Comment - wrapper for Item. * * @author Pavlov Artem * @since 21.07.2017 */ public class Comment { /** * The comporator for sort comment to date and time. */ private Comparator<Comment> sortDate = new Comparator<Comment>() { @Override public int compare(Comment commentFirst, Comment commentSecond) { return commentFirst.getDateAndTimeCreate().compareTo(commentSecond.getDateAndTimeCreate()); } }; /** * The var for get date and time comment. */ private String dateAndTimeCreate; /** * The var for text comment. */ private String comment; /** * The getter for corporator`s sort to date. * * @return link to corporator; */ public Comparator<Comment> getSortDate() { return sortDate; } /** * The getter for return date and time. * * @return return date and time to string; */ public String getDateAndTimeCreate() { return dateAndTimeCreate; } /** * The getter for get comment. * * @return return comment; */ public String getComment() { return comment; } /** * The setter for var comment. * * @param comment - text comment; */ public void setComment(String comment) { this.comment = comment; } /** * The constructor for class Comment. * * @param comment - text comment`s; */ public Comment(String comment) { this.dateAndTimeCreate = parseDateAndTime(); this.comment = comment; } /** * The method for parse format date to string. * * @return return date and time to string; */ private String parseDateAndTime() { DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, new Locale("ru", "RU")); return dateFormat.format(new Date()); } }
def move_geo(self, oname=None, oindex=0, dx=0, dy=0, dz=0): if not self.valid: return None geo = self.get_top_geo() if oname is None else self.get_geo(oname, oindex) return geo.move_geo(dx, dy, dz)
export function toCamelCase(v: any): any { return toSomeCase(v, (s) => s.replace(/_[a-z]/g, (match) => match.charAt(1).toUpperCase())); } export function toSnakeCase(v: any): any { return toSomeCase(v, (s) => s.replace(/[A-Z]/g, (match) => '_' + match.toLowerCase())); } function toSomeCase(v: any, fn: (s: string) => string, isValue?: boolean): any { if (typeof v === 'string') { return isValue ? v : fn(v); } else if (Array.isArray(v)) { return v.map(w => toSomeCase(w, fn, true)); } else if (v === null || typeof v === 'undefined') { return v; } else if (typeof v === 'object') { const rv: { [key: string]: string } = {}; for (const key of Object.keys(v)) { rv[fn(key)] = toSomeCase(v[key], fn, true); } return rv; } else { return v; } }
def add_task_name_and_id_to_log_messages( task_id, task, *_args, **_kwargs ): root_loggers_handler = logging.getLogger().handlers[0] root_loggers_handler.setFormatter( logging.Formatter( "[%(asctime)s: %(levelname)s/%(processName)s] " + f"{task.name}[{task_id}] " + "%(message)s" ) )
An Upstate New York high school student wants his classmates to remember him as someone who loves cats. And lasers. Schenectady High School senior Draven Rodriguez has started a petition to get his unusual photo featured in the yearbook as his senior portrait. "I'm hoping that with enough signatures, my school simply can't turn this down," he writes. The picture shows Rodriguez wearing a suit, cuddling with a fluffy cat in front of an '80s style laser background. He says Vincent Giordano took and edited the picture, and gave permission to use it. CBS 6 in Albany reports the school gave Rodriguez permission to put the "cat-tastic" image in the yearbook, but not as his senior portrait. "To clarify, the school HAS NOT YET DECLINED this photo," Rodriguez wrote on his petition. "This is my pre-emptive strike just in case such a thing were to happen. I wanted as many backers as possible before the deadline of September 15th." As of Thursday morning, more than 650 people signed the petition, surpassing his original goal of 500. He's also gained support from a Jezebel writer who calls Rodriguez an "American hero," inviting readers to join the cause. "As a former teen who had a cat feature prominently in one of her senior portraits, I could not be any more pro-this," Jezebel News Editor Erin Gloria Ryan writes. "Let's make this happen." To see the petition, visit www.ipetitions.com/petition/get-my-photo-into-the-yearbook. **UPDATE: Petition has reached 6,000 signatures as of Saturday, Sept. 13. Rodriguez says "The school and I have worked out a compromise we're all happy with. [The photo] will be in there, just not in the senior section. More news to follow..."
<gh_stars>1-10 package net.minecraft.profiler; import com.google.common.collect.Maps; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.Map.Entry; import net.minecraft.profiler.IPlayerUsage; import net.minecraft.util.HttpUtil; public class PlayerUsageSnooper { private final Map field_152773_a = Maps.newHashMap(); private final Map field_152774_b = Maps.newHashMap(); private final String field_76480_b = UUID.randomUUID().toString(); private final URL field_76481_c; private final IPlayerUsage field_76478_d; private final Timer field_76479_e = new Timer("Snooper Timer", true); private final Object field_76476_f = new Object(); private final long field_98224_g; private boolean field_76477_g; private int field_76483_h; private static final String __OBFID = "CL_00001515"; public PlayerUsageSnooper(String p_i1563_1_, IPlayerUsage p_i1563_2_, long p_i1563_3_) { try { this.field_76481_c = new URL("http://snoop.minecraft.net/" + p_i1563_1_ + "?version=" + 2); } catch (MalformedURLException var6) { throw new IllegalArgumentException(); } this.field_76478_d = p_i1563_2_; this.field_98224_g = p_i1563_3_; } public void func_76463_a() { if(!this.field_76477_g) { this.field_76477_g = true; this.func_152766_h(); this.field_76479_e.schedule(new TimerTask() { private static final String __OBFID = "CL_00001516"; public void run() { if(PlayerUsageSnooper.this.field_76478_d.func_70002_Q()) { HashMap var1; synchronized(PlayerUsageSnooper.this.field_76476_f) { var1 = Maps.newHashMap(PlayerUsageSnooper.this.field_152774_b); if(PlayerUsageSnooper.this.field_76483_h == 0) { var1.putAll(PlayerUsageSnooper.this.field_152773_a); } var1.put("snooper_count", Integer.valueOf(PlayerUsageSnooper.access$308(PlayerUsageSnooper.this))); var1.put("snooper_token", PlayerUsageSnooper.this.field_76480_b); } HttpUtil.func_151226_a(PlayerUsageSnooper.this.field_76481_c, var1, true); } } }, 0L, 900000L); } } private void func_152766_h() { this.func_76467_g(); this.func_152768_a("snooper_token", this.field_76480_b); this.func_152767_b("snooper_token", this.field_76480_b); this.func_152767_b("os_name", System.getProperty("os.name")); this.func_152767_b("os_version", System.getProperty("os.version")); this.func_152767_b("os_architecture", System.getProperty("os.arch")); this.func_152767_b("java_version", System.getProperty("java.version")); this.func_152767_b("version", "1.8"); this.field_76478_d.func_70001_b(this); } private void func_76467_g() { RuntimeMXBean var1 = ManagementFactory.getRuntimeMXBean(); List var2 = var1.getInputArguments(); int var3 = 0; Iterator var4 = var2.iterator(); while(var4.hasNext()) { String var5 = (String)var4.next(); if(var5.startsWith("-X")) { this.func_152768_a("jvm_arg[" + var3++ + "]", var5); } } this.func_152768_a("jvm_args", Integer.valueOf(var3)); } public void func_76471_b() { this.func_152767_b("memory_total", Long.valueOf(Runtime.getRuntime().totalMemory())); this.func_152767_b("memory_max", Long.valueOf(Runtime.getRuntime().maxMemory())); this.func_152767_b("memory_free", Long.valueOf(Runtime.getRuntime().freeMemory())); this.func_152767_b("cpu_cores", Integer.valueOf(Runtime.getRuntime().availableProcessors())); this.field_76478_d.func_70000_a(this); } public void func_152768_a(String p_152768_1_, Object p_152768_2_) { Object var3 = this.field_76476_f; synchronized(this.field_76476_f) { this.field_152774_b.put(p_152768_1_, p_152768_2_); } } public void func_152767_b(String p_152767_1_, Object p_152767_2_) { Object var3 = this.field_76476_f; synchronized(this.field_76476_f) { this.field_152773_a.put(p_152767_1_, p_152767_2_); } } public Map func_76465_c() { LinkedHashMap var1 = Maps.newLinkedHashMap(); Object var2 = this.field_76476_f; synchronized(this.field_76476_f) { this.func_76471_b(); Iterator var3 = this.field_152773_a.entrySet().iterator(); Entry var4; while(var3.hasNext()) { var4 = (Entry)var3.next(); var1.put(var4.getKey(), var4.getValue().toString()); } var3 = this.field_152774_b.entrySet().iterator(); while(var3.hasNext()) { var4 = (Entry)var3.next(); var1.put(var4.getKey(), var4.getValue().toString()); } return var1; } } public boolean func_76468_d() { return this.field_76477_g; } public void func_76470_e() { this.field_76479_e.cancel(); } public String func_80006_f() { return this.field_76480_b; } public long func_130105_g() { return this.field_98224_g; } // $FF: synthetic method static int access$308(PlayerUsageSnooper p_access$308_0_) { return p_access$308_0_.field_76483_h++; } }
package be.ida_mediafoundry.jetpack.patchsystem.servlets; import be.ida_mediafoundry.jetpack.patchsystem.JetpackConstants; import be.ida_mediafoundry.jetpack.patchsystem.executors.JobResult; import be.ida_mediafoundry.jetpack.patchsystem.services.PatchSystemJobService; import com.google.gson.Gson; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.ServletResolverConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Check whether patches are still running or not. */ @Component( service = { Servlet.class }, property = { ServletResolverConstants.SLING_SERVLET_PATHS + "=/services/patches/check", Constants.SERVICE_DESCRIPTION + "=Check if patch system is still running or not", Constants.SERVICE_VENDOR + ":String=" + JetpackConstants.VENDOR, }) public class CheckPatchStatusServlet extends SlingAllMethodsServlet { private static final Logger LOG = LoggerFactory.getLogger(CheckPatchStatusServlet.class); @Reference private PatchSystemJobService patchSystemJobService; @Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) { response.setContentType(JetpackConstants.APPLICATION_JSON); try { process(response); } catch (Exception e) { LOG.error("Error during CheckPatchStatusServlet", e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } private void process(SlingHttpServletResponse response) throws IOException { JobResult jobResult = patchSystemJobService.getPatchSystemStatus(); Gson gson = new Gson(); response.getWriter().write(gson.toJson(jobResult)); response.setStatus(HttpServletResponse.SC_OK); } }
<gh_stars>0 import tensorflow as tf import os # load model config def load_config(config_path="config.json", verbose=1): import json with open(config_path, "r") as config_file: config_data = json.load(config_file) # show content of config if verbose: print(json.dumps(config_data, indent=2, sort_keys=True)) return config_data def save_config(data_parameter, model_parameter, training_parameter, network): # writing config file into model folder import json new_config = {"data_parameter": data_parameter, "model_parameter": model_parameter, "training_parameter": training_parameter} with open(network.config_path, 'w+') as config: config.write(json.dumps(new_config, sort_keys=True, indent=2)) print(f"Model folder created and config saved: {network.config_path}") def allow_growth(): import tensorflow as tf # Copied from: https://tensorflow.google.cn/guide/gpu?hl=en#limiting_gpu_memory_growth gpus = tf.config.experimental.list_physical_devices("GPU") if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) except RuntimeError as e: print(e) # Copied from stackoverflow. originally posted by <NAME>, license: CC BY-SA 4.0, link: https://stackoverflow.com/a/3233356 import collections.abc def update(d, u): for k, v in u.items(): if isinstance(v, collections.abc.Mapping): d[k] = update(d.get(k, {}), v) else: d[k] = v return d
// GetPreference returns the Preference Option value, as described in RFC 3315, // Section 22.8. // // The integer preference value is sent by a server to a client to affect the // selection of a server by the client. func GetPreference(o dhcp6.Options) (Preference, error) { v, err := o.GetOne(dhcp6.OptionPreference) if err != nil { return 0, err } var p Preference err = (&p).UnmarshalBinary(v) return p, err }
<filename>components/application-operator/pkg/controller/reconciler_test.go<gh_stars>0 package controller import ( "context" "testing" "github.com/kyma-project/kyma/components/application-operator/pkg/controller/mocks" helmmocks "github.com/kyma-project/kyma/components/application-operator/pkg/kymahelm/remoteenvironemnts/mocks" "github.com/kyma-project/kyma/components/remote-environment-broker/pkg/apis/applicationconnector/v1alpha1" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" hapi_4 "k8s.io/helm/pkg/proto/hapi/release" "sigs.k8s.io/controller-runtime/pkg/reconcile" ) const ( reName = "re-name" ) type reChecker struct { t *testing.T expectedStatus string expectedDescription string } func (checker reChecker) checkAccessLabel(args mock.Arguments) { reInstance := args.Get(1).(*v1alpha1.RemoteEnvironment) assert.Equal(checker.t, reName, reInstance.Spec.AccessLabel) } func (checker reChecker) checkStatus(args mock.Arguments) { reInstance := args.Get(1).(*v1alpha1.RemoteEnvironment) assert.Equal(checker.t, checker.expectedStatus, reInstance.Status.InstallationStatus.Status) assert.Equal(checker.t, checker.expectedDescription, reInstance.Status.InstallationStatus.Description) } func TestRemoteEnvironmentReconciler_Reconcile(t *testing.T) { releaseStatus := hapi_4.Status_DEPLOYED statusDescription := "Deployed" statusChecker := reChecker{ t: t, expectedStatus: releaseStatus.String(), expectedDescription: statusDescription, } t.Run("should install chart when new RE is created", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREInstance).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(statusChecker.checkStatus).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(false, nil) releaseManager.On("InstallNewREChart", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should skip chart installation when skip-installation label set to true", func(t *testing.T) { // given skippedChecker := reChecker{ t: t, expectedStatus: installationSkippedStatus, expectedDescription: "Installation will not be performed", } namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREWhichIsNotInstalled).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(skippedChecker.checkStatus).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(false, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should set access-label when new RE is created", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREWithoutAccessLabel).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(statusChecker.checkAccessLabel).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(false, nil) releaseManager.On("InstallNewREChart", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should check status if chart exist despite skip-installation label set to true", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREWhichIsNotInstalled).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(statusChecker.checkStatus).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(true, nil) releaseManager.On("CheckReleaseStatus", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should delete chart when RE is deleted", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Return(errors.NewNotFound(schema.GroupResource{}, reName)) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(true, nil) releaseManager.On("DeleteREChart", reName).Return(nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should not delete chart when RE is deleted and release does not exist", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Return(errors.NewNotFound(schema.GroupResource{}, reName)) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(false, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should update status if RE is updated", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREInstance).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(statusChecker.checkStatus).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(true, nil) releaseManager.On("CheckReleaseStatus", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should correct access-label if updated with wrong value", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREWithWrongAccessLabel).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(statusChecker.checkStatus).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(true, nil) releaseManager.On("CheckReleaseStatus", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.NoError(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should return error if error while Getting instance different than NotFound", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Return(errors.NewResourceExpired("error")) releaseManager := &helmmocks.ReleaseManager{} reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.Error(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should return error when failed to check releases existence", func(t *testing.T) { // given namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREInstance).Return(nil) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(false, errors.NewBadRequest("error")) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.Error(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) t.Run("should return error when failed to update RE", func(t *testing.T) { namespacedName := types.NamespacedName{ Name: reName, } managerClient := &mocks.RemoteEnvironmentManagerClient{} managerClient.On( "Get", context.Background(), namespacedName, mock.AnythingOfType("*v1alpha1.RemoteEnvironment")). Run(setupREWithWrongAccessLabel).Return(nil) managerClient.On("Update", context.Background(), mock.AnythingOfType("*v1alpha1.RemoteEnvironment")).Return(errors.NewBadRequest("Error")) releaseManager := &helmmocks.ReleaseManager{} releaseManager.On("CheckReleaseExistence", reName).Return(true, nil) releaseManager.On("CheckReleaseStatus", reName).Return(releaseStatus, statusDescription, nil) reReconciler := NewReconciler(managerClient, releaseManager) request := reconcile.Request{ NamespacedName: namespacedName, } // when result, err := reReconciler.Reconcile(request) // then assert.Error(t, err) assert.NotNil(t, result) managerClient.AssertExpectations(t) releaseManager.AssertExpectations(t) }) } func getREFromArgs(args mock.Arguments) *v1alpha1.RemoteEnvironment { reInstance := args.Get(2).(*v1alpha1.RemoteEnvironment) reInstance.Name = reName return reInstance } func setupREInstance(args mock.Arguments) { reInstance := getREFromArgs(args) reInstance.Spec.AccessLabel = reName } func setupREWhichIsNotInstalled(args mock.Arguments) { reInstance := getREFromArgs(args) reInstance.Spec.SkipInstallation = true } func setupREWithoutAccessLabel(args mock.Arguments) { reInstance := getREFromArgs(args) reInstance.Spec.AccessLabel = "" } func setupREWithWrongAccessLabel(args mock.Arguments) { reInstance := getREFromArgs(args) reInstance.Spec.AccessLabel = "" }
/** * @author Anton Katilin * @author Vladimir Kondratyev */ final class ShowHintAction extends AnAction { private final QuickFixManager myManager; public ShowHintAction(@Nonnull final QuickFixManager manager, @Nonnull final JComponent component) { myManager = manager; registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS).getShortcutSet(), component); } @Override public void actionPerformed(final AnActionEvent e) { final GuiEditor editor = myManager.getEditor(); if(editor == null) { return; } // 1. Show light bulb myManager.showIntentionHint(); // 2. Commit possible non committed value and show popup final PropertyInspector propertyInspector = DesignerToolWindowManager.getInstance(myManager.getEditor()).getPropertyInspector(); if(propertyInspector != null && propertyInspector.isEditing()) { propertyInspector.stopEditing(); } myManager.showIntentionPopup(); } @Override public void update(AnActionEvent e) { // Alt-Enter hotkey for editor takes precedence over this action e.getPresentation().setEnabled(e.getData(CommonDataKeys.EDITOR) == null); } }
def crypto_onetimeauth(message, key): if len(key) != crypto_onetimeauth_KEYBYTES: raise ValueError('Invalid secret key') tok = ctypes.create_string_buffer(crypto_onetimeauth_BYTES) _ = nacl.crypto_onetimeauth( tok, message, ctypes.c_ulonglong(len(message)), key) return tok.raw[:crypto_onetimeauth_BYTES]
use std::io::{Write, Read}; use crate::{RpcValue, MetaMap, Value, Decimal, DateTime}; use std::collections::BTreeMap; use crate::writer::{WriteResult, Writer, ByteWriter}; use crate::metamap::MetaKey; use crate::reader::{Reader, ByteReader, ReadError}; use crate::rpcvalue::{Map}; pub struct CponWriter<'a, W> where W: Write { byte_writer: ByteWriter<'a, W>, indent: String, nest_count: usize, } impl<'a, W> CponWriter<'a, W> where W: Write { pub fn new(write: &'a mut W) -> Self { CponWriter { byte_writer: ByteWriter::new(write), indent: "".to_string(), nest_count: 0, } } pub fn set_indent(&mut self, indent: &str) { self.indent = indent.to_string(); } fn is_oneliner_list(lst: &Vec<RpcValue>) -> bool { if lst.len() > 10 { return false; } for it in lst.iter() { match it.value() { Value::List(_) => return false, Value::Map(_) => return false, Value::IMap(_) => return false, _ => continue, } } return true; } fn is_oneliner_map<K>(iter: &mut dyn Iterator<Item = (K, &RpcValue)>) -> bool { let mut n = 0; loop { if n == 5 { return false } match iter.next() { Some(val) => { match val.1.value() { Value::List(_) => return false, Value::Map(_) => return false, Value::IMap(_) => return false, _ => (), } }, None => break, }; n += 1; }; return true } fn is_oneliner_meta(map: &MetaMap) -> bool { if map.0.len() > 5 { return false; } for k in map.0.iter() { match k.value.value() { Value::List(_) => return false, Value::Map(_) => return false, Value::IMap(_) => return false, _ => continue, } } return true; } fn start_block(&mut self) { self.nest_count += 1; } fn end_block(&mut self, is_oneliner: bool) -> WriteResult { let cnt = self.byte_writer.count(); self.nest_count -= 1; if !self.indent.is_empty() { self.indent_element(is_oneliner, true)?; } Ok(self.byte_writer.count() - cnt) } fn indent_element(&mut self, is_oneliner: bool, is_first_field: bool) -> WriteResult { let cnt = self.byte_writer.count(); if !self.indent.is_empty() { if is_oneliner { if !is_first_field { self.write_byte(b' ')?; } } else { self.write_byte(b'\n')?; for _ in 0 .. self.nest_count { self.byte_writer.write_bytes(self.indent.as_bytes())?; } } } Ok(self.byte_writer.count() - cnt) } fn write_byte(&mut self, b: u8) -> WriteResult { self.byte_writer.write_byte(b) } fn write_bytes(&mut self, b: &[u8]) -> WriteResult { self.byte_writer.write_bytes(b) } fn write_int(&mut self, n: i64) -> WriteResult { let s = n.to_string(); let cnt = self.write_bytes(s.as_bytes())?; Ok(self.byte_writer.count() - cnt) } fn write_uint(&mut self, n: u64) -> WriteResult { let s = n.to_string(); let cnt = self.write_bytes(s.as_bytes())?; Ok(self.byte_writer.count() - cnt) } fn write_double(&mut self, n: f64) -> WriteResult { let s = format!("{:e}", n); let cnt = self.write_bytes(s.as_bytes())?; Ok(self.byte_writer.count() - cnt) } fn write_string(&mut self, s: &str) -> WriteResult { let cnt = self.byte_writer.count(); self.write_byte(b'"')?; //let bytes = s.as_bytes(); for c in s.chars() { match c { '\0' => { self.write_byte(b'\\')?; self.write_byte(b'0')?; } '\\' => { self.write_byte(b'\\')?; self.write_byte(b'\\')?; } '\t' => { self.write_byte(b'\\')?; self.write_byte(b't')?; } '\r' => { self.write_byte(b'\\')?; self.write_byte(b'r')?; } '\n' => { self.write_byte(b'\\')?; self.write_byte(b'n')?; } '"' => { self.write_byte(b'\\')?; self.write_byte(b'"')?; } _ => { let mut b = [0; 4]; let bytes = c.encode_utf8(&mut b); self.write_bytes(bytes.as_bytes())?; } } } self.write_byte(b'"')?; Ok(self.byte_writer.count() - cnt) } /// Escape blob to be UTF8 compatible fn write_blob(&mut self, bytes: &[u8]) -> WriteResult { let cnt = self.byte_writer.count(); self.write_bytes(b"b\"")?; for b in bytes { match b { 0 => { self.write_byte(b'\\')?; self.write_byte(b'0')?; } b'\\' => { self.write_byte(b'\\')?; self.write_byte(b'\\')?; } b'\t' => { self.write_byte(b'\\')?; self.write_byte(b't')?; } b'\r' => { self.write_byte(b'\\')?; self.write_byte(b'r')?; } b'\n' => { self.write_byte(b'\\')?; self.write_byte(b'n')?; } b'"' => { self.write_byte(b'\\')?; self.write_byte(b'"')?; } _ => { if *b >= 128 { self.write_bytes(b"\\x")?; fn to_hex(b: u8) -> u8 { if b < 10 { return b'0' + b; } else { return b'a' + (b - 10); } } self.write_byte(to_hex(*b / 16))?; self.write_byte(to_hex(*b % 16))?; } else { self.write_byte(*b)?; } } } } self.write_byte(b'"')?; Ok(self.byte_writer.count() - cnt) } // fn write_bytes_hex(&mut self, b: &[u8]) -> WriteResult { // let cnt = self.byte_writer.count(); // self.write_bytes(b"x\"")?; // let s = hex::encode(b); // self.write_bytes(s.as_bytes())?; // self.write_byte(b'"')?; // Ok(self.byte_writer.count() - cnt) // } fn write_decimal(&mut self, decimal: &Decimal) -> WriteResult { let s = decimal.to_cpon_string(); let cnt = self.write_bytes(s.as_bytes())?; return Ok(self.byte_writer.count() - cnt) } fn write_datetime(&mut self, dt: &DateTime) -> WriteResult { let cnt = self.write_bytes("d\"".as_bytes())?; let s = dt.to_cpon_string(); self.write_bytes(s.as_bytes())?; self.write_byte(b'"')?; return Ok(self.byte_writer.count() - cnt) } fn write_list(&mut self, lst: &Vec<RpcValue>) -> WriteResult { let cnt = self.byte_writer.count(); let is_oneliner = Self::is_oneliner_list(lst); self.write_byte(b'[')?; self.start_block(); let mut n = 0; let it = lst.iter(); for v in it { if n > 0 { self.write_byte(b',')?; } self.indent_element(is_oneliner, n == 0)?; self.write(v)?; n += 1; } self.end_block(is_oneliner)?; self.write_byte(b']')?; Ok(self.byte_writer.count() - cnt) } fn write_map(&mut self, map: &Map) -> WriteResult { let cnt = self.byte_writer.count(); let is_oneliner = Self::is_oneliner_map(&mut map.iter()); self.write_byte(b'{')?; self.start_block(); let mut n = 0; for (k, v) in map { if n > 0 { self.write_byte(b',')?; } self.indent_element(is_oneliner, n == 0)?; self.write_string(k)?; self.write_byte(b':')?; self.write(v)?; n += 1; } self.end_block(is_oneliner)?; self.write_byte(b'}')?; Ok(self.byte_writer.count() - cnt) } fn write_imap(&mut self, map: &BTreeMap<i32, RpcValue>) -> WriteResult { let cnt = self.byte_writer.count(); let is_oneliner = Self::is_oneliner_map(&mut map.iter()); self.write_byte(b'i')?; self.write_byte(b'{')?; self.start_block(); let mut n = 0; for (k, v) in map { if n > 0 { self.write_byte(b',')?; } self.indent_element(is_oneliner, n == 0)?; self.write_int(*k as i64)?; self.write_byte(b':')?; self.write(v)?; n += 1; } self.end_block(is_oneliner)?; self.write_byte(b'}')?; Ok(self.byte_writer.count() - cnt) } } impl<'a, W> Writer for CponWriter<'a, W> where W: Write { fn write(&mut self, val: &RpcValue) -> WriteResult { let cnt = self.byte_writer.count(); let mm = val.meta(); if !mm.is_empty() { self.write_meta(mm)?; } self.write_value(val.value())?; Ok(self.byte_writer.count() - cnt) } fn write_meta(&mut self, map: &MetaMap) -> WriteResult { let cnt: usize = self.byte_writer.count(); let is_oneliner = Self::is_oneliner_meta(map); self.write_byte(b'<')?; self.start_block(); let mut n = 0; for k in map.0.iter() { if n > 0 { self.write_byte(b',')?; } self.indent_element(is_oneliner, n == 0)?; match &k.key { MetaKey::Str(s) => { self.write_string(s)?; }, MetaKey::Int(i) => { self.write_bytes(i.to_string().as_bytes())?; }, } self.write_byte(b':')?; self.write(&k.value)?; n += 1; } self.end_block(is_oneliner)?; self.write_byte(b'>')?; Ok(self.byte_writer.count() - cnt) } fn write_value(&mut self, val: &Value) -> WriteResult { let cnt: usize = self.byte_writer.count(); match val { Value::Null => self.write_bytes("null".as_bytes()), Value::Bool(b) => if *b { self.write_bytes("true".as_bytes()) } else { self.write_bytes("false".as_bytes()) }, Value::Int(n) => self.write_int(*n), Value::UInt(n) => { self.write_uint(*n)?; self.write_byte(b'u') }, Value::String(s) => self.write_string(s), Value::Blob(b) => self.write_blob(b), Value::Double(n) => self.write_double(*n), Value::Decimal(d) => self.write_decimal(d), Value::DateTime(d) => self.write_datetime(d), Value::List(lst) => self.write_list(lst), Value::Map(map) => self.write_map(map), Value::IMap(map) => self.write_imap(map), }?; Ok(self.byte_writer.count() - cnt) } } pub struct CponReader<'a, R> where R: Read { byte_reader: ByteReader<'a, R>, } impl<'a, R> CponReader<'a, R> where R: Read { pub fn new(read: &'a mut R) -> Self { CponReader { byte_reader: ByteReader::new(read) } } fn peek_byte(&mut self) -> u8 { self.byte_reader.peek_byte() } fn get_byte(&mut self) -> Result<u8, ReadError> { self.byte_reader.get_byte() } fn make_error(&self, msg: &str) -> ReadError { self.byte_reader.make_error(msg) } fn skip_white_insignificant(&mut self) -> Result<(), ReadError> { loop { let b = self.peek_byte(); if b == 0 { break; } if b > b' ' { match b { b'/' => { self.get_byte()?; let b = self.get_byte()?; match b { b'*' => { // multiline_comment_entered loop { let b = self.get_byte()?; if b == b'*' { let b = self.get_byte()?; if b == b'/' { break; } } } } b'/' => { // to end of line comment entered loop { let b = self.get_byte()?; if b == b'\n' { break; } } } _ => { return Err(self.make_error("Malformed comment")) } } } b':' => { self.get_byte()?; // skip key delimiter } b',' => { self.get_byte()?; // skip val delimiter } _ => { break; } } } else { self.get_byte()?; } } return Ok(()) } fn read_string(&mut self) -> Result<Value, ReadError> { let mut buff: Vec<u8> = Vec::new(); self.get_byte()?; // eat " loop { let b = self.get_byte()?; match &b { b'\\' => { let b = self.get_byte()?; match &b { b'\\' => buff.push(b'\\'), b'"' => buff.push(b'"'), b'n' => buff.push(b'\n'), b'r' => buff.push(b'\r'), b't' => buff.push(b'\t'), b'0' => buff.push(b'\0'), _ => buff.push(b), } } b'"' => { // end of string break; } _ => { buff.push(b); } } } let s = std::str::from_utf8(&buff); match s { Ok(s) => return Ok(Value::new(s)), Err(e) => return Err(self.make_error(&format!("Invalid String, Utf8 error: {}", e))), } } fn decode_byte(&self, b: u8) -> Result<u8, ReadError> { match b { b'A' ..= b'F' => Ok(b - b'A' + 10), b'a' ..= b'f' => Ok(b - b'a' + 10), b'0' ..= b'9' => Ok(b - b'0'), c => Err(self.make_error(&format!("Illegal hex encoding character: {}", c))), } } fn read_blob_esc(&mut self) -> Result<Value, ReadError> { let mut buff: Vec<u8> = Vec::new(); self.get_byte()?; // eat b self.get_byte()?; // eat " loop { let b = self.get_byte()?; match &b { b'\\' => { let b = self.get_byte()?; match &b { b'\\' => buff.push(b'\\'), b'"' => buff.push(b'"'), b'n' => buff.push(b'\n'), b'r' => buff.push(b'\r'), b't' => buff.push(b'\t'), b'0' => buff.push(b'\0'), b'x' => { let hi = self.get_byte()?; let lo = self.get_byte()?; let b = self.decode_byte(hi)? * 16 + self.decode_byte(lo)?; buff.push(b) }, _ => buff.push(b), } } b'"' => { // end of string break; } _ => { buff.push(b); } } } Ok(Value::new(buff)) } fn read_blob_hex(&mut self) -> Result<Value, ReadError> { let mut buff: Vec<u8> = Vec::new(); self.get_byte()?; // eat x self.get_byte()?; // eat " loop { let mut b1; loop { b1 = self.get_byte()?; if b1 > b' ' { break; } } if b1 == b'"' { // end of blob break; } let b2 = self.get_byte()?; let b = self.decode_byte(b1)? * 16 + self.decode_byte(b2)?; buff.push(b); } Ok(Value::new(buff)) } fn read_int(&mut self, no_signum: bool) -> Result<(u64, bool, i32), ReadError> { let mut base = 10; let mut val: u64 = 0; let mut neg = false; let mut n = 0; let mut digit_cnt = 0; loop { let b = self.peek_byte(); match b { 0 => break, b'+' | b'-' => { if n != 0 { break; } if no_signum { return Err(self.make_error("Unexpected signum")) } let b = self.get_byte()?; if b == b'-' { neg = true; } } b'x' => { if n == 1 && val != 0 { break; } if n != 1 { break; } self.get_byte()?; base = 16; } b'0' ..= b'9' => { self.get_byte()?; val *= base; //log::debug!("val: {:x} {}", val, (b as i64)); val += (b - b'0') as u64; digit_cnt += 1; } b'A' ..= b'F' => { if base != 16 { break; } self.get_byte()?; val *= base; val += (b - b'A') as u64 + 10; digit_cnt += 1; } b'a' ..= b'f' => { if base != 16 { break; } self.get_byte()?; val *= base; val += (b - b'a') as u64 + 10; digit_cnt += 1; } _ => break, } n += 1; } Ok((val, neg, digit_cnt)) } fn read_number(&mut self) -> Result<Value, ReadError> { let mut mantisa; let mut exponent = 0; let mut decimals = 0; let mut dec_cnt = 0; let mut is_decimal = false; let mut is_uint = false; let mut is_neg = false; let b = self.peek_byte(); if b == b'+' { is_neg = false; self.get_byte()?; } else if b == b'-' { is_neg = true; self.get_byte()?; } let (n, _, digit_cnt) = self.read_int(false)?; if digit_cnt == 0 { return Err(self.make_error("Number should contain at least one digit.")) } mantisa = n; #[derive(PartialEq)] enum State { Mantisa, Decimals, }; let mut state = State::Mantisa; loop { let b = self.peek_byte(); match b { b'u' => { is_uint = true; self.get_byte()?; break; } b'.' => { if state != State::Mantisa { return Err(self.make_error("Unexpected decimal point.")) } state = State::Decimals; is_decimal = true; self.get_byte()?; let (n, _, digit_cnt) = self.read_int(true)?; decimals = n; dec_cnt = digit_cnt as i64; } b'e' | b'E' => { if state != State::Mantisa && state != State::Decimals { return Err(self.make_error("Unexpected exponet mark.")) } //state = State::Exponent; is_decimal = true; self.get_byte()?; let (n, neg, digit_cnt) = self.read_int(false)?; exponent = n as i64; if neg == true { exponent = -exponent; } if digit_cnt == 0 { return Err(self.make_error("Malformed number exponetional part.")) } break; } _ => { break; } } } if is_decimal { for _i in 0 .. dec_cnt { mantisa *= 10; } mantisa += decimals; let mut snum = mantisa as i64; if is_neg { snum = -snum } return Ok(Value::new(Decimal::new(snum, (exponent - dec_cnt) as i8))) } if is_uint { return Ok(Value::new(mantisa)) } let mut snum = mantisa as i64; if is_neg { snum = -snum } return Ok(Value::new(snum)) } fn read_list(&mut self) -> Result<Value, ReadError> { let mut lst = Vec::new(); self.get_byte()?; // eat '[' loop { self.skip_white_insignificant()?; let b = self.peek_byte(); if b == b']' { self.get_byte()?; break; } let val = self.read()?; lst.push(val); } return Ok(Value::new(lst)) } fn read_map(&mut self) -> Result<Value, ReadError> { let mut map: Map = Map::new(); self.get_byte()?; // eat '{' loop { self.skip_white_insignificant()?; let b = self.peek_byte(); if b == b'}' { self.get_byte()?; break; } let key = self.read_string(); let skey = match &key { Ok(b) => { match b { Value::String(s) => { s }, _ => return Err(self.make_error("Read MetaMap key internal error")), } }, _ => return Err(self.make_error(&format!("Invalid Map key '{}'", b))), }; self.skip_white_insignificant()?; let val = self.read()?; map.insert(skey.to_string(), val); } return Ok(Value::new(map)) } fn read_imap(&mut self) -> Result<Value, ReadError> { self.get_byte()?; // eat 'i' let b = self.get_byte()?; // eat '{' if b != b'{' { return Err(self.make_error("Wrong IMap prefix, '{' expected.")) } let mut map: BTreeMap<i32, RpcValue> = BTreeMap::new(); loop { self.skip_white_insignificant()?; let b = self.peek_byte(); if b == b'}' { self.get_byte()?; break; } let (k, neg, _) = self.read_int(true)?; let key = if neg == true { k as i64 * -1 } else { k as i64 }; self.skip_white_insignificant()?; let val = self.read()?; map.insert(key as i32, val); } return Ok(Value::new(map)) } fn read_datetime(&mut self) -> Result<Value, ReadError> { self.get_byte()?; // eat 'd' let v = self.read_string()?; if let Value::String(sdata) = v { const PATTERN: &'static str = "2020-02-03T11:59:43"; if sdata.len() >= PATTERN.len() { let s = &sdata[..]; let naive_str = &s[..PATTERN.len()]; if let Ok(ndt) = chrono::NaiveDateTime::parse_from_str(naive_str, "%Y-%m-%dT%H:%M:%S") { let mut msec = 0; let mut offset = 0; let mut rest = &s[PATTERN.len()..]; if rest.len() > 0 && rest.as_bytes()[0] == b'.' { rest = &rest[1..]; if rest.len() >= 3 { if let Ok(ms) = rest[..3].parse::<i32>() { msec = ms; rest = &rest[3..]; } else { return Err(self.make_error(&format!("Invalid DateTime msec part: '{}", rest))) } } } if rest.len() > 0 { if rest.len() == 1 && rest.as_bytes()[0] == b'Z' { } else if rest.len() == 3 { if let Ok(hrs) = rest.parse::<i32>() { offset = 60 * 60 * hrs; } else { return Err(self.make_error(&format!("Invalid DateTime TZ part: '{}", rest))) } } else if rest.len() == 5 { if let Ok(hrs) = rest.parse::<i32>() { offset = 60 * (60 * (hrs / 100) + (hrs % 100)); } else { return Err(self.make_error(&format!("Invalid DateTime TZ part: '{}", rest))) } } else { return Err(self.make_error(&format!("Invalid DateTime TZ part: '{}", rest))) } } let dt = DateTime::from_epoch_msec_tz((ndt.timestamp() - (offset as i64)) * 1000 + (msec as i64), offset); return Ok(Value::new(dt)) } } return Err(self.make_error(&format!("Invalid DateTime: '{:?}", sdata))) } return Err(self.make_error("Invalid DateTime")) } fn read_true(&mut self) -> Result<Value, ReadError> { self.read_token("true")?; return Ok(Value::new(true)) } fn read_false(&mut self) -> Result<Value, ReadError> { self.read_token("false")?; return Ok(Value::new(false)) } fn read_null(&mut self) -> Result<Value, ReadError> { self.read_token("null")?; return Ok(Value::new(())) } fn read_token(&mut self, token: &str) -> Result<(), ReadError> { for c in token.as_bytes() { let b = self.get_byte()?; if b != *c { return Err(self.make_error(&format!("Incomplete '{}' literal.", token))) } } return Ok(()) } } impl<'a, R> Reader for CponReader<'a, R> where R: Read { fn try_read_meta(&mut self) -> Result<Option<MetaMap>, ReadError> { self.skip_white_insignificant()?; let b = self.peek_byte(); if b != b'<' { return Ok(None) } self.get_byte()?; let mut map = MetaMap::new(); loop { self.skip_white_insignificant()?; let b = self.peek_byte(); if b == b'>' { self.get_byte()?; break; } let key = self.read()?; self.skip_white_insignificant()?; let val = self.read()?; if key.is_int() { map.insert(key.as_i32(), val); } else { map.insert(key.as_str(), val); } } Ok(Some(map)) } fn read_value(&mut self) -> Result<Value, ReadError> { self.skip_white_insignificant()?; let b = self.peek_byte(); let v = match &b { b'0' ..= b'9' | b'+' | b'-' => self.read_number(), b'"' => self.read_string(), b'b' => self.read_blob_esc(), b'x' => self.read_blob_hex(), b'[' => self.read_list(), b'{' => self.read_map(), b'i' => self.read_imap(), b'd' => self.read_datetime(), b't' => self.read_true(), b'f' => self.read_false(), b'n' => self.read_null(), _ => Err(self.make_error(&format!("Invalid char {}", b))), }?; Ok(v) } } #[cfg(test)] mod test { use crate::{MetaMap, RpcValue}; use crate::Decimal; use std::collections::BTreeMap; use crate::cpon::CponReader; use crate::reader::Reader; use crate::rpcvalue::Map; #[test] fn test_read() { assert_eq!(RpcValue::from_cpon("null").unwrap().is_null(), true); assert_eq!(RpcValue::from_cpon("false").unwrap().as_bool(), false); assert_eq!(RpcValue::from_cpon("true").unwrap().as_bool(), true); assert_eq!(RpcValue::from_cpon("0").unwrap().as_i32(), 0); assert_eq!(RpcValue::from_cpon("123").unwrap().as_i32(), 123); assert_eq!(RpcValue::from_cpon("-123").unwrap().as_i32(), -123); assert_eq!(RpcValue::from_cpon("+123").unwrap().as_i32(), 123); assert_eq!(RpcValue::from_cpon("123u").unwrap().as_u32(), 123u32); assert_eq!(RpcValue::from_cpon("0xFF").unwrap().as_i32(), 255); assert_eq!(RpcValue::from_cpon("-0x1000").unwrap().as_i32(), -4096); assert_eq!(RpcValue::from_cpon("123.4").unwrap().as_decimal(), Decimal::new(1234, -1)); assert_eq!(RpcValue::from_cpon("0.123").unwrap().as_decimal(), Decimal::new(123, -3)); assert_eq!(RpcValue::from_cpon("-0.123").unwrap().as_decimal(), Decimal::new(-123, -3)); assert_eq!(RpcValue::from_cpon("0e0").unwrap().as_decimal(), Decimal::new(0, 0)); assert_eq!(RpcValue::from_cpon("0.123e3").unwrap().as_decimal(), Decimal::new(123, 0)); assert_eq!(RpcValue::from_cpon("1000000.").unwrap().as_decimal(), Decimal::new(1000000, 0)); assert_eq!(RpcValue::from_cpon(r#""foo""#).unwrap().as_str(), "foo"); assert_eq!(RpcValue::from_cpon(r#""ěščřžýáí""#).unwrap().as_str(), "ěščřžýáí"); assert_eq!(RpcValue::from_cpon("b\"foo\tbar\nbaz\"").unwrap().as_blob(), b"foo\tbar\nbaz"); assert_eq!(RpcValue::from_cpon(r#""foo\"bar""#).unwrap().as_str(), r#"foo"bar"#); let lst1 = vec![RpcValue::new(123), RpcValue::new("foo")]; let cpon = r#"[123 , "foo"]"#; let rv = RpcValue::from_cpon(cpon).unwrap(); let lst2 = rv.as_list(); assert_eq!(lst2, &lst1); let mut map: Map = Map::new(); map.insert("foo".to_string(), RpcValue::new(123)); map.insert("bar".to_string(), RpcValue::new("baz")); let cpon = r#"{"foo": 123,"bar":"baz"}"#; assert_eq!(RpcValue::from_cpon(cpon).unwrap().as_map(), &map); let mut map: BTreeMap<i32, RpcValue> = BTreeMap::new(); map.insert(1, RpcValue::new(123)); map.insert(2, RpcValue::new("baz")); let cpon = r#"i{1: 123,2:"baz"}"#; assert_eq!(RpcValue::from_cpon(cpon).unwrap().as_imap(), &map); let cpon = r#"<1: 123,2:"baz">"#; let mut b = cpon.as_bytes(); let mut rd = CponReader::new(&mut b); let mm1 = rd.try_read_meta().unwrap().unwrap(); let mut mm2 = MetaMap::new(); mm2.insert(1, RpcValue::new(123)); mm2.insert(2, RpcValue::new("baz")); assert_eq!(mm1, mm2); //let cpon1 = r#"<1:123,2:"foo","bar":"baz">42"#; //let rv = cpon1.to_rpcvalue().unwrap(); //let cpon2 = rv.to_cpon_string().unwrap(); //assert_eq!(cpon1, cpon2); } }
<commit_msg>Use BaseCommand instead of NoArgsCommand <commit_before>from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): def handle_noargs(self, **options): from symposion.proposals.kinds import ensure_proposal_records ensure_proposal_records() <commit_after>from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): from symposion.proposals.kinds import ensure_proposal_records ensure_proposal_records()
<filename>2 sem/cw7/vector_d.c #include <stdlib.h> #include <stdbool.h> #include "vector_d.h" void d_create(vector_d* v){ v->size = 0; v->capacity = 0; v->buffer = NULL; } void d_destroy(vector_d* v){ v->size = 0; v->capacity = 0; free(v->buffer); v->buffer = NULL; } int d_size(vector_d* v){ return v->size; } double d_get(vector_d* v, int position){ return v->buffer[position]; } void d_set(vector_d* v, int position, double value){ v->buffer[position] = value; } bool d_grow_buffer(vector_d* v){ int new_capacity = v->capacity * 3 / 2; if (v->capacity == 0){ new_capacity = 10; } double* tmp = realloc(v->buffer, sizeof(double) * new_capacity); if (tmp != NULL){ v->buffer = tmp; v->capacity = new_capacity; return true; } else { return false; } } bool d_append(vector_d* v, double value){ if (v->size >= v->capacity){ if (!d_grow_buffer(v)){ return false; } } v->buffer[v->size] = value; v->size++; return true; } bool d_resize(vector_d* v, int new_size){ if (v->capacity < new_size){ double* tmp = realloc(v->buffer, sizeof(double) * new_size); if (tmp == NULL){ return false; } v->buffer = tmp; v->capacity = new_size; } int first_size = v->size; v->size = new_size; for (int i = first_size; i < new_size; ++i){ v->buffer[i] = 0; } return true; } void d_clear(vector_d* v){ double* old = v->buffer; free(old); v->size = v->capacity = 0; v->buffer = NULL; } void d_insert(vector_d* v, int position, double value){ int idx = d_size(v) - 1; d_append(v, d_get(v, idx)); while(idx > position){ d_set(v, idx, d_get(v, idx-1)); --idx; } d_set(v, position, value); }
/** * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.jbpm.persistence; import java.util.ArrayList; import java.util.Collections; import org.kie.internal.process.CorrelationKey; import org.jbpm.persistence.correlation.CorrelationKeyInfo; import java.util.HashMap; import java.util.List; import java.util.Map; import org.drools.persistence.map.MapBasedPersistenceContext; import org.jbpm.persistence.processinstance.ProcessInstanceInfo; public class MapBasedProcessPersistenceContext extends MapBasedPersistenceContext implements NonTransactionalProcessPersistentSession , ProcessPersistenceContext { private ProcessStorage storage; private Map<Long, ProcessInstanceInfo> processes; private Map<CorrelationKeyInfo, ProcessInstanceInfo> processInstancesByBusinessKey; public MapBasedProcessPersistenceContext(ProcessStorage storage) { super(storage); MapBasedProcessPersistenceContext.this.storage = storage; MapBasedProcessPersistenceContext.this.processes = new HashMap<Long, ProcessInstanceInfo>(); MapBasedProcessPersistenceContext.this.processInstancesByBusinessKey = new HashMap<CorrelationKeyInfo, ProcessInstanceInfo>(); } public ProcessInstanceInfo persist(ProcessInstanceInfo processInstanceInfo) { if ((processInstanceInfo.getId()) == null) { processInstanceInfo.setId(storage.getNextProcessInstanceId()); } processes.put(processInstanceInfo.getId(), processInstanceInfo); return processInstanceInfo; } public ProcessInstanceInfo findProcessInstanceInfo(Long processId) { ProcessInstanceInfo processInstanceInfo = processes.get(processId); if (processInstanceInfo == null) { processInstanceInfo = storage.findProcessInstanceInfo(processId); } return processInstanceInfo; } public List<ProcessInstanceInfo> getStoredProcessInstances() { return Collections.unmodifiableList(new ArrayList<ProcessInstanceInfo>(processes.values())); } @Override public void close() { super.close(); clearStoredProcessInstances(); } public void remove(ProcessInstanceInfo processInstanceInfo) { storage.removeProcessInstanceInfo(processInstanceInfo.getId()); } public List<Long> getProcessInstancesWaitingForEvent(String type) { return storage.getProcessInstancesWaitingForEvent(type); } public void clearStoredProcessInstances() { processes.clear(); } @Override public CorrelationKeyInfo persist(CorrelationKeyInfo correlationKeyInfo) { ProcessInstanceInfo piInfo = MapBasedProcessPersistenceContext.this.processes.get(correlationKeyInfo.getProcessInstanceId()); if (piInfo != null) { MapBasedProcessPersistenceContext.this.processInstancesByBusinessKey.put(correlationKeyInfo, piInfo); } return correlationKeyInfo; } @Override public Long getProcessInstanceByCorrelationKey(CorrelationKey correlationKey) { ProcessInstanceInfo piInfo = MapBasedProcessPersistenceContext.this.processInstancesByBusinessKey.get(correlationKey); return piInfo.getId(); } }
<reponame>LevyForchh/mac-branch-deep-linking /** @file BNCApplication.h @package Branch @brief Current application and extension info. @author <NAME> @date January 8, 2018 @copyright Copyright © 2018 Branch. All rights reserved. */ #import "BranchHeader.h" NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, BNCApplicationUpdateState) { BNCApplicationUpdateStateInstall = 0, //!< Application was recently installed. BNCApplicationUpdateStateNonUpdate = 1, //!< Application was neither newly installed nor updated. BNCApplicationUpdateStateUpdate = 2, //!< Application was recently updated. BNCApplicationUpdateStateError = 3, //!< Error determining update state. BNCApplicationUpdateStateReinstall = 4, //!< App was re-installed. }; @interface BNCApplication : NSObject /// A reference to the current running application. + (BNCApplication*_Nonnull) currentApplication; /// The bundle identifier of the current @property (atomic, readonly) NSString*_Nullable bundleID; /// The team that was for code signing. @property (atomic, readonly) NSString*_Nullable teamID; /// The bundle display name from the info plist. @property (atomic, readonly) NSString*_Nullable displayName; /// The bundle short display name from the info plist. @property (atomic, readonly) NSString*_Nullable shortDisplayName; /// The short version ID as is typically shown to the user, like in iTunes (CFBundleShortVersionString). @property (atomic, readonly) NSString*_Nullable displayVersionString; /// The version ID that developers use (CFBundleVersion). @property (atomic, readonly) NSString*_Nullable versionString; /// The creation date of the current executable. @property (atomic, readonly) NSDate*_Nullable currentBuildDate; /// Previous value of the creation date of the current executable, if available. @property (atomic, readonly) NSDate*_Nullable previousAppBuildDate; /// The creating date of the exectuble the first time it was recorded by Branch. @property (atomic, readonly) NSDate*_Nullable firstInstallBuildDate; /// The date this app was installed on this device. @property (atomic, readonly) NSDate*_Nullable currentInstallDate; /// The date this app was first installed on this device. @property (atomic, readonly) NSDate*_Nullable firstInstallDate; /// The update state off the application. @property (atomic, readonly) BNCApplicationUpdateState updateState; /// YES if running as an application. @property (atomic, readonly) BOOL isApplication; /// YES if running as an application extension. @property (atomic, readonly) BOOL isApplicationExtension; /// The app extension type or `nil` for a full application. @property (atomic, readonly) NSString*_Nullable extensionType; /// The Branch extension type. @property (atomic, readonly) NSString* branchExtensionType; /// The default URL scheme for the app as found in the app's Info.plist. @property (atomic, readonly) NSString*_Nullable defaultURLScheme; /// The unique application identifier. Typically this is `teamID.bundleID`: XYZ123.com.company.app. @property (atomic, readonly) NSString*_Nullable applicationID; /// The push notification environment. Usually `development` or `production` or `nil`. @property (atomic, readonly) NSString*_Nullable pushNotificationEnvironment; /// The keychain access groups from the entitlements. @property (atomic, readonly) NSArray<NSString*>*_Nullable keychainAccessGroups; /// The associated domains from the entitlements. @property (atomic, readonly) NSArray<NSString*>*_Nullable associatedDomains; @end NS_ASSUME_NONNULL_END
On March 30, theaters across the U.S. will, for one night only, will screen a movie comprised of concert footage from throughout Led Zeppelin 's career. Now we know what songs we can expect to hear. The 13 songs, listed below, are all taken from the 2003 Led Zeppelin DVD and run in chronological order of their performance, from the Jan. 9, 1970, show at the Royal Albert Hall through Knebworth on Aug. 4, 1979, which was the last British concert the group played with John Bonham. Along the way are classics like "Communication Breakdown," "Immigrant Song," "In My Time of Dying" and "Whole Lotta Love." Two songs, "Misty Mountain Hop" and "The Ocean," appear to have been edited together from performances at their three-night stand at Madison Square Garden in 1973, the dates that resulted in the 1976 film The Song Remains the Same . To find out more information about the movie, including theater locations and ticket purchases, visit the website for Fathom Events . You can also view the trailer . This is the latest installment of Fathom's Classic Music Series, which recently screened concerts by Aerosmith and Hall & Oates . Led Zeppelin Song Listing 1 "Communication Breakdown" (Royal Albert Hall – Jan. 9, 1970) 2. "Bring It on Home/Bring It on Back" (Royal Albert Hall – Jan. 9, 1970) 3. "Immigrant Song" (Sydney Showground – Feb. 27, 1972) 4. "Black Dog" (Madison Square Garden – July 28, 1973) 5. "Misty Mountain Hop" (Madison Square Garden – July 27 & 28, 1973) 6. "The Ocean" (Madison Square Garden – July 27 & 29, 1973) 7. "Going to California" (Earls Court – May 25, 1975) 8. "In My Time of Dying" (Earls Court – May 24, 1975) 9. "Stairway to Heaven" (Earls Court – May 25, 1975) 10. "Rock and Roll" (Knebworth – Aug. 4, 1979) 11. "Nobody's Fault but Mine" (Knebworth – Aug. 4, 1979) 12. "Kashmir" (Knebworth – Aug. 4, 1979) 13. "Whole Lotta Love" (Knebworth – Aug. 4, 1979) See Led Zeppelin and Other Rockers in the Top 100 Albums of the ’70s
/** * Fail entries matching a specified ExchangeContext. * * @param[in] ec A pointer to the ExchangeContext object. * * @param[in] err The error for failing table entries. * */ void ChipExchangeManager::FailRetransmitTableEntries(ExchangeContext * ec, CHIP_ERROR err) { for (int i = 0; i < CHIP_CONFIG_RMP_RETRANS_TABLE_SIZE; i++) { if (RetransTable[i].exchContext == ec) { void * msgCtxt = RetransTable[i].msgCtxt; ClearRetransmitTable(RetransTable[i]); if (ec->OnSendError) ec->OnSendError(ec, err, msgCtxt); } } }
///// \file python_module_interaction.cpp ///// ///// \brief ///// ///// \authors maarten ///// \date 2020-11-27 ///// \copyright Copyright 2017-2020 The Institute for New Economic Thinking, ///// Oxford Martin School, University of Oxford ///// ///// Licensed under the Apache License, Version 2.0 (the "License"); ///// you may not use this file except in compliance with the License. ///// You may obtain a copy of the License at ///// ///// http://www.apache.org/licenses/LICENSE-2.0 ///// ///// Unless required by applicable law or agreed to in writing, ///// software distributed under the License is distributed on an "AS ///// IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ///// express or implied. See the License for the specific language ///// governing permissions and limitations under the License. ///// ///// You may obtain instructions to fulfill the attribution ///// requirements in CITATION.cff ///// //#include <esl/interaction/python_module_interaction.hpp> //#include <esl/interaction/transfer.hpp> //using namespace esl; //using namespace esl::simulation; //using namespace esl::interaction; // // //#include <boost/serialization/export.hpp> // //#ifdef WITH_PYTHON //#include <string> // //# include <boost/python/suite/indexing/indexing_suite.hpp> //# include <boost/python/suite/indexing/vector_indexing_suite.hpp> //# include <boost/python/iterator.hpp> //# include <boost/python/call_method.hpp> //# include <boost/python/tuple.hpp> // // //BOOST_CLASS_EXPORT(esl::interaction::python_message); // // //template <class container_t_, bool NoProxy, class DerivedPolicies> //class multimap_indexing_suite; // //namespace detail //{ // template <class container_t_, bool NoProxy> // class final_map_derived_policies // : public multimap_indexing_suite<container_t_, NoProxy, final_map_derived_policies<container_t_, NoProxy> > {}; //} // // //template < typename multimap_t_ // , bool NoProxy = false // , typename DerivedPolicies = ::detail::final_map_derived_policies<multimap_t_, NoProxy> > //class multimap_indexing_suite //: public indexing_suite<multimap_t_, DerivedPolicies // , NoProxy // , true // , typename multimap_t_::value_type::second_type // , typename multimap_t_::key_type // , typename multimap_t_::key_type //> //{ //public: // // typedef typename multimap_t_::value_type value_type; // typedef typename multimap_t_::value_type::second_type data_type; // typedef typename multimap_t_::key_type key_type; // typedef typename multimap_t_::key_type index_type; // typedef typename multimap_t_::size_type size_type; // typedef typename multimap_t_::difference_type difference_type; // // template <class Class> static void extension_def(Class& cl) // { // // Wrap the map's element (value_type) // std::string name_ = "multimap_indexing_suite_"; // object class_name(cl.attr("__name__")); // extract<std::string> class_name_extractor(class_name); // name_ += class_name_extractor(); // name_ += "_entry"; // // typedef typename boost::mpl::if_< // boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> > // , return_internal_reference<> // , default_call_policies // >::type get_data_return_policy; // // class_<value_type>(name_.c_str()) // .def("__repr__", &DerivedPolicies::representation) // .def("data", &DerivedPolicies::get_data, get_data_return_policy()) // .def("key", &DerivedPolicies::get_key) // ; // } // // static object representation(typename multimap_t_::value_type const &e) // { // return "(%s, %s)" % boost::python::make_tuple(e.first, e.second); // } // // static // typename boost::mpl::if_< // boost::mpl::and_<boost::is_class<data_type>, boost::mpl::bool_<!NoProxy> > // , data_type & // , data_type // >::type // get_data(typename multimap_t_::value_type &e) // { // return e.second; // } // // static typename multimap_t_::key_type // get_key(typename multimap_t_::value_type &e) // { // return e.first; // } // // static data_type &get_item(multimap_t_ &container, index_type i_) // { // typename multimap_t_::iterator i = container.find(i_); // if (i == container.end()){ // PyErr_SetString(PyExc_KeyError, "Invalid key"); // throw_error_already_set(); // } // return i->second; // } // // static void set_item(multimap_t_ &container, index_type i, data_type const& v) // { // for(auto &[k,value_]: container){ // if(k == i){ // value_ = v; // } // } // } // // static void // delete_item(multimap_t_ &container, index_type i) // { // container.erase(i); // } // // static size_t // size(multimap_t_ &container) // { // return container.size(); // } // // static bool // contains(multimap_t_ &container, key_type const &key) // { // return container.find(key) != container.end(); // } // // static bool // compare_index(multimap_t_ &container, index_type a, index_type b) // { // return container.key_comp()(a, b); // } // // static index_type // convert_index(multimap_t_ &container, PyObject *i_) // { // (void) container; // extract<key_type const&> i(i_); // if (i.check()){ // return i(); // }else{ // extract<key_type> i2(i_); // if (i2.check()) { // return i2(); // } // } // // PyErr_SetString(PyExc_TypeError, "Invalid index type"); // throw_error_already_set(); // return index_type(); // } //}; // // // // // //void send_message_python(communicator &c, boost::python::object o) //{ // (void)c; // (void)o; // extract<const communicator::message_t &> extractor_(o); // //} // ////communicator::callback_handle make_handle() ////{ //// return [&](communicator::message_t, //// simulation::time_interval, //// std::seed_seq &) { //// }; ////} // //// ////communicator::callback_t make_callback(boost::python::object &o) ////{ //// return communicator::callback_t //// { .function = [] (communicator::message_t, //// simulation::time_interval, //// std::seed_seq &) //// { //// return simulation::time_point(123); //// } //// , .description = "asdf" //// , .file = "asdf.f" //// , .line = 123 //// , .message = "asdfasdf" //// } ; ////} // // //BOOST_PYTHON_MODULE(_interaction) //{ // def("make_callback_handle", &make_callback_handle); // // class_<communicator::callback_handle>( "callback_handle"); // // class_<communicator::callback_t>( "callback_t") // .def_readwrite("function", &communicator::callback_t::function) // .def_readwrite("description", &communicator::callback_t::description) // .def_readwrite("message", &communicator::callback_t::message) // .def_readwrite("file", &communicator::callback_t::file) // .def_readwrite("line", &communicator::callback_t::line) // //.def("__call__", &communicator::callback_t::operator ()) // ; // // enum_<communicator::scheduling>("scheduling") // .value("in_order", communicator::scheduling::in_order) // .value("random", communicator::scheduling::random) // ; // // class_<communicator::inbox_t>("inbox_t") // .def(multimap_indexing_suite<communicator::inbox_t>()); // // // class_<communicator::outbox_t>("outbox_t") // .def(boost::python::vector_indexing_suite<communicator::outbox_t>()); // // class_<communicator>("communicator") // .def("send_message", send_message_python) // .def_readwrite("inbox", &communicator::inbox) // .def_readwrite("outbox", &communicator::outbox) // ; // // class_<header>("header", init<message_code, identity<agent>, identity<agent>, simulation::time_point, simulation::time_point>()) // .def(init<message_code, identity<agent>, identity<agent>, simulation::time_point>()) // .def(init<message_code, identity<agent>, identity<agent>>()) // .def(init<message_code, identity<agent>>()) // .def(init<message_code>()) // .def(init<message_code>()) // .def_readwrite("type", &header::type) // .def_readwrite("sender", &header::sender) // .def_readwrite("recipient", &header::recipient) // .def_readwrite("sent", &header::sent) // .def_readwrite("received", &header::received) // ; // // class_<python_message, bases<header>>("message") // .def_readonly("code", &python_message::python_code) // ; //} // //#endif // // // // // // // // // // // // // // // //
//ExecuteState define the current_state using argument name in the user's data. // //If exists callback in user's data (state_with_callback), execute it first with the executeCallback method. //Terminates execution if callback returns false. // //If there is no callback, the flow continues and if the current state has a method in the item State.Callback, this value will be defined in the user's current data (state_with_callback) to be executed later. // //After all checks, the method in State.Executes is executed. //The current state is defined using the value of State.Next if execution return true. // //Return execution boolean and error if exists. func (b *Bot) ExecuteState(name string) (bool, error) { for _, state := range b.States { if state.Name == name { if b.Data.UserID == "" { return false, errors.New("Undefined user to execute state " + state.Name + ".") } if state.Executes == nil { return false, errors.New("Method to execute in the " + state.Name + " state is nil.") } b.Data.SetCurrentState(state.Name) callbackResp, err := b.executeCallback() if err != nil { return false, err } if callbackResp == false { return false, nil } if state.Callback != nil { err := b.Data.SetStateWithCallback(state.Name) if err != nil { return false, err } } execute := state.Executes(b) if execute == true && state.Next != "" { b.Data.SetCurrentState(state.Next) } return execute, nil } } return false, errors.New("No state to execute with name " + name + ".") }
package org.travlyn.shared.model.api; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModelProperty; import org.springframework.validation.annotation.Validated; import org.travlyn.shared.model.db.StopEntity; import org.travlyn.shared.model.db.StopRatingEntity; import javax.validation.Valid; import java.util.*; /** * Stop */ @Validated public class Stop extends AbstractDataTransferObject { @JsonProperty("id") @ApiModelProperty(value = "Identifier", required = true, example = "123") private int id = -1; @JsonProperty("longitude") @ApiModelProperty(value = "Longitude", required = true, example = "123.456") private double longitude; @JsonProperty("latitude") @ApiModelProperty(value = "Latitude", required = true, example = "123.456") private double latitude; @JsonProperty("name") @ApiModelProperty(value = "Name", required = true, example = "Statue of Liberty") private String name = null; @JsonProperty("description") @ApiModelProperty(value = "Additional information about stop", required = true, example = "This is a description about the Statue of Liberty") private String description = null; @JsonProperty("image") @ApiModelProperty(value = "Thumbnail for Stop", required = true, example = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/22/Karlsruhe_town_centre_air.jpg/300px-Karlsruhe_town_centre_air.jpg") private String image = null; @JsonProperty("pricing") @ApiModelProperty(value = "Approximate price estimation for one person in USD", required = true, example = "50") private Double pricing = 0.0; @JsonProperty("timeEffort") @ApiModelProperty(value = "Approximate time estimation", required = true, example = "2") private Double timeEffort = 0.0; @JsonProperty("averageRating") @ApiModelProperty(value = "Average percentage rating by user", required = true, example = "0.98") private Double averageRating = 0.0; @JsonProperty("ratings") @ApiModelProperty(value = "List of Ratings by Users") @Valid private List<Rating> ratings = new ArrayList<>(); @JsonProperty("category") @ApiModelProperty(value = "Category", required = true) private Category category = new Category(); @JsonProperty("city") @ApiModelProperty(value = "City the stop belongs to", required = true) private City city = null; public Stop id(int id) { this.id = id; return this; } /** * Get Identifier * * @return id **/ public int getId() { return id; } public void setId(int id) { this.id = id; } public Stop longitude(double longitude) { this.longitude = longitude; return this; } /** * Get Longitude * * @return longitude **/ public double getLongitude() { return longitude; } public Stop setLongitude(double longitude) { this.longitude = longitude; return this; } public Stop latitude(double latitude) { this.latitude = latitude; return this; } /** * Get Latitude * * @return latitude **/ public double getLatitude() { return latitude; } public Stop setLatitude(double latitude) { this.latitude = latitude; return this; } public Stop name(String name) { this.name = name; return this; } /** * Get Name * * @return name **/ public String getName() { return name; } public Stop setName(String name) { this.name = name; return this; } public Stop description(String description) { this.description = description; return this; } /** * Additional information about stop * * @return description **/ public String getDescription() { return description; } public Stop image(String image) { this.image = image; return this; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public Stop pricing(Double pricing) { this.pricing = pricing; return this; } /** * Average pricing for one person in USD * * @return pricing **/ public Double getPricing() { return pricing; } public Stop setPricing(Double pricing) { this.pricing = pricing; return this; } public Stop timeEffort(Double timeEffort) { this.timeEffort = timeEffort; return this; } /** * Time effort in hours * * @return timeEffort **/ public Double getTimeEffort() { return timeEffort; } public Stop setTimeEffort(Double timeEffort) { this.timeEffort = timeEffort; return this; } public Stop averageRating(Double averageRating) { this.averageRating = averageRating; return this; } /** * Average percentage rating by user * * @return averageRating **/ public Double getAverageRating() { return averageRating; } public Stop setAverageRating(Double averageRating) { this.averageRating = averageRating; return this; } public Stop ratings(List<Rating> ratings) { this.ratings = ratings; return this; } public Stop addRatingsItem(Rating ratingsItem) { if (this.ratings == null) { this.ratings = new ArrayList<Rating>(); } this.ratings.add(ratingsItem); return this; } /** * Get ratings * * @return ratings **/ @Valid public List<Rating> getRatings() { return ratings; } public void setRatings(List<Rating> ratings) { this.ratings = ratings; } public Stop category(Category category) { this.category = category; return this; } /** * Get Category * * @return category **/ @Valid public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public City getCity() { return city; } public void city(City city) { this.city = city; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Stop stop = (Stop) o; return Objects.equals(this.id, stop.id) && Objects.equals(this.longitude, stop.longitude) && Objects.equals(this.latitude, stop.latitude) && Objects.equals(this.name, stop.name) && Objects.equals(this.description, stop.description) && Objects.equals(this.pricing, stop.pricing) && Objects.equals(this.timeEffort, stop.timeEffort) && Objects.equals(this.averageRating, stop.averageRating) && Objects.equals(this.ratings, stop.ratings) && Objects.equals(this.category, stop.category); } @Override public int hashCode() { return Objects.hash(id, longitude, latitude, name, description, pricing, timeEffort, averageRating, ratings, category); } @Override public StopEntity toEntity() { StopEntity stopEntity = new StopEntity(); stopEntity.setId(this.id); stopEntity.setLongitude(this.longitude); stopEntity.setLatitude(this.latitude); stopEntity.setName(this.name); stopEntity.setDescription(this.description); stopEntity.setPricing(this.pricing); stopEntity.setTimeEffort(this.timeEffort); stopEntity.setAverageRating(this.averageRating); Set<StopRatingEntity> ratingEntities = new HashSet<>(); this.ratings.forEach(rating -> { StopRatingEntity stopRatingEntity = (StopRatingEntity) rating.toEntity(); stopRatingEntity.setStop(stopEntity); ratingEntities.add(stopRatingEntity); }); stopEntity.setRatings(ratingEntities); stopEntity.setCategory(this.category.toEntity()); if (this.city != null) stopEntity.setCity(this.city.toEntity()); stopEntity.setImage(this.image); return stopEntity; } }
Yahoo CEO Marissa Mayer stands to make $55 million if the struggling company gets sold -- and she gets booted. The company revealed Mayer's severance package and her 2015 pay when it updated its annual report on Friday evening. Mayer's golden parachute would be a huge payout for a chief executive who hasn't been able to stop the technology behemoth's free fall. In 2015, the value of her company's stock fell by 33%. Most of the $55 million severance package is made up of restricted stock units and options. Only $3 million is actual cash. On Friday, Yahoo also revealed that Mayer got a significant pay cut last year. Her "reported pay" -- what she was promised -- was $36 million. But her "realized pay" -- what she was actually able to keep -- is closer to $14 million. Because of the complex nature of executive pay, she could wind up making more than that someday in the future. Either way, though, it's a massive pay cut from the previous year, when her "reported pay" was $42 million. Mayer's income was drastically reduced "because the company's 2015 performance fell short of the rigorous annual financial goals we set," the company states in its annual report. The report also reveals Yahoo's executives decided to give up their bonuses last year. Yahoo (YHOO) representatives declined to provide additional comment to CNNMoney. There's lots of attention on Mayer's pay, because her tenure at Yahoo could soon be over. Her four-year odyssey to improve Yahoo's finances hasn't worked. The company has spent billions of dollars buying promising firms and hiring well-known media personalities. It started focusing on mobile and video. Yet the company's core business -- Internet advertising -- has been completely overtaken by Facebook (FB) and Google (GOOGL). While Yahoo treads water, it's the tiny Silicon Valley players that are landing the huge deals, like Snapchat partnering with NBC for Olympics coverage. In an effort to cut costs, Yahoo fired 15% of its staff earlier this year. But the latest numbers were abysmal, with Yahoo posting a $99 million loss in the first quarter of 2016. As a result, Mayer has said that selling Yahoo is now "a top priority." It's gotten so bad that activist investors have swooped in, and Mayer's arch-nemesis is now her boss. Activist hedge fund manager Jeff Smith, who has long fought with Mayer over control of Yahoo, has joined the company's board, along with three other executives chosen by him. CNN's David Goldman contributed to this report.
def menu_option_load(config, config_list): print("List of available saved configurations:") print(config_list) while True: config_name = input("Enter a name of a configuration to load (enter \"end\" to return to the menu): ") if config_name == "end": break elif configuration.config_exists(config_name): config = configuration.load_config(config_name) break else: print("{} is an invalid configuration name.".format(config_name)) return config
// /src/content/bolt/materialiconstwotone/24px.svg import { createSvgIcon } from './createSvgIcon'; export const SvgBoltTwotone = createSvgIcon( `<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24" viewBox="0 0 24 24" width="24"> <g> <rect fill="none" height="24" width="24"/> </g> <g> <path d="M11,21h-1l1-7H7.5c-0.88,0-0.33-0.75-0.31-0.78C8.48,10.94,10.42,7.54,13.01,3h1l-1,7h3.51c0.4,0,0.62,0.19,0.4,0.66 C12.97,17.55,11,21,11,21z"/> </g> </svg>` );
Austin, Texas. Shutterstock In the wee hours of the morning on Sunday, the mighty state of Texas was asleep. The honky-tonks in Austin were shuttered, the air-conditioned office towers of Houston were powered down, and the wind whistled through the dogwood trees and live oaks on the gracious lawns of Preston Hollow. Out in the desolate flats of West Texas, the same wind was turning hundreds of wind turbines, producing tons of electricity at a time when comparatively little supply was needed. And then a very strange thing happened: The so-called spot price of electricity in Texas fell toward zero, hit zero, and then went negative for several hours. As the Lone Star State slumbered, power producers were paying the state's electricity system to take electricity off their hands. At one point, the negative price was $8.52 per megawatt hour. Impossible, most economists would say. In any market — and especially in a state devoted to the free market, like Texas — makers won't provide a product or service at a negative cost. Yet this could have happened only in Texas, which (not surprisingly) has carved out a unique approach to electricity. Consider these three unique factors about Texas. First, Texas is an electricity island. The state often behaves as if it were its own sovereign nation, and indeed it was an independent republic for nearly 10 years. Alone among the 48 continental states, Texas runs an electricity grid that does not connect with those that serve other states. The grid is run by Electric Reliability Council of Texas, or Ercot. By contrast, most states are part of larger regional bodies like PJM (which covers 13 states in the Midwest and Middle Atlantic) or MISO, which oversees the grid in a big chunk of the middle of the country. Being an island has given Texas has greater control over its electricity market: Texas won't suffer blackouts if there are problems in Oklahoma or Louisiana. Texas is an electricity island. Bouchecl via Wikimedia Commons But it also means electricity produced in the state has to be consumed in the state at the moment it is produced — it can't be shipped elsewhere, where others might need it. Second, Texas has way more wind power than any other state. In 2014, wind accounted for 4.4% of electricity produced in the US. Texas, which has more installed wind capacity (15,635 megawatts) than any other state and is home to nearly 10,000 turbines, got 9% of its electricity from wind in 2014. But that understates the influence of wind. Demand for electricity varies a great deal over the course of the day — it rises as people wake up, turn on the lights, and go to work; peaks in the late of afternoon; and then falls off sharply at night. The supply of wind can change a lot, too, depending on how much the wind is blowing. So in the middle of the night, if the wind is strong, wind power can dominate. On March 29 at 2:12 a.m., for example, wind accounted for about 40% of the state's electricity production. There's another nice feature about wind. Unlike natural gas or coal, there is no fuel cost. Once a turbine is up and running, the wind is free. Third, Texas has a unique market structure. It's complicated, but Ercot has set up the grid in such a way that it acquires a large amount of power through continuous auctions. Every five minutes, power generators in the state electronically bid into Ercot's real-time market, offering to provide chunks of energy at particular prices. Pismo via Wikimedia Commons Ercot fills the open needs by selecting the bids that are cheapest and that make the most sense from a grid-management perspective — i.e., the power is being fed into the grid at points where the distribution and transmission systems can handle it. Every 15 minutes, the bids settle — at the highest price paid for electricity accepted in the round. So if 100 MW of electricity are needed, and some producers offer 60 MW at $50 per megawatt-hour, some offer 30 MW at $80 per megawatt-hour, and others offer 40 MW at $100 per megawatt-hour, all the bidders will receive the highest price of $100. (Note: The price Ercot pays is the wholesale generation charge.) After midnight on Sunday, the combination of these three factors pushed the real-time price of electricity lower. Demand fell — at 4 a.m., the amount of electricity needed in the state was about 45% lower than the evening peak. The wind was blowing consistently — much later in the day Texas would establish a new instantaneous-wind-generation record. At 3 a.m., wind was supplying about 30% of the state's electricity, as this daily wind-integration report shows. And because the state is an electricity island, all the power produced by the state's wind farms could be sold only to Ercot, not grids elsewhere in the country. That gave wind-farm owners a great incentive to lower their prices. The data shows that the clearing price in the real-time market went from $17.40 per megawatt-hour for the interval ending 12:15 a.m., to zero for the interval ending 1:45 a.m. Then it went into negative territory and stayed at zero or less until about 8:15 a.m. For the interval that ended 5:45 a.m., the real-time price of electricity in Texas was minus $8.52 per megawatt-hour. How could this be? I mean, even the most efficient producer couldn't afford to provide electricity free or pay someone to take it. Well, there's one more wrinkle. Typically, wind is bid at the lowest prices — because you don't need fuel, it doesn't really cost that much money to keep wind turbines moving once they have been built. But wind operators have another advantage over generators that use coal or natural gas: A federal production tax credit of 2.3 cents per kilowatt-hour that applies to every kilowatt of power produced. And that means that even if wind operators give the power away or offer the system money to take it, they still receive a tax credit equal to $23 per megawatt-hour. Those tax credits have a monetary value — either to the wind-farm owner or to a third party that might want to buy them. As a result, in periods of slack overall demand and high wind production, it makes all the economic sense in the world for wind-farm owners to offer to sell lots of power into the system at negative prices.
#ifndef CYFRE_TRANSPOSE_CPP #define CYFRE_TRANSPOSE_CPP #include <iostream> #include "../classes/matrix_class.hpp" namespace cyfre { /// transpose self template<class T> void mat<T>::transpose() { #ifdef DISPLAY_FUNC_CALLS auto start = std::chrono::high_resolution_clock::now(); std::cout<<"void transpose()\n"; #endif size_t i,j,k=0; T* rht = new T[width*height]; #ifndef OMPTHREAD for(j=0; j<width; ++j) { for(i=0; i<height; ++i) { rht[k++] = matrix[i*width+j]; } } #else if(height*width<=TRANSPOSE_MT_TREASHOLD) { for(j=0; j<width; ++j) { for(i=0; i<height; ++i) { rht[k++] = matrix[i*width+j]; } } } else { size_t m, o; #pragma omp parallel for num_threads(omp_get_max_threads()) for(size_t n = 0; n<width*height; n++) { m = n/width; o = n%width; rht[n] = matrix[height*o+m]; } } #endif delete [] matrix; matrix = rht; std::swap(height,width); #ifdef DISPLAY_FUNC_CALLS auto finish = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start); std::cout<<"took "<<duration.count()<<" nanoseconds\n\n"; #endif } /// @returns a transposed matrix copy template<typename T> mat<T> transpose(mat<T> input) { input.transpose(); return input; } } #endif
<reponame>COHRINT/pnt-ddf<gh_stars>0 import re from copy import copy import numpy as np from bpdb import set_trace from numpy import sqrt from numpy.linalg import cholesky, inv, norm from scipy.linalg import block_diag from scipy.optimize import least_squares from scipy.spatial.distance import mahalanobis from scipy.special import erf from scipy.stats import multivariate_normal from pntddf.covariance_intersection import covariance_intersection from pntddf.information import Information, invert from pntddf.state_log import State_Log np.set_printoptions(suppress=True) def unit(x): return x / np.linalg.norm(x) class LSQ_Filter: def __init__(self, env, agent): self.env = env self.agent = agent self.measurements = [] self.local_measurements_for_retransmission = [] self.completed = False self.broadcast_time = self.env.NUM_AGENTS * self.env.TRANSMISSION_WINDOW * 1 self.giveup_time = 60 def estimate(self, measurement): self.add_measurement(measurement) self.add_local_measurement(measurement) measurements = self.measurements if self.completed and self.agent.clock.time() > self.broadcast_time: return True elif self.completed: return False elif self.agent.clock.time() > self.giveup_time: self.x = np.array(self.env.x0) self.P = self.env.P0 self.completed = True return True duplex_pairs = set(self.env.PAIRS_DUPLEX) measurement_pairs = set( [ meas.receiver.name + meas.transmitter.name for meas in measurements if "rho" in meas.name ] ) all_measurement_pairs = len(duplex_pairs - measurement_pairs) == 0 if all_measurement_pairs and self.agent.clock.time() > self.broadcast_time: lower_bounds = np.array( [ -1e-6 if re.match(r"[xyz]_dot", str(state)) else -np.inf for state in self.env.dynamics.x_vec ] ) upper_bounds = np.array( [ 1e-6 if re.match(r"[xyz]_dot", str(state)) else np.inf for state in self.env.dynamics.x_vec ] ) bounds = (lower_bounds, upper_bounds) finished = False while not finished: x0 = np.random.multivariate_normal(self.env.x0, self.env.P0) x0 = np.array( [ max(l, min(u, x)) for l, u, x in zip(lower_bounds, upper_bounds, x0) ] ) lsq_result = least_squares(self.lsq_func, x0, bounds=bounds) y = self.lsq_func(lsq_result.x) J = (y ** 2).sum() R = np.diag([meas.sigma_adjusted for meas in measurements]) fudge_factor = 10 if J > (y @ inv(R) @ y) * fudge_factor: continue else: finished = True if lsq_result.success: self.completed = True x = lsq_result.x H = lsq_result.jac R = np.diag([meas.sigma_adjusted for meas in measurements]) P = inv(H.T @ inv(R) @ H) time_delta = self.env.TRANSMISSION_WINDOW * self.env.NUM_AGENTS Q = self.agent.estimator.filt.generate_Q(time_delta, np.array([0])) self.x = x self.P = P + Q # not necessary, but speeds up the process if one agent shares a decent initial estimate if not self.agent.name == "Z": self.agent.radio.transmit_estimate(x, P + Q) def lsq_func(self, x): measurements = self.measurements residuals = [] for measurement in measurements: tau = self.get_tau(measurement, x) x_back_prediction = self.env.dynamics.step_x(x, tau, 0) r = measurement.z - measurement.predict(x_back_prediction) if "rho" in measurement.name: T_name = measurement.transmitter.name sigma_process_T = self.env.agent_configs[T_name].getfloat( "sigma_clock_process" ) R_name = measurement.receiver.name sigma_process_R = self.env.agent_configs[R_name].getfloat( "sigma_clock_process" ) sigma_s_T = abs( 1 / 3 * sigma_process_T ** 2 * tau ** 3 * self.env.c ** 2 ) sigma_s_R = abs( 1 / 3 * sigma_process_R ** 2 * tau ** 3 * self.env.c ** 2 ) sigma = np.sqrt(measurement.sigma ** 2 + sigma_s_T + sigma_s_R) else: sigma = measurement.sigma measurement.sigma_adjusted = sigma residuals.append(r / sigma) return np.array(residuals) def get_tau(self, measurement, x): t = self.agent.clock.time() if measurement.local: tau = measurement.timestamp_receive - t else: R = measurement.receiver.name Delta_R, _ = self.agent.estimator.filt.get_clock_estimate(R, x) P = self.agent.name Delta_P, _ = self.agent.estimator.filt.get_clock_estimate(P, x) tau = measurement.timestamp_receive - Delta_R + Delta_P - t return tau def add_measurement(self, measurement): measurement_names = [meas.name for meas in self.measurements] if measurement.name in measurement_names: # only have most recent measurement of each type meas_index = measurement_names.index(measurement.name) del self.measurements[meas_index] self.measurements.append(copy(measurement)) def add_local_measurement(self, measurement): if measurement.local: measurement.local = False measurement.explicit = True self.local_measurements_for_retransmission.append(measurement) def get_local_measurements_for_retransmission(self): local_measurements = copy(self.local_measurements_for_retransmission) self.local_measurements_for_retransmission = [] return local_measurements class Unscented_Kalman_Filter: def __init__(self, env, agent): self.env = env self.agent = agent self.t_k = 0 self.t_kp1 = 0 # tracking how far we've added process noise self.t_Q = 0 self.clock_estimate_dict = self.env.dynamics.get_clock_estimate_function() self.state_log = State_Log(env, agent) self.define_initial_state() self.define_event_triggering_measurements() self.define_constants() def define_initial_state(self, x=np.array([]), P=np.array([])): if x.size == 0: self.x = self.env.x0.copy() else: self.x = x if P.size == 0: self.P = self.env.P0.copy() else: self.P = P def define_event_triggering_measurements(self): self.event_triggering_messages = [] def define_constants(self): self.Q_sigma_clock = self.env.filter_config.getfloat("Q_sigma_clock") self.Q_sigma_target = self.env.filter_config.getfloat("Q_sigma_target") alpha = self.env.filter_config.getfloat("alpha") beta = self.env.filter_config.getfloat("beta") N = self.env.NUM_STATES kappa = 6 - N lamb = alpha ** 2 * (N + kappa) - N self.w_m = [lamb / (N + lamb)] + [1 / (2 * (N + lamb))] * 2 * N self.w_c = [lamb / (N + lamb) + (1 - alpha ** 2 + beta)] + [ 1 / (2 * (N + lamb)) ] * 2 * N self.N = N self.lamb = lamb def predict_self(self): x_hat = self.x.copy() P = self.P.copy() tau = self.get_tau() t_estimate = self.get_time_estimate() x_prediction = self.env.dynamics.step_x(x_hat, tau, t_estimate) P_prediction = self.env.dynamics.step_P(P, tau) tau_Q = self.get_tau_Q() u = self.env.dynamics.u(t_estimate) Q = self.generate_Q(time_delta=tau_Q, u=u) P_prediction += Q self.x = x_prediction self.P = P_prediction def predict_info(self, info): pass def generate_Q(self, time_delta, u): Q_clock = block_diag( *[ np.array( [ [1 / 3 * time_delta ** 3, 1 / 2 * time_delta ** 2], [1 / 2 * time_delta ** 2, 1 / 1 * time_delta ** 1], ] ) * self.Q_sigma_clock ** 2 * self.env.c ** 2 for agent_name in self.env.agent_clocks_to_be_estimated ] ) Q_target_scale = self.Q_sigma_target ** 2 Q_target = block_diag( *[ np.block( [ [ np.eye(self.env.n_dim) * 1 / 3 * time_delta ** 3, np.eye(self.env.n_dim) * 1 / 2 * time_delta ** 2, ], [ np.eye(self.env.n_dim) * 1 / 2 * time_delta ** 2, np.eye(self.env.n_dim) * 1 / 1 * time_delta ** 1, ], ] ) * Q_target_scale for rover_name in self.env.ROVER_NAMES ] ) if Q_clock.size > 0 and Q_target.size > 0: Q = block_diag(Q_clock, Q_target) elif Q_target.size > 0: Q = Q_target else: Q = Q_clock return Q def generate_sigma_points(self, x, P): sigma_points = [ x, *np.split( np.ravel(x + cholesky((self.N + self.lamb) * P).T), self.N, ), *np.split( np.ravel(x - cholesky((self.N + self.lamb) * P).T), self.N, ), ] return sigma_points def local_update(self, measurement): x_prediction = self.x.copy() P_prediction = self.P.copy() chi = self.generate_sigma_points(x_prediction, P_prediction) upsilon = [measurement.predict(chi_i) for chi_i in chi] y_prediction = sum([w * upsilon_i for w, upsilon_i in zip(self.w_m, upsilon)]) P_xy = sum( [ w * (chi_i - x_prediction)[np.newaxis].T @ (upsilon_i - y_prediction)[np.newaxis] for w, chi_i, upsilon_i in zip(self.w_c, chi, upsilon) ] ) R = measurement.R P_yy = ( sum( [ w * (upsilon_i - y_prediction)[np.newaxis].T @ (upsilon_i - y_prediction)[np.newaxis] for w, upsilon_i in zip(self.w_c, upsilon) ] ) + R ) if measurement.implicit: phi = lambda z: (1 / np.sqrt(2 * np.pi)) * np.exp(-0.5 * (z ** 2)) Qfxn = lambda x: 1 - 0.5 * (1 + erf(x / np.sqrt(2))) Q_e = P_yy nu_minus = -self.env.delta / np.sqrt(Q_e) nu_plus = self.env.delta / np.sqrt(Q_e) z_bar = ( (phi(nu_minus) - phi(nu_plus)) / (Qfxn(nu_minus) - Qfxn(nu_plus)) * np.sqrt(Q_e) ) var_theta = ( (phi(nu_minus) - phi(nu_plus)) / (Qfxn(nu_minus) - Qfxn(nu_plus)) ) ** 2 - ( ((nu_minus) * phi(nu_minus) - nu_plus * phi(nu_plus)) / (Qfxn(nu_minus) - Qfxn(nu_plus)) ) K = np.array(P_xy / P_yy, ndmin=2) measurement.r = z_bar # just for plotting residuals measurement.t = self.agent.clock.magic_time() measurement.P_yy_sigma = np.sqrt(P_yy) x_hat = (x_prediction + K * z_bar).ravel() P_hat = P_prediction - var_theta * P_yy * (K.T @ K) assert 0 <= var_theta <= 1 else: y = measurement.z K = np.array(P_xy / P_yy, ndmin=2) r = y - y_prediction measurement.r = r # just for plotting residuals measurement.t = self.agent.clock.magic_time() measurement.P_yy_sigma = np.sqrt(P_yy) x_hat = (x_prediction + K * r).ravel() P_hat = P_prediction - P_yy * (K.T @ K) if measurement.local and self.env.et: meas = copy(measurement) meas.local = False if np.abs(r) > self.env.delta: meas.explicit = True meas.implicit = False else: meas.explicit = False meas.implicit = True self.event_triggering_messages.append(meas) self.x = x_hat self.P = P_hat def log(self, measurement): if measurement.local: self.state_log.log_state() self.state_log.log_u() def step(self): self.update_t() def set_time_from_measurement(self, measurement): if self.agent.name == "Z": self.t_kp1 = self.agent.clock.magic_time() elif measurement.local: self.t_kp1 = measurement.timestamp_receive else: Delta_R, _ = self.get_clock_estimate(measurement.receiver.name) Delta_P, _ = self.get_clock_estimate(self.agent.name) self.t_kp1 = measurement.timestamp_receive - Delta_R + Delta_P self.t_Q_prev = self.t_Q self.t_Q = max(self.t_Q, self.t_kp1) def update_t(self): self.t_k = self.t_kp1 def get_tau(self): tau = self.t_kp1 - self.t_k return tau def get_tau_Q(self): tau_Q = self.t_Q - self.t_Q_prev return tau_Q def get_local_info(self): Y = inv(self.P) y = Y @ self.x local_info = Information(y, Y) return local_info def get_event_triggering_measurements(self): et_messages = copy(self.event_triggering_messages) self.event_triggering_messages = [] return et_messages def get_rover_state_estimate(self): x = self.x.copy() x_rover = self.env.dynamics.get_rover_state_estimate(self.agent.name, x) return x_rover def get_clock_estimate(self, agent_name="", x=np.array([])): if x.size == 0: x = self.x.copy() if not agent_name: agent_name = self.agent.name Delta, Delta_dot = self.env.dynamics.Delta_functions[agent_name](*x) return Delta, Delta_dot def get_time_estimate(self, x=np.array([])): if x.size == 0: x = self.x.copy() Delta, _ = self.env.dynamics.Delta_functions[self.agent.name](*x) t_estimate = self.t_kp1 - Delta return t_estimate
<reponame>ericmillin/client // Copyright © 2019 The Knative Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package revision import ( "errors" "fmt" "strings" "time" "github.com/spf13/cobra" "knative.dev/client/pkg/kn/commands" v1 "knative.dev/client/pkg/serving/v1" servingv1 "knative.dev/serving/pkg/apis/serving/v1" ) // NewRevisionDeleteCommand represent 'revision delete' command func NewRevisionDeleteCommand(p *commands.KnParams) *cobra.Command { var waitFlags commands.WaitFlags // prune filter, used with "-p" var pruneFilter string var pruneAll bool RevisionDeleteCommand := &cobra.Command{ Use: "delete NAME [NAME ...]", Short: "Delete revisions", Example: ` # Delete a revision 'svc1-abcde' in default namespace kn revision delete svc1-abcde # Delete all unreferenced revisions kn revision delete --prune-all # Delete all unreferenced revisions for a given service 'mysvc' kn revision delete --prune mysvc`, RunE: func(cmd *cobra.Command, args []string) error { prune := cmd.Flags().Changed("prune") argsLen := len(args) if argsLen < 1 && !pruneAll && !prune { return errors.New("'kn revision delete' requires one or more revision name") } if argsLen > 0 && pruneAll { return errors.New("'kn revision delete' with --prune-all flag requires no arguments") } namespace, err := p.GetNamespace(cmd) if err != nil { return err } client, err := p.NewServingClient(namespace) if err != nil { return err } // Create list filters var params []v1.ListConfig if prune { params = append(params, v1.WithService(pruneFilter)) } if prune || pruneAll { args, err = getUnreferencedRevisionNames(params, client) if err != nil { return err } if len(args) == 0 { fmt.Fprintf(cmd.OutOrStdout(), "No unreferenced revisions found.\n") return nil } } errs := []string{} for _, name := range args { timeout := time.Duration(0) if waitFlags.Wait { timeout = time.Duration(waitFlags.TimeoutInSeconds) * time.Second } err = client.DeleteRevision(name, timeout) if err != nil { errs = append(errs, err.Error()) } else { fmt.Fprintf(cmd.OutOrStdout(), "Revision '%s' deleted in namespace '%s'.\n", name, namespace) } } if len(errs) > 0 { return errors.New("Error: " + strings.Join(errs, "\nError: ")) } return nil }, } flags := RevisionDeleteCommand.Flags() flags.StringVar(&pruneFilter, "prune", "", "Remove unreferenced revisions for a given service in a namespace.") flags.BoolVar(&pruneAll, "prune-all", false, "Remove all unreferenced revisions in a namespace.") commands.AddNamespaceFlags(RevisionDeleteCommand.Flags(), false) waitFlags.AddConditionWaitFlags(RevisionDeleteCommand, commands.WaitDefaultTimeout, "delete", "revision", "deleted") return RevisionDeleteCommand } // Return unreferenced revision names func getUnreferencedRevisionNames(lConfig []v1.ListConfig, client v1.KnServingClient) ([]string, error) { revisionList, err := client.ListRevisions(lConfig...) if err != nil { return []string{}, err } // Sort revisions by namespace, service, generation (in this order) sortRevisions(revisionList) revisionNames := []string{} for _, revision := range revisionList.Items { if revision.GetRoutingState() != servingv1.RoutingStateActive { revisionNames = append(revisionNames, revision.Name) } } return revisionNames, nil }
#ifndef vtkTestingColors_h #define vtkTestingColors_h // Standard colors used by many vtk scripts static float vtk_antique_white[3] = { 0.9804, 0.9216, 0.8431 }; static float vtk_azure[3] = { 0.9412, 1.0000, 1.0000 }; static float vtk_bisque[3] = { 1.0000, 0.8941, 0.7686 }; static float vtk_blanched_almond[3] = { 1.0000, 0.9216, 0.8039 }; static float vtk_cornsilk[3] = { 1.0000, 0.9725, 0.8627 }; static float vtk_eggshell[3] = { 0.9900, 0.9000, 0.7900 }; static float vtk_floral_white[3] = { 1.0000, 0.9804, 0.9412 }; static float vtk_gainsboro[3] = { 0.8627, 0.8627, 0.8627 }; static float vtk_ghost_white[3] = { 0.9725, 0.9725, 1.0000 }; static float vtk_honeydew[3] = { 0.9412, 1.0000, 0.9412 }; static float vtk_ivory[3] = { 1.0000, 1.0000, 0.9412 }; static float vtk_lavender[3] = { 0.9020, 0.9020, 0.9804 }; static float vtk_lavender_blush[3] = { 1.0000, 0.9412, 0.9608 }; static float vtk_lemon_chiffon[3] = { 1.0000, 0.9804, 0.8039 }; static float vtk_linen[3] = { 0.9804, 0.9412, 0.9020 }; static float vtk_mint_cream[3] = { 0.9608, 1.0000, 0.9804 }; static float vtk_misty_rose[3] = { 1.0000, 0.8941, 0.8824 }; static float vtk_moccasin[3] = { 1.0000, 0.8941, 0.7098 }; static float vtk_navajo_white[3] = { 1.0000, 0.8706, 0.6784 }; static float vtk_old_lace[3] = { 0.9922, 0.9608, 0.9020 }; static float vtk_papaya_whip[3] = { 1.0000, 0.9373, 0.8353 }; static float vtk_peach_puff[3] = { 1.0000, 0.8549, 0.7255 }; static float vtk_seashell[3] = { 1.0000, 0.9608, 0.9333 }; static float vtk_snow[3] = { 1.0000, 0.9804, 0.9804 }; static float vtk_thistle[3] = { 0.8471, 0.7490, 0.8471 }; static float vtk_titanium_white[3] = { 0.9900, 1.0000, 0.9400 }; static float vtk_wheat[3] = { 0.9608, 0.8706, 0.7020 }; static float vtk_white[3] = { 1.0000, 1.0000, 1.0000 }; static float vtk_white_smoke[3] = { 0.9608, 0.9608, 0.9608 }; static float vtk_zinc_white[3] = { 0.9900, 0.9700, 1.0000 }; // Greys static float vtk_cold_grey[3] = { 0.5000, 0.5400, 0.5300 }; static float vtk_dim_grey[3] = { 0.4118, 0.4118, 0.4118 }; static float vtk_grey[3] = { 0.7529, 0.7529, 0.7529 }; static float vtk_light_grey[3] = { 0.8275, 0.8275, 0.8275 }; static float vtk_slate_grey[3] = { 0.4392, 0.5020, 0.5647 }; static float vtk_slate_grey_dark[3] = { 0.1843, 0.3098, 0.3098 }; static float vtk_slate_grey_light[3] = { 0.4667, 0.5333, 0.6000 }; static float vtk_warm_grey[3] = { 0.5000, 0.5000, 0.4100 }; // Blacks static float vtk_black[3] = { 0.0000, 0.0000, 0.0000 }; static float vtk_ivory_black[3] = { 0.1600, 0.1400, 0.1300 }; static float vtk_lamp_black[3] = { 0.1800, 0.2800, 0.2300 }; // Reds static float vtk_alizarin_crimson[3] = { 0.8900, 0.1500, 0.2100 }; static float vtk_brick[3] = { 0.6100, 0.4000, 0.1200 }; static float vtk_cadmium_red_deep[3] = { 0.8900, 0.0900, 0.0500 }; static float vtk_coral[3] = { 1.0000, 0.4980, 0.3137 }; static float vtk_coral_light[3] = { 0.9412, 0.5020, 0.5020 }; static float vtk_deep_pink[3] = { 1.0000, 0.0784, 0.5765 }; static float vtk_english_red[3] = { 0.8300, 0.2400, 0.1000 }; static float vtk_firebrick[3] = { 0.6980, 0.1333, 0.1333 }; static float vtk_geranium_lake[3] = { 0.8900, 0.0700, 0.1900 }; static float vtk_hot_pink[3] = { 1.0000, 0.4118, 0.7059 }; static float vtk_indian_red[3] = { 0.6900, 0.0900, 0.1200 }; static float vtk_light_salmon[3] = { 1.0000, 0.6275, 0.4784 }; static float vtk_madder_lake_deep[3] = { 0.8900, 0.1800, 0.1900 }; static float vtk_maroon[3] = { 0.6902, 0.1882, 0.3765 }; static float vtk_pink[3] = { 1.0000, 0.7529, 0.7961 }; static float vtk_pink_light[3] = { 1.0000, 0.7137, 0.7569 }; static float vtk_raspberry[3] = { 0.5300, 0.1500, 0.3400 }; static float vtk_red[3] = { 1.0000, 0.0000, 0.0000 }; static float vtk_rose_madder[3] = { 0.8900, 0.2100, 0.2200 }; static float vtk_salmon[3] = { 0.9804, 0.5020, 0.4471 }; static float vtk_tomato[3] = { 1.0000, 0.3882, 0.2784 }; static float vtk_venetian_red[3] = { 0.8300, 0.1000, 0.1200 }; // Browns static float vtk_beige[3] = { 0.6400, 0.5800, 0.5000 }; static float vtk_brown[3] = { 0.5000, 0.1647, 0.1647 }; static float vtk_brown_madder[3] = { 0.8600, 0.1600, 0.1600 }; static float vtk_brown_ochre[3] = { 0.5300, 0.2600, 0.1200 }; static float vtk_burlywood[3] = { 0.8706, 0.7216, 0.5294 }; static float vtk_burnt_sienna[3] = { 0.5400, 0.2100, 0.0600 }; static float vtk_burnt_umber[3] = { 0.5400, 0.2000, 0.1400 }; static float vtk_chocolate[3] = { 0.8235, 0.4118, 0.1176 }; static float vtk_deep_ochre[3] = { 0.4500, 0.2400, 0.1000 }; static float vtk_flesh[3] = { 1.0000, 0.4900, 0.2500 }; static float vtk_flesh_ochre[3] = { 1.0000, 0.3400, 0.1300 }; static float vtk_gold_ochre[3] = { 0.7800, 0.4700, 0.1500 }; static float vtk_greenish_umber[3] = { 1.0000, 0.2400, 0.0500 }; static float vtk_khaki[3] = { 0.9412, 0.9020, 0.5490 }; static float vtk_khaki_dark[3] = { 0.7412, 0.7176, 0.4196 }; static float vtk_light_beige[3] = { 0.9608, 0.9608, 0.8627 }; static float vtk_peru[3] = { 0.8039, 0.5216, 0.2471 }; static float vtk_rosy_brown[3] = { 0.7373, 0.5608, 0.5608 }; static float vtk_raw_sienna[3] = { 0.7800, 0.3800, 0.0800 }; static float vtk_raw_umber[3] = { 0.4500, 0.2900, 0.0700 }; static float vtk_sepia[3] = { 0.3700, 0.1500, 0.0700 }; static float vtk_sienna[3] = { 0.6275, 0.3216, 0.1765 }; static float vtk_saddle_brown[3] = { 0.5451, 0.2706, 0.0745 }; static float vtk_sandy_brown[3] = { 0.9569, 0.6431, 0.3765 }; static float vtk_tan[3] = { 0.8235, 0.7059, 0.5490 }; static float vtk_van_dyke_brown[3] = { 0.3700, 0.1500, 0.0200 }; // Oranges static float vtk_cadmium_orange[3] = { 1.0000, 0.3800, 0.0100 }; static float vtk_cadmium_red_light[3] = { 1.0000, 0.0100, 0.0500 }; static float vtk_carrot[3] = { 0.9300, 0.5700, 0.1300 }; static float vtk_dark_orange[3] = { 1.0000, 0.5490, 0.0000 }; static float vtk_mars_orange[3] = { 0.5900, 0.2700, 0.0800 }; static float vtk_mars_yellow[3] = { 0.8900, 0.4400, 0.1000 }; static float vtk_orange[3] = { 1.0000, 0.5000, 0.0000 }; static float vtk_orange_red[3] = { 1.0000, 0.2706, 0.0000 }; static float vtk_yellow_ochre[3] = { 0.8900, 0.5100, 0.0900 }; // Yellows static float vtk_aureoline_yellow[3] = { 1.0000, 0.6600, 0.1400 }; static float vtk_banana[3] = { 0.8900, 0.8100, 0.3400 }; static float vtk_cadmium_lemon[3] = { 1.0000, 0.8900, 0.0100 }; static float vtk_cadmium_yellow[3] = { 1.0000, 0.6000, 0.0700 }; static float vtk_cadmium_yellow_light[3] = { 1.0000, 0.6900, 0.0600 }; static float vtk_gold[3] = { 1.0000, 0.8431, 0.0000 }; static float vtk_goldenrod[3] = { 0.8549, 0.6471, 0.1255 }; static float vtk_goldenrod_dark[3] = { 0.7216, 0.5255, 0.0431 }; static float vtk_goldenrod_light[3] = { 0.9804, 0.9804, 0.8235 }; static float vtk_goldenrod_pale[3] = { 0.9333, 0.9098, 0.6667 }; static float vtk_light_goldenrod[3] = { 0.9333, 0.8667, 0.5098 }; static float vtk_melon[3] = { 0.8900, 0.6600, 0.4100 }; static float vtk_naples_yellow_deep[3] = { 1.0000, 0.6600, 0.0700 }; static float vtk_yellow[3] = { 1.0000, 1.0000, 0.0000 }; static float vtk_yellow_light[3] = { 1.0000, 1.0000, 0.8784 }; // Greens static float vtk_chartreuse[3] = { 0.4980, 1.0000, 0.0000 }; static float vtk_chrome_oxide_green[3] = { 0.4000, 0.5000, 0.0800 }; static float vtk_cinnabar_green[3] = { 0.3800, 0.7000, 0.1600 }; static float vtk_cobalt_green[3] = { 0.2400, 0.5700, 0.2500 }; static float vtk_emerald_green[3] = { 0.0000, 0.7900, 0.3400 }; static float vtk_forest_green[3] = { 0.1333, 0.5451, 0.1333 }; static float vtk_green[3] = { 0.0000, 1.0000, 0.0000 }; static float vtk_green_dark[3] = { 0.0000, 0.3922, 0.0000 }; static float vtk_green_pale[3] = { 0.5961, 0.9843, 0.5961 }; static float vtk_green_yellow[3] = { 0.6784, 1.0000, 0.1843 }; static float vtk_lawn_green[3] = { 0.4863, 0.9882, 0.0000 }; static float vtk_lime_green[3] = { 0.1961, 0.8039, 0.1961 }; static float vtk_mint[3] = { 0.7400, 0.9900, 0.7900 }; static float vtk_olive[3] = { 0.2300, 0.3700, 0.1700 }; static float vtk_olive_drab[3] = { 0.4196, 0.5569, 0.1373 }; static float vtk_olive_green_dark[3] = { 0.3333, 0.4196, 0.1843 }; static float vtk_permanent_green[3] = { 0.0400, 0.7900, 0.1700 }; static float vtk_sap_green[3] = { 0.1900, 0.5000, 0.0800 }; static float vtk_sea_green[3] = { 0.1804, 0.5451, 0.3412 }; static float vtk_sea_green_dark[3] = { 0.5608, 0.7373, 0.5608 }; static float vtk_sea_green_medium[3] = { 0.2353, 0.7020, 0.4431 }; static float vtk_sea_green_light[3] = { 0.1255, 0.6980, 0.6667 }; static float vtk_spring_green[3] = { 0.0000, 1.0000, 0.4980 }; static float vtk_spring_green_medium[3] = { 0.0000, 0.9804, 0.6039 }; static float vtk_terre_verte[3] = { 0.2200, 0.3700, 0.0600 }; static float vtk_viridian_light[3] = { 0.4300, 1.0000, 0.4400 }; static float vtk_yellow_green[3] = { 0.6039, 0.8039, 0.1961 }; // Cyans static float vtk_aquamarine[3] = { 0.4980, 1.0000, 0.8314 }; static float vtk_aquamarine_medium[3] = { 0.4000, 0.8039, 0.6667 }; static float vtk_cyan[3] = { 0.0000, 1.0000, 1.0000 }; static float vtk_cyan_white[3] = { 0.8784, 1.0000, 1.0000 }; static float vtk_turquoise[3] = { 0.2510, 0.8784, 0.8157 }; static float vtk_turquoise_dark[3] = { 0.0000, 0.8078, 0.8196 }; static float vtk_turquoise_medium[3] = { 0.2824, 0.8196, 0.8000 }; static float vtk_turquoise_pale[3] = { 0.6863, 0.9333, 0.9333 }; // Blues static float vtk_alice_blue[3] = { 0.9412, 0.9725, 1.0000 }; static float vtk_blue[3] = { 0.0000, 0.0000, 1.0000 }; static float vtk_blue_light[3] = { 0.6784, 0.8471, 0.9020 }; static float vtk_blue_medium[3] = { 0.0000, 0.0000, 0.8039 }; static float vtk_cadet[3] = { 0.3725, 0.6196, 0.6275 }; static float vtk_cobalt[3] = { 0.2400, 0.3500, 0.6700 }; static float vtk_cornflower[3] = { 0.3922, 0.5843, 0.9294 }; static float vtk_cerulean[3] = { 0.0200, 0.7200, 0.8000 }; static float vtk_dodger_blue[3] = { 0.1176, 0.5647, 1.0000 }; static float vtk_indigo[3] = { 0.0300, 0.1800, 0.3300 }; static float vtk_manganese_blue[3] = { 0.0100, 0.6600, 0.6200 }; static float vtk_midnight_blue[3] = { 0.0980, 0.0980, 0.4392 }; static float vtk_navy[3] = { 0.0000, 0.0000, 0.5020 }; static float vtk_peacock[3] = { 0.2000, 0.6300, 0.7900 }; static float vtk_powder_blue[3] = { 0.6902, 0.8784, 0.9020 }; static float vtk_royal_blue[3] = { 0.2549, 0.4118, 0.8824 }; static float vtk_slate_blue[3] = { 0.4157, 0.3529, 0.8039 }; static float vtk_slate_blue_dark[3] = { 0.2824, 0.2392, 0.5451 }; static float vtk_slate_blue_light[3] = { 0.5176, 0.4392, 1.0000 }; static float vtk_slate_blue_medium[3] = { 0.4824, 0.4078, 0.9333 }; static float vtk_sky_blue[3] = { 0.5294, 0.8078, 0.9216 }; static float vtk_sky_blue_deep[3] = { 0.0000, 0.7490, 1.0000 }; static float vtk_sky_blue_light[3] = { 0.5294, 0.8078, 0.9804 }; static float vtk_steel_blue[3] = { 0.2745, 0.5098, 0.7059 }; static float vtk_steel_blue_light[3] = { 0.6902, 0.7686, 0.8706 }; static float vtk_turquoise_blue[3] = { 0.0000, 0.7800, 0.5500 }; static float vtk_ultramarine[3] = { 0.0700, 0.0400, 0.5600 }; // Magentas static float vtk_blue_violet[3] = { 0.5412, 0.1686, 0.8863 }; static float vtk_cobalt_violet_deep[3] = { 0.5700, 0.1300, 0.6200 }; static float vtk_magenta[3] = { 1.0000, 0.0000, 1.0000 }; static float vtk_orchid[3] = { 0.8549, 0.4392, 0.8392 }; static float vtk_orchid_dark[3] = { 0.6000, 0.1961, 0.8000 }; static float vtk_orchid_medium[3] = { 0.7294, 0.3333, 0.8275 }; static float vtk_permanent_red_violet[3] = { 0.8600, 0.1500, 0.2700 }; static float vtk_plum[3] = { 0.8667, 0.6275, 0.8667 }; static float vtk_purple[3] = { 0.6275, 0.1255, 0.9412 }; static float vtk_purple_medium[3] = { 0.5765, 0.4392, 0.8588 }; static float vtk_ultramarine_violet[3] = { 0.3600, 0.1400, 0.4300 }; static float vtk_violet[3] = { 0.5600, 0.3700, 0.6000 }; static float vtk_violet_dark[3] = { 0.5804, 0.0000, 0.8275 }; static float vtk_violet_red[3] = { 0.8157, 0.1255, 0.5647 }; static float vtk_violet_red_medium[3] = { 0.7804, 0.0824, 0.5216 }; static float vtk_violet_red_pale[3] = { 0.8588, 0.4392, 0.5765 }; #endif // vtkTestingColors_h
def run_all(directory='.'): results = [] for file in _findfiles(directory): results.append(run_one(file)) return results
<filename>src/components/header.tsx import React from "react"; import { Link } from "gatsby"; import "../styles/components/header.scss"; type HeaderState = { showDropdown: boolean; }; type HeaderProps = { title: string; links: Array<{ name: string; path: string }>; }; class Header extends React.Component<HeaderProps, HeaderState> { constructor(props: HeaderProps) { super(props); this.state = { showDropdown: false }; } render() { return ( <> <div className="header__container"> <button onClick={() => { this.setState((prevState) => { return { showDropdown: !prevState.showDropdown, }; }); }} > <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#000000" > <path style={this.state.showDropdown ? { opacity: 0 } : {}} d="M0 0h24v24H0V0z" fill="none" /> <path style={this.state.showDropdown ? { opacity: 0 } : {}} d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z" /> <path style={this.state.showDropdown ? {} : { opacity: 0 }} d="M0 0h24v24H0V0z" fill="none" /> <path style={this.state.showDropdown ? {} : { opacity: 0 }} d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z" /> </svg> </button> <div className="header__row"> {this.props.links.map((el) => ( <Link key={el.name} to={el.path}> {el.name} </Link> ))} </div> <h1>{this.props.title}</h1> <div></div> </div> <div className="header__col" style={ this.state.showDropdown ? { opacity: 1, pointerEvents: "all" } : {} } > {this.props.links.map((el) => ( <Link key={el.name} style={ this.state.showDropdown ? {} : { transform: "translateY(50%)", } } to={el.path} > {el.name} </Link> ))} </div> </> ); } } export default Header;
<filename>Pro5/src/com/cn/test1.java package com.cn; import java.io.*; public class test1 { /** * @param args */ public static void main(String[] args) { BufferedReader br1 = null; BufferedReader br2 = null; BufferedWriter bw = null; // TODO Auto-generated method stub try { br1 = new BufferedReader(new FileReader("a.txt")); br2 = new BufferedReader(new FileReader("b.txt")); bw = new BufferedWriter(new FileWriter("c.txt")); String s1 = null; String s2 = null; String s3 = null; while((s1 = br1.readLine())!= null) { System.out.println(s1); bw.write(s1); bw.newLine(); if((s2 = br2.readLine())!= null); { System.out.println(s2); bw.write(s2); bw.newLine(); } } while((s3 = br2.readLine())!= null) { System.out.print(s2); bw.write(s3); bw.newLine(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { bw.close(); br1.close(); br2.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
A New Algorithm for Real-time Implementation of Order-statistic Filters In this paper we introduce a new algorithm for implementing Ll-lters which are special nonlin-ear digital lters generalizing and combining L-lters and FIR lters in an optimal way. Although the proposed algorithm requires quite more comparisons than the traditional approach to running ordering algorithms, it will be shown to be very eecient for real-time implementation because it avoids needless arithmetic operations and data shifts. Having presented the underlying idea of the algorithm, we give an example for the implementation on a speciic digital signal processor. Further we compare computational cost and memory requirements necessary for these types of lters.
// The util message of basic DPOP. // For each *valid* value combination of the boundary variables it stores the // utility value associated to such value combination and the the best value // combination of its private variables. // // @note: // The values are hence retrieved in the value propagation phase, either by a // search or by retrieving the values stored. class UtilMsg : public Message { public: typedef std::unique_ptr<UtilMsg> uptr; typedef std::shared_ptr<UtilMsg> sptr; typedef size_t code_t; typedef int idx_t; public: UtilMsg(); virtual ~UtilMsg(); bool operator==(const UtilMsg& other); virtual UtilMsg* clone(); virtual std::string type() const { return "UTIL"; } virtual void reset() { } virtual std::string dump() const; void setContent(int* utilTable, size_t nbRows) { p_util_table = utilTable; p_util_table_rows = nbRows; } size_t getUtilTableRows() { return p_util_table_rows; } size_t getUtilTableCols() { return p_nb_worlds; } int* getUtilTablePtr() { return p_util_table; } protected: DISALLOW_COPY_AND_ASSIGN(UtilMsg); private: int* p_util_table; size_t p_util_table_rows; size_t p_nb_worlds; }
<reponame>nilye/nib import {Editor, Path, Node, Root} from "../.."; export const NodeStep = { insert( root: Root | Node, path: Path, node: Node ){ let index = path.pop(), parent = Node.get(root, path) as Node parent.nodes.splice(index, 0, node) }, remove( root: Root | Node, path: Path ){ let index = path.pop(), parent = Node.get(root, path) as Node parent.nodes.splice(index, 1) }, set( root: Root | Node, path: Path, properties: object ){ let node = Node.get(root, path) as Node for (let [k,v] of Object.entries(properties)){ if (v == null || !properties.hasOwnProperty(k)){ delete node[k] } else { node[k] = v } } }, split( root: Root | Node, index: number ){ } }
/* a specialized version of the standard ngx_conf_parse() function */ char * ngx_stream_lua_conf_lua_block_parse(ngx_conf_t *cf, ngx_command_t *cmd) { ngx_stream_lua_block_parser_ctx_t ctx; int level = 1; char *rv; u_char *p; size_t len; ngx_str_t *src, *dst; ngx_int_t rc; ngx_uint_t i, start_line; ngx_array_t *saved; enum { parse_block = 0, parse_param } type; if (cf->conf_file->file.fd != NGX_INVALID_FILE) { type = parse_block; } else { type = parse_param; } saved = cf->args; cf->args = ngx_array_create(cf->temp_pool, 4, sizeof(ngx_str_t)); if (cf->args == NULL) { return NGX_CONF_ERROR; } ctx.token_len = 0; start_line = cf->conf_file->line; dd("init start line: %d", (int) start_line); ctx.start_line = start_line; for ( ;; ) { rc = ngx_stream_lua_conf_read_lua_token(cf, &ctx); dd("parser start line: %d", (int) start_line); switch (rc) { case NGX_ERROR: goto done; case FOUND_LEFT_CURLY: ctx.start_line = cf->conf_file->line; if (type == parse_param) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "block directives are not supported " "in -g option"); goto failed; } level++; dd("seen block start: level=%d", (int) level); break; case FOUND_RIGHT_CURLY: level--; dd("seen block done: level=%d", (int) level); if (type != parse_block || level < 0) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"}\": level %d, " "starting at line %ui", level, start_line); goto failed; } if (level == 0) { ngx_stream_lua_assert(cf->handler); src = cf->args->elts; for (len = 0, i = 0; i < cf->args->nelts; i++) { len += src[i].len; } dd("saved nelts: %d", (int) saved->nelts); dd("temp nelts: %d", (int) cf->args->nelts); #if 0 ngx_stream_lua_assert(saved->nelts == 1); #endif dst = ngx_array_push(saved); if (dst == NULL) { return NGX_CONF_ERROR; } dst->len = len; dst->len--; p = ngx_palloc(cf->pool, len); if (p == NULL) { return NGX_CONF_ERROR; } dst->data = p; for (i = 0; i < cf->args->nelts; i++) { p = ngx_copy(p, src[i].data, src[i].len); } p[-1] = '\0'; cf->args = saved; rv = (*cf->handler)(cf, cmd, cf->handler_conf); if (rv == NGX_CONF_OK) { goto done; } if (rv == NGX_CONF_ERROR) { goto failed; } ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, rv); goto failed; } break; case FOUND_LBRACKET_STR: case FOUND_LBRACKET_CMT: case FOUND_RIGHT_LBRACKET: case FOUND_COMMENT_LINE: case FOUND_DOUBLE_QUOTED: case FOUND_SINGLE_QUOTED: break; default: ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unknown return value from the lexer: %i", rc); goto failed; } } failed: rc = NGX_ERROR; done: if (rc == NGX_ERROR) { return NGX_CONF_ERROR; } return NGX_CONF_OK; }
<reponame>cgreencode/Nimbus """ Rename this file to 'secret.py' once all settings are defined """ SECRET_KEY = "..." HOSTNAME = "example.com" DATABASE_URL = "mysql://<user>:<password>@<host>/<database>" AWS_ACCESS_KEY_ID = "12345" AWS_SECRET_ACCESS_KEY = "12345"
#include <stdio.h> #include "optin.h" int main(int argc, char** argv) { int ret, i; optin* o; /* Option variables */ int test = -1; int ival1 = 10; int ival2 = 0; float fval1 = 0.7f; float fval2 = 0.0f; int flagval1 = 0; int flagval2 = 0; char* strval1; char* strval2; int i1 = 0; int i2 = 0; int i3 = 0; ret = -1; o = optin_new(); if (!optin_has_option(o, "help")) { fprintf(stderr, "ERROR: built-in option \"help\" is NOT present\n"); goto done; } optin_add_int(o, "test", "The test number to run", OPTIN_REQUIRED, &test); optin_add_int(o, "ival1", "First integer value", OPTIN_HAS_DEFAULT, &ival1); optin_add_int(o, "ival2", "Second integer value", OPTIN_REQUIRED, &ival2); optin_add_float(o, "fval1", "First float value", OPTIN_HAS_DEFAULT, &fval1); optin_add_float(o, "fval2", "Second float value", OPTIN_REQUIRED, &fval2); optin_add_flag(o, "flagval1", "First flag", OPTIN_REQUIRED, &flagval1); optin_add_flag(o, "flagval2", "Second flag", OPTIN_HAS_DEFAULT, &flagval2); optin_set_shortname(o, "flagval1", 'g'); optin_add_string(o, "strval1", "First string value", OPTIN_HAS_DEFAULT, &strval1); optin_add_string(o, "strval2", "Second string value", OPTIN_REQUIRED, &strval2); optin_add_switch(o, "s1", "s1"); optin_add_switch(o, "s2", "s2"); if (optin_has_option(o, "xyzzy")) { fprintf(stderr, "ERROR: optin_has_option() returned positive for test of non-existent option\n"); goto done; } ret = optin_process(o, &argc, argv); switch(test) { case 1: if (ival2 != 10) { fprintf(stderr, "ival2 is %d and should be 10\n", ival2); ret = -1; break; } if (fval2 - 3.14 > 0.0001) { fprintf(stderr, "fval2 is %f and should be 3.14\n", fval2); ret = -1; break; } if (strcmp(strval2, "this is a string")) { fprintf(stderr, "strval2 is '%s' and should be 'this is a string'\n", strval2); ret = -1; break; } if (flagval1 != 1) { fprintf(stderr, "flagval1 is %d and should be 1\n", flagval1); ret = -1; break; } ret = 0; break; default: fprintf(stderr, "Invalid test number: %d\n", test); ret = -1; break; } done: if (ret != 0) { fprintf(stderr, "TEST FAILED, PRINTING DIAGNOSTIC INFORMATION:\n"); optin_debug_print(o); } optin_destroy(o); return ret; }
// GetListCatalogPrivateEndpointsSortOrderEnumValues Enumerates the set of values for ListCatalogPrivateEndpointsSortOrderEnum func GetListCatalogPrivateEndpointsSortOrderEnumValues() []ListCatalogPrivateEndpointsSortOrderEnum { values := make([]ListCatalogPrivateEndpointsSortOrderEnum, 0) for _, v := range mappingListCatalogPrivateEndpointsSortOrderEnum { values = append(values, v) } return values }
The USACECOM Digital Integrated Lab infrastructure The US Army Communications-Electronics Command (CECOM) Research and Engineering Center (RDEC) has developed at Fort Monmouth, New Jersey an integrated advanced research environment known as the Digital Integrated Laboratory (DIL). The DIL allows users to rapidly create unique integrated laboratory testbed environments by interconnecting government laboratories and testbeds, distant Army Battle Labs, remote field sites, and dispersed contractor testbeds as well as providing access to defense simulation networks and commercial communications networks. The complexity of today's research and development for Army C3IEW systems and the need for more efficient resource utilization has led to the creation of the DIL. The backbone of this integrated research environment and key to its flexibility is the distributed communications infrastructure which links the numerous laboratories and facilities. As the demands for information transport and connectivity of the DIL evolve, so too must the communications infrastructure evolve. To this accommodate evolution the DIL infrastructure has been designed to allow for future communications technologies to be incorporated as they become available and to allow for the smooth integration of these added capabilities with minimal loss of investment.
def aboutToShowContextMenuEvent(self): if len(self._items) > 0: self._popupMenu.clear() itemSelected = self.selectedItems()[0] if id(itemSelected) in self._items: for action in self._items[id(itemSelected)]: self._popupMenu.addAction(action)
def print(*objects, sep=None, end=None): if sep is None: sep = ' ' if end is None: end = '\n' array = map(str, objects) printed = sep.join(array)+end try: if objects[0].__class__ is str: printed = objects[0] except: pass try: PyOutputHelper.print(printed, script=threading.current_thread().script_path) except AttributeError: PyOutputHelper.print(printed, script=None)
class Undirected_Graph_Node: """ Undirected Graph Node object """ def __init__(self, val=0, neighbors=None): self.val = val self.neighbors = neighbors if neighbors is not None else []
/* estimate the cost-saving if object o from IC p is placed in register r */ int cost_savings(struct IC *p,int r,struct obj *o) { int c=p->code; if(o->flags&VKONST){ return 0; } if(o->flags&DREFOBJ) return 4; if(c==SETRETURN&&r==p->z.reg&&!(o->flags&DREFOBJ)) return 3; if(c==GETRETURN&&r==p->q1.reg&&!(o->flags&DREFOBJ)) return 3; return 2; }
Natural Medicines for Psychotic Disorders Abstract Patients with psychotic disorders regularly use natural medicines, although it is unclear whether these are effective and safe. The aim of this study was to provide an overview of evidence for improved outcomes by natural medicines. A systematic literature search was performed through Medline, PsycINFO, CINAHL, and Cochrane until May 2015. In 110 randomized controlled trials, evidence was found for glycine, sarcosine, N-acetylcysteine, some Chinese and ayurvedic herbs, ginkgo biloba, estradiol, and vitamin B6 to improve psychotic symptoms when added to antipsychotics. Ginkgo biloba and vitamin B6 seemed to reduce tardive dyskinesia and akathisia. Results on other compounds were negative or inconclusive. All natural agents, except reserpine, were well tolerated. Most study samples were small, study periods were generally short, and most results need replication. However, there is some evidence for beneficial effects of certain natural medicines. D espite much progress in treatment options in the last century, the pharmacological treatment of psychotic disorders is often unsatisfactory, as expressed in persistent positive, negative, cognitive and affective symptoms, and problems in social functioning (Kane and Correll, 2010). Psychotic symptoms are often only partially resolved (Rummel-Kluge et al., 2010), especially cognitive and negative symptoms (Buckley and Stahl, 2007). Apart from clozapine, second-generation antipsychotics are generally as effective as first-generation antipsychotics for positive symptoms, but the promise of greater efficacy for negative symptoms has not been fulfilled (Leucht et al., 2012). Many patients continue experiencing persistent symptoms and relapses during treatment with antipsychotics, particularly when they fail to adhere to prescribed medications (Van Os and Kapur, 2009). Psychiatric medication adherence is a problem because many patients do not want them or consider them unnecessary (Cooper et al., 2007), or experience undesired adverse effects (Pai and Vella, 2012). For antipsychotics, these adverse effects include weight gain, sexual dysfunction, glycemic and lipid dysfunction, extrapyramidal symptoms (EPS), and sedation (Stahl, 2008). Many patients with psychotic disorders use nonconventional medicines or treatments in the hope of decreasing undesired adverse effects or a more successful recovery (Hazra et al., 2010;Stevinson, 2001). Nonconventional medicine includes therapeutic lifestyle changes and complementary and alternative medicine (CAM) (Hoenders, 2013). Complementary medicine comprises diagnostics, treatments, and prevention strategies based on theories accepted in biomedicine and substantiated by some scientific evidence (two or more randomized controlled trials ), but for various (cultural or practical) reasons are no part of biomedicine (Hoenders et al., 2011). Alternative medicine comprises diagnostics, treatments, and prevention strategies using other than the basic concepts of biomedicine. So far, there is little proof for the efficacy of the latter treatments and/or considerable controversy about their scientific validation (Lake, 2007). Natural medicine is part of complementary medicine, using agents produced by living organisms (plant, tree, seed, vegetable, fruit, animal, and human) instead of nonnatural (i.e., chemical) agents only being obtained from laboratory experiments (Porter, 1998). Some patients prefer natural medicines, assuming that natural is better and will cause fewer adverse effects. This is obviously not (always) true, as the natural environment contains agents that can be toxic to humans. The molecular structure and dosage of a substance rather than its source determine its effect on human health (Topliss et al., 2002). Besides, herbal medicines can cause undesired effects including interactions with prescription medication (Ernst, 2003a(Ernst, , 2003b. Hazra et al. (2010) reported a lifetime and 1-year prevalence rate of CAM use in Canadian psychotic outpatients of 88% and 68%, respectively. A major difficulty these patients encounter is the heterogeneity in treatment options with CAM, ranging from possibly interesting agents to useless, or even dangerous, ones (Ernst, 2003b). For instance, the concomitant use of antipsychotics and Chinese herbs was found to induce significantly improved clinical outcomes compared with antipsychotics only (Rathbone et al., 2007). However, a small but significant number of patients concomitantly treated with Chinese herbs have a greater risk of developing worse outcomes (Zhang et al., 2011b). In recent years, patients' preferences and views have received more attention in making treatment choices (e.g., shared decision making and "patient-centered care" ). The introduction of patient's choice in deciding which antipsychotic to choose has been proposed (Morrison et al., 2012). However, it is difficult for both patients and physicians to make informed decisions in the absence of reliable information on the emerging evidence for CAM or natural medicine. Considering its high usage in psychotic patients, there is an urgent need for readily available scientific information. This article reviews the literature on the efficacy and safety of natural medicines for psychotic disorders. (controlled) trials; b) mechanism studies exploring the effects of natural medicines; c) animal studies; d) affective disorders/other disorders/no disorder/(relapse) prevention; e) conference abstracts; f) book chapters; g) clinical trial registrations; h) comments, addenda, corrigenda, and letters; i) non-English languages (e.g., Chinese, Japanese, Hebrew, German, and Spanish); and (j) duplicate hits that had not been removed systematically. Second, two authors (H.J.R.H. and A.A.B.V.) independently indicated whether papers-based on the abstracts-should (possibly) be included. Consultation followed about dubious cases and in case of discordance. Thereupon, 427 studies remained, of which the full papers on RCTs were retrieved and studied. Of these, another 160 were excluded. A flowchart of the study selection is presented in Figure 1. We found 147 reviews and checked whether RCTs in their reference lists matching our inclusion criteria were included. Eight RCTs with a Jadad score of 3 or higher (see paragraph on risk of bias assessment and Table 2) found through cross-references were added. Eighteen RCTs were excluded because of a Jadad score less than 3. The reviews (not shown in Table 3) will be contrasted to our findings in the Discussion section. Classification of Agents The RCTs included were divided into six groups based on supposed underlying mechanisms of action (Table 3). For a good grasp of the results, we briefly present the working mechanisms of the agents from five groups (not from the group "other substances"). (i) Omega-3 fatty acids. Polyunsaturated fatty acids (PUFAs) are essential for brain functioning (Tsalamanios et al., 2006). They have multiple important biological roles, including membrane functioning, neurotransmission, signal transduction, and eicosanoid synthesis. Research suggests that PUFA level reduction is related to schizophrenia (Berger et al., 2006). Concordant with these findings, omega-3 PUFA may have positive effects in the treatment of schizophrenia (Emsley et al., 2002;Peet, 2008). (ii) Glutamate. Besides dopamine, glutamate is thought to play a role in schizophrenia . On the basis of the hypothesis that the glutamatergic system may be compromised in schizophrenia, the use of N-methyl-D-aspartate (NMDA) receptor modulators may compensate for alterations in the glutamate system (Singh and Singh, 2011). Agents with coagonistic properties to (glutaminergic) NMDA receptors are glycine (full, endogenous agonist), D-serine (full, endogenous agonist), D-cycloserine (partial, exogenous agonist), D-alanine (partial, endogenous agonist), and sarcosine (= methylglycine, acting as a reuptake inhibitor of glycine and source of glycine). The glycine transporter-1 (GlyT-1) plays a pivotal role in maintaining the glycine concentration within synapses at a subsaturating level. Sarcosine is a GlyT-1 inhibitor, meaning that its presence results in increased glycine concentrations. Lower cerebral glycine levels are suggested to be found in patients with schizophrenia. The administration of sarcosine is therefore proposed to relieve symptoms of schizophrenia when added to nonclozapine antipsychotics . Whereas the mechanisms of NAC are now beginning to be understood, NAC is probably exerting benefits beyond being a precursor to the antioxidant glutathione, also modulating glutamatergic, neurotropic, and inflammatory pathways (Dean et al., 2011). (iii) Eastern (Chinese and ayurvedic) herbs. Eastern herbs are provided in the context of treatment with complete systems of medicine that evolved over thousands of years, such as TCM and Ayurveda. These treatments include prescription of herbal compounds, massage, diet, acupuncture, and the regulation of lifestyle (Clifford, 1994;Kaptchuck, 2000). Most clinical studies were performed on acupuncture (beyond the scope of this review) and on herbal compounds. (iv) B vitamins. Nobel laureate Linus Pauling proposed a way of understanding and treating psychiatric disorders by correcting malfunctions in the body's chemistry, calling this approach "orthomolecular psychiatry" (Pauling, 1968). His idea was partly built on studies by Osmond and Hoffer (1962) and Hoffer and Osmond (1964), reporting good results when treating patients with schizophrenia with large doses of vitamins, especially vitamin B3. Hoffer (1971Hoffer ( , 1972 published two more positive results with B vitamins. However, attempts to replicate his findings seem to have failed (Ban and Lehmann, 1975;Wittkopp and Abuzzahab, 1972). The contradicting findings may be explained because vitamine B is suggested to be effective in early psychosis but not in chronic schizophrenia (Hoffer and Osmond, 1964). One of the proposed mechanisms is abnormal one-carbon metabolism due to vitamin deficiencies (Hoffer, 2008). Variable levels of the components of one-carbon metabolism (folic acid and vitamin B12) and consequently altered levels of homocysteine and phospholipid DHA have been reported both in medicated patients and in medication-naive first-episode psychotic patients (Kale et al., 2010). Folate status in patients with schizophrenia correlates inversely with negative symptoms . (v) Antioxidants. Oxygen is essential in life but also generates reactive molecules (so-called free radicals) throughout the body. These free radicals are potentially harmful because they can damage essential molecules such as DNA and the enzymes necessary for proper cell functioning. Antioxidants may capture these reactive free radicals and convert them back to less reactive forms of the molecules (Singh , 2010). Research suggests that oxidative damage (maybe due to defective enzyme systems) may contribute to the course and outcome of schizophrenia (Fendri et al., 2006;Mahadik and Mukherjee, 1996;Mahadik et al., 2001) and is already present in patients with firstepisode psychosis (Flatow et al., 2013). Ascorbic acid (vitamin C), an antioxidant vitamin, plays an important role in protecting free radical-induced damage in the body. It is present in brain tissue and dopamine-dominant areas in higher concentrations compared with other organs (Harrison and May, 2009). Ginkgo biloba, an extract of the leaves of the ginkgo biloba tree, is also suggested to have antioxidant properties (Maclennan et al., 2002), improving brain circulation at the microvascular level (Kuboto et al., 2001;Sun et al., 2003;Yan et al., 2008) and, thus, improving outcome in psychosis. Long-term treatment with antipsychotics is associated with a variety of movement disorders, including tardive dyskinesia (TD). Both dopamine receptor supersensitivity and oxidative stress-induced neurotoxicity in the nigrostriatal system are suggested to be involved in its pathogenesis (Kulkarni and Naidu, 2003). The pineal hormone melatonin is a potent antioxidant and attenuates dopaminergic activity in the striatum and dopamine release from the hypothalamus (Shamir et al., 2001). Thus, treatment with antioxidative agents may have a beneficial effect for both treatment of psychotic symptoms and prevention of TD. Vitamin E has been suggested for TD because it is a lipid-soluble antioxidant that decreases free radical formation (Herrera and Barbas, 2001). Risk of Bias Assessment Two assessors (A.A.B.V. and N.K.V.) independently rated the methodological quality of the eligible RCTs using the Jadad scale (Jadad et al., 1996). Interrater agreement on the Jadad scores before consensus discussion amounted to 0.83. Besides, H.J.R.H. independently rated a random selection of 17 papers (15%) from the selected RCTs. Interrater agreement of all three assessors was 0.71. Any scoring disagreements between the assessors were resolved through consensus discussion between these three authors. The 110 RCTs with a Jadad score of 3 or higher were included in the current review, categorized into six groups (see the Classification of agents section). For each of the 110 studies fulfilling the selection criteria, the following assessments were made: which natural agent was used; was this combined with antipsychotics, and if so, which antipsychotics and what dosage; the effect of the natural agent on negative, positive, cognitive, depressive, and general symptoms and on adverse effects of antipsychotics; possible adverse effects of the natural agent; number of participants in the study; control group characteristics; number of dropouts; study duration; and Jadad score. The results are shown in Table 3. Results In total, 110 RCTs that matched the inclusion criteria were identified. Detailed effects are given in Table 3. Most of the studies were performed in the United States, followed by (in decreasing order) Israel, Canada, Taiwan, China, India, United Kingdom, Australia, Iran, South Africa, Switzerland, the Netherlands, Austria, Ireland, Korea, and Norway. (ii) Glutamate improvement of positive symptoms in one and worsening in another study (from seven) ; and little or no effect on cognitive and depressive symptoms or general psychopathology and no improvement of adverse effects of antipsychotics was shown. Five (from five) studies found no improvement of adverse effects of antipsychotics Duncan et al., 2004;Goff et al., 2005;Heresco-Levy et al., 2002;Van Berckel et al., 1999). No studies were reported on D-cycloserine without antipsychotics. No adverse effects of D-cycloserine were reported. The only study on D-alanine reported positive effects when added to antipsychotics on negative, positive, cognitive, and general symptoms, but no effect on depressive symptoms . No effect on adverse effects of antipsychotics was found. Adverse effects of D-alanine (insomnia and nausea) were reported. All three studies combining sarcosine with antipsychotics (not clozapine) found positive effects in almost all symptom domains Tsai et al., 2004). When combined with clozapine (one study), no treatment effects were found . In addition, when given without antipsychotics (one study), sarcosine did not improve symptoms . Sarcosine did not improve adverse effects of antipsychotics in four (from four) studies Tsai et al., 2004). Adverse effects of sarcosine included weight gain, insomnia, palpitations, dizziness, and sedation. One large study on NAC added to antipsychotics reported improved positive symptoms but no improvement of negative, cognitive, or general symptoms and no improvement of adverse effects of antipsychotics , whereas one small study found some improvement of cognitive symptoms . The large study reported that there were no adverse effects, and in the small study , occurrence of any adverse effect was not mentioned. (iii) Eastern (Chinese and Ayurvedic) Herbs Many studies on Eastern herbs were found, but only six had a Jadad score of three or higher (Chen et al., 2008a(Chen et al., , 2008b(Chen et al., , 2009Mahal et al., 1976;Mundewadi et al., 2008;Naidoo, 1956). One old study on reserpine found "clinical improvement" after 11 weeks compared with placebo in 80 patients not treated with antipsychotics but with electroconvulsice therapy (Naidoo, 1956). Several adverse effects were reported: nasal congestion, periorbital edema, diarrhea, epigastric pain, salivating, pseudo-Parkinsonian state, severe headaches, and deep pains in limbs. Another old study (Mahal et al., 1976) found positive effects of brahmyadiyoga without antipsychotics compared with placebo and equal to chlorpromazin in 136 patients with schizophrenia (Mahal et al., 1976); no adverse effects were reported. Four (from six) more recent studies found significant effects on general psychopathology when adding ayurvedic herbs (reserpine: one study ; bacopa monnieri and nardostachys jatamansi: one study ; a mixture of 13 Chinese herbs: two studies ). However, the Jadad score is not a perfect tool because it does not judge the selection of subjects, the sample size and power, and the quality of the data analyses. Therefore, RCTs with a Jadad score of 3 or higher might still have methodological weaknesses, which hamper drawing firm conclusions. Fourth, some studies (e.g., Bhavani et al., 1962;Greenbaum 1970;Naidoo, 1956) were done in the pre-Diagnostic and Statistical Manual of Mental Disorders, 3rd Edition (DSM-3) era, when standards of care and diagnostics may have been of lower quality than nowadays, which hampers interpretation of their results. Fifth, in most of the studies included, effect sizes were not provided nor was it possible to calculate them, which makes it difficult to compare the results or to estimate the clinical relevance of some of the findings. Sixth, it cannot be ruled out that some of the studies were underpowered, which might have hampered finding a significant effect. Clinical Implications Clinicians need to be aware that patients often use natural medicines without medical prescription, whereas some patients assume that natural is better than chemical and causes fewer adverse effects. Although beneficial effects may occur, this is certainly not always true. Some natural agents that may be suggested for treatment of psychotic disorders are toxic to humans (Topliss et al., 2002), and some herbal medicines can cause adverse effects or interact with medication (Ernst, 2003b). Only 3% of the user population is aware of the potential risks of interactions between herbs and prescription medication (Walter and Rey, 1999). From a medical perspective, it is therefore important to know what patients buy and try. Another concern are the media reports on contamination of Chinese herbs with heavy metals. However, after investigation of 334 samples, Harris et al. (2011) conclude that "the vast majority (95%) of medications in this study contained levels of heavy metals or pesticides that would be of negligible concern." Because of these concerns, patients want their medical doctors to advise them on complementary (or natural) medicines (Gray et al., 1998;Hoenders et al., 2006). The World Health Organization (2013) has repeatedly advised its member states to "formulate national policy and regulation for the proper use of CAM and its integration into national health care systems; establish regulatory mechanisms to control the safety and quality of products and of CAM practice; create awareness about safe and effective CAM therapies among the public and consumers" and "promote therapeutically sound use of appropriate Traditional Medicine by practitioners and consumers." Respecting patients' opinions and informing them may also improve the therapeutic relationship (Stevinson, 2001) and thus enhance treatment outcome (Gill, 2013;Koenig, 2000), which depends on the quality of the therapeutic alliance (Baldwin et al., 2007). This review gives clinicians and patients an overview of the results of RCTs, which fit a minimal level of quality (minimum Jadad score of 3), on the efficacy and safety of natural medicines for psychotic disorders. However, many questions about clinical use (e.g., dosage, safety, interactions, and quality) remain unanswered. ACKNOWLEDGMENTS We thank Truus van Ittersum (University Medical Center Groningen) for expertly performing the literature searches, Sietse Dijk (University Medical Center Groningen) for his assistance in obtaining the papers for this review, Karen van der Ploeg, MSc (Center for Integrative Psychiatry, Lentis) for assisting in the selection procedure, and Edzard Geertsema, PhD (University Medical Center Groningen) for his detailed information about the chemical structure and characteristics of the agents. DISCLOSURE The authors declare no conflict of interest.
// ConvertFunction returns the right GDNative 'As<Type>' function for this param kind as a string func (rmp *registryMethodParam) ConvertFunction() string { conversions := map[string]string{ "bool": "AsBool()", "uint": "AsUint()", "int": "AsInt()", "float64": "AsReal()", "string": "AsString()", "vector2": "AsVector2()", "vector3": "AsVector3()", "rect2": "AsRect2()", "transform2d": "AsTransform2D()", "plane": "AsPlane()", "quat": "AsQuat()", "aabb": "AsAabb()", "basis": "AsBasis()", "transform": "AsTransform()", "color": "AsColor()", "nodepath": "AsNodePath()", "rid": "AsRid()", "object": "AsObject()", "dictionary": "AsDictionary()", "arraytype": "AsArray()", "arraytype_byte": "AsPoolByteArray()", "arraytype_int": "AsPoolIntArray()", "arraytype_float": "AsPoolRealArray()", "arraytype_string": "AsPoolStringArray()", "arraytype_vector2": "AsPoolVector2Array()", "arraytype_vector3": "AsPoolVector3Array()", "arraytype_color": "AsPoolColorArray()", } value, ok := conversions[rmp.kind] if ok { return value } switch rmp.kind { case "float32": value = conversions["float64"] case "int8", "int16", "int32", "int64", "byte": value = conversions["int"] case "uint8", "uint16", "uint32", "uint64": value = conversions["uint"] case "gdnative.Float", "gdnative.Double": value = conversions["float64"] case "gdnative.Int64T", "gdnative.SignedChar": value = conversions["int"] case "gdnative.Uint", "gdnative.Uint8T", "gdnative.Uint32T", "gdnative.Uint64T": value = conversions["uint"] case "gdnative.String", "gdnative.Char", "gdnative.WcharT": value = conversions["string"] default: if strings.HasPrefix(rmp.kind, "gdnative.") { value = rmp.kind } if strings.HasPrefix(rmp.kind, "godot.") || strings.HasPrefix(rmp.kind, "*godot.") { value = conversions["object"] } if strings.Contains(rmp.kind, "ArrayType") { value = conversions[parseArrayType(rmp.kind)] } if strings.Contains(rmp.kind, "MapType") { value = conversions["dictionary"] } } if value == "" { value = conversions["object"] } return value }
/** * * @author Kevin R. Dixon */ public class DefaultWeightedPairTest extends DefaultPairTest { public DefaultWeightedPairTest(String testName) { super(testName); } /** * Test of getWeight method, of class gov.sandia.cognition.util.DefaultWeightedPair. */ public void testGetWeight() { System.out.println("getWeight"); DefaultWeightedPair<Double, Double> instance = new DefaultWeightedPair<Double, Double>(); assertNull(instance.getFirst()); assertNull(instance.getSecond()); assertEquals(0.0, instance.getWeight()); double weight = Math.random(); instance = new DefaultWeightedPair<Double, Double>(Math.random(), Math.random(), weight); assertEquals(weight, instance.getWeight()); } /** * Test of setWeight method, of class gov.sandia.cognition.util.DefaultWeightedPair. */ public void testSetWeight() { System.out.println("setWeight"); double weight = Math.random(); DefaultWeightedPair<Double, Double> instance = new DefaultWeightedPair<Double, Double>(Math.random(), Math.random(), weight); assertEquals(weight, instance.getWeight()); double w2 = weight + 1.0; instance.setWeight(w2); assertEquals(w2, instance.getWeight()); } }
// UnmarshalString parses given string and constructs a Token from it or fails // with an error. func UnmarshalString(s string) (Token, error) { var t Token data, err := unescapeSplit(s, 4) if err != nil { return t, wrap("token", err) } t.rawPayload = []byte(data[0]) t.Email = data[3] payload, err := unescapeSplit(data[0], 4) if err != nil { return t, wrap("payload", err) } t.Provider = payload[0] t.Client = payload[1] t.Scope, err = url.ParseQuery(payload[2]) if err != nil { return t, wrap("payload", "parsing scope failed") } expire, err := strconv.ParseInt(payload[3], 10, 64) if err != nil { return t, wrap("payload", "invalid expire time") } t.ExpireAt = time.Unix(expire, 0) signatures, err := decodeKeys(data[1]) if err != nil { return t, wrap("signatures", err) } t.Signature = signatures[0] t.HMACSignature = signatures[1] keys, err := decodeKeys(data[2]) if err != nil { return t, wrap("keys", err) } t.PublicKey = keys[0] t.HMACSecret = keys[1] return t, nil }
/* processes deferred events and flush wmem */ static void mptcp_release_cb(struct sock *sk) { for (;;) { unsigned long flags = 0; if (test_and_clear_bit(MPTCP_PUSH_PENDING, &mptcp_sk(sk)->flags)) flags |= BIT(MPTCP_PUSH_PENDING); if (test_and_clear_bit(MPTCP_RETRANSMIT, &mptcp_sk(sk)->flags)) flags |= BIT(MPTCP_RETRANSMIT); if (!flags) break; spin_unlock_bh(&sk->sk_lock.slock); if (flags & BIT(MPTCP_PUSH_PENDING)) __mptcp_push_pending(sk, 0); if (flags & BIT(MPTCP_RETRANSMIT)) __mptcp_retrans(sk); cond_resched(); spin_lock_bh(&sk->sk_lock.slock); } if (test_and_clear_bit(MPTCP_CLEAN_UNA, &mptcp_sk(sk)->flags)) __mptcp_clean_una_wakeup(sk); if (test_and_clear_bit(MPTCP_ERROR_REPORT, &mptcp_sk(sk)->flags)) __mptcp_error_report(sk); __mptcp_update_wmem(sk); __mptcp_update_rmem(sk); }
/** * Tests the given argument values against the local preconditions, which are the {@link * ExecutableBooleanExpression} objects in {@link #preExpressions} in this {@link * ExecutableSpecification}. * * @param args the argument values * @return false if any local precondition fails on the argument values, true if all succeed */ private boolean checkPreExpressions(Object[] args) { for (ExecutableBooleanExpression preCondition : preExpressions) { if (!preCondition.check(args)) { return false; } } return true; }
chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] #<Z_Len(chars),+> algebra s = raw_input() def get_index(a_list, elem): for i in range(0, len(a_list)): if elem == a_list[i]: return i def get_smallest_dist_mod(a,b,mod): #Length to fill the blank #Conventional Distance return min(mod - max(a,b) + min(a,b), max(a,b) - min(a,b)) c_cout = 0 for i in range(-1, len(s)-1): #for each element in s a = get_index(chars, s[i] if i != -1 else 'a') b = get_index(chars, s[i+1]) c_cout += get_smallest_dist_mod(a,b,len(chars)) print c_cout
#pragma once #include "../Core/Defs.hpp" #include "SoundCore.hpp" namespace doll { DOLL_FUNC detail::ISoundHW *DOLL_API snd_xa2_initHW(); }