content
stringlengths
10
4.9M
/** * Validate if a NodeTemplate is from a specific type * * @param node */ public void verifyNode(PaaSNodeTemplate node, String type) { IndexedNodeType indexedNodeType = node.getIndexedToscaElement(); if (!ToscaUtils.isFromType(type, indexedNodeType)) { throw new ResourceMatchingFailedException("Failed to match type <" + indexedNodeType.getElementId() + "> only <" + type + "> type is supported"); } }
cases=int(input()) answers=[0]*cases for i in range(cases): amount=int(input()) candiesR=input().split() orangesR=input().split() candies=[0]*amount oranges=[0]*amount for j in range(amount): candies[j]=int(candiesR[j]) oranges[j]=int(orangesR[j]) for j in range(amount): answers[i]+=max((candies[j]-min(candies)),oranges[j]-min(oranges)) for i in range(cases): print(answers[i])
// Get or create a tag func GetOrCreateTag(tagRequest TagRequest) Tag { if tagRequest.Name == "" { return Tag{} } tag := Tag{ Name: tagRequest.Name, } DB.Where("name=?", tag.Name).FirstOrCreate(&tag) return tag }
def send_note(bird, prob): req = {"req": "note.add"} req["file"] = "bird.qo" req["start"] = True req["body"] = {"bird": bird, "prob": prob, "from": sms_from, "to": sms_to} rsp = card.Transaction(req)
def remove_stress( word_pron: WordPronunciation, keep_stress: bool = False ) -> WordPronunciation: if keep_stress: return word_pron word_pron.phonemes = [REGEX_STRESS.sub("", p) for p in word_pron.phonemes] return word_pron
"I hope to show those who don't believe you can be an LGBT person of faith that there are many of us doing just that." A new photoseries from columnist/speaker Eliel Cruz highlights queer people of faith within our community. #FaithfullyLGBT is a place for LGBT people of faith, any faith, to share news stories, their own stories and find other people going through similar experiences in places of worship. “Despite their being ample evidence that there is a significant portion of LGBT individuals who are themselves religious, both LGBT organizations and faith traditions perpetuate the false divide,” Cruz tells us. “Meeting so many LGBT people of faith made me want to share their stories to begin to put a face to those of us who live in the intersection of faith and sexuality. I hope to show those who don’t believe you can be an LGBT person of faith that there are many of us doing just that.” Cruz says he’s most surprised by the willingness of the participants to share their stories. “You can tell they haven’t been given the space to share their truths, not in LGBT or religious spaces,” he says. “For some of them, they were being seen for the first time as both Christian and LGBT and not one or the other.” Below, meet the first 9 participants, all photographed by Daniel Rarela.
def spark_session(example_repo_path: str) -> SparkSession: repo_config = load_repo_config(repo_path=Path(example_repo_path)) return get_spark_session_or_start_new_with_repoconfig( store_config=repo_config.offline_store, )
import test from "ava" import { nameToWords, wordsToName } from "./words" test("nameToWords", t => { t.deepEqual(nameToWords("Foo_Bar_Baz32"), ["foo", "bar", "baz32"]) }) test("wordsToName", t => { t.deepEqual(wordsToName(["foo", "bar", "baz32"]), "Foo_Bar_Baz32") })
def check_interval(self, interval, value, include=True): if interval is None: return True else: if include: return (value >= interval[0]) and (value <= interval[1]) else: return (value < interval[0]) or (value > interval[1])
<reponame>BezzubovEgor/react-router-navigation-confirm<filename>example/src/demo/components/HandlersExample.tsx import * as React from 'react'; import { HistoryListener, NavigationConfirmModal } from 'react-router-navigation-confirm'; import { ExampleBlock, ExampleRoutes, InlineCode } from 'src/common/components'; export const HandlersExample = () => { const onCancel = () => alert('onCancel handler'); const onConfirm = () => alert('onConfirm handler'); return ( <ExampleBlock> <p><b>Try to click buttons below to navigate and show navigation confirm dialog...</b></p> <ExampleRoutes /> <ExampleBlock.Code>{ CODE_EXAMPLE }</ExampleBlock.Code> <ExampleBlock.Description> Example of <InlineCode>onCancel</InlineCode> and <InlineCode>onConfirm</InlineCode> handlers </ExampleBlock.Description> <HistoryListener> <NavigationConfirmModal onCancel={ onCancel } onConfirm={ onConfirm } /> </HistoryListener> </ExampleBlock> ); }; const CODE_EXAMPLE = `\ import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, Link, Switch, Redirect } from 'react-router-dom'; import { NavigationConfirmModal, HistoryListener } from 'react-router-navigation-confirm'; const FirstPage = () => <h1>Page #1</h1>; const SecondPage = () => <h1>Page #2</h1>; const ThirdPage = () => <h1>Page #3</h1>; const App = () => ( <div className="App"> <Link to="/1"><button>#1</button></Link> <Link to="/2"><button>#2</button></Link> <Link to="/3"><button>#3</button></Link> <div> <Switch> <Route path="/1" component={FirstPage} /> <Route path="/2" component={SecondPage} /> <Route path="/3" component={ThirdPage} /> <Redirect to="/1" /> </Switch> </div> { /** * You can use NavigationConfirmModal component on any route you want */ } <NavigationConfirmModal onCancel={ () => alert('onCancel handler') } onConfirm={ () => alert('onConfirm handler') } /> </div> ); ReactDOM.render( <BrowserRouter> <div> <HistoryListener> <App /> { /** * You need to pass History listener to root router component, not to nested routes */ } </HistoryListener> </div> </BrowserRouter> , document.getElementById('root') ); `;
<filename>src/sodium/include/sodium/crypto_stream_aes256estream.h #ifndef crypto_stream_aes256estream_H #define crypto_stream_aes256estream_H /* * WARNING: This is just a stream cipher. It is NOT authenticated encryption. * While it provides some protection against eavesdropping, it does NOT * provide any security against active attacks. * Furthermore, this implementation was not part of NaCl. * Unless you know what you're doing, what you are looking for is probably * the crypto_box functions. */ #include "export.h" #define crypto_stream_aes256estream_KEYBYTES 32U #define crypto_stream_aes256estream_NONCEBYTES 16U #define crypto_stream_aes256estream_BEFORENMBYTES 276U #ifdef __cplusplus extern "C" { #endif SODIUM_EXPORT int crypto_stream_aes256estream(unsigned char *,unsigned long long,const unsigned char *,const unsigned char *); SODIUM_EXPORT int crypto_stream_aes256estream_xor(unsigned char *,const unsigned char *,unsigned long long,const unsigned char *,const unsigned char *); SODIUM_EXPORT int crypto_stream_aes256estream_beforenm(unsigned char *,const unsigned char *); SODIUM_EXPORT int crypto_stream_aes256estream_afternm(unsigned char *,unsigned long long,const unsigned char *,const unsigned char *); SODIUM_EXPORT int crypto_stream_aes256estream_xor_afternm(unsigned char *,const unsigned char *,unsigned long long,const unsigned char *,const unsigned char *); #ifdef __cplusplus } #endif #define crypto_stream_aes256estream_hongjun crypto_stream_aes256estream #define crypto_stream_aes256estream_hongjun_xor crypto_stream_aes256estream_xor #define crypto_stream_aes256estream_hongjun_beforenm crypto_stream_aes256estream_beforenm #define crypto_stream_aes256estream_hongjun_afternm crypto_stream_aes256estream_afternm #define crypto_stream_aes256estream_hongjun_xor_afternm crypto_stream_aes256estream_xor_afternm #endif
def meta(self, page_type): meta_alternate = '<link rel="alternate" type="application/rss+xml" href="%s/atom.xml" />\n' meta_stylesheet = '<link rel="stylesheet" type="text/css" href="%s">\n' meta_description = '<meta name="description" content="%s">\n' meta_html = '<title>%s</title>\n' % self.title if self.meta_description(page_type) is not None: meta_html += meta_description % self.meta_description(page_type).replace('"', '\\"') if not self.is_indexable(): meta_html += '<meta name="robots" content="noindex">' meta_html += meta_alternate % self.website.config.value('website_base_url') meta_html += meta_stylesheet % self.website.css_filename return meta_html
export const routes = { HOME: "/", ABOUT: "/about", NO_PAGE_FOUND: "/no-page", AUTH: "/auth", START_PARTY: "/start-party", SELECT_VIDEO: "/select-video", CREATE_ROOM: "/create-room", CREATE_LINK_FOR_LATER: "/create-link-for-later", SELECT_STREAMING_SERVICE: "/select-streaming-service", JOIN_ROOM: "/join-room", };
<reponame>mik2k2/dendrite<filename>syncapi/storage/sqlite3/send_to_device_table.go // Copyright 2019-2020 The Matrix.org Foundation C.I.C. // // 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 sqlite3 import ( "context" "database/sql" "encoding/json" "github.com/matrix-org/dendrite/internal" "github.com/matrix-org/dendrite/internal/sqlutil" "github.com/matrix-org/dendrite/syncapi/storage/tables" "github.com/matrix-org/dendrite/syncapi/types" "github.com/sirupsen/logrus" ) const sendToDeviceSchema = ` -- Stores send-to-device messages. CREATE TABLE IF NOT EXISTS syncapi_send_to_device ( -- The ID that uniquely identifies this message. id INTEGER PRIMARY KEY AUTOINCREMENT, -- The user ID to send the message to. user_id TEXT NOT NULL, -- The device ID to send the message to. device_id TEXT NOT NULL, -- The event content JSON. content TEXT NOT NULL ); ` const insertSendToDeviceMessageSQL = ` INSERT INTO syncapi_send_to_device (user_id, device_id, content) VALUES ($1, $2, $3) ` const selectSendToDeviceMessagesSQL = ` SELECT id, user_id, device_id, content FROM syncapi_send_to_device WHERE user_id = $1 AND device_id = $2 AND id > $3 AND id <= $4 ORDER BY id DESC ` const deleteSendToDeviceMessagesSQL = ` DELETE FROM syncapi_send_to_device WHERE user_id = $1 AND device_id = $2 AND id < $3 ` const selectMaxSendToDeviceIDSQL = "" + "SELECT MAX(id) FROM syncapi_send_to_device" type sendToDeviceStatements struct { db *sql.DB insertSendToDeviceMessageStmt *sql.Stmt selectSendToDeviceMessagesStmt *sql.Stmt deleteSendToDeviceMessagesStmt *sql.Stmt selectMaxSendToDeviceIDStmt *sql.Stmt } func NewSqliteSendToDeviceTable(db *sql.DB) (tables.SendToDevice, error) { s := &sendToDeviceStatements{ db: db, } _, err := db.Exec(sendToDeviceSchema) if err != nil { return nil, err } if s.insertSendToDeviceMessageStmt, err = db.Prepare(insertSendToDeviceMessageSQL); err != nil { return nil, err } if s.selectSendToDeviceMessagesStmt, err = db.Prepare(selectSendToDeviceMessagesSQL); err != nil { return nil, err } if s.deleteSendToDeviceMessagesStmt, err = db.Prepare(deleteSendToDeviceMessagesSQL); err != nil { return nil, err } if s.selectMaxSendToDeviceIDStmt, err = db.Prepare(selectMaxSendToDeviceIDSQL); err != nil { return nil, err } return s, nil } func (s *sendToDeviceStatements) InsertSendToDeviceMessage( ctx context.Context, txn *sql.Tx, userID, deviceID, content string, ) (pos types.StreamPosition, err error) { var result sql.Result result, err = sqlutil.TxStmt(txn, s.insertSendToDeviceMessageStmt).ExecContext(ctx, userID, deviceID, content) if p, err := result.LastInsertId(); err != nil { return 0, err } else { pos = types.StreamPosition(p) } return } func (s *sendToDeviceStatements) SelectSendToDeviceMessages( ctx context.Context, txn *sql.Tx, userID, deviceID string, from, to types.StreamPosition, ) (lastPos types.StreamPosition, events []types.SendToDeviceEvent, err error) { rows, err := sqlutil.TxStmt(txn, s.selectSendToDeviceMessagesStmt).QueryContext(ctx, userID, deviceID, from, to) if err != nil { return } defer internal.CloseAndLogIfError(ctx, rows, "SelectSendToDeviceMessages: rows.close() failed") for rows.Next() { var id types.StreamPosition var userID, deviceID, content string if err = rows.Scan(&id, &userID, &deviceID, &content); err != nil { logrus.WithError(err).Errorf("Failed to retrieve send-to-device message") return } if id > lastPos { lastPos = id } event := types.SendToDeviceEvent{ ID: id, UserID: userID, DeviceID: deviceID, } if err = json.Unmarshal([]byte(content), &event.SendToDeviceEvent); err != nil { logrus.WithError(err).Errorf("Failed to unmarshal send-to-device message") continue } events = append(events, event) } if lastPos == 0 { lastPos = to } return lastPos, events, rows.Err() } func (s *sendToDeviceStatements) DeleteSendToDeviceMessages( ctx context.Context, txn *sql.Tx, userID, deviceID string, pos types.StreamPosition, ) (err error) { _, err = sqlutil.TxStmt(txn, s.deleteSendToDeviceMessagesStmt).ExecContext(ctx, userID, deviceID, pos) return } func (s *sendToDeviceStatements) SelectMaxSendToDeviceMessageID( ctx context.Context, txn *sql.Tx, ) (id int64, err error) { var nullableID sql.NullInt64 stmt := sqlutil.TxStmt(txn, s.selectMaxSendToDeviceIDStmt) err = stmt.QueryRowContext(ctx).Scan(&nullableID) if nullableID.Valid { id = nullableID.Int64 } return }
<gh_stars>1-10 package main import ( "context" "flag" "time" format "github.com/cloudevents/sdk-go/binding/format/protobuf/v2" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/event" "github.com/vorteil/direktiv-knative-source/pkg/direktivsource" igrpc "github.com/vorteil/direktiv/pkg/flow/grpc" "google.golang.org/grpc" ) type direktivConnector struct { esr *direktivsource.EventSourceReceiver client igrpc.EventingClient conn *grpc.ClientConn } var direktiv string func (dc *direktivConnector) connect() error { dc.esr.Logger().Infof("connecting to %s", direktiv) // insecure, linkerd adds mtls/tls if required conn, err := grpc.Dial(direktiv, []grpc.DialOption{grpc.WithInsecure(), grpc.WithBlock()}...) if err != nil { dc.esr.Logger().Fatalf("can not connect to %s: %v", direktiv, err) } dc.conn = conn dc.client = igrpc.NewEventingClient(conn) return nil } func (dc *direktivConnector) getStream() (igrpc.Eventing_RequestEventsClient, error) { return dc.client.RequestEvents(context.Background(), &igrpc.EventingRequest{Uuid: dc.esr.ID()}) } func init() { flag.StringVar(&direktiv, "direktiv", "", "direktiv address, e.g. direktiv-flow.default:3333") } func main() { esr := direktivsource.NewEventSourceReceiver("direktiv-source") dc := &direktivConnector{ esr: esr, } flag.Parse() dc.connect() var ( stream igrpc.Eventing_RequestEventsClient err error ) for { if stream == nil { if stream, err = dc.getStream(); err != nil { esr.Logger().Errorf("failed to connect to direktiv: %v", err) time.Sleep(3 * time.Second) continue } } esr.Logger().Infof("waiting for event") response, err := stream.Recv() if err != nil { esr.Logger().Errorf("failed to receive message: %v", err) stream = nil time.Sleep(3 * time.Second) continue } var ev event.Event err = format.Protobuf.Unmarshal(response.Ce, &ev) if err != nil { esr.Logger().Errorf("failed to unmarshal message: %v", err) continue } dc.esr.OverridesApply(&ev) if dc.esr.Overrides() != nil && dc.esr.Overrides().Extensions != nil { for n, v := range dc.esr.Overrides().Extensions { ev.SetExtension(n, v) } } ctx := cloudevents.ContextWithTarget(context.Background(), esr.Env().Sink) if result := esr.Client().Send(ctx, ev); cloudevents.IsUndelivered(result) { esr.Logger().Errorf("failed to send, %v", result) } } }
Andrew Coyne marshals an impressive range of statistics to make the case that rising income inequality is not a serious issue. A careful reading of his article shows that this is not the case. As Coyne himself agrees, top incomes (incomes of the top 20%) rose much faster than those of middle and lower income groups for two of the last three decades. Things got worse over the 1980s and 1990s, and then there was a change, of sorts. He is right that the 1980s and 1990s were decades of rising inequality due mainly to the deep recessions of the early 1980s and early 1990s which were followed by very slow recoveries. His charts also show that rising market income inequality during that period was also reflected in rising income inequality after the impact of taxes and transfers is taken into account. The equalizing role of the tax and transfer system became much less effective, as has been highlighted by the OECD and others. It is a stretch for Coyne to argue that the last decade or so has been more typical than two of the past three decades, though he is right that low unemployment from the late 1990s made a big difference. That said, Coyne fails to make an absolutely key point that clearly emerges from his own data. What happened between the late 1990s and the Great Recession of 2008 was that income inequality arguably stabilized at higher levels. There was no reversal in the trend. The income share of the top 20%, both before and after taxes, stabilized or slightly increased, but did not decrease. Meanwhile, the income share of the top 1% continued to increase significantly until 2008. It should be underlined that data on the income share of the top 1% — based on tax returns — is more accurate than data on the income of the top 20% which is based on household surveys. Surveys usually fail to capture the incomes of the very, very rich. The key point is that good (or at least better) times for the economy from about 2000 to 2008 did not change the dismal trend of the previous two decades. A temporarily rising tide did not make incomes more equal than they had been, as used to be the case in years of recovery. Coyne's best efforts notwithstanding, income inequality is very much an issue. Photo: arjunkamloops. Used under a Creative Commons BY-SA 2.0 licence.
<reponame>stuliveshere/Seismic-Processing-Prac3<filename>prac3/exercise4.py #spherical divergence correction import toolbox import numpy as np import pylab pylab.rcParams['image.interpolation'] = 'sinc' #-------------------------------------------------- # useful functions #------------------------------------------------- None if __name__ == "__main__": #initialise dataset print "initialising dataset" #find our test CDP #extract it #display it #set and apply tar #display it
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flume.tools; import java.util.Calendar; import java.util.TimeZone; import com.google.common.base.Preconditions; import org.apache.flume.annotations.InterfaceAudience; import org.apache.flume.annotations.InterfaceStability; @InterfaceAudience.Private @InterfaceStability.Evolving public class TimestampRoundDownUtil { /** * * @param timestamp - The time stamp to be rounded down. * For parsing the <tt>timestamp</tt> the system default timezone will be used. * @param roundDownSec - The <tt>timestamp</tt> is rounded down to the largest * multiple of <tt>roundDownSec</tt> seconds * less than or equal to <tt>timestamp.</tt> Should be between 0 and 60. * @return - Rounded down timestamp * @throws IllegalStateException * @see TimestampRoundDownUtil#roundDownTimeStampSeconds(long, int, TimeZone) */ public static long roundDownTimeStampSeconds(long timestamp, int roundDownSec) throws IllegalStateException { return roundDownTimeStampSeconds(timestamp, roundDownSec, null); } /** * * @param timestamp - The time stamp to be rounded down. * @param roundDownSec - The <tt>timestamp</tt> is rounded down to the largest * multiple of <tt>roundDownSec</tt> seconds * less than or equal to <tt>timestamp.</tt> Should be between 0 and 60. * @param timeZone - The timezone to use for parsing the <tt>timestamp</tt>. * @return - Rounded down timestamp * @throws IllegalStateException */ public static long roundDownTimeStampSeconds(long timestamp, int roundDownSec, TimeZone timeZone) throws IllegalStateException { Preconditions.checkArgument(roundDownSec > 0 && roundDownSec <= 60, "RoundDownSec must be > 0 and <=60"); Calendar cal = roundDownField(timestamp, Calendar.SECOND, roundDownSec, timeZone); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } /** * * @param timestamp - The time stamp to be rounded down. * For parsing the <tt>timestamp</tt> the system default timezone will be used. * @param roundDownMins - The <tt>timestamp</tt> is rounded down to the * largest multiple of <tt>roundDownMins</tt> minutes less than * or equal to <tt>timestamp.</tt> Should be between 0 and 60. * @return - Rounded down timestamp * @throws IllegalStateException * @see TimestampRoundDownUtil#roundDownTimeStampMinutes(long, int, TimeZone) */ public static long roundDownTimeStampMinutes(long timestamp, int roundDownMins) throws IllegalStateException { return roundDownTimeStampMinutes(timestamp, roundDownMins, null); } /** * * @param timestamp - The time stamp to be rounded down. * @param roundDownMins - The <tt>timestamp</tt> is rounded down to the * largest multiple of <tt>roundDownMins</tt> minutes less than * or equal to <tt>timestamp.</tt> Should be between 0 and 60. * @param timeZone - The timezone to use for parsing the <tt>timestamp</tt>. * If <tt>null</tt> the system default will be used. * @return - Rounded down timestamp * @throws IllegalStateException */ public static long roundDownTimeStampMinutes(long timestamp, int roundDownMins, TimeZone timeZone) throws IllegalStateException { Preconditions.checkArgument(roundDownMins > 0 && roundDownMins <= 60, "RoundDown must be > 0 and <=60"); Calendar cal = roundDownField(timestamp, Calendar.MINUTE, roundDownMins, timeZone); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } /** * * @param timestamp - The time stamp to be rounded down. * For parsing the <tt>timestamp</tt> the system default timezone will be used. * @param roundDownHours - The <tt>timestamp</tt> is rounded down to the * largest multiple of <tt>roundDownHours</tt> hours less than * or equal to <tt>timestamp.</tt> Should be between 0 and 24. * @return - Rounded down timestamp * @throws IllegalStateException * @see TimestampRoundDownUtil#roundDownTimeStampHours(long, int, TimeZone) */ public static long roundDownTimeStampHours(long timestamp, int roundDownHours) throws IllegalStateException { return roundDownTimeStampHours(timestamp, roundDownHours, null); } /** * * @param timestamp - The time stamp to be rounded down. * @param roundDownHours - The <tt>timestamp</tt> is rounded down to the * largest multiple of <tt>roundDownHours</tt> hours less than * or equal to <tt>timestamp.</tt> Should be between 0 and 24. * @param timeZone - The timezone to use for parsing the <tt>timestamp</tt>. * If <tt>null</tt> the system default will be used. * @return - Rounded down timestamp * @throws IllegalStateException */ public static long roundDownTimeStampHours(long timestamp, int roundDownHours, TimeZone timeZone) throws IllegalStateException { Preconditions.checkArgument(roundDownHours > 0 && roundDownHours <= 24, "RoundDown must be > 0 and <=24"); Calendar cal = roundDownField(timestamp, Calendar.HOUR_OF_DAY, roundDownHours, timeZone); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } private static Calendar roundDownField(long timestamp, int field, int roundDown, TimeZone timeZone) { Preconditions.checkArgument(timestamp > 0, "Timestamp must be positive"); Calendar cal = (timeZone == null) ? Calendar.getInstance() : Calendar.getInstance(timeZone); cal.setTimeInMillis(timestamp); int fieldVal = cal.get(field); int remainder = (fieldVal % roundDown); cal.set(field, fieldVal - remainder); return cal; } }
/** * Created by qiunet. * 18/1/30 */ public class TestPlayerInfo extends BaseStringLogicTestCase { @Override protected int getRequestID() { return 1004; } @Override protected String requestBuild(Robot robot) { return robot.getToken(); } @Override protected void responseData(Robot robot, String s) { System.out.println("=============="+s+"============"); } @Override public boolean conditionJudge(Robot robot) { return true; } }
Mobilizing Mothers for War Studies document that in wartime, states often employ maternal imagery and mobilize women as mothers.Yet we know relatively little about when and why states and their opposition do so. This study seeks to build theory for this phenomenon through frame analysis of the Nicaraguan Contra War. The author proposes that maternal framing, aimed at mothers as well as a broader national and international audience, benefits militaries in at least three ways: (1) channeling maternal grievances, (2) disseminating propaganda through “apolitical” mothers, and (3) evoking emotions and sympathy nationally and internationally. This study furthermore explores three underexamined features of both gendered studies of war and frame analysis: (1) It applies frame theory to states, (2) it develops our understanding of crossnational gendered framing strategies, and (3) it introduces gender framing to the study of war.
// CheckVersion set version and supportGeneratedColumn func (db *DB) CheckVersion() error { verGeneratedColumn, err := version.Parse(MinMysqlVersion) if err != nil { return errors.WithStack(err) } var v string row := db.db.QueryRowx(`SELECT version();`) if err := row.Scan(&v); err != nil { return errors.WithStack(err) } v = formatMariaVersion(v) db.Version = v ver, err := version.Parse(v) if err != nil { return errors.WithStack(err) } if ver.LessThan(verGeneratedColumn) { db.supportGeneratedColumn = false } else { db.supportGeneratedColumn = true } return nil }
def make_createblockdevicedataset_mixin(profiled_api): class Mixin(CreateBlockDeviceDatasetImplementationMixin, TestCase): def setUp(self): super(Mixin, self).setUp() if profiled_api: self.api = fakeprofiledloopbackblockdeviceapi_for_test( self, allocation_unit=LOOPBACK_ALLOCATION_UNIT ) else: self.api = loopbackblockdeviceapi_for_test( self, allocation_unit=LOOPBACK_ALLOCATION_UNIT ) self.mountroot = mountroot_for_test(self) self.deployer = BlockDeviceDeployer( node_uuid=uuid4(), hostname=u"192.0.2.10", block_device_api=self.api, mountroot=self.mountroot ) return Mixin
/** * Constructor * * @param tx the pin instance to use for transmission * * @param rx the pin instance to use for reception * **/ SAMDSerial::SAMDSerial(Pin& tx, Pin& rx) : Serial(tx, rx) { this->instance_number = 255; this->baudrate = CODAL_SERIAL_DEFAULT_BAUD_RATE; memset(&USART_INSTANCE, 0, sizeof(USART_INSTANCE)); configurePins(tx, rx); }
Santa Clara County officials have declared a local emergency after they said someone intentionally cut an underground fiber optic cable in south San Jose, causing a widespread phone service outage in southern Santa Clara and Santa Cruz counties today that included disruption to 911 emergency phone service. John Britton, a spokesman for AT&T, said it appears somebody opened a manhole in South San Jose, climbed down eight to 10 feet and cut four or five fiber-optic cables.Britton also said there was a report of underground cables being cut in San Carlos. AT&T is offering a $100,000 reward for information leading to the arrest and conviction of whoever is responsible for the sabotage, Britton said. The outage initially affected some cell phones, Internet access and about 52,200 Verizon household land lines in Morgan Hill, Gilroy and Santa Cruz County, according to the Santa Clara County Office of Emergency Services. The cell phone networks affected are Verizon, Nextel, Sprint and some AT&T. Verizon is the sole provider of land lines in the South County area. “We’ve never to this extent in recent history had this kind of phone outage,” said Gilroy police Sgt. Jim Gillio. ATMs in South Santa Clara County were not working. Saint Louise Regional Hospital in Gilroy cancelled all elective surgeries in response to the emergency, according to county officials. “It’s kind of like an earthquake” said Jack Ahlin, a driver with T. Marx Towing who was standing outside the Gilroy police department. Service is also affected in South San Jose around Monterey Road and Bailey Avenue. Crews are repairing cut wires located underground on Monterey Road just north of the Blossom Hill Road exit in South San Jose. As of 2 p.m. one of the cables had been repaired and some service had been restored, Britton said. Full service is not expected to be restored until about midnight. San Jose police spokesman Sgt. Ronnie Lopez said the manhole covers are heavy and would take quite an effort to lift, perhaps even requiring a tool. AT&T’s contract with the Communication Workers of America expired at 11:59 p.m. Saturday, but Britton said “we have a really good relationship with the union” and that negotiations continue between the two sides. Asked if the potential sabotage had anything to with the strike-threatened contract negotiations between AT&T and the Communication Workers of America, union national spokeswoman Candice Johnson replied: “Absolutely not. Our members are not involved in this.” Johnson said that CWA would cooperate with the investigation. Any implication that a disgruntled worker cut the wires was false, she said. “That would be counterproductive, ” Johnson said “We are on the job. So it doesn’t make any sense. Our goal is to get a quality, fair contract and that us our focus right now.” Johnson said she did not know if police had contacted the local union. Meanwhile the disruption continues for thousands of residents. The Santa Clara County Emergency Operations Center has been activated; the Santa Clara County Fire Department has moved more firefighters to south county fire stations; the county sheriff has increasing staffing and patrols; and additional ambulances have been positioned in the area. Authorities say that residents with an emergency who can’t reach 911 should use a cell phone if possible to call the police dispatch numbers for help. The numbers are: Gilroy (408) 846-0350; Morgan Hill: (408) 779-2101; unincorporated areas: (408) 299-2311; and San Jose: (408) 277-8900 Search and rescue crews have set up the following locations to respond to residents reporting locations: Uvas and Watsonville roads, near Gilroy; McKean and Bailey roads, near South San Jose and Morgan Hill; Oak Glen and Edmonson roads, near Morgan Hill; Watsonville Road and Highway 152, near Gilroy; New and Church avenues, near San Martin; and Maple and Foothill avenues, near San Martin. Gilroy police called in eight officers to help patrol the city, more the doubling the force of seven officers on the streets on a typical day, according to Gillio. He said residents should flag down an officer if they need help. The city of Gilroy is also sending out emergency notifications on cable channel 17 and 1610 a.m. radio and setting up freeway signs directing people to the cable and radio outlets, according to city spokesman Joe Kline. The city also sent fliers to the schools with information about how to report an emergency. Children were asked to bring the fliers home to their parents. Elsewhere, officials are urging people to go to their nearest fire or police department or local hospital or flag down an emergency vehicle. “Verizon is completely down; other carriers are intermittent at best,” said Zachary DeVine, a Santa Clara County spokesman. The damaged fiber optic line owned is by AT&T and leased out to Verizon, DeVine said. The problem was first reported around 2 a.m. when police in Morgan Hill and Gilroy contacted Santa Clara county dispatchers to report their phones were down. That began a chain of reactions as Santa Clara County officials responded immediately, DeVine said. The county has held over fire crews and has sent additional sheriff’s deputies to Morgan Hill and Gilroy. Police and fire radios remain operational, meaning field officers are able to get calls from dispatchers and communicate with one another to coordinate aid for anyone reporting to a local fire or police station, DeVine said. Contact Mark Gomez at [email protected] or (408) 920-5869.
def compute_image_histogram(infile, nbins=100, threshold=0.0): import numpy as np import nibabel as nb data = nb.load(infile).get_data().ravel() if threshold > 0: data = data / max(data) data = data[data >= threshold] histogram_values, bin_edges = np.histogram(data, bins=nbins) return histogram_values
Hat tip to my friend Mike for the excellent Photoshop. With an uncertain future on Long Island, the Islanders, and owner Charles Wang, are looking at all available options to keep the once-great franchise in the greater New York area. It’s almost certain that the Islanders will leave Nassau Coliseum when their lease expires in 2015 because it is a horribly outdated excuse for an arena that resembles a poorly lit barn.There are preliminary discussions between another Long Island county, Suffolk, and Charles Wang to determine if the Isles could fit there. Others suggest that the Islanders could move to either Queens or Brooklyn. I don’t know anything about Queens, except that Kevin James drives a mail route there, so I can’t vouch for its viability, but I do know that Brooklyn is absolutely perfect for the Islanders – at least culturally.Brooklyn is one of the five boroughs in New York City and is home to Williamsburg, a hub for hipsters. Now hipsters don’t necessarily appear like the sports loving type, what with their oversized glasses and super tight jeans, but don’t let appearances fool you, there is enough about the Islanders that hipsters can grab hold of.Well, for one, Islander fans are apathetic. That’s evident after years of paltry attendance figures and a dismal turnout at the polls to determine whether Nassau County should help finance Charles Wang’s new arena. But not caring about the Islanders is perfect for Brooklyn hipsters. Hispters love being apathetic, or at least looking apathetic. Having the Islanders in Brooklyn would at least make not caring about the team cool.But there are also aspects about the Islanders that might turn cool Brooklyn apathy into genuine hipster love.First, the Islanders are easily the least popular of all three New York area teams: the Rangers are a classic, original six team who routinely appear at the top of the NHL attendance leaders; and the Devils have won three Stanley Cups in the last two decades. In comparison, the Islanders have been run into the ground for over two decades and routinely draw sparse crowds. The only NHL team that might be less cool than the Islanders is the Coyotes and it’s only a matter of time until they move somewhere in Canada, thereby increasing their popularity immediately. The fact that no one likes the Islanders makes them hipster cool. I think the only team that hipsters could like even more is the California Golden Seals. Who are they? Oh, they’re some obscure team you’ve probably never heard of.But the Islanders were popular during the 1980s, so you might think this should discredit them among their potential hipster fans. Well, no. You see, the 1980s is actually one of the most beloved decades for the modern hipster. Hipsters love 80s nostalgia, even though, for the most part, it was a decade they were born in, not the decade they actually grew up in and can remember.Another reason hipsters would immediately adopt the Islanders is their love of facial hair. The Islanders in the mid-1970s began the tradition of growing their beards during the playoffs for solidarity. The tradition remained popular throughout the Islanders’ dynasty of the 1980s (hipster alert!), but was abandoned until the mid-90s, when it became permanently embedded in playoff culture. Hipsters love beards and moustaches, especially ones grown ironically, which is good because they can all show up to regular season games with ironic playoff beards, because, obviously, the current Islanders won’t need to grow any this post-season.Additionally, if the Islanders do indeed move to Brooklyn, the fans can clamour for management to bring back the old Highliner uniforms: the ones with the fisherman logo that are routinely listed as one of the worst jersey designs in the history of the league. This might seem puzzling, but hipsters love to wear ugly things ironically. Supporting a team with one of the most hideous designs in the league will ensure that the hipsters rock the new Islanders’ gear all over Brooklyn. Plus, there is a fisherman in the logo and I’m pretty sure fisherman wear plaid. You know who loves plaid? Hipsters.Moving the Islanders to Brooklyn would also take hockey arguments to a whole new level. New hipster fans could wax poetically about how mainstream Wayne Gretzky is and how Mike Bossy was actually the greatest goal scorer of all-time.If the Islanders wanted to really make this work they could start advertising in Vice and play Bon Iver during the intermissions and Fucked Up after every goal . They could even sell PBR exclusively throughout the arena and official Islander super-skinny jeans in the gift shop.This seems like a match made in hipster heaven.
Effects at a Linear Collider with Polarized Beams 1 The four-fermion contact-interaction searches in the process ee → μμ at a future ee Linear Collider with c.m. energy √ s = 0.5 TeV and with both beams longitudinally polarized are studied. We evaluate the corresponding model-independent constraints on the coupling constants, emphasizing the role of beam polarization, and make a comparison with the case of Bhabha scattering. Talk given at the International School-Seminar ”The Actual Problems of Particle Physics”, Gomel, August 7 – 16, 2001
/** * This class implements a simple HTTP server. A HttpServer is bound to an IP address * and port number and listens for incoming TCP connections from clients on this address. * The sub-class {@link HttpsServer} implements a server which handles HTTPS requests. * <p> * One or more {@link HttpHandler} objects must be associated with a server * in order to process requests. Each such HttpHandler is registered * with a root URI path which represents the * location of the application or service on this server. The mapping of a handler * to a HttpServer is encapsulated by a {@link HttpContext} object. HttpContexts * are created by calling {@link #createContext(String,HttpHandler)}. * Any request for which no handler can be found is rejected with a 404 response. * Management of threads can be done external to this object by providing a * {@link java.util.concurrent.Executor} object. If none is provided a default * implementation is used. * <p> * <a id="mapping_description"></a> * <b>Mapping request URIs to HttpContext paths</b><p> * When a HTTP request is received, * the appropriate HttpContext (and handler) is located by finding the context * whose path is the longest matching prefix of the request URI's path. * Paths are matched literally, which means that the strings are compared * case sensitively, and with no conversion to or from any encoded forms. * For example. Given a HttpServer with the following HttpContexts configured. * <table class="striped"><caption style="display:none">description</caption> * <thead> * <tr><th scope="col"><i>Context</i></th><th scope="col"><i>Context path</i></th></tr> * </thead> * <tbody> * <tr><th scope="row">ctx1</th><td>"/"</td></tr> * <tr><th scope="row">ctx2</th><td>"/apps/"</td></tr> * <tr><th scope="row">ctx3</th><td>"/apps/foo/"</td></tr> * </tbody> * </table> * <p> * the following table shows some request URIs and which, if any context they would * match with. * <table class="striped"><caption style="display:none">description</caption> * <thead> * <tr><th scope="col"><i>Request URI</i></th><th scope="col"><i>Matches context</i></th></tr> * </thead> * <tbody> * <tr><th scope="row">"http://foo.com/apps/foo/bar"</th><td>ctx3</td></tr> * <tr><th scope="row">"http://foo.com/apps/Foo/bar"</th><td>no match, wrong case</td></tr> * <tr><th scope="row">"http://foo.com/apps/app1"</th><td>ctx2</td></tr> * <tr><th scope="row">"http://foo.com/foo"</th><td>ctx1</td></tr> * </tbody> * </table> * <p> * <b>Note about socket backlogs</b><p> * When binding to an address and port number, the application can also specify an integer * <i>backlog</i> parameter. This represents the maximum number of incoming TCP connections * which the system will queue internally. Connections are queued while they are waiting to * be accepted by the HttpServer. When the limit is reached, further connections may be * rejected (or possibly ignored) by the underlying TCP implementation. Setting the right * backlog value is a compromise between efficient resource usage in the TCP layer (not setting * it too high) and allowing adequate throughput of incoming requests (not setting it too low). * @since 1.6 */ public abstract class HttpServer { /** */ protected HttpServer () { } /** * creates a HttpServer instance which is initially not bound to any local address/port. * The HttpServer is acquired from the currently installed {@link HttpServerProvider} * The server must be bound using {@link #bind(InetSocketAddress,int)} before it can be used. * @throws IOException */ public static HttpServer create () throws IOException { return create (null, 0); } /** * Create a <code>HttpServer</code> instance which will bind to the * specified {@link java.net.InetSocketAddress} (IP address and port number) * * A maximum backlog can also be specified. This is the maximum number of * queued incoming connections to allow on the listening socket. * Queued TCP connections exceeding this limit may be rejected by the TCP implementation. * The HttpServer is acquired from the currently installed {@link HttpServerProvider} * * @param addr the address to listen on, if <code>null</code> then bind() must be called * to set the address * @param backlog the socket backlog. If this value is less than or equal to zero, * then a system default value is used. * @throws BindException if the server cannot bind to the requested address, * or if the server is already bound. * @throws IOException */ public static HttpServer create ( InetSocketAddress addr, int backlog ) throws IOException { HttpServerProvider provider = HttpServerProvider.provider(); return provider.createHttpServer (addr, backlog); } /** * Binds a currently unbound HttpServer to the given address and port number. * A maximum backlog can also be specified. This is the maximum number of * queued incoming connections to allow on the listening socket. * Queued TCP connections exceeding this limit may be rejected by the TCP implementation. * @param addr the address to listen on * @param backlog the socket backlog. If this value is less than or equal to zero, * then a system default value is used. * @throws BindException if the server cannot bind to the requested address or if the server * is already bound. * @throws NullPointerException if addr is <code>null</code> */ public abstract void bind (InetSocketAddress addr, int backlog) throws IOException; /** * Starts this server in a new background thread. The background thread * inherits the priority, thread group and context class loader * of the caller. */ public abstract void start () ; /** * sets this server's {@link java.util.concurrent.Executor} object. An * Executor must be established before {@link #start()} is called. * All HTTP requests are handled in tasks given to the executor. * If this method is not called (before start()) or if it is * called with a <code>null</code> Executor, then * a default implementation is used, which uses the thread * which was created by the {@link #start()} method. * @param executor the Executor to set, or <code>null</code> for default * implementation * @throws IllegalStateException if the server is already started */ public abstract void setExecutor (Executor executor); /** * returns this server's Executor object if one was specified with * {@link #setExecutor(Executor)}, or <code>null</code> if none was * specified. * @return the Executor established for this server or <code>null</code> if not set. */ public abstract Executor getExecutor () ; /** * stops this server by closing the listening socket and disallowing * any new exchanges from being processed. The method will then block * until all current exchange handlers have completed or else when * approximately <i>delay</i> seconds have elapsed (whichever happens * sooner). Then, all open TCP connections are closed, the background * thread created by start() exits, and the method returns. * Once stopped, a HttpServer cannot be re-used. * * @param delay the maximum time in seconds to wait until exchanges have finished. * @throws IllegalArgumentException if delay is less than zero. */ public abstract void stop (int delay); /** * Creates a HttpContext. A HttpContext represents a mapping from a * URI path to a exchange handler on this HttpServer. Once created, all requests * received by the server for the path will be handled by calling * the given handler object. The context is identified by the path, and * can later be removed from the server using this with the {@link #removeContext(String)} method. * <p> * The path specifies the root URI path for this context. The first character of path must be * '/'. <p> * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a> * to HttpContext instances. * @param path the root URI path to associate the context with * @param handler the handler to invoke for incoming requests. * @throws IllegalArgumentException if path is invalid, or if a context * already exists for this path * @throws NullPointerException if either path, or handler are <code>null</code> */ public abstract HttpContext createContext (String path, HttpHandler handler) ; /** * Creates a HttpContext without initially specifying a handler. The handler must later be specified using * {@link HttpContext#setHandler(HttpHandler)}. A HttpContext represents a mapping from a * URI path to an exchange handler on this HttpServer. Once created, and when * the handler has been set, all requests * received by the server for the path will be handled by calling * the handler object. The context is identified by the path, and * can later be removed from the server using this with the {@link #removeContext(String)} method. * <p> * The path specifies the root URI path for this context. The first character of path must be * '/'. <p> * The class overview describes how incoming request URIs are <a href="#mapping_description">mapped</a> * to HttpContext instances. * @param path the root URI path to associate the context with * @throws IllegalArgumentException if path is invalid, or if a context * already exists for this path * @throws NullPointerException if path is <code>null</code> */ public abstract HttpContext createContext (String path) ; /** * Removes the context identified by the given path from the server. * Removing a context does not affect exchanges currently being processed * but prevents new ones from being accepted. * @param path the path of the handler to remove * @throws IllegalArgumentException if no handler corresponding to this * path exists. * @throws NullPointerException if path is <code>null</code> */ public abstract void removeContext (String path) throws IllegalArgumentException ; /** * Removes the given context from the server. * Removing a context does not affect exchanges currently being processed * but prevents new ones from being accepted. * @param context the context to remove * @throws NullPointerException if context is <code>null</code> */ public abstract void removeContext (HttpContext context) ; /** * returns the address this server is listening on * @return the address/port number the server is listening on */ public abstract InetSocketAddress getAddress() ; }
President-elect Donald Trump will begin to dismantle the Affordable Care Act almost immediately when he takes office this month through a series of executive orders, Mike Pence reportedly told House Republicans in a meeting on Capitol Hill on Wednesday morning. Rep. Chris Collins (R-NY), a steadfast Trump ally in the lower chamber, said Congressional Republicans will have a replacement bill ready in six months. Meanwhile, President Obama was meeting separately with Democrats to discuss a strategy going forward for shielding his signature legislative achievement. Rep. Jackie Speier (D-CA) was tweeting from inside the meeting and said Obama criticized the GOP for its handling of the repeal process. “You don’t tear down a house before having plans and building a new one,” Obama purportedly said, adding that he could have done a better job “communicating the importance” of the Affordable Care Act.
// // Ingest and process data from RRD files // func (tr *Transformer) Run() error { Create or open data repository var r *repository.BadgerRepo var err error if tr.forceIngest { r, err = repository.NewBadgerRepo("./kv/") if err != nil { return err } tr.repository = r } if tr.skipIngest { fmt.Println("--- Skipping ingest, using existing data:") r, err = repository.OpenExistingBadgerRepo("./kv/") if err != nil { return err } tr.repository = r } if !tr.skipIngest { fmt.Println("--- Ingesting results data:") err = ingestResults(tr.inputFolder, r) if err != nil { return err } } defer tr.repository.Close() if tr.stopAfterIngest { fmt.Println("--- Halting post-ingest.") return nil } = Get the data stats, and show to user fmt.Println("--- Data stats:") fmt.Println() tr.stats = r.GetStats() for k, v := range tr.stats { fmt.Printf("\t%s: %d\n", k, v) } fmt.Println() ==================================== Build the codeframe helper cfh, err := helper.NewCodeframeHelper(r) if err != nil { return err } tr.helper = cfh ==================================== Build the object helper oh, err := helper.NewObjectHelper(r) if err != nil { return err } tr.objecthelper = oh ================================== run the report processing streams err = tr.streamResults() if err != nil { return err } ================================= split splitter.EnableProgBar(tr.showProgress) err = splitter.NrtSplit("./config_split/config.toml") if err != nil { return err } ================================= tidy up err = os.RemoveAll("./out/null/") if err != nil { return err } return nil }
def _extract_property_info(self,prop_addr): size_byte = self.game_memory[prop_addr] property_number = size_byte & 0x1F property_size = ((size_byte & 0xE0) >> 5) + 1 return property_number,property_size
//-------------------------------------------------------------------------- // Reload config - indirectly called from SIGHUP handler void Shell::reload() { Log::Streams log; log.summary << "SIGHUP received\n"; if (config.read(config_element)) application.read_config(config); else log.error << "Failed to re-read config, using existing" << endl; application.reconfigure(); }
<gh_stars>10-100 package com.hbm.items.gear; import net.minecraft.item.EnumRarity; import net.minecraft.item.ItemHoe; import net.minecraft.item.ItemStack; public class HoeSchrabidium extends ItemHoe { public HoeSchrabidium(ToolMaterial p_i45343_1_) { super(p_i45343_1_); } @Override public EnumRarity getRarity(ItemStack p_77613_1_) { return EnumRarity.rare; } }
Béla I, (born c. 1020—died September 1063), king of Hungary (1060–63) who fought a successful war against the Holy Roman emperor Henry III to defend his country’s independence. His father, Prince Vazul (also called Basil or Vászoly), was a nephew of King Stephen I. On the death of his son Imre, Stephen declared not Vazul but another nephew, the Venetian Peter Orseolo, to be his successor. Vazul rose in revolt, and Stephen had him blinded in 1031. Vazul’s three sons fled, first to the Czech lands and then to Poland, where Béla was baptized. After deposing and executing Peter in 1046, the Hungarian nobles called back Vazul’s sons, and Andrew (Endre) took the throne. He made Béla duke of one-third of the realm and also heir to the throne. While Béla was away on various military campaigns, Andrew had his four-year-old son Salamon named heir. This broke the Hungarian custom of seniorate, by which the heir was the eldest brother or nephew within the extended family. Béla raised an army in Poland and led it back to Hungary in 1060. Andrew died in this internecine struggle. Béla was crowned king in Székesfehérvár. It was during his reign that János, son of the tribal chief Vata, led the last pagan rebellion in Hungary, which Béla crushed in 1061. Béla was preparing for a military campaign against emperor Henry IV, who supported Salamon’s claim to the throne, when he died as a result of injuries that he sustained when the wooden structure of his throne collapsed.
<reponame>13765155217/huangz package io.github.biezhi.elves.request; import io.github.biezhi.elves.response.Result; import io.github.biezhi.elves.response.Response; /** * 解析器接口 * * @author biezhi * @date 2018/1/12 */ public interface Parser<T> { Result<T> parse(Response response); }
def _setup(self, config_path): config = read_yaml(config_path) self.check_interval = config.get('check_interval', 30) self.monitors = [ Monitor( mon, counter=self._monitor_counter, logger=self._logger, ) for mon in config.get('monitors', []) ] self.alerts = { 'log': Alert( 'log', {'command': ['echo', '{alert_message}!']}, counter=self._alert_counter, logger=self._logger, ) } self.alerts.update({ alert_name: Alert( alert_name, alert, counter=self._alert_counter, logger=self._logger, ) for alert_name, alert in config.get('alerts', {}).items() })
<filename>Data/Copointed.hs module Data.Copointed where import Control.Comonad import Data.Default import Data.Functor.Identity import Data.Functor.Compose import Data.Functor.Coproduct import Data.Tree import Data.Semigroup as Semigroup import Control.Monad.Trans.Identity import qualified Control.Monad.Trans.Writer.Lazy as Lazy import qualified Control.Monad.Trans.Writer.Strict as Strict import qualified Control.Comonad.Trans.Discont.Lazy as Lazy import qualified Control.Comonad.Trans.Discont.Memo as Memo import qualified Control.Comonad.Trans.Discont.Strict as Strict import qualified Control.Comonad.Trans.Env.Lazy as Lazy import qualified Control.Comonad.Trans.Env.Strict as Strict import qualified Control.Comonad.Trans.Store.Lazy as Lazy import qualified Control.Comonad.Trans.Store.Memo as Memo import qualified Control.Comonad.Trans.Store.Strict as Strict import Data.List.NonEmpty (NonEmpty(..)) -- | 'Copointed' does not require a 'Functor', as the only relationship -- between 'copoint' and 'fmap' is given by a free theorem. class Copointed p where copoint :: p a -> a instance Copointed Identity where copoint = runIdentity instance Default m => Copointed ((->)m) where copoint f = f def instance Copointed ((,) a) where copoint = snd instance Copointed ((,,) a b) where copoint (_,_,a) = a instance Copointed ((,,,) a b c) where copoint (_,_,_,a) = a instance Copointed Tree where copoint = rootLabel instance (Copointed p, Copointed q) => Copointed (Compose p q) where copoint = copoint . copoint . getCompose instance (Copointed p, Copointed q) => Copointed (Coproduct p q) where copoint = coproduct copoint copoint instance Copointed m => Copointed (IdentityT m) where copoint = copoint . runIdentityT instance Copointed m => Copointed (Lazy.WriterT w m) where copoint = fst . copoint . Lazy.runWriterT instance Copointed m => Copointed (Strict.WriterT w m) where copoint = fst . copoint . Strict.runWriterT instance Copointed Dual where copoint = getDual instance Copointed Sum where copoint = getSum instance Copointed NonEmpty where copoint ~(a :| _) = a instance Copointed Semigroup.First where copoint = Semigroup.getFirst instance Copointed Semigroup.Last where copoint = Semigroup.getLast instance Copointed Semigroup.Max where copoint = Semigroup.getMax instance Copointed Semigroup.Min where copoint = Semigroup.getMin instance Copointed (Lazy.DiscontT s w) where copoint (Lazy.DiscontT f w) = f w instance Copointed (Strict.DiscontT s w) where copoint (Strict.DiscontT f w) = f w instance Copointed (Memo.DiscontT s w) where copoint = extract instance Copointed w => Copointed (Lazy.EnvT e w) where copoint = copoint . Lazy.lowerEnvT instance Copointed w => Copointed (Strict.EnvT e w) where copoint = copoint . Strict.lowerEnvT instance Copointed w => Copointed (Lazy.StoreT s w) where copoint (Lazy.StoreT wf s) = copoint wf s instance Copointed w => Copointed (Strict.StoreT s w) where copoint (Strict.StoreT wf s) = copoint wf s instance Copointed w => Copointed (Memo.StoreT s w) where copoint = copoint . Memo.lowerStoreT
<filename>src/interlocked.h // Copyright (c) 2004-2020 <NAME> / LittleWing Company Limited. // See LICENSE file for terms and conditions of use. #ifndef INTERLOCKED_H_INCLUDED #define INTERLOCKED_H_INCLUDED #include "core.h" inline int32_t interlocked_exchange_int32(volatile int32_t* target, int32_t value) { __asm__ __volatile__ ("xchgl %0, %1" : "+r" (value), "+m" (*target) : : "memory"); return value; } /* inline int32_t interlocked_compare_exchange(volatile int32_t* target, int32_t exchange, int32_t compare) { int32_t value; __asm__ __volatile__("lock; cmpxchgl %1, %2" : "=a" (value) : "r" (exchange), "m" (*target), "0" (compare) : "memory"); return value; } inline void interlocked_or_uint8(volatile uint8_t* target, uint8_t bits) { __asm__ __volatile__ ("lock; orb %1, %0" : "+m" (*target) : "r" (bits) : "memory"); } inline void interlocked_add_int32(volatile int32_t* target, int32_t value) { __asm__ __volatile__ ("lock; addl %1, %0" : "+m" (*target) : "r" (value) : "memory"); } */ #endif /* typedef int32_t spinlock_t; #define SPINLOCK_LOOP_MAX 1000 inline void spin_lock(volatile spinlock_t* lock) { while (interlocked_exchange_int32(lock, 1)) { int n = SPINLOCK_LOOP_MAX; do { __asm__ ("pause"); } while ((--n) & (*lock)); if (*lock) usleep(1); } } inline void spin_unlock(spinlock_t* lock) { *lock = 0; } inline int32_t i386_atomic_exchange(volatile int32_t* the_value, int32_t new_value) { int32_t old_value; __asm__ __volatile__ ("xchg %0,(%2)" : "=r" (old_value) : "0" (new_value), "r" (the_value)); return old_value; } inline void i386_atomic_or(volatile uint8_t* the_value, uint8_t bits) { __asm__ __volatile__ ("lock;or %0,%1" : : "r" (bits), "m" (*the_value) : "memory"); } */
<reponame>zealoussnow/chromium<gh_stars>100-1000 // Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SPECULATION_RULES_DOCUMENT_SPECULATION_RULES_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_SPECULATION_RULES_DOCUMENT_SPECULATION_RULES_H_ #include "third_party/blink/public/mojom/speculation_rules/speculation_rules.mojom-blink.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/speculation_rules/speculation_rule_set.h" #include "third_party/blink/renderer/platform/heap/collection_support/heap_vector.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" #include "third_party/blink/renderer/platform/heap/heap.h" #include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" #include "third_party/blink/renderer/platform/supplementable.h" namespace blink { // This corresponds to the document's list of speculation rule sets. // // Updates are pushed asynchronously. class CORE_EXPORT DocumentSpeculationRules : public GarbageCollected<DocumentSpeculationRules>, public Supplement<Document> { public: static const char kSupplementName[]; static DocumentSpeculationRules& From(Document&); static DocumentSpeculationRules* FromIfExists(Document&); explicit DocumentSpeculationRules(Document&); const HeapVector<Member<SpeculationRuleSet>>& rule_sets() const { return rule_sets_; } // Appends a newly added rule set. void AddRuleSet(SpeculationRuleSet*); void Trace(Visitor*) const override; private: // Retrieves a valid proxy to the speculation host in the browser. // May be null if the execution context does not exist. mojom::blink::SpeculationHost* GetHost(); // Pushes the current speculation candidates to the browser, immediately. void UpdateSpeculationCandidates(); HeapVector<Member<SpeculationRuleSet>> rule_sets_; HeapMojoRemote<mojom::blink::SpeculationHost> host_; bool has_pending_update_ = false; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_SPECULATION_RULES_DOCUMENT_SPECULATION_RULES_H_
// GetGinAccounts returns a gin.Accounts struct with values pulled from a Config struct func GetGinAccounts(config *Config) gin.Accounts { a := make(gin.Accounts) for _, user := range config.Users { a[user.Name] = user.Password } return a }
In 2006, Ron Suskind published “The One Percent Doctrine,” a book about the U.S. war on terrorists after 9/11. The title was drawn from an assessment by then-Vice President Dick Cheney , who, in the face of concerns that a Pakistani scientist was offering nuclear-weapons expertise to Al Qaeda , reportedly declared: “If there’s a 1% chance that Pakistani scientists are helping Al Qaeda build or develop a nuclear weapon, we have to treat it as a certainty in terms of our response.” Cheney contended that the U.S. had to confront a very new type of threat: a “low-probability, high-impact event.” Soon after Suskind’s book came out, the legal scholar Cass Sunstein , who then was at the University of Chicago , pointed out that Mr. Cheney seemed to be endorsing the same “precautionary principle” that also animated environmentalists. Sunstein wrote in his blog: “According to the Precautionary Principle, it is appropriate to respond aggressively to low-probability, high-impact events — such as climate change . Indeed, another vice president — Al Gore — can be understood to be arguing for a precautionary principle for climate change (though he believes that the chance of disaster is well over 1 percent).” Of course, Mr. Cheney would never accept that analogy. Indeed, many of the same people who defend Mr. Cheney’s One Percent Doctrine on nukes tell us not to worry at all about catastrophic global warming, where the odds are, in fact, a lot higher than 1 percent, if we stick to business as usual. That is unfortunate, because Cheney’s instinct is precisely the right framework with which to think about the climate issue — and this whole “climategate” controversy as well. “Climategate” was triggered on Nov. 17 when an unidentified person hacked into the e-mails and data files of the University of East Anglia’s Climatic Research Unit, one of the leading climate science centers in the world — and then posted them on the Internet. In a few instances, they revealed some leading climatologists seemingly massaging data to show more global warming and excluding contradictory research. Advertisement Continue reading the main story Frankly, I found it very disappointing to read a leading climate scientist writing that he used a “trick” to “hide” a putative decline in temperatures or was keeping contradictory research from getting a proper hearing. Yes, the climate-denier community, funded by big oil , has published all sorts of bogus science for years — and the world never made a fuss. That, though, is no excuse for serious climatologists not adhering to the highest scientific standards at all times. Photo That said, be serious: The evidence that our planet, since the Industrial Revolution, has been on a broad warming trend outside the normal variation patterns — with periodic micro-cooling phases — has been documented by a variety of independent research centers.
def create_neurons(self, n: int, row: int, x_sep: int, diameter: int) -> list: out = [] if n % 2 == 0: num_on_each_side = n / 2 - 1 offset = x_sep * num_on_each_side offset += diameter + ((x_sep - diameter) / 2) else: num_on_each_side = floor(n / 2) offset = x_sep * num_on_each_side offset += diameter / 2 initial_x = int(self.width / 2 - offset) initial_y = int((self.height / 4) * (row + 1)) initial_y -= int(diameter / 2) for i in range(n): start_x = initial_x + (x_sep * i) start_y = initial_y out.append(self.canvas.create_oval( ((start_x, start_y), (start_x + diameter, start_y + diameter)), fill=LINEAR[0], tag='neuron' )) return out
/** createDictFromFiles() : * Based on type of param given, train dictionary using the corresponding algorithm * @return dictInfo containing dictionary buffer and dictionary size */ dictInfo* createDictFromFiles(sampleInfo *info, unsigned maxDictSize, ZDICT_random_params_t *randomParams, ZDICT_cover_params_t *coverParams, ZDICT_legacy_params_t *legacyParams, ZDICT_fastCover_params_t *fastParams) { unsigned const displayLevel = randomParams ? randomParams->zParams.notificationLevel : coverParams ? coverParams->zParams.notificationLevel : legacyParams ? legacyParams->zParams.notificationLevel : fastParams ? fastParams->zParams.notificationLevel : DEFAULT_DISPLAYLEVEL; void* const dictBuffer = malloc(maxDictSize); dictInfo* dInfo = NULL; if (!dictBuffer) EXM_THROW(12, "not enough memory for trainFromFiles"); { size_t dictSize; if(randomParams) { dictSize = ZDICT_trainFromBuffer_random(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, *randomParams); }else if(coverParams) { if (!coverParams->d || !coverParams->k){ dictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, coverParams); } else { dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, *coverParams); } } else if(legacyParams) { dictSize = ZDICT_trainFromBuffer_legacy(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, *legacyParams); } else if(fastParams) { if (!fastParams->d || !fastParams->k) { dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, fastParams); } else { dictSize = ZDICT_trainFromBuffer_fastCover(dictBuffer, maxDictSize, info->srcBuffer, info->samplesSizes, info->nbSamples, *fastParams); } } else { dictSize = 0; } if (ZDICT_isError(dictSize)) { DISPLAYLEVEL(1, "dictionary training failed : %s \n", ZDICT_getErrorName(dictSize)); free(dictBuffer); return dInfo; } dInfo = (dictInfo *)malloc(sizeof(dictInfo)); dInfo->dictBuffer = dictBuffer; dInfo->dictSize = dictSize; } return dInfo; }
/** * Git History generates an event when it is installed, updated, or uninstalled, that is anonymous, non-personal, and cannot be correlated. * - Each event only contains the Git History and Visual Studio Code version numbers, and a 256 bit cryptographically strong pseudo-random nonce. * - The two version numbers recorded in these events only allow aggregate compatibility information to be generated (e.g. 50% of users are * using Visual Studio Code >= 1.41.0). These insights enable Git History to utilise the latest features of Visual Studio Code as soon as * the majority of users are using a compatible version. The data cannot, and will not, be used for any other purpose. * - Full details are available at: https://api.mhutchie.com/vscode-git-graph/about */ import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import { LifeCycleStage, LifeCycleState, generateNonce, getDataDirectory, getLifeCycleStateInDirectory, saveLifeCycleStateInDirectory, sendQueue } from './utils'; import { getExtensionVersion } from '../utils'; /** * Run on startup to detect if Git History has been installed or updated, and if so generate an event. * @param extensionContext The extension context of Git History. */ export async function onStartUp(extensionContext: vscode.ExtensionContext) { if (vscode.env.sessionId === 'someValue.sessionId') { // Extension is running in the Extension Development Host, don't proceed. return; } let state = await getLifeCycleStateInDirectory(extensionContext.globalStoragePath); if (state !== null && !state.apiAvailable) { // The API is no longer available, don't proceed. return; } const versions = { extension: await getExtensionVersion(extensionContext), vscode: vscode.version }; if (state === null || state.current.extension !== versions.extension) { // This is the first startup after installing Git History, or Git History has been updated since the last startup. const nonce = await getNonce(); if (state === null) { // Install state = { previous: null, current: versions, apiAvailable: true, queue: [{ stage: LifeCycleStage.Install, extension: versions.extension, vscode: versions.vscode, nonce: nonce }], attempts: 1 }; } else { // Update state.previous = state.current; state.current = versions; state.queue.push({ stage: LifeCycleStage.Update, from: state.previous, to: state.current, nonce: nonce }); state.attempts = 1; } await saveLifeCycleState(extensionContext, state); state.apiAvailable = await sendQueue(state.queue); state.queue = []; await saveLifeCycleState(extensionContext, state); } else if (state.queue.length > 0 && state.attempts < 2) { // There are one or more events in the queue that previously failed to send, send them state.attempts++; await saveLifeCycleState(extensionContext, state); state.apiAvailable = await sendQueue(state.queue); state.queue = []; await saveLifeCycleState(extensionContext, state); } } /** * Saves the life cycle state to the extensions global storage directory (for use during future updates), * and to a directory in this Git History installation (for use during future uninstalls). * @param extensionContext The extension context of Git History. * @param state The state to save. */ function saveLifeCycleState(extensionContext: vscode.ExtensionContext, state: LifeCycleState) { return Promise.all([ saveLifeCycleStateInDirectory(extensionContext.globalStoragePath, state), saveLifeCycleStateInDirectory(getDataDirectory(), state) ]); } /** * Get a nonce generated for this installation of Git History. * @returns A 256 bit cryptographically strong pseudo-random nonce. */ function getNonce() { return new Promise<string>((resolve, reject) => { const dir = getDataDirectory(); const file = path.join(dir, 'lock.json'); fs.mkdir(dir, (err) => { if (err) { if (err.code === 'EEXIST') { // The directory already exists, attempt to read the previously created data fs.readFile(file, (err, data) => { if (err) { // Unable to read the file, reject reject(); } else { try { // Resolve to the previously generated nonce resolve(JSON.parse(data.toString()).nonce); } catch (_) { reject(); } } }); } else { // An unexpected error occurred, reject reject(); } } else { // The directory was created, generate a nonce const nonce = generateNonce(); fs.writeFile(file, JSON.stringify({ nonce: nonce }), (err) => { if (err) { // Unable to save data reject(); } else { // Nonce successfully saved, resolve to it resolve(nonce); } }); } }); }); }
/** * author: lx * date: 15-8-27 * * request using volley, with returned data parsed into a JsonHolder object. */ public class VolleyJsonRequest<T> extends VolleyStringRequest<T> { private static Gson sGson = new Gson(); private TypeToken<T> mTypeToken; public VolleyJsonRequest(String url, Map<String, String> params, TypeToken<T> typeToken) { super(url, params); mTypeToken = typeToken; } @Override protected T parseResult(@NonNull String data) { return sGson.fromJson(data, mTypeToken.getType()); } }
from django.db import models from rdmo.core.managers import (AvailabilityManagerMixin, AvailabilityQuerySetMixin, CurrentSiteManagerMixin, CurrentSiteQuerySetMixin, GroupsManagerMixin, GroupsQuerySetMixin) class CatalogQuestionSet(CurrentSiteQuerySetMixin, GroupsQuerySetMixin, AvailabilityQuerySetMixin, models.QuerySet): def filter_catalog(self, catalog): return self.filter(models.Q(catalogs=None) | models.Q(catalogs=catalog)) class CatalogManager(CurrentSiteManagerMixin, GroupsManagerMixin, AvailabilityManagerMixin, models.Manager): def get_queryset(self): return CatalogQuestionSet(self.model, using=self._db) def filter_catalog(self, catalog): return self.get_queryset().filter_catalog(catalog) class QuestionSetQuerySet(models.QuerySet): def order_by_catalog(self, catalog): return self.filter(section__catalog=catalog, questionset=None).order_by('section__order', 'order') def filter_by_catalog(self, catalog): return self.filter(section__catalog=catalog) class QuestionSetManager(models.Manager): def get_queryset(self): return QuestionSetQuerySet(self.model, using=self._db) def order_by_catalog(self, catalog): return self.get_queryset().order_by_catalog(catalog) def filter_by_catalog(self, catalog): return self.get_queryset().filter_by_catalog(catalog) class QuestionQuerySet(models.QuerySet): def order_by_catalog(self, catalog): return self.filter(questionset__section__catalog=catalog).order_by('questionset__section__order', 'questionset__order', 'order') def filter_by_catalog(self, catalog): return self.filter(questionset__section__catalog=catalog) class QuestionManager(models.Manager): def get_queryset(self): return QuestionQuerySet(self.model, using=self._db) def order_by_catalog(self, catalog): return self.get_queryset().order_by_catalog(catalog) def filter_by_catalog(self, catalog): return self.get_queryset().filter_by_catalog(catalog)
CLOSE The Fairfield brewery will hold an anniversary celebration this weekend. 10/13/16 Michael Izzo Anniversary celebration this weekend at brewery Buy Photo Cricket Hill Brewing in Fairfield celebrates their 15th anniversary. Founder Rick Reed and co-owner Ed Gangi talk about the milestone and the beer. MOR 1015 Cricket Hill Brewing turns 15 (Photo: Karen Mancinelli, Karen Mancinelli)Buy Photo FAIRFIELD – Rick Reed still remembers brewing his first – and still favorite – beer at his 15-barrel brewhouse. It was 2001, and he was making what would become a Cricket Hill staple, the East Coast Lager. Lagers aren’t typically brewed by small breweries because they take significantly longer than ales to make, about six weeks. But time was all Reed had when he was opening up 15 years ago. “We had the space and all the licensing we needed to open except for the background check, and then 9/11 hit and we weren’t high on anyone’s priority list,” Reed said. “So we had all the time in the world and didn’t have to worry about wasting precious tank time, so why not make a lager? Waiting for that background check almost ruined us, but we got the lager out of it.” A decade and a half later, Cricket Hill Brewing continues to thrive, creating new brews and expanding its distribution. And this weekend at the recently-expanded tasting room on Kulick Road in Fairfield, Reed will celebrate his brewery’s 15th anniversary with the release of Fiestbeir – an Oktoberfest Marzen style lager featuring German Munich malt and Sterling Hops – on draft and in bottles. There will also be a dozen other Cricket Hill brews on tap, as well as special anniversary merchandise for sale. Friday will feature live music, a staple for the tasting room. While there will be plenty to cheer this weekend at Cricket Hill, Reed, founder and co-owner of the brewery, still remembers how difficult it was launching the brewery all those years ago. “The first few years were rough. New Jersey wasn’t ready for microbreweries like they are now. I worried we were going to have to close every single day,” Reed said. “When we opened we were the sixth brewery in New Jersey, and the first in five years up to that point. Now with the changes in brewing laws there are 64.” Fifteen years later Cricket Hill is on tap and for sale in hundreds of stores, bars, and restaurants. Reed said it’s a big advantage to have a decade-plus jump on his fellow brewers. “New Jersey has caught up. We’re interested in craft beer now,” Reed said. “And after 15 years of refining and tweaking, we’ve got a great, balanced lineup of beers.” Until a year ago, Cricket Hill only bottled the four year-round and three seasonal selections. But they now have bottle releases for all of their offerings, with just a select few tasting room only specials remaining unbottled. “We’re inventing new things all of the time, using bourbon and wine barrels to age stouts and tripels,” Reed said. “But the year-rounders will never change. Those are four solid citizens.” Those citizens are the lager, American Pale Ale, Hopnotic IPA, and Colonel Blides ESB, named for the owner of a machine shop next door, who has helped repair several Cricket Hill equipment malfunctions through the years. “My advice to anyone opening up a brewery,” Reed said, “Do it next to a machine shop.” Reed said he enjoys all of his beers except for a recently made sour, his least favorite style. “Other people like it but I’m not a fan. They brewed that one without telling me,” Reed said. “Me, I’m a lager guy. I’ll take my East Coast Lager every day.” Upcoming releases include the sour and a bourbon barrel-aged imperial porter. “We’re at a place now where we’re trying to build our brand,” co-owner Ed Gangi said. “Coming up with new beer.” Those new additions include the Schnick Schnack session sour, Brew Jitsu session IPA, and Soggy Sack wet hop ale. Buy Photo Cricket Hill Brewing owners Ed Gangi and Rick Reed, who founded the company, near one of the bourbon barrels where they age some types of beer. Cricket Hill Brewing in Fairfield celebrates their 15th anniversary. Founder Rick Reed and co-owner Ed Gangi talk about the milestone and the beer. MOR 1015 Cricket Hill Brewing turns 15 (Photo: Karen Mancinelli, Karen Mancinelli) Gangi started at Cricket Hill as a volunteer in 2008 and ended up buying into the business a few years ago. “He makes my life a whole lot easier,” Reed said while sipping a lager. “Quality control.” Gangi praised Reed for the legacy he’s forged in the beer industry in his first 15 years professionally brewing. “A lot of people that now work for other breweries – 15 least that we’re aware of – started here,” Gangi said. “Rick’s know in the industry for helping out.” While more fermenters have been added, Cricket Hill remains the same 15-barrel brew house it was a 15 years earlier, bottling on-site and self-distributing. And with the new additions to the facility, Reed said he has no plans to leave what he calls the alcohol capital of New Jersey in Fairfield, home to two breweries, three distilleries, and a wine-making shop. Buy Photo Founder Rick Reed and co-owner Ed Gangi talk about some of the adventures in bottling with a vintage EnZinger Bottler. Cricket Hill Brewing in Fairfield celebrates their 15th anniversary. Founder Rick Reed and co-owner Ed Gangi talk about the milestone and the beer. MOR 1015 Cricket Hill Brewing turns 15 (Photo: Karen Mancinelli, Karen Mancinelli) “My definition of a craft beer is it all has to be done in one spot,” Reed said. “As soon as you don’t, you’re not craft anymore.” And staying “craft” is something that matters to Reed, who won’t touch a macrobeer. “It used to be all of us vs. the Big Three (Budweiser, Coors and Miller) and we won that battle,” Reed said. “Now, to me, it’s about us microbrewers in New Jersey against other states. Because I’ll put a Jersey beer up against anything in Vermont or Colorado or California.” Reed, who still leads weekend tours at Cricket Hill, has given several passionate speeches on the “battle” against the Big Three. One such speech was posted to YouTube in 2008, when the website was still in its infancy, and accumulated more than 50,000 views. While he can’t guarantee another viral moment, Reed promises there will be more speeches this weekend for anyone who wants to swing by for a pint. Staff Writer Michael Izzo: 973-428-6636; [email protected] If you go : Where: Cricket Hill Brewery, 24 Kulick Road in Fairfield When: Thursday and Friday from 5 to 8 p.m. and Saturday from 1 to 5 p.m. Read or Share this story: http://dailyre.co/2ebpmGI
/* Copyright 2016 The Kubernetes Authors All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "encoding/json" "errors" "fmt" "io" "os" "time" "github.com/spf13/cobra" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/client-go/kubernetes" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/helm/cmd/helm/installer" "k8s.io/helm/pkg/getter" "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/helm/helmpath" "k8s.io/helm/pkg/helm/portforwarder" "k8s.io/helm/pkg/repo" ) const initDesc = ` This command installs Tiller (the Helm server-side component) onto your Kubernetes Cluster and sets up local configuration in $HELM_HOME (default ~/.helm/). As with the rest of the Helm commands, 'helm init' discovers Kubernetes clusters by reading $KUBECONFIG (default '~/.kube/config') and using the default context. To set up just a local environment, use '--client-only'. That will configure $HELM_HOME, but not attempt to connect to a Kubernetes cluster and install the Tiller deployment. When installing Tiller, 'helm init' will attempt to install the latest released version. You can specify an alternative image with '--tiller-image'. For those frequently working on the latest code, the flag '--canary-image' will install the latest pre-release version of Tiller (e.g. the HEAD commit in the GitHub repository on the master branch). To dump a manifest containing the Tiller deployment YAML, combine the '--dry-run' and '--debug' flags. ` const ( stableRepository = "stable" localRepository = "local" localRepositoryIndexFile = "index.yaml" ) var ( stableRepositoryURL = "https://kubernetes-charts.storage.googleapis.com" // This is the IPv4 loopback, not localhost, because we have to force IPv4 // for Dockerized Helm: https://github.com/kubernetes/helm/issues/1410 localRepositoryURL = "http://127.0.0.1:8879/charts" ) type initCmd struct { image string clientOnly bool canary bool upgrade bool namespace string dryRun bool forceUpgrade bool skipRefresh bool out io.Writer client helm.Interface home helmpath.Home opts installer.Options kubeClient kubernetes.Interface serviceAccount string maxHistory int replicas int wait bool } func newInitCmd(out io.Writer) *cobra.Command { i := &initCmd{out: out} cmd := &cobra.Command{ Use: "init", Short: "initialize Helm on both client and server", Long: initDesc, RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 0 { return errors.New("This command does not accept arguments") } i.namespace = settings.TillerNamespace i.home = settings.Home i.client = ensureHelmClient(i.client) return i.run() }, } f := cmd.Flags() f.StringVarP(&i.image, "tiller-image", "i", "", "override Tiller image") f.BoolVar(&i.canary, "canary-image", false, "use the canary Tiller image") f.BoolVar(&i.upgrade, "upgrade", false, "upgrade if Tiller is already installed") f.BoolVar(&i.forceUpgrade, "force-upgrade", false, "force upgrade of Tiller to the current helm version") f.BoolVarP(&i.clientOnly, "client-only", "c", false, "if set does not install Tiller") f.BoolVar(&i.dryRun, "dry-run", false, "do not install local or remote") f.BoolVar(&i.skipRefresh, "skip-refresh", false, "do not refresh (download) the local repository cache") f.BoolVar(&i.wait, "wait", false, "block until Tiller is running and ready to receive requests") f.BoolVar(&tlsEnable, "tiller-tls", false, "install Tiller with TLS enabled") f.BoolVar(&tlsVerify, "tiller-tls-verify", false, "install Tiller with TLS enabled and to verify remote certificates") f.StringVar(&tlsKeyFile, "tiller-tls-key", "", "path to TLS key file to install with Tiller") f.StringVar(&tlsCertFile, "tiller-tls-cert", "", "path to TLS certificate file to install with Tiller") f.StringVar(&tlsCaCertFile, "tls-ca-cert", "", "path to CA root certificate") f.StringVar(&stableRepositoryURL, "stable-repo-url", stableRepositoryURL, "URL for stable repository") f.StringVar(&localRepositoryURL, "local-repo-url", localRepositoryURL, "URL for local repository") f.BoolVar(&i.opts.EnableHostNetwork, "net-host", false, "install Tiller with net=host") f.StringVar(&i.serviceAccount, "service-account", "", "name of service account") f.IntVar(&i.maxHistory, "history-max", 0, "limit the maximum number of revisions saved per release. Use 0 for no limit.") f.IntVar(&i.replicas, "replicas", 1, "amount of tiller instances to run on the cluster") f.StringVar(&i.opts.NodeSelectors, "node-selectors", "", "labels to specify the node on which Tiller is installed (app=tiller,helm=rocks)") f.VarP(&i.opts.Output, "output", "o", "skip installation and output Tiller's manifest in specified format (json or yaml)") f.StringArrayVar(&i.opts.Values, "override", []string{}, "override values for the Tiller Deployment manifest (can specify multiple or separate values with commas: key1=val1,key2=val2)") return cmd } // tlsOptions sanitizes the tls flags as well as checks for the existence of required // tls files indicated by those flags, if any. func (i *initCmd) tlsOptions() error { i.opts.EnableTLS = tlsEnable || tlsVerify i.opts.VerifyTLS = tlsVerify if i.opts.EnableTLS { missing := func(file string) bool { _, err := os.Stat(file) return os.IsNotExist(err) } if i.opts.TLSKeyFile = tlsKeyFile; i.opts.TLSKeyFile == "" || missing(i.opts.TLSKeyFile) { return errors.New("missing required TLS key file") } if i.opts.TLSCertFile = tlsCertFile; i.opts.TLSCertFile == "" || missing(i.opts.TLSCertFile) { return errors.New("missing required TLS certificate file") } if i.opts.VerifyTLS { if i.opts.TLSCaCertFile = tlsCaCertFile; i.opts.TLSCaCertFile == "" || missing(i.opts.TLSCaCertFile) { return errors.New("missing required TLS CA file") } } } return nil } // run initializes local config and installs Tiller to Kubernetes cluster. func (i *initCmd) run() error { if err := i.tlsOptions(); err != nil { return err } i.opts.Namespace = i.namespace i.opts.UseCanary = i.canary i.opts.ImageSpec = i.image i.opts.ForceUpgrade = i.forceUpgrade i.opts.ServiceAccount = i.serviceAccount i.opts.MaxHistory = i.maxHistory i.opts.Replicas = i.replicas writeYAMLManifest := func(apiVersion, kind, body string, first, last bool) error { w := i.out if !first { // YAML starting document boundary marker if _, err := fmt.Fprintln(w, "---"); err != nil { return err } } if _, err := fmt.Fprintln(w, "apiVersion:", apiVersion); err != nil { return err } if _, err := fmt.Fprintln(w, "kind:", kind); err != nil { return err } if _, err := fmt.Fprint(w, body); err != nil { return err } if !last { return nil } // YAML ending document boundary marker _, err := fmt.Fprintln(w, "...") return err } if len(i.opts.Output) > 0 { var body string var err error const tm = `{"apiVersion":"extensions/v1beta1","kind":"Deployment",` if body, err = installer.DeploymentManifest(&i.opts); err != nil { return err } switch i.opts.Output.String() { case "json": var out bytes.Buffer jsonb, err := yaml.ToJSON([]byte(body)) if err != nil { return err } buf := bytes.NewBuffer(make([]byte, 0, len(tm)+len(jsonb)-1)) buf.WriteString(tm) // Drop the opening object delimiter ('{'). buf.Write(jsonb[1:]) if err := json.Indent(&out, buf.Bytes(), "", " "); err != nil { return err } if _, err = i.out.Write(out.Bytes()); err != nil { return err } return nil case "yaml": if err := writeYAMLManifest("extensions/v1beta1", "Deployment", body, true, false); err != nil { return err } return nil default: return fmt.Errorf("unknown output format: %q", i.opts.Output) } } if settings.Debug { var body string var err error // write Deployment manifest if body, err = installer.DeploymentManifest(&i.opts); err != nil { return err } if err := writeYAMLManifest("extensions/v1beta1", "Deployment", body, true, false); err != nil { return err } // write Service manifest if body, err = installer.ServiceManifest(i.namespace); err != nil { return err } if err := writeYAMLManifest("v1", "Service", body, false, !i.opts.EnableTLS); err != nil { return err } // write Secret manifest if i.opts.EnableTLS { if body, err = installer.SecretManifest(&i.opts); err != nil { return err } if err := writeYAMLManifest("v1", "Secret", body, false, true); err != nil { return err } } } if i.dryRun { return nil } if err := ensureDirectories(i.home, i.out); err != nil { return err } if err := ensureDefaultRepos(i.home, i.out, i.skipRefresh); err != nil { return err } if err := ensureRepoFileFormat(i.home.RepositoryFile(), i.out); err != nil { return err } fmt.Fprintf(i.out, "$HELM_HOME has been configured at %s.\n", settings.Home) if !i.clientOnly { if i.kubeClient == nil { _, c, err := getKubeClient(settings.KubeContext) if err != nil { return fmt.Errorf("could not get kubernetes client: %s", err) } i.kubeClient = c } if err := installer.Install(i.kubeClient, &i.opts); err != nil { if !apierrors.IsAlreadyExists(err) { return fmt.Errorf("error installing: %s", err) } if i.upgrade { if err := installer.Upgrade(i.kubeClient, &i.opts); err != nil { return fmt.Errorf("error when upgrading: %s", err) } if err := i.ping(); err != nil { return err } fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been upgraded to the current version.") } else { fmt.Fprintln(i.out, "Warning: Tiller is already installed in the cluster.\n"+ "(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)") } } else { fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been installed into your Kubernetes Cluster.\n\n"+ "Please note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.\n"+ "For more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation") } if err := i.ping(); err != nil { return err } } else { fmt.Fprintln(i.out, "Not installing Tiller due to 'client-only' flag having been set") } fmt.Fprintln(i.out, "Happy Helming!") return nil } func (i *initCmd) ping() error { if i.wait { _, kubeClient, err := getKubeClient(settings.KubeContext) if err != nil { return err } if !watchTillerUntilReady(settings.TillerNamespace, kubeClient, settings.TillerConnectionTimeout) { return fmt.Errorf("tiller was not found. polling deadline exceeded") } // establish a connection to Tiller now that we've effectively guaranteed it's available if err := setupConnection(); err != nil { return err } i.client = newClient() if err := i.client.PingTiller(); err != nil { return fmt.Errorf("could not ping Tiller: %s", err) } } return nil } // ensureDirectories checks to see if $HELM_HOME exists. // // If $HELM_HOME does not exist, this function will create it. func ensureDirectories(home helmpath.Home, out io.Writer) error { configDirectories := []string{ home.String(), home.Repository(), home.Cache(), home.LocalRepository(), home.Plugins(), home.Starters(), home.Archive(), } for _, p := range configDirectories { if fi, err := os.Stat(p); err != nil { fmt.Fprintf(out, "Creating %s \n", p) if err := os.MkdirAll(p, 0755); err != nil { return fmt.Errorf("Could not create %s: %s", p, err) } } else if !fi.IsDir() { return fmt.Errorf("%s must be a directory", p) } } return nil } func ensureDefaultRepos(home helmpath.Home, out io.Writer, skipRefresh bool) error { repoFile := home.RepositoryFile() if fi, err := os.Stat(repoFile); err != nil { fmt.Fprintf(out, "Creating %s \n", repoFile) f := repo.NewRepoFile() sr, err := initStableRepo(home.CacheIndex(stableRepository), out, skipRefresh, home) if err != nil { return err } lr, err := initLocalRepo(home.LocalRepository(localRepositoryIndexFile), home.CacheIndex("local"), out, home) if err != nil { return err } f.Add(sr) f.Add(lr) if err := f.WriteFile(repoFile, 0644); err != nil { return err } } else if fi.IsDir() { return fmt.Errorf("%s must be a file, not a directory", repoFile) } return nil } func initStableRepo(cacheFile string, out io.Writer, skipRefresh bool, home helmpath.Home) (*repo.Entry, error) { fmt.Fprintf(out, "Adding %s repo with URL: %s \n", stableRepository, stableRepositoryURL) c := repo.Entry{ Name: stableRepository, URL: stableRepositoryURL, Cache: cacheFile, } r, err := repo.NewChartRepository(&c, getter.All(settings)) if err != nil { return nil, err } if skipRefresh { return &c, nil } // In this case, the cacheFile is always absolute. So passing empty string // is safe. if err := r.DownloadIndexFile(""); err != nil { return nil, fmt.Errorf("Looks like %q is not a valid chart repository or cannot be reached: %s", stableRepositoryURL, err.Error()) } return &c, nil } func initLocalRepo(indexFile, cacheFile string, out io.Writer, home helmpath.Home) (*repo.Entry, error) { if fi, err := os.Stat(indexFile); err != nil { fmt.Fprintf(out, "Adding %s repo with URL: %s \n", localRepository, localRepositoryURL) i := repo.NewIndexFile() if err := i.WriteFile(indexFile, 0644); err != nil { return nil, err } //TODO: take this out and replace with helm update functionality if err := createLink(indexFile, cacheFile, home); err != nil { return nil, err } } else if fi.IsDir() { return nil, fmt.Errorf("%s must be a file, not a directory", indexFile) } return &repo.Entry{ Name: localRepository, URL: localRepositoryURL, Cache: cacheFile, }, nil } func ensureRepoFileFormat(file string, out io.Writer) error { r, err := repo.LoadRepositoriesFile(file) if err == repo.ErrRepoOutOfDate { fmt.Fprintln(out, "Updating repository file format...") if err := r.WriteFile(file, 0644); err != nil { return err } } return nil } // watchTillerUntilReady waits for the tiller pod to become available. This is useful in situations where we // want to wait before we call New(). // // Returns true if it exists. If the timeout was reached and it could not find the pod, it returns false. func watchTillerUntilReady(namespace string, client kubernetes.Interface, timeout int64) bool { deadlinePollingChan := time.NewTimer(time.Duration(timeout) * time.Second).C checkTillerPodTicker := time.NewTicker(500 * time.Millisecond) doneChan := make(chan bool) defer checkTillerPodTicker.Stop() go func() { for range checkTillerPodTicker.C { _, err := portforwarder.GetTillerPodName(client.CoreV1(), namespace) if err == nil { doneChan <- true break } } }() for { select { case <-deadlinePollingChan: return false case <-doneChan: return true } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.proxy.frontend.postgresql.command; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.PostgreSQLCommandPacket; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.PostgreSQLCommandPacketType; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.extended.PostgreSQLPreparedStatementRegistry; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.extended.execute.PostgreSQLComExecutePacket; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.extended.parse.PostgreSQLComParsePacket; import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.simple.PostgreSQLComQueryPacket; import org.apache.shardingsphere.proxy.backend.session.ConnectionSession; import org.apache.shardingsphere.proxy.frontend.command.executor.CommandExecutor; import org.apache.shardingsphere.proxy.frontend.postgresql.command.generic.PostgreSQLComTerminationExecutor; import org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.execute.PostgreSQLComExecuteExecutor; import org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.parse.PostgreSQLComParseExecutor; import org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extended.sync.PostgreSQLComSyncExecutor; import org.apache.shardingsphere.proxy.frontend.postgresql.command.query.simple.PostgreSQLComQueryExecutor; import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.EmptyStatement; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public final class PostgreSQLCommandExecutorFactoryTest { @Mock private ConnectionSession connectionSession; @Mock private PostgreSQLConnectionContext connectionContext; @Before public void setup() { PostgreSQLPreparedStatementRegistry.getInstance().register(1); PostgreSQLPreparedStatementRegistry.getInstance().register(1, "2", "", new EmptyStatement(), Collections.emptyList()); } @Test public void assertNewInstance() throws SQLException { Collection<InputOutput> inputOutputs = Arrays.asList( new InputOutput(PostgreSQLCommandPacketType.SIMPLE_QUERY, PostgreSQLComQueryPacket.class, PostgreSQLComQueryExecutor.class), new InputOutput(PostgreSQLCommandPacketType.PARSE_COMMAND, PostgreSQLComParsePacket.class, PostgreSQLComParseExecutor.class), new InputOutput(PostgreSQLCommandPacketType.EXECUTE_COMMAND, PostgreSQLComExecutePacket.class, PostgreSQLComExecuteExecutor.class), new InputOutput(PostgreSQLCommandPacketType.SYNC_COMMAND, null, PostgreSQLComSyncExecutor.class), new InputOutput(PostgreSQLCommandPacketType.TERMINATE, null, PostgreSQLComTerminationExecutor.class) ); for (InputOutput inputOutput : inputOutputs) { Class<? extends PostgreSQLCommandPacket> commandPacketClass = inputOutput.getCommandPacketClass(); if (null == commandPacketClass) { commandPacketClass = PostgreSQLCommandPacket.class; } PostgreSQLCommandPacket packet = preparePacket(commandPacketClass); CommandExecutor actual = PostgreSQLCommandExecutorFactory.newInstance(inputOutput.getCommandPacketType(), packet, connectionSession, connectionContext); assertThat(actual, instanceOf(inputOutput.getResultClass())); } } private PostgreSQLCommandPacket preparePacket(final Class<? extends PostgreSQLCommandPacket> commandPacketClass) { PostgreSQLCommandPacket result = mock(commandPacketClass); if (result instanceof PostgreSQLComQueryPacket) { when(((PostgreSQLComQueryPacket) result).getSql()).thenReturn(""); } return result; } @RequiredArgsConstructor @Getter private static final class InputOutput { private final PostgreSQLCommandPacketType commandPacketType; private final Class<? extends PostgreSQLCommandPacket> commandPacketClass; private final Class<? extends CommandExecutor> resultClass; } }
def as_location(self): long_location = self.get_parent_atlas()._get_nodeLocations().elements[self.index] return pyatlas.geometry.location_from_packed_int(long_location)
<gh_stars>0 #include <stdio.h> int main() { short n[3], nn[4]; short i, j, flag; nn[0] = 123; LOOP: if ((nn[1]=nn[0]++) > 329) goto EXIT; nn[2] = 2 * nn[1]; nn[3] = 3 * nn[1]; flag = 1; for (i = 1; i < 4; i++) { for (j = 0; j < 3; j++) { n[j] = nn[i] % 10; if (!(flag&(1<<n[j]))) flag |= (1<<n[j]); else goto LOOP; nn[i] /= 10; } } printf("%d %d %d\n", nn[0]-1, 2*(nn[0]-1), 3*(nn[0]-1)); goto LOOP; EXIT: return 0; }
// Fills the 'buffer' with maximum of 'count' bytes. Actual number of bytes copied into the buffer // is returned. // If local cache buffer doesn't contain enough bytes, then a request to the service for 'count' bytes is sent, // (blocking while receiving response), and the 'buffer' is filled with the returned data (random bytes). // Otherwise, the 'buffer' is filled with locally cached data. // If user requested less then cache size, the cache is refilled and data is returned from the cache. // Upon failure, exceptions are thrown. // Returns: count of bytes (received) copied into the supplied buffer. size_t QRBG::AcquireBytes(byte* buffer, size_t count) throw(ConnectError, CommunicationError, ServiceDenied) { # if defined(PLATFORM_WIN) timeStart = GetTickCount(); # elif defined(PLATFORM_LINUX) gettimeofday(&timeStart, NULL); # endif size_t nCopied = 0; if (count <= inBufferSize) { EnsureCachedEnough(count); nCopied = AcquireBytesFromCache(buffer, count); } else { nCopied = AcquireBytesFromService(buffer, count); } # if defined(PLATFORM_WIN) timeEnd = GetTickCount(); # elif defined(PLATFORM_LINUX) gettimeofday(&timeEnd, NULL); # endif return nCopied; }
def to_spark(self, flatten=True): t = self.expand_types() if flatten: t = t.flatten() return pyspark.sql.DataFrame(t._jt.toDF(Env.hc()._jsql_context), Env.sql_context())
Professional Preparation of Future Teachers of Vocational Training in the Transport Area of Expertise with Use of the Author's Educational Application : The paper presents the content, as well as approaches to the use in the educational process of the author’s Electronic educational methodical complex (EEMC) “Construction of car”. The course is created for students of the speciality 015 Professional education (Transport, the operation and repairing of automobiles). Its content covers general topics including the study of a car engine, electrical equipment and automotive driveline. The created electronic course embraces, in addition to textual material, illustrations, dynamic models, instructions, manuals, textbooks, reference books and glossaries, test material for each topic. Its possibilities of application during lectures, in the course of performing 15 laboratory works, organizing test control of knowledge, as well as for managing students’ independent study activities have been shown. Approaches to expert evaluation of the developed electronic study course by 11 criteria have been disclosed. The directions for further improve-ment of the content and methods of organizing the study and cognitive activity of students when using the course have been highlighted. These include the organization of level assimilation of the material, the creation of an individual educational trajectory of students. A rather high assessment of the developed author’s course received from experts allows it to be used in the system of vocational preparation specialists in the transport area of expertise.
/** * The Address parser should parse an address with a street name, a building * number, and a city name. */ @Test public void testCityParsing() { Address a1 = Address.parse("1234 Foo"); assertNotNull(a1); assertEquals("1234", a1.postcode()); assertEquals("Foo", a1.city()); Address a2 = Address.parse("1234 Foo Bar"); assertNotNull(a2); assertEquals("1234", a2.postcode()); assertEquals("Foo Bar", a2.city()); Address a3 = Address.parse("Foo Road, Foo City"); assertNotNull(a3); assertEquals("Foo Road", a3.street()); assertEquals("Foo City", a3.city()); Address a4 = Address.parse("Foo Road 14 Foo City"); assertNotNull(a4); assertEquals("Foo Road", a4.street()); assertEquals("14", a4.number()); assertEquals("Foo City", a4.city()); Address a5 = Address.parse("Foo 1234 Bar"); assertNotNull(a5); assertEquals("Foo", a5.street()); assertEquals("1234", a5.postcode()); assertEquals("Bar", a5.city()); Address a6 = Address.parse("Foo, 1234 Bar"); assertNotNull(a6); assertEquals("Foo", a6.street()); assertEquals("1234", a6.postcode()); assertEquals("Bar", a6.city()); }
<reponame>TheDayC/ecommerce-microservice import { NextFunction, Request, Response } from 'express'; import {IProduct} from './db'; export interface CustomRequest extends Request { products?: IProduct[]; } export type ExpressFunc = (req: CustomRequest, res: Response, next: NextFunction) => void;
// hexFile reads the given file and decodes the hex data contained in it. // Whitespace and any lines beginning with the # character are ignored. func hexFile(file string) []byte { fileContent, err := ioutil.ReadFile(file) if err != nil { panic(err) } var text []byte for _, line := range bytes.Split(fileContent, []byte("\n")) { line = bytes.TrimSpace(line) if len(line) > 0 && line[0] == '#' { continue } text = append(text, line...) } if bytes.HasPrefix(text, []byte("0x")) { text = text[2:] } data := make([]byte, hex.DecodedLen(len(text))) if _, err := hex.Decode(data, text); err != nil { panic("invalid hex in " + file) } return data }
<reponame>manifoldco/component-plan-matrix<gh_stars>1-10 import { displayTierCost } from './cost'; describe('displayTierCost', () => { it('very cheap', () => { expect(displayTierCost(8000, 'email')).toBe('$0.08 / 10k emails'); }); it('somewhat cheap', () => { expect(displayTierCost(800000, 'email')).toBe('$0.08 / 100 emails'); }); it('expensive', () => { expect(displayTierCost(800000000, 'email')).toBe('$0.80 / email'); }); it('precise', () => { expect(displayTierCost(1303000, 'email')).toBe('$13.03 / 10k emails'); }); it('seconds', () => { expect(displayTierCost(360000, 'second')).toBe('$1.30 / hour'); }); });
Yet another security researcher is poking holes in the security of Mega, this time by pointing out that the confirmation messages e-mailed to new users can in many cases be cracked to reveal their password and take over their Mega accounts. Steve "Sc00bz" Thomas, the researcher who uncovered the weakness, has released a program called MegaCracker that can extract passwords from the link contained in confirmation e-mails. Mega e-mails a link to all new users and requires that they click on it before they can use the cloud-based storage system, which boasts a long roster of encryption and security protections. Security professionals have long considered it taboo to send passwords in either plaintext or as cryptographic hashes in e-mails because of the ease attackers have in intercepting unencrypted messages sent over Internet. Despite that admonishment, the link included in Mega confirmation e-mails contains not only a hash of the password, but it also includes other sensitive data, such as the encrypted master key used to decrypt the files stored in the account. MegaCracker works by isolating the AES-hashed password embedded in the link and attempting to guess the plaintext that was used to generate it. "Since e-mail is unencrypted, anyone listening to the traffic can read the message," Thomas told Ars. "It makes no sense to send a confirmation link with a hash of your password." In addition to the ease of intercepting e-mails as they traverse the Internet, the confirmation link could be recovered by government-backed investigators or others with a legal subpoena. Mega officials didn't immediately respond to a request for comment. On its website, the service said MegaCracker is "An excellent reminder not to use guessable/dictionary passwords, specifically not if your password also serves as the master encryption key to all files that you store on MEGA." A confirmation sent to one Ars reporter looked like this: https://mega.co.nz/#confirmcEkb58OFjQaYsoK5k9Xtabp_0cOLWlBz73NnnrnHvUh5yD0U2QIAKN6earEfPsRjeXJ1cy5mYXJpdmFyQGFyc3RlY2huaWNhLmNvbQlDeXJ1cyBGYXJpdmFyqskhB4hNfxs When converted from base64 into an alternate encoding scheme known as hexadecimal, it looks like this: 70491be7c3858d0698b282b993d5ed69ba7fd1c38b5a5073ef73679eb9c7bd4879c83d14d9020028de9e6ab11f3ec463797275732e6661726976617240617273746563686e6963612e636f6d0943797275732046617269766172aac92107884d7f1b This long string is, in fact, six shorter strings, that include the encrypted master key (70491be7c3858d0698b282b993d5ed69), the AES-hashed user password (ba7fd1c38b5a5073ef73679eb9c7bd48), as well as hashes hexes of the e-mail address (63797275732e6661726976617240617273746563686e6963612e636f6d), user's name (43797275732046617269766172), and two other elements Thomas still hasn't identified. MegaCracker simply isolates the password hash and provides a platform for cracking it. The program requires crackers to supply their own list of word guesses. With the ability to guess 120 to 600 passwords per second it's a bit on the slow side, although it works faster with a precomputed file. With a bit of tweaking, oclHashcat-plus and other standalone password crackers could probably be used crack the hashes much more quickly. Thomas said the inclusion of a password hash and encrypted master key is highly unusual in confirmation e-mails. Similar e-mails sent by Netflix, Amazon, Twitter, and other services send links containing a random value that only the receiver and the server know. An attacker could use MegaCracker to reveal weaker passwords, and then use that passcode to decrypt the encrypted master key. From there, the attacker can take complete control of someone's Mega account and all the encrypted data stored in it. Thomas is just one of the security researchers who has taken Mega's new service to task. Articles posted in the past 24 hours by Forbes and IDG News advised readers to be wary of the encryption provided by the service. Much of the criticism rests on the reliance of in-the-browser encryption from the SSL (secure sockets layer) protocol, which has been repeatedly bypassed over the years, most recently in late 2012. In its response, Mega officials didn't dispute that claim, writing only: "But if you can break SSL, you can break a lot of things that are even more interesting than MEGA." Ars' own critique of the encryption package found that it included some puzzling design choices. Expect to see a steady stream of critiques and fixes in Mega's security hygiene in the coming weeks, as researchers delve in further and Mega engineers respond. As Ars has long counseled, readers would do well to remain highly skeptical of storing anything confidential online unless the encryption has been certified by outside auditors, or at least has been used for a few years with no reports of compromise or serious security flaws. Update After this article was published Mega CTO Mathias Ortmann emailed a statement that indicates anyone who chose a weak password when registering their account has been temporarily stuck with the bad passcode. The statement, which is included in its entirety below, also seems to defend the decision to embed sensitive information in the plain-text emails Mega sends users:
Stable heat and particle flux detachment with efficient particle exhaust in the island divertor of Wendelstein 7-X The island divertor concept is an innovative and promising idea to handle heat and particle exhaust in stellarators. At the Wendelstein 7-X (W7-X) stellarator, this divertor concept plays a central role in the device mission to demonstrate reactor relevant plasma confinement for steady-state time scales of up to 30 minutes in the high-performance campaign (OP2) starting in 2022. During the recently concluded first campaign with the inertially cooled island divertor, a large step in the experimental qualification of this divertor concept has been made. In discharges heated with electron cylotron resonance heating of 5−6 MW, central densities in the range of 0.7−1.2 × 1020 m−3 have been reached in combination with full divertor heat flux detachment. Also, significant neutral gas pressures and neutral compression ratios were shown for the first time in combination with reduced divertor particle flux. The divertor heat loads drop by an order of magnitude from >5 MW m−2 to below 0.5 MW m−2 with increasing density, and substantial compression of neutrals reaching neutral pressure in the sub-divertor volume of >6.0 × 10−4 mbar was seen. These elevated neutral pressure levels can be obtained and maintained with an up to 80% reduction of the particle fluxes onto the divertor target tiles. This discharge scenario was held stably detached for up to 28 seconds, which is equivalent to several hundred energy confinement times τ E and longer than the time scales for current relaxation. No impurity accumulation was seen at constant Z eff ≈ 1.5 and the stored energy stayed constant at levels of W dia  >  600 kJ. The level of neutral pressure and compression reached in this scenario extrapolates well to the steady-state particle exhaust requirements for high-performance steady-state operation in OP2, in which the fully actively cooled high-heat-flux divertor will be available. An overview of this recently discovered divertor regime is given and the status ofthe physics understanding based on modeling of these regimes with the EMC3-EIRENE code is presented.
<reponame>githayu/nicofinder-extension<filename>src/background/getNicoUserSession.ts export async function getNicoUserSession(): Promise<string | void> { return new Promise((resolve) => chrome.cookies.getAll( { domain: 'nicovideo.jp', name: 'user_session', }, (cookies) => { if (!cookies.length) { resolve() } else { resolve(cookies[0].value) } } ) ) }
/** @module index */ export * from './auth'; export * from './build'; export * from './cache'; export * from './config'; export * from './connect'; export * from './count'; export * from './lock'; export * from './log'; export * from './info'; export * from './test'; export { Component } from './Component';
Application of query-based learning to power system static security assessment A query-based learning and inverted neural network methods are developed for static security assessment of power system. By the proposed method, the demand for huge amounts of data to evaluate the security of the power system can be considerably reduced. The inversion algorithm to generate input patterns at the boundaries of the security region is introduced. The query algorithm is used to enhance the accuracy of the boundaries in the areas where more training data are needed. The IEEE-30 bus system is used to test the proposed method.<<ETX>>
// 그룹 멤버들의 이름을 저장하고 원하는 이름을 알려줌 public class ManageName { private final String ONE = "최현정"; private final String TWO = "장해솔"; private final String THREE = "박재민"; private final String FOUR = "고동영"; private final String FIVE = "이정현"; private final String SIX = "류슬기"; private final String SEVEN = "조진형"; private final String EIGHT = "한다은"; private final String NINE = "오진욱"; private final String TEN = "노찬욱"; private final String ELEVEN = "박소현"; private final String TWELVE = "박기범"; private final String THIRTEEN = "최임식"; private final String FOURTEEN = "탁성진"; private final String FIFTEEN = "하진주"; private final String SIXTEEN = "이승윤"; private final String SEVENTEEN = "이범진"; private String name; public void setName(int nameNum) { switch (nameNum) { case 1: name = ONE; break; case 2: name = TWO; break; case 3: name = THREE; break; case 4: name = FOUR; break; case 5: name = FIVE; break; case 6: name = SIX; break; case 7: name = SEVEN; break; case 8: name = EIGHT; break; case 9: name = NINE; break; case 10: name = TEN; break; case 11: name = ELEVEN; break; case 12: name = TWELVE; break; case 13: name = THIRTEEN; break; case 14: name = FOURTEEN; break; case 15: name = FIFTEEN; break; case 16: name = SIXTEEN; break; case 17: name = SEVENTEEN; break; } } public String getName() { return name; } }
<filename>src/Estimators/OperatorEstBase.h ////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2020 QMCPACK developers. // // File developed by: <NAME>, <EMAIL>, Oak Ridge National Laboratory // // File refactored from: OperatorBase.h ////////////////////////////////////////////////////////////////////////////////////// /**@file */ #ifndef QMCPLUSPLUS_OPERATORESTBASE_H #define QMCPLUSPLUS_OPERATORESTBASE_H #include "Particle/ParticleSet.h" #include "OhmmsData/RecordProperty.h" #include "Utilities/RandomGenerator.h" #include "QMCHamiltonians/observable_helper.h" #include "QMCWaveFunctions/OrbitalSetTraits.h" #include "type_traits/DataLocality.h" #include <bitset> namespace qmcplusplus { class DistanceTableData; class TrialWaveFunction; /** @ingroup Estimators * @brief An abstract class for gridded estimators * */ class OperatorEstBase { public: using QMCT = QMCTraits; using MCPWalker = Walker<QMCTraits, PtclOnLatticeTraits>; /** the type in this variant changes based on data locality */ using Data = UPtr<std::vector<QMCT::RealType>>; /// locality for accumulation data DataLocality data_locality_; ///name of this object std::string myName; QMCT::FullPrecRealType get_walkers_weight() const { return walkers_weight_; } ///constructor OperatorEstBase(DataLocality dl); OperatorEstBase(const OperatorEstBase& oth); ///virtual destructor virtual ~OperatorEstBase() = default; /** Accumulate whatever it is you are accumulating with respect to walkers * * This method is assumed to be called from the crowd context * It provides parallelism with respect to computational effort of the estimator * without causing a global sync. * Depending on data locality the accumlation of the result may be different from * the single thread write directly into the OperatorEstimator data. */ virtual void accumulate(RefVector<MCPWalker>& walkers, RefVector<ParticleSet>& psets) = 0; /** Reduce estimator result data from crowds to rank * * This is assumed to be called from only from one thread per crowds->rank * reduction. Implied is this is during a global sync or there is a guarantee * that the crowd operator estimators accumulation data is not being written to. * * There could be concurrent operations inside the scope of the collect call. */ virtual void collect(const RefVector<OperatorEstBase>& oebs); virtual void normalize(QMCT::RealType invToWgt); virtual void startBlock(int steps) = 0; std::vector<QMCT::RealType>& get_data_ref() { return *data_; } Data& get_data() { return data_; }; /*** create and tie OperatorEstimator's observable_helper hdf5 wrapper to stat.h5 file * @param gid hdf5 group to which the observables belong * * The default implementation does nothing. The derived classes which compute * big data, e.g. density, should overwrite this function. */ virtual void registerOperatorEstimator(hid_t gid) {} virtual OperatorEstBase* clone() = 0; /** Write to previously registered observable_helper hdf5 wrapper. * * if you haven't registered Operator Estimator * this will do nothing. */ void write(); /** zero data appropriately for the DataLocality */ void zero(); /** Return the total walker weight for this block */ QMCT::FullPrecRealType get_walkers_weight() { return walkers_weight_; } protected: QMCT::FullPrecRealType walkers_weight_; // convenient Descriptors hdf5 for Operator Estimators only populated for rank scope OperatorEstimator UPtrVector<observable_helper> h5desc_; /** create the typed data block for the Operator. * * this is only slightly better than a byte buffer * it allows easy porting of the legacy implementations * Which wrote into a shared buffer per walker. * And it make's datalocality fairly easy but * more descriptive and safe data structures would be better */ static Data createLocalData(size_t size, DataLocality data_locality); Data data_; }; } // namespace qmcplusplus #endif
/* * IMPORTANT: Method's calls order is crucial. Change it (or not) carefully. */ @Override public void dispose() { super.dispose(); defineMandatoryBorderSpacing(mInnerChartTop, mInnerChartBottom); defineLabelsPosition(mInnerChartTop, mInnerChartBottom); }
def ptr(c_type, val, shape=None): if isiterable(shape) and len(shape) == 2: ptr_obj = ptr_typ(c_type, shape)() for i, row in enumerate(val): for j, element in enumerate(row): ptr_obj[i][j] = val[i][j] return ptr_obj elif isiterable(val): return (c_type*len(val))(*val) else: return POINTER(c_type)(c_type(val))
import Queue from 'bull'; interface Payload { postId: string; } const expirationQueue = new Queue<Payload>( 'post:expiration', { redis: { host: process.env.REDIS_HOST } } ); expirationQueue.process( async ( job ) => { console.log( 'I want to publish and expiration:complete event for postId', job.data.postId ); } ); export { expirationQueue };
#include "bwa_wrapper.h" #include "Pipeline.h" #include "util.h" #include "TestCommon.h" TEST_F(UtilTests, SeqTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; uint64_t start_ts = getUs(); std::stringstream ss; for (int i = 0; i < test_num; i++) { serialize(ss, seqs[i]); } ASSERT_LT(0, ss.str().size()); VLOG(1) << test_num << " seqs (for chain record) has " << ss.str().size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; start_ts = getUs(); bseq1_t* seqs_test = (bseq1_t*)malloc(test_num*sizeof(bseq1_t)); for (int i = 0; i < test_num; i++) { deserialize(ss, seqs_test[i]); } VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; // skip testing } TEST_F(UtilTests, MemChainTest) { int test_num = batch_num > 32 ? 32 : batch_num; // here only test the first 32 to save time for (int i = 0; i < test_num; i++) { mem_chain_v chains = mem_seq2chain_wrapper(aux, seqs); std::stringstream ss; serialize(ss, chains); ASSERT_LT(0, ss.str().size()); mem_chain_v chains_test; deserialize(ss, chains_test); ASSERT_EQ(chains.n, chains_test.n); ASSERT_EQ(chains.m, chains_test.m); for (int j = 0; j < chains.n; j++) { check_mem_chain(chains.a[j], chains_test.a[j]); } // free chains for (int j = 0; j < chains.n; j++) { free(chains.a[j].seeds); free(chains_test.a[j].seeds); } free(chains.a); free(chains_test.a); } } TEST_F(UtilTests, MemAlnregTest) { int test_num = batch_num > 32 ? 32 : batch_num; for (int i = 0; i < test_num; i++) { mem_chain_v chains = mem_seq2chain_wrapper(aux, seqs); mem_alnreg_v alnregs; kv_init(alnregs); for (int j = 0; j < chains.n; j++) { mem_chain2aln( aux->opt, aux->idx->bns, aux->idx->pac, seqs[i].l_seq, (uint8_t*)seqs[i].seq, &chains.a[j], &alnregs); } // serialize mem_alnreg_v std::stringstream ss; serialize(ss, alnregs); ASSERT_LT(0, ss.str().size()); mem_alnreg_v alnregs_test; deserialize(ss, alnregs_test); ASSERT_EQ(alnregs.n, alnregs_test.n); ASSERT_EQ(alnregs.m, alnregs_test.m); for (int j = 0; j < alnregs.n; j++) { check_mem_alnreg(alnregs.a[j], alnregs_test.a[j]); } } } TEST_F(UtilTests, MemChainVFullTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; mem_chain_v* chains_base = (mem_chain_v*)malloc(sizeof(mem_chain_v)*test_num); mem_chain_v* chains_test = (mem_chain_v*)malloc(sizeof(mem_chain_v)*test_num); for (int i = 0; i < test_num; i++) { chains_base[i] = mem_seq2chain_wrapper(aux, seqs); } // start serialization std::stringstream ss; uint64_t start_ts = getUs(); for (int i = 0; i < test_num; i++) { serialize(ss, chains_base[i]); } VLOG(1) << test_num << " chains has " << ss.str().size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; // start deserialization start_ts = getUs(); for (int i = 0; i < test_num; i++) { deserialize(ss, chains_test[i]); } VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; // verify for (int i = 0; i < test_num; i++) { ASSERT_EQ(chains_base[i].n, chains_test[i].n); ASSERT_EQ(chains_base[i].m, chains_test[i].m); for (int j = 0; j < chains_base[i].n; j++) { check_mem_chain(chains_base[i].a[j], chains_test[i].a[j]); // free chains free(chains_base[i].a[j].seeds); free(chains_test[i].a[j].seeds); } free(chains_base[i].a); free(chains_test[i].a); } free(chains_base); free(chains_test); } TEST_F(UtilTests, MemAlnregVFullTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; mem_alnreg_v* aln_base = (mem_alnreg_v*)malloc(test_num*sizeof(mem_alnreg_v)); mem_alnreg_v* aln_test = (mem_alnreg_v*)malloc(test_num*sizeof(mem_alnreg_v)); for (int i = 0; i < test_num; i++) { mem_chain_v chains = mem_seq2chain_wrapper(aux, seqs); kv_init(aln_base[i]); for (int j = 0; j < chains.n; j++) { mem_chain2aln( aux->opt, aux->idx->bns, aux->idx->pac, seqs[i].l_seq, (uint8_t*)seqs[i].seq, &chains.a[j], &aln_base[i]); } } // start serialization std::stringstream ss; uint64_t start_ts = getUs(); for (int i = 0; i < test_num; i++) { serialize(ss, aln_base[i]); } VLOG(1) << test_num << " regions has " << ss.str().size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; // start deserialization start_ts = getUs(); for (int i = 0; i < test_num; i++) { deserialize(ss, aln_test[i]); } VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; // verify for (int i = 0; i < test_num; i++) { ASSERT_EQ(aln_base[i].n, aln_test[i].n); ASSERT_EQ(aln_base[i].m, aln_test[i].m); for (int j = 0; j < aln_base[i].n; j++) { check_mem_alnreg(aln_base[i].a[j], aln_test[i].a[j]); } free(aln_base[i].a); free(aln_test[i].a); } free(aln_base); free(aln_test); } TEST_F(UtilTests, SeqsRecordTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; SeqsRecord record; record.start_idx = 0x1027; // use a magic number for testing record.batch_num = test_num; record.seqs = seqs; uint64_t start_ts = getUs(); std::string ser_data = serialize(record); ASSERT_GT(ser_data.size(), 0); VLOG(1) << test_num << " seqs has " << ser_data.size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; start_ts = getUs(); SeqsRecord record_test; deserialize(ser_data.c_str(), ser_data.length(), record_test); VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; ASSERT_EQ(record.start_idx, record_test.start_idx); ASSERT_EQ(record.batch_num, record_test.batch_num); for (int i = 0; i < test_num; i++) { check_bseq(seqs[i], record_test.seqs[i]); } freeSeqs(record_test.seqs, test_num); } TEST_F(UtilTests, ChainsRecordTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; // compute mem_chain_v mem_chain_v* chains = (mem_chain_v*)malloc(sizeof(mem_chain_v)*test_num); for (int i = 0; i < test_num; i++) { chains[i] = mem_seq2chain_wrapper(aux, seqs); } // construct record ChainsRecord record; record.start_idx = 0x1027; // use a magic number for testing record.batch_num = test_num; record.seqs = seqs; record.chains = chains; uint64_t start_ts = getUs(); // serialization std::string ser_data = serialize(record); ASSERT_GT(ser_data.size(), 0); VLOG(1) << test_num << " chains has " << ser_data.size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; start_ts = getUs(); // deserialization ChainsRecord test; deserialize(ser_data.c_str(), ser_data.length(), test); VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; // check results ASSERT_EQ(record.start_idx, test.start_idx); ASSERT_EQ(record.batch_num, test.batch_num); for (int i = 0; i < test_num; i++) { check_bseq(seqs[i], test.seqs[i]); ASSERT_EQ(record.chains[i].n, test.chains[i].n); for (int j = 0; j < record.chains[i].n; j++) { check_mem_chain(record.chains[i].a[j], test.chains[i].a[j]); } } // clean up freeSeqs(test.seqs, test_num); freeChains(test.chains, test_num); } TEST_F(UtilTests, RegionsRecordTest) { int test_num = batch_num > 4096 ? 4096 : batch_num; // compute mem_alnreg_v mem_alnreg_v* alnreg = (mem_alnreg_v*)malloc(test_num*sizeof(mem_alnreg_v)); for (int i = 0; i < test_num; i++) { mem_chain_v chains = mem_seq2chain_wrapper(aux, seqs); kv_init(alnreg[i]); for (int j = 0; j < chains.n; j++) { mem_chain2aln( aux->opt, aux->idx->bns, aux->idx->pac, seqs[i].l_seq, (uint8_t*)seqs[i].seq, &chains.a[j], alnreg+i); } } // construct record RegionsRecord record; record.start_idx = 0x1027; // use a magic number for testing record.batch_num = test_num; record.seqs = seqs; record.alnreg = alnreg; uint64_t start_ts = getUs(); // serialization std::string ser_data = serialize(record); ASSERT_GT(ser_data.size(), 0); VLOG(1) << test_num << " chains has " << ser_data.size() << " bytes, " << "serialization takes " << getUs() - start_ts << " us"; start_ts = getUs(); // deserialization RegionsRecord test; deserialize(ser_data.c_str(), ser_data.length(), test); VLOG(1) << "deserialization takes " << getUs() - start_ts << " us"; // check results ASSERT_EQ(record.start_idx, test.start_idx); ASSERT_EQ(record.batch_num, test.batch_num); for (int i = 0; i < test_num; i++) { check_bseq(seqs[i], test.seqs[i]); ASSERT_EQ(record.alnreg[i].n, test.alnreg[i].n); for (int j = 0; j < record.alnreg[i].n; j++) { check_mem_alnreg(record.alnreg[i].a[j], test.alnreg[i].a[j]); } } freeSeqs(test.seqs, test_num); freeAligns(test.alnreg, test_num); }
/** * Takes in an instance of {@link CloudTask}, generates and triggers a * {@link org.apache.reef.runtime.common.driver.resourcemanager.ResourceStatusEvent}. * * @param cloudTask and instance of {@link CloudTask}. */ public void onAzureBatchTaskStatus(final CloudTask cloudTask) { ResourceStatusEventImpl.Builder eventBuilder = ResourceStatusEventImpl.newBuilder() .setIdentifier(cloudTask.id()) .setState(TaskStatusMapper.getReefTaskState(cloudTask)) .setRuntimeName(RuntimeIdentifier.RUNTIME_NAME); if (TaskState.COMPLETED.equals(cloudTask.state())) { eventBuilder.setExitCode(cloudTask.executionInfo().exitCode()); } this.reefEventHandlers.onResourceStatus(eventBuilder.build()); }
/// Returns the byte offset corresponding to the line `line`. pub fn offset_of_line(&self, text: &Rope, line: usize) -> usize { match self.breaks { Some(ref breaks) => { breaks.convert_metrics::<BreaksMetric, BreaksBaseMetric>(line) } None => text.offset_of_line(line) } }
from __future__ import division import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Arc C = np.array( [ [1, -1j], [1, 1j] ] ) Cinv = np.array( [ [1/2, 1/2], [1/2*1j, -1/2*1j] ] ) Tstar = np.array( [ [1+1/2*1j, -1/2*1j], [1/2*1j, 1-1/2*1j] ] ) Sstar = np.array( [ [-1j, 0], [0, 1j] ] ) # draw unit circle def drawUnitCirc(axis) : unitCirc = Arc( (0, 0), 2, 2, theta1=0, theta2=360, color='k') axis.add_patch(unitCirc) # given invertible 2x2 matrix A, returns A(z) where action is by Mobius transformation def mobiusTransform(A, z) : if z == np.inf : if A[1, 0] == 0.0 : return np.inf return A[0, 0] / A[1, 0] elif A[1, 0] * z + A[1, 1] == 0.0 : return np.inf return (A[0, 0] * z + A[0, 1]) / (A[1, 0] * z + A[1, 1]) # given point in upper half plane, computes the corresponding point in standard # fundamental domain # Assuming group is generated by z maps to z+1 and z maps to -R^2/z def pullbackToF(z, R) : # check if |re(z)| <= 1/2 x = z.real if x <= 0.5 and x >= -0.5 : # if norm is bigger than R, done if abs(z) >= R : return z # otherwise, map out of circle of radius R else : return pullbackToF(-R**2/z, R) # otherwise, need to map into |re(z)| <= 1/2 else : return pullbackToF(x - round(x) + z.imag*1j, R) # Returns theta and P values of F-pullback # (Does this by mapping to upper half plane model) def pullbackList(thetajs, P, R) : numPoints = len(thetajs) thetajStars = np.zeros(numPoints) pjStars = np.zeros(numPoints) for j in range(numPoints) : # convert polar to rectangular tau = P*np.cos(thetajs[j]) + 1j*P*np.sin(thetajs[j]) # map unit disk to upper half plane z = 1j*(1+tau)/(1-tau) # pull back to standard fundamental domain zStar = pullbackToF(z, R) # map back to unit disk tauStar = (zStar - 1j)/(zStar + 1j) # convert rectangular to polar x = tauStar.real y = tauStar.imag p = np.sqrt(x**2 + y**2) theta = np.arccos(x/p) if y < 0 : theta = 2*np.pi - theta # store results thetajStars[j] = theta pjStars[j] = p return thetajStars, pjStars # converts rectangular (x, y) coordinates to polar (r, theta) coordinates def rectToPol(x, y) : r = np.sqrt(x**2 + y**2) theta = np.arccos(x/r) if y < 0 : theta = 2*np.pi - theta return r, theta # converts polar (r, theta) coordinates to rectangular (x, y) coordinates def polToRect(r, theta) : x = r*np.cos(theta) y = r*np.sin(theta) return x, y # plot list of points given in polar coordinates def plotPolarList(rs, thetas, optionStr, axis) : # get x and y coordinates N = len(rs) xs = np.zeros(N) ys = np.zeros(N) for i in range(N) : x, y = polToRect(rs[i], thetas[i]) xs[i] = x ys[i] = y axis.plot( xs, ys, optionStr) # plot geodesic defined by two endpoints # - endpoints are on unit circle, so are described by angles # - assumes thetas are input in range [0, 2pi) # - geodesics are circles tangent to the boundary def plotGeodesic(theta1, theta2, axis) : if theta1 == theta2 : raise Exception('theta1 cannot equal theta2') # find acute angle between thetas ang = np.abs(theta1 - theta2) wasObtuse = 0 if ang == np.pi : # plot line between them x1, y1 = polToRect(1, theta1) x2, y2 = polToRect(1, theta2) axis.plot( [x1, x2], [y1, y2], color='k') return elif ang > np.pi : ang = 2*np.pi - ang wasObtuse = 1 # Assume we rotate to be symmetric across x-axis and in 1st/4th quadrant theta = ang / 2 # get coordinates of center rC = 1 / np.cos(theta) thetaC = (theta1 + theta2) / 2 if wasObtuse : thetaC += np.pi xC, yC = polToRect(rC, thetaC) # get diameter xP, yP = polToRect(1, theta) diam = 2*np.sqrt( (xP - rC)**2 + yP**2 ) # plot arc ang1 = np.pi/2 + theta + thetaC ang2 = 3*np.pi/2 - theta + thetaC arc = Arc( (xC, yC), diam, diam, theta1=180*ang1/np.pi, theta2=180*ang2/np.pi, color='k') axis.add_patch(arc) # gets 6 endpoints defining the standard fundamental domain for a Hecke group with parameter R def getHeckeEndpoints(R) : endPts = [0, 0, 0, 0, 0, 0] # end points are images of -1/2, inf, 1/2, inf, -R, R under Cayley transform endPts[0] = mobiusTransform(C, -1/2) endPts[1] = mobiusTransform(C, np.inf) endPts[2] = mobiusTransform(C, 1/2) endPts[3] = mobiusTransform(C, np.inf) endPts[4] = mobiusTransform(C, -R) endPts[5] = mobiusTransform(C, R) return endPts # plots the standard fundamental domain for a Hecke group with parameter R def heckeFundDomain(R, axis) : # draw unit circle drawUnitCirc(axis) # get end points endPts = getHeckeEndpoints(R) # for each pair, plot geodesic for i in range(3) : e1 = endPts[2*i] e2 = endPts[2*i+1] r, theta1 = rectToPol(e1.real, e1.imag) r, theta2 = rectToPol(e2.real, e2.imag) plotGeodesic(theta1, theta2, axis) # given six starting points and a Mobius transformation, plots fundamental domain # defined by the image of those points under the map # optional argument: a point in the domain to be plotted def plotShiftedDomain(pts, A, axis, ptInDomain=None) : # for each pair, find image under A then plot geodesic for i in range(3) : e1 = pts[2*i] e2 = pts[2*i+1] Ae1 = mobiusTransform(A, e1) Ae2 = mobiusTransform(A, e2) r, theta1 = rectToPol(Ae1.real, Ae1.imag) r, theta2 = rectToPol(Ae2.real, Ae2.imag) plotGeodesic(theta1, theta2, axis) # if optional argument is included, also plot that shifted point if ptInDomain != None : P = mobiusTransform(A, ptInDomain) axis.plot(P.real, P.imag, 'k.') # given radius rho, plots N points in that circle after map back to upper half plane def plotCircInH(rho, N) : # make circle of thetas thetas = 2*np.pi*np.arange(N) / N # for each theta, get x, y vals of pts in H xs = np.zeros(N) ys = np.zeros(N) for i in range(N) : x, y = polToRect(rho, thetas[i]) z = mobiusTransform(Cinv, x + 1j*y) xs[i] = z.real ys[i] = z.imag # plot the points plt.plot(xs, ys, 'k.') # set up figure with disk drawn to plot on def setupDisk() : fig = plt.figure() ax = plt.axes( xlim=(-1.1, 1.1), ylim=(-1.1, 1.1), aspect='equal') drawUnitCirc(ax) return fig, ax
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package newWan.discovery; import hydra.DistributedSystemHelper; import hydra.Log; import hydra.RemoteTestModule; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.gemstone.gemfire.internal.cache.wan.DistributedSystemListener; import com.gemstone.gemfire.distributed.Locator; import com.gemstone.gemfire.distributed.internal.InternalLocator; /** * Implementation for DistributedSystemListener used to test Jayesh usecase. * It it set using system property -Dgemfire.DistributedSystemListner * * @author rdiyewar * @since 6.8 */ public class MyDistributedSystemListener implements DistributedSystemListener { public static List<String> siteAddedList = new ArrayList<String>(); public static List<String> siteRemovedList = new ArrayList<String>(); @Override public void removedDistributedSystem(int remoteDsId) { long siteRemovedcount = DynamicDiscoveryBB.getInstance() .getSharedCounters().incrementAndRead( DynamicDiscoveryBB.SITE_REMOVED_LISTENER_INVOCATION_COUNTER); String remoteDsName = DistributedSystemHelper .getDistributedSystemName(remoteDsId); Log.getLogWriter() .info( "In " + getMyUniqueName() + " removed distributed system " + remoteDsId); if (!siteRemovedList.contains(remoteDsName)) { siteRemovedList.add(remoteDsName); } else { // duplicate invocation DynamicDiscoveryBB .throwException("Duplicate invocation of MyDistributedSystemListener.removedDistributedSystem for " + remoteDsName); } List<Locator> locators = Locator.getLocators(); Map gfLocMap = ((InternalLocator)locators.get(0)).getAllLocatorsInfo(); if (gfLocMap.containsKey(remoteDsId)) { DynamicDiscoveryBB.throwException("Expected remote site " + remoteDsId + " to be removed , but it is found with locators " + gfLocMap.get(remoteDsId) + ". InternalLocator.getAllLocatorsInfo=" + gfLocMap); } else { Log .getLogWriter() .info( "In MyDistributedSystemListener.removedDistributedSystem: InternalLocator.getAllLocatorsInfo=" + gfLocMap); } } @Override public void addedDistributedSystem(int remoteDsId) { long siteAddedcount = DynamicDiscoveryBB.getInstance().getSharedCounters() .incrementAndRead( DynamicDiscoveryBB.SITE_ADDED_LISTENER_INVOCATION_COUNTER); String remoteDsName = DistributedSystemHelper .getDistributedSystemName(remoteDsId); Log.getLogWriter().info( "In " + getMyUniqueName() + " added distributed system " + remoteDsId); if (!siteAddedList.contains(remoteDsName)) { siteAddedList.add(remoteDsName); } else { // duplicate invocation DynamicDiscoveryBB .throwException("Duplicate invocation of addedDistributedSystem for " + remoteDsName); } List<Locator> locators = Locator.getLocators(); Map gfLocMap = ((InternalLocator)locators.get(0)).getAllLocatorsInfo(); if (!gfLocMap.containsKey(remoteDsId)) { DynamicDiscoveryBB.throwException("Expected remote site " + remoteDsId + " in " + getMyUniqueName() + " , but it is not found." + " InternalLocator.getAllLocatorsInfo=" + gfLocMap); } else { Log .getLogWriter() .info( "In MyDistributedSystemListener.addedDistributedSystem: InternalLocator.getAllLocatorsInfo=" + gfLocMap); } } /** * Uses RemoteTestModule information to produce a name to uniquely identify a * client vm (vmid, clientName, host, pid) for the calling thread */ private String getMyUniqueName() { StringBuffer buf = new StringBuffer(50); buf.append("vm_").append(RemoteTestModule.getMyVmid()); buf.append("_").append(RemoteTestModule.getMyClientName()); buf.append("_").append(RemoteTestModule.getMyHost()); buf.append("_").append(RemoteTestModule.getMyPid()); return buf.toString(); } }
//////////////////////////////////////////////////////////////////////////////// // Load heightmap chunk from VMSH file // // return : True if the heightmap chunk is successfully loaded // //////////////////////////////////////////////////////////////////////////////// bool HeightMapChunk::loadVMSH(Renderer& renderer, Texture& texture, const std::string& filepath) { float* vertices = 0; uint16_t* indices = 0; uint32_t verticesCount = 0; uint32_t indicesCount = 0; std::ifstream file; file.open(filepath.c_str(), std::ios::in | std::ios::binary); if (file.is_open()) { char header[4] = {0}; char majorVersion = 0; char minorVersion = 0; file.read(header, sizeof(char)*4); file.read(&majorVersion, sizeof(char)); file.read(&minorVersion, sizeof(char)); if ((header[0] != 'V') || (header[1] != 'M') || (header[2] != 'S') || (header[3] != 'H')) { return false; } if ((majorVersion != 1) || (minorVersion != 0)) { return false; } char type = 0; file.read(&type, sizeof(char)); if (type != 0) { return false; } file.read((char*)&verticesCount, sizeof(uint32_t)); file.read((char*)&indicesCount, sizeof(uint32_t)); if ((verticesCount <= 0) || (indicesCount <= 0)) { return false; } try { vertices = new float[verticesCount]; indices = new uint16_t[indicesCount]; } catch (const std::bad_alloc&) { vertices = 0; indices = 0; } catch (...) { vertices = 0; indices = 0; } if (!vertices || !indices) { return false; } file.read((char*)vertices, sizeof(float)*verticesCount); file.read((char*)indices, sizeof(uint16_t)*indicesCount); file.close(); } if (!renderer.createVertexBuffer( m_vertexBuffer, vertices, indices, verticesCount, indicesCount)) { if (vertices) { delete[] vertices; } if (indices) { delete[] indices; } return false; } m_indicesCount = indicesCount; if (vertices) { delete[] vertices; } if (indices) { delete[] indices; } if (!texture.isValid()) { return false; } resetTransforms(); m_texture = &texture; return true; }
def loss(logits, labels): with tf.name_scope('Loss'): cross_entropy = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels, name='cross_entropy')) loss = cross_entropy + tf.add_n(tf.get_collection( tf.GraphKeys.REGULARIZATION_LOSSES)) tf.summary.scalar('loss', loss) return loss
<filename>querydsl-core/src/main/java/com/querydsl/core/SimpleQuery.java /* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/team) * * 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 com.querydsl.core; import javax.annotation.Nonnegative; import com.querydsl.core.types.OrderSpecifier; import com.querydsl.core.types.ParamExpression; /** * {@code SimpleQuery} defines a simple querying interface than {@link Query} * * @author tiwe * * @param <Q> concrete subtype * @see Query */ public interface SimpleQuery<Q extends SimpleQuery<Q>> extends FilteredClause<Q> { /** * Set the limit / max results for the query results * * @param limit max rows * @return the current object */ Q limit(@Nonnegative long limit); /** * Set the offset for the query results * * @param offset row offset * @return the current object */ Q offset(@Nonnegative long offset); /** * Set both limit and offset of the query results * * @param modifiers query modifiers * @return the current object */ Q restrict(QueryModifiers modifiers); /** * Add order expressions * * @param o order * @return the current object */ Q orderBy(OrderSpecifier<?>... o); /** * Set the given parameter to the given value * * @param <T> * @param param param * @param value binding * @return the current object */ <T> Q set(ParamExpression<T> param, T value); /** * Set the Query to return distinct results * * @return the current object */ Q distinct(); }
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <string> #include <map> #include <queue> #include <set> using ll = long long; using graph = std::vector<std::vector<ll>>; using wGraph = std::vector<std::vector<std::pair<ll,ll>>>; #define rep(i,n) for (int i=0; i < int(n); i++) using namespace std; struct edge { ll to; ll cost; }; // <最短距離, 頂点の番号> using P = pair<ll, ll>; ll V; #define MAX_V 100005 #define INF (1ll << 50) vector<edge> G[MAX_V]; ll d[MAX_V]; void dijkstra(ll s) { priority_queue<P, vector<P>, greater<P> > que; fill(d, d+V, INF); d[s] = 0; que.push(P(0, s)); while (!que.empty()) { P p = que.top(); que.pop(); ll v = p.second; if (d[v] < p.first) continue; for (ll i=0; i<G[v].size(); ++i) { edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); } } } } int main() { cin >> V; ll X,Y; cin >> X >> Y; X--;Y--; for (ll i=0; i<V - 1; ++i) { auto e = edge{i + 1,1}; G[i].push_back(e); e = edge{i,1}; G[i + 1].push_back(e); } auto e = edge{Y,1}; G[X].push_back(e); e = edge{X,1}; G[Y].push_back(e); dijkstra(X); for (int i = 0; i < V; ++i) { //cout << d[i] << endl; } //cout << endl; ll count[V]; for (int i = 0; i < V; ++i) { count[i] = 0; } for (int si = 0; si < V-1; ++si) { for (int gi = si + 1; gi < V; ++gi) { ll l = min((ll)(gi-si),d[gi] + d[si]); count[l - 1]++; } } for (int i = 0; i < V - 1; ++i) { cout << count[i] << endl; } }
// Code generated by truss. // Rerunning truss will overwrite this file. // DO NOT EDIT! // Package grpc provides a gRPC client for the Rello service. package grpc import ( "github.com/pkg/errors" "golang.org/x/net/context" "google.golang.org/grpc" "google.golang.org/grpc/metadata" "github.com/go-kit/kit/endpoint" grpctransport "github.com/go-kit/kit/transport/grpc" // This Service pb "github.com/adamryman/ambition-rello/rello-service" "github.com/adamryman/ambition-rello/rello-service/svc" ) // New returns an service backed by a gRPC client connection. It is the // responsibility of the caller to dial, and later close, the connection. func New(conn *grpc.ClientConn, options ...ClientOption) (pb.RelloServer, error) { var cc clientConfig for _, f := range options { err := f(&cc) if err != nil { return nil, errors.Wrap(err, "cannot apply option") } } clientOptions := []grpctransport.ClientOption{ grpctransport.ClientBefore( contextValuesToGRPCMetadata(cc.headers)), } var checklistwebhookEndpoint endpoint.Endpoint { checklistwebhookEndpoint = grpctransport.NewClient( conn, "rello.Rello", "CheckListWebhook", EncodeGRPCCheckListWebhookRequest, DecodeGRPCCheckListWebhookResponse, pb.Empty{}, clientOptions..., ).Endpoint() } return svc.Endpoints{ CheckListWebhookEndpoint: checklistwebhookEndpoint, }, nil } // GRPC Client Decode // DecodeGRPCCheckListWebhookResponse is a transport/grpc.DecodeResponseFunc that converts a // gRPC checklistwebhook reply to a user-domain checklistwebhook response. Primarily useful in a client. func DecodeGRPCCheckListWebhookResponse(_ context.Context, grpcReply interface{}) (interface{}, error) { reply := grpcReply.(*pb.Empty) return reply, nil } // GRPC Client Encode // EncodeGRPCCheckListWebhookRequest is a transport/grpc.EncodeRequestFunc that converts a // user-domain checklistwebhook request to a gRPC checklistwebhook request. Primarily useful in a client. func EncodeGRPCCheckListWebhookRequest(_ context.Context, request interface{}) (interface{}, error) { req := request.(*pb.ChecklistUpdate) return req, nil } type clientConfig struct { headers []string } // ClientOption is a function that modifies the client config type ClientOption func(*clientConfig) error func CtxValuesToSend(keys ...string) ClientOption { return func(o *clientConfig) error { o.headers = keys return nil } } func contextValuesToGRPCMetadata(keys []string) grpctransport.RequestFunc { return func(ctx context.Context, md *metadata.MD) context.Context { var pairs []string for _, k := range keys { if v, ok := ctx.Value(k).(string); ok { pairs = append(pairs, k, v) } } if pairs != nil { *md = metadata.Join(*md, metadata.Pairs(pairs...)) } return ctx } }
YOU DID IT! We surpassed our goal of 100,000 missions completed for Military Appreciation Month! It was a resounding success because of you, our players, helping to contribute to this great cause. Every single day we’re humbled and honored to have such a great community. When we first thought of this program, we never thought the participation rate would be so high, but all of you stepped up in a tremendous way... and we would like to do the same. In addition to the $100,000 we’ve already pledged, your overwhelming support has inspired us to add $25,000 to that amount, for a grand total donation of $125,000 to Fisher House Foundation! If you're still working on your charity missions, don't worry! They'll remain available until May 31. In support of Military Appreciation Month, Wargaming America has partnered up with Fisher House Foundation, a military charity organization that provides free, temporary lodging to military and veterans’ families, allowing them to be close to their loved ones during a medical crisis and focus on what’s important -- the healing process. How You Can Help For every charity mission completed from 04:20 PST on May 1 through 04:20 PST on May 31, Wargaming America will donate $1 to Fisher House Foundation, up to $100,000. Missions Mission Restrictions Personal Reserve Reward(s) Earn 100K XP in a Tier IV-X Earn 100,000 XP over any number of battles. All battle types except Rampage Tiers IV+ Once per account 2x 100% XP Booster (1 hr. duration, no expiration) 2x 200% Crew XP Booster (1 hr. duration, no expiration) 1x 50% Credit Booster (1 hr. duration, no expiration) A Note on Personal Reserve Rewards Personal Reserves of the same type don't stack, so there's no advantage to activating multiple boosts of the same type at the same time. If Personal Reserves of different percentages are activated at the same time, only the smaller percentage will take effect. You can also make a direct donation via the Wargaming America Fisher House fundraising page. Learn more about Fisher House on their website.
The role of endothelial lipase in lipid metabolism, inflammation, and cancer. Endothelial lipase (LIPG) plays a critical role in lipoprotein metabolism, cytokine expression, and the lipid composition of cells. Thus far, the extensive investigations of LIPG have focused on its mechanisms and involvement in metabolic syndromes such as atherosclerosis. However, recent developments have found that LIPG plays a role in cancer. This review summarizes the field of LIPG study. We focus on the role of LIPG in lipid metabolism and the inflammatory response, and highlight the recent insights in its involvement in tumor progression. Finally, we discuss potential therapeutic strategies for targeting LIPG in cancer, and the therapeutic potential of LIPG as a drug target.
/* * Copyright (c) 2002-2021 Gargoyle Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * https://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 com.gargoylesoftware.htmlunit.general.huge; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import com.gargoylesoftware.htmlunit.BrowserParameterizedRunner; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.HtmlUnitNYI; /** * Tests two Host classes, if one prototype is parent of another. * * This class handles all host names which starts by character 'S'. * * @author <NAME> * @author <NAME> */ @RunWith(BrowserParameterizedRunner.class) public class HostParentOfSTest extends HostParentOf { /** * Returns the parameterized data. * @return the parameterized data * @throws Exception if an error occurs */ @Parameters public static Collection<Object[]> data() throws Exception { return HostParentOf.data(input -> { final char ch = Character.toUpperCase(input.charAt(0)); return ch == 'S' && StringUtils.compareIgnoreCase(input, "SVGG") < 0; }); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _Screen_Screen() throws Exception { test("Screen", "Screen"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _ScreenOrientation_ScreenOrientation() throws Exception { test("ScreenOrientation", "ScreenOrientation"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _ScriptProcessorNode_ScriptProcessorNode() throws Exception { test("ScriptProcessorNode", "ScriptProcessorNode"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SecurityPolicyViolationEvent_SecurityPolicyViolationEvent() throws Exception { test("SecurityPolicyViolationEvent", "SecurityPolicyViolationEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _Selection_Selection() throws Exception { test("Selection", "Selection"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true", FF = "true", FF78 = "true") public void _ServiceWorker_ServiceWorker() throws Exception { test("ServiceWorker", "ServiceWorker"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true", FF = "true", FF78 = "true") public void _ServiceWorkerContainer_ServiceWorkerContainer() throws Exception { test("ServiceWorkerContainer", "ServiceWorkerContainer"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true", FF = "true", FF78 = "true") public void _ServiceWorkerRegistration_ServiceWorkerRegistration() throws Exception { test("ServiceWorkerRegistration", "ServiceWorkerRegistration"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _Set_Set() throws Exception { test("Set", "Set"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true") public void _SharedArrayBuffer_SharedArrayBuffer() throws Exception { test("SharedArrayBuffer", "SharedArrayBuffer"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _ShadowRoot_ShadowRoot() throws Exception { test("ShadowRoot", "ShadowRoot"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SharedWorker_SharedWorker() throws Exception { test("SharedWorker", "SharedWorker"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SourceBuffer_SourceBuffer() throws Exception { test("SourceBuffer", "SourceBuffer"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SourceBufferList_SourceBufferList() throws Exception { test("SourceBufferList", "SourceBufferList"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", FF = "true", FF78 = "true") public void _SpeechSynthesis_SpeechSynthesis() throws Exception { test("SpeechSynthesis", "SpeechSynthesis"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SpeechSynthesisErrorEvent_SpeechSynthesisErrorEvent() throws Exception { test("SpeechSynthesisErrorEvent", "SpeechSynthesisErrorEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SpeechSynthesisEvent_SpeechSynthesisErrorEvent() throws Exception { test("SpeechSynthesisEvent", "SpeechSynthesisErrorEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SpeechSynthesisEvent_SpeechSynthesisEvent() throws Exception { test("SpeechSynthesisEvent", "SpeechSynthesisEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SpeechSynthesisUtterance_SpeechSynthesisUtterance() throws Exception { test("SpeechSynthesisUtterance", "SpeechSynthesisUtterance"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", FF = "true", FF78 = "true") public void _SpeechSynthesisVoice_SpeechSynthesisVoice() throws Exception { test("SpeechSynthesisVoice", "SpeechSynthesisVoice"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _StereoPannerNode_StereoPannerNode() throws Exception { test("StereoPannerNode", "StereoPannerNode"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _Storage_Storage() throws Exception { test("Storage", "Storage"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _StorageEvent_StorageEvent() throws Exception { test("StorageEvent", "StorageEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _StorageManager_StorageManager() throws Exception { test("StorageManager", "StorageManager"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _StyleMedia_StyleMedia() throws Exception { test("StyleMedia", "StyleMedia"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _StyleSheet_CSSStyleSheet() throws Exception { test("StyleSheet", "CSSStyleSheet"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _StyleSheet_StyleSheet() throws Exception { test("StyleSheet", "StyleSheet"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _StyleSheetList_StyleSheetList() throws Exception { test("StyleSheetList", "StyleSheetList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SubtleCrypto_SubtleCrypto() throws Exception { test("SubtleCrypto", "SubtleCrypto"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAElement_SVGAElement() throws Exception { test("SVGAElement", "SVGAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAngle_SVGAngle() throws Exception { test("SVGAngle", "SVGAngle"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedAngle_SVGAnimatedAngle() throws Exception { test("SVGAnimatedAngle", "SVGAnimatedAngle"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedBoolean_SVGAnimatedBoolean() throws Exception { test("SVGAnimatedBoolean", "SVGAnimatedBoolean"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedEnumeration_SVGAnimatedEnumeration() throws Exception { test("SVGAnimatedEnumeration", "SVGAnimatedEnumeration"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedInteger_SVGAnimatedInteger() throws Exception { test("SVGAnimatedInteger", "SVGAnimatedInteger"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedLength_SVGAnimatedLength() throws Exception { test("SVGAnimatedLength", "SVGAnimatedLength"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedLengthList_SVGAnimatedLengthList() throws Exception { test("SVGAnimatedLengthList", "SVGAnimatedLengthList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedNumber_SVGAnimatedNumber() throws Exception { test("SVGAnimatedNumber", "SVGAnimatedNumber"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedNumberList_SVGAnimatedNumberList() throws Exception { test("SVGAnimatedNumberList", "SVGAnimatedNumberList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedPreserveAspectRatio_SVGAnimatedPreserveAspectRatio() throws Exception { test("SVGAnimatedPreserveAspectRatio", "SVGAnimatedPreserveAspectRatio"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedRect_SVGAnimatedRect() throws Exception { test("SVGAnimatedRect", "SVGAnimatedRect"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedString_SVGAnimatedString() throws Exception { test("SVGAnimatedString", "SVGAnimatedString"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGAnimatedTransformList_SVGAnimatedTransformList() throws Exception { test("SVGAnimatedTransformList", "SVGAnimatedTransformList"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimateElement_SVGAnimateElement() throws Exception { test("SVGAnimateElement", "SVGAnimateElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimateMotionElement_SVGAnimateMotionElement() throws Exception { test("SVGAnimateMotionElement", "SVGAnimateMotionElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimateTransformElement_SVGAnimateTransformElement() throws Exception { test("SVGAnimateTransformElement", "SVGAnimateTransformElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimationElement_SVGAnimateElement() throws Exception { test("SVGAnimationElement", "SVGAnimateElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimationElement_SVGAnimateMotionElement() throws Exception { test("SVGAnimationElement", "SVGAnimateMotionElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimationElement_SVGAnimateTransformElement() throws Exception { test("SVGAnimationElement", "SVGAnimateTransformElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimationElement_SVGAnimationElement() throws Exception { test("SVGAnimationElement", "SVGAnimationElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGAnimationElement_SVGSetElement() throws Exception { test("SVGAnimationElement", "SVGSetElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGCircleElement_SVGCircleElement() throws Exception { test("SVGCircleElement", "SVGCircleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGClipPathElement_SVGClipPathElement() throws Exception { test("SVGClipPathElement", "SVGClipPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGComponentTransferFunctionElement_SVGComponentTransferFunctionElement() throws Exception { test("SVGComponentTransferFunctionElement", "SVGComponentTransferFunctionElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGComponentTransferFunctionElement_SVGFEFuncAElement() throws Exception { test("SVGComponentTransferFunctionElement", "SVGFEFuncAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGComponentTransferFunctionElement_SVGFEFuncBElement() throws Exception { test("SVGComponentTransferFunctionElement", "SVGFEFuncBElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGComponentTransferFunctionElement_SVGFEFuncGElement() throws Exception { test("SVGComponentTransferFunctionElement", "SVGFEFuncGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGComponentTransferFunctionElement_SVGFEFuncRElement() throws Exception { test("SVGComponentTransferFunctionElement", "SVGFEFuncRElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGDefsElement_SVGDefsElement() throws Exception { test("SVGDefsElement", "SVGDefsElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGDescElement_SVGDescElement() throws Exception { test("SVGDescElement", "SVGDescElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGAElement() throws Exception { test("SVGElement", "SVGAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGAnimateElement() throws Exception { test("SVGElement", "SVGAnimateElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGAnimateMotionElement() throws Exception { test("SVGElement", "SVGAnimateMotionElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGAnimateTransformElement() throws Exception { test("SVGElement", "SVGAnimateTransformElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGAnimationElement() throws Exception { test("SVGElement", "SVGAnimationElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGCircleElement() throws Exception { test("SVGElement", "SVGCircleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGClipPathElement() throws Exception { test("SVGElement", "SVGClipPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGComponentTransferFunctionElement() throws Exception { test("SVGElement", "SVGComponentTransferFunctionElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGDefsElement() throws Exception { test("SVGElement", "SVGDefsElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGDescElement() throws Exception { test("SVGElement", "SVGDescElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGElement() throws Exception { test("SVGElement", "SVGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGEllipseElement() throws Exception { test("SVGElement", "SVGEllipseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEBlendElement() throws Exception { test("SVGElement", "SVGFEBlendElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEColorMatrixElement() throws Exception { test("SVGElement", "SVGFEColorMatrixElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEComponentTransferElement() throws Exception { test("SVGElement", "SVGFEComponentTransferElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFECompositeElement() throws Exception { test("SVGElement", "SVGFECompositeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEConvolveMatrixElement() throws Exception { test("SVGElement", "SVGFEConvolveMatrixElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEDiffuseLightingElement() throws Exception { test("SVGElement", "SVGFEDiffuseLightingElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEDisplacementMapElement() throws Exception { test("SVGElement", "SVGFEDisplacementMapElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEDistantLightElement() throws Exception { test("SVGElement", "SVGFEDistantLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGFEDropShadowElement() throws Exception { test("SVGElement", "SVGFEDropShadowElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEFloodElement() throws Exception { test("SVGElement", "SVGFEFloodElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEFuncAElement() throws Exception { test("SVGElement", "SVGFEFuncAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEFuncBElement() throws Exception { test("SVGElement", "SVGFEFuncBElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEFuncGElement() throws Exception { test("SVGElement", "SVGFEFuncGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEFuncRElement() throws Exception { test("SVGElement", "SVGFEFuncRElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEGaussianBlurElement() throws Exception { test("SVGElement", "SVGFEGaussianBlurElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEImageElement() throws Exception { test("SVGElement", "SVGFEImageElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEMergeElement() throws Exception { test("SVGElement", "SVGFEMergeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEMergeNodeElement() throws Exception { test("SVGElement", "SVGFEMergeNodeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEMorphologyElement() throws Exception { test("SVGElement", "SVGFEMorphologyElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEOffsetElement() throws Exception { test("SVGElement", "SVGFEOffsetElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFEPointLightElement() throws Exception { test("SVGElement", "SVGFEPointLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFESpecularLightingElement() throws Exception { test("SVGElement", "SVGFESpecularLightingElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFESpotLightElement() throws Exception { test("SVGElement", "SVGFESpotLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFETileElement() throws Exception { test("SVGElement", "SVGFETileElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFETurbulenceElement() throws Exception { test("SVGElement", "SVGFETurbulenceElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGFilterElement() throws Exception { test("SVGElement", "SVGFilterElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGForeignObjectElement() throws Exception { test("SVGElement", "SVGForeignObjectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGGElement() throws Exception { test("SVGElement", "SVGGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGGeometryElement() throws Exception { test("SVGElement", "SVGGeometryElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGGradientElement() throws Exception { test("SVGElement", "SVGGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGGraphicsElement() throws Exception { test("SVGElement", "SVGGraphicsElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGImageElement() throws Exception { test("SVGElement", "SVGImageElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGLinearGradientElement() throws Exception { test("SVGElement", "SVGLinearGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGLineElement() throws Exception { test("SVGElement", "SVGLineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGMarkerElement() throws Exception { test("SVGElement", "SVGMarkerElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGMaskElement() throws Exception { test("SVGElement", "SVGMaskElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGMetadataElement() throws Exception { test("SVGElement", "SVGMetadataElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGMPathElement() throws Exception { test("SVGElement", "SVGMPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGPathElement() throws Exception { test("SVGElement", "SVGPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGPatternElement() throws Exception { test("SVGElement", "SVGPatternElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGPolygonElement() throws Exception { test("SVGElement", "SVGPolygonElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGPolylineElement() throws Exception { test("SVGElement", "SVGPolylineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGRadialGradientElement() throws Exception { test("SVGElement", "SVGRadialGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGRectElement() throws Exception { test("SVGElement", "SVGRectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGScriptElement() throws Exception { test("SVGElement", "SVGScriptElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGElement_SVGSetElement() throws Exception { test("SVGElement", "SVGSetElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGStopElement() throws Exception { test("SVGElement", "SVGStopElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGStyleElement() throws Exception { test("SVGElement", "SVGStyleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGSVGElement() throws Exception { test("SVGElement", "SVGSVGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGSwitchElement() throws Exception { test("SVGElement", "SVGSwitchElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGSymbolElement() throws Exception { test("SVGElement", "SVGSymbolElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTextContentElement() throws Exception { test("SVGElement", "SVGTextContentElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTextElement() throws Exception { test("SVGElement", "SVGTextElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTextPathElement() throws Exception { test("SVGElement", "SVGTextPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTextPositioningElement() throws Exception { test("SVGElement", "SVGTextPositioningElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTitleElement() throws Exception { test("SVGElement", "SVGTitleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGTSpanElement() throws Exception { test("SVGElement", "SVGTSpanElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGUseElement() throws Exception { test("SVGElement", "SVGUseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGElement_SVGViewElement() throws Exception { test("SVGElement", "SVGViewElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGEllipseElement_SVGEllipseElement() throws Exception { test("SVGEllipseElement", "SVGEllipseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEBlendElement_SVGFEBlendElement() throws Exception { test("SVGFEBlendElement", "SVGFEBlendElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEColorMatrixElement_SVGFEColorMatrixElement() throws Exception { test("SVGFEColorMatrixElement", "SVGFEColorMatrixElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEComponentTransferElement_SVGFEComponentTransferElement() throws Exception { test("SVGFEComponentTransferElement", "SVGFEComponentTransferElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFECompositeElement_SVGFECompositeElement() throws Exception { test("SVGFECompositeElement", "SVGFECompositeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEConvolveMatrixElement_SVGFEConvolveMatrixElement() throws Exception { test("SVGFEConvolveMatrixElement", "SVGFEConvolveMatrixElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEDiffuseLightingElement_SVGFEDiffuseLightingElement() throws Exception { test("SVGFEDiffuseLightingElement", "SVGFEDiffuseLightingElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEDisplacementMapElement_SVGFEDisplacementMapElement() throws Exception { test("SVGFEDisplacementMapElement", "SVGFEDisplacementMapElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEDistantLightElement_SVGFEDistantLightElement() throws Exception { test("SVGFEDistantLightElement", "SVGFEDistantLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGFEDropShadowElement_SVGFEDropShadowElement() throws Exception { test("SVGFEDropShadowElement", "SVGFEDropShadowElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEFloodElement_SVGFEFloodElement() throws Exception { test("SVGFEFloodElement", "SVGFEFloodElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEFuncAElement_SVGFEFuncAElement() throws Exception { test("SVGFEFuncAElement", "SVGFEFuncAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEFuncBElement_SVGFEFuncBElement() throws Exception { test("SVGFEFuncBElement", "SVGFEFuncBElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEFuncGElement_SVGFEFuncGElement() throws Exception { test("SVGFEFuncGElement", "SVGFEFuncGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEFuncRElement_SVGFEFuncRElement() throws Exception { test("SVGFEFuncRElement", "SVGFEFuncRElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEGaussianBlurElement_SVGFEGaussianBlurElement() throws Exception { test("SVGFEGaussianBlurElement", "SVGFEGaussianBlurElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEImageElement_SVGFEImageElement() throws Exception { test("SVGFEImageElement", "SVGFEImageElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEMergeElement_SVGFEMergeElement() throws Exception { test("SVGFEMergeElement", "SVGFEMergeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEMergeNodeElement_SVGFEMergeNodeElement() throws Exception { test("SVGFEMergeNodeElement", "SVGFEMergeNodeElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEMorphologyElement_SVGFEMorphologyElement() throws Exception { test("SVGFEMorphologyElement", "SVGFEMorphologyElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEOffsetElement_SVGFEOffsetElement() throws Exception { test("SVGFEOffsetElement", "SVGFEOffsetElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFEPointLightElement_SVGFEPointLightElement() throws Exception { test("SVGFEPointLightElement", "SVGFEPointLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFESpecularLightingElement_SVGFESpecularLightingElement() throws Exception { test("SVGFESpecularLightingElement", "SVGFESpecularLightingElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFESpotLightElement_SVGFESpotLightElement() throws Exception { test("SVGFESpotLightElement", "SVGFESpotLightElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFETileElement_SVGFETileElement() throws Exception { test("SVGFETileElement", "SVGFETileElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFETurbulenceElement_SVGFETurbulenceElement() throws Exception { test("SVGFETurbulenceElement", "SVGFETurbulenceElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGFilterElement_SVGFilterElement() throws Exception { test("SVGFilterElement", "SVGFilterElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGForeignObjectElement_SVGForeignObjectElement() throws Exception { test("SVGForeignObjectElement", "SVGForeignObjectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGGElement_SVGGElement() throws Exception { test("SVGGElement", "SVGGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGCircleElement() throws Exception { test("SVGGeometryElement", "SVGCircleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGEllipseElement() throws Exception { test("SVGGeometryElement", "SVGEllipseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGGeometryElement() throws Exception { test("SVGGeometryElement", "SVGGeometryElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGLineElement() throws Exception { test("SVGGeometryElement", "SVGLineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGPathElement() throws Exception { test("SVGGeometryElement", "SVGPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGPolygonElement() throws Exception { test("SVGGeometryElement", "SVGPolygonElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGPolylineElement() throws Exception { test("SVGGeometryElement", "SVGPolylineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGeometryElement_SVGRectElement() throws Exception { test("SVGGeometryElement", "SVGRectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGGradientElement_SVGGradientElement() throws Exception { test("SVGGradientElement", "SVGGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGGradientElement_SVGLinearGradientElement() throws Exception { test("SVGGradientElement", "SVGLinearGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGGradientElement_SVGRadialGradientElement() throws Exception { test("SVGGradientElement", "SVGRadialGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGAElement() throws Exception { test("SVGGraphicsElement", "SVGAElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGCircleElement() throws Exception { test("SVGGraphicsElement", "SVGCircleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true") @HtmlUnitNYI(CHROME = "false", EDGE = "false") public void _SVGGraphicsElement_SVGClipPathElement() throws Exception { test("SVGGraphicsElement", "SVGClipPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGDefsElement() throws Exception { test("SVGGraphicsElement", "SVGDefsElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGEllipseElement() throws Exception { test("SVGGraphicsElement", "SVGEllipseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGForeignObjectElement() throws Exception { test("SVGGraphicsElement", "SVGForeignObjectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGGElement() throws Exception { test("SVGGraphicsElement", "SVGGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGGeometryElement() throws Exception { test("SVGGraphicsElement", "SVGGeometryElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGGraphicsElement() throws Exception { test("SVGGraphicsElement", "SVGGraphicsElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGImageElement() throws Exception { test("SVGGraphicsElement", "SVGImageElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGLineElement() throws Exception { test("SVGGraphicsElement", "SVGLineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGPathElement() throws Exception { test("SVGGraphicsElement", "SVGPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGPolygonElement() throws Exception { test("SVGGraphicsElement", "SVGPolygonElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGPolylineElement() throws Exception { test("SVGGraphicsElement", "SVGPolylineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGRectElement() throws Exception { test("SVGGraphicsElement", "SVGRectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGSVGElement() throws Exception { test("SVGGraphicsElement", "SVGSVGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGSwitchElement() throws Exception { test("SVGGraphicsElement", "SVGSwitchElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGTextContentElement() throws Exception { test("SVGGraphicsElement", "SVGTextContentElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGTextElement() throws Exception { test("SVGGraphicsElement", "SVGTextElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGTextPathElement() throws Exception { test("SVGGraphicsElement", "SVGTextPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGTextPositioningElement() throws Exception { test("SVGGraphicsElement", "SVGTextPositioningElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGTSpanElement() throws Exception { test("SVGGraphicsElement", "SVGTSpanElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGGraphicsElement_SVGUseElement() throws Exception { test("SVGGraphicsElement", "SVGUseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGImageElement_SVGImageElement() throws Exception { test("SVGImageElement", "SVGImageElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGLength_SVGLength() throws Exception { test("SVGLength", "SVGLength"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGLengthList_SVGLengthList() throws Exception { test("SVGLengthList", "SVGLengthList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGLinearGradientElement_SVGLinearGradientElement() throws Exception { test("SVGLinearGradientElement", "SVGLinearGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGLineElement_SVGLineElement() throws Exception { test("SVGLineElement", "SVGLineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGMarkerElement_SVGMarkerElement() throws Exception { test("SVGMarkerElement", "SVGMarkerElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGMaskElement_SVGMaskElement() throws Exception { test("SVGMaskElement", "SVGMaskElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGMatrix_SVGMatrix() throws Exception { test("SVGMatrix", "SVGMatrix"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGMetadataElement_SVGMetadataElement() throws Exception { test("SVGMetadataElement", "SVGMetadataElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGMPathElement_SVGMPathElement() throws Exception { test("SVGMPathElement", "SVGMPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGNumber_SVGNumber() throws Exception { test("SVGNumber", "SVGNumber"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGNumberList_SVGNumberList() throws Exception { test("SVGNumberList", "SVGNumberList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPathElement_SVGPathElement() throws Exception { test("SVGPathElement", "SVGPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSeg() throws Exception { test("SVGPathSeg", "SVGPathSeg"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegArcAbs() throws Exception { test("SVGPathSeg", "SVGPathSegArcAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegArcRel() throws Exception { test("SVGPathSeg", "SVGPathSegArcRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegClosePath() throws Exception { test("SVGPathSeg", "SVGPathSegClosePath"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoCubicAbs() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoCubicAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoCubicRel() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoCubicRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoCubicSmoothAbs() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoCubicSmoothAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoCubicSmoothRel() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoCubicSmoothRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoQuadraticAbs() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoQuadraticAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoQuadraticRel() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoQuadraticRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoQuadraticSmoothAbs() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoQuadraticSmoothAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegCurvetoQuadraticSmoothRel() throws Exception { test("SVGPathSeg", "SVGPathSegCurvetoQuadraticSmoothRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoAbs() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoHorizontalAbs() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoHorizontalAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoHorizontalRel() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoHorizontalRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoRel() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoVerticalAbs() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoVerticalAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegLinetoVerticalRel() throws Exception { test("SVGPathSeg", "SVGPathSegLinetoVerticalRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegMovetoAbs() throws Exception { test("SVGPathSeg", "SVGPathSegMovetoAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSeg_SVGPathSegMovetoRel() throws Exception { test("SVGPathSeg", "SVGPathSegMovetoRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegArcAbs_SVGPathSegArcAbs() throws Exception { test("SVGPathSegArcAbs", "SVGPathSegArcAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegArcRel_SVGPathSegArcRel() throws Exception { test("SVGPathSegArcRel", "SVGPathSegArcRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegClosePath_SVGPathSegClosePath() throws Exception { test("SVGPathSegClosePath", "SVGPathSegClosePath"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoCubicAbs_SVGPathSegCurvetoCubicAbs() throws Exception { test("SVGPathSegCurvetoCubicAbs", "SVGPathSegCurvetoCubicAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoCubicRel_SVGPathSegCurvetoCubicRel() throws Exception { test("SVGPathSegCurvetoCubicRel", "SVGPathSegCurvetoCubicRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoCubicSmoothAbs_SVGPathSegCurvetoCubicSmoothAbs() throws Exception { test("SVGPathSegCurvetoCubicSmoothAbs", "SVGPathSegCurvetoCubicSmoothAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoCubicSmoothRel_SVGPathSegCurvetoCubicSmoothRel() throws Exception { test("SVGPathSegCurvetoCubicSmoothRel", "SVGPathSegCurvetoCubicSmoothRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoQuadraticAbs_SVGPathSegCurvetoQuadraticAbs() throws Exception { test("SVGPathSegCurvetoQuadraticAbs", "SVGPathSegCurvetoQuadraticAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoQuadraticRel_SVGPathSegCurvetoQuadraticRel() throws Exception { test("SVGPathSegCurvetoQuadraticRel", "SVGPathSegCurvetoQuadraticRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoQuadraticSmoothAbs_SVGPathSegCurvetoQuadraticSmoothAbs() throws Exception { test("SVGPathSegCurvetoQuadraticSmoothAbs", "SVGPathSegCurvetoQuadraticSmoothAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegCurvetoQuadraticSmoothRel_SVGPathSegCurvetoQuadraticSmoothRel() throws Exception { test("SVGPathSegCurvetoQuadraticSmoothRel", "SVGPathSegCurvetoQuadraticSmoothRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoAbs_SVGPathSegLinetoAbs() throws Exception { test("SVGPathSegLinetoAbs", "SVGPathSegLinetoAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoHorizontalAbs_SVGPathSegLinetoHorizontalAbs() throws Exception { test("SVGPathSegLinetoHorizontalAbs", "SVGPathSegLinetoHorizontalAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoHorizontalRel_SVGPathSegLinetoHorizontalRel() throws Exception { test("SVGPathSegLinetoHorizontalRel", "SVGPathSegLinetoHorizontalRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoRel_SVGPathSegLinetoRel() throws Exception { test("SVGPathSegLinetoRel", "SVGPathSegLinetoRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoVerticalAbs_SVGPathSegLinetoVerticalAbs() throws Exception { test("SVGPathSegLinetoVerticalAbs", "SVGPathSegLinetoVerticalAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegLinetoVerticalRel_SVGPathSegLinetoVerticalRel() throws Exception { test("SVGPathSegLinetoVerticalRel", "SVGPathSegLinetoVerticalRel"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", CHROME = "false", EDGE = "false") public void _SVGPathSegList_SVGPathSegList() throws Exception { test("SVGPathSegList", "SVGPathSegList"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegMovetoAbs_SVGPathSegMovetoAbs() throws Exception { test("SVGPathSegMovetoAbs", "SVGPathSegMovetoAbs"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGPathSegMovetoRel_SVGPathSegMovetoRel() throws Exception { test("SVGPathSegMovetoRel", "SVGPathSegMovetoRel"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPatternElement_SVGPatternElement() throws Exception { test("SVGPatternElement", "SVGPatternElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPoint_SVGPoint() throws Exception { test("SVGPoint", "SVGPoint"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPointList_SVGPointList() throws Exception { test("SVGPointList", "SVGPointList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPolygonElement_SVGPolygonElement() throws Exception { test("SVGPolygonElement", "SVGPolygonElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPolylineElement_SVGPolylineElement() throws Exception { test("SVGPolylineElement", "SVGPolylineElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGPreserveAspectRatio_SVGPreserveAspectRatio() throws Exception { test("SVGPreserveAspectRatio", "SVGPreserveAspectRatio"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGRadialGradientElement_SVGRadialGradientElement() throws Exception { test("SVGRadialGradientElement", "SVGRadialGradientElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGRect_SVGRect() throws Exception { test("SVGRect", "SVGRect"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGRectElement_SVGRectElement() throws Exception { test("SVGRectElement", "SVGRectElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGScriptElement_SVGScriptElement() throws Exception { test("SVGScriptElement", "SVGScriptElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _SVGSetElement_SVGSetElement() throws Exception { test("SVGSetElement", "SVGSetElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGStopElement_SVGStopElement() throws Exception { test("SVGStopElement", "SVGStopElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGStringList_SVGStringList() throws Exception { test("SVGStringList", "SVGStringList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGStyleElement_SVGStyleElement() throws Exception { test("SVGStyleElement", "SVGStyleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGSVGElement_SVGSVGElement() throws Exception { test("SVGSVGElement", "SVGSVGElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGSwitchElement_SVGSwitchElement() throws Exception { test("SVGSwitchElement", "SVGSwitchElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGSymbolElement_SVGSymbolElement() throws Exception { test("SVGSymbolElement", "SVGSymbolElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextContentElement_SVGTextContentElement() throws Exception { test("SVGTextContentElement", "SVGTextContentElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextContentElement_SVGTextElement() throws Exception { test("SVGTextContentElement", "SVGTextElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextContentElement_SVGTextPathElement() throws Exception { test("SVGTextContentElement", "SVGTextPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextContentElement_SVGTextPositioningElement() throws Exception { test("SVGTextContentElement", "SVGTextPositioningElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextContentElement_SVGTSpanElement() throws Exception { test("SVGTextContentElement", "SVGTSpanElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextElement_SVGTextElement() throws Exception { test("SVGTextElement", "SVGTextElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextPathElement_SVGTextPathElement() throws Exception { test("SVGTextPathElement", "SVGTextPathElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextPositioningElement_SVGTextElement() throws Exception { test("SVGTextPositioningElement", "SVGTextElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextPositioningElement_SVGTextPositioningElement() throws Exception { test("SVGTextPositioningElement", "SVGTextPositioningElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTextPositioningElement_SVGTSpanElement() throws Exception { test("SVGTextPositioningElement", "SVGTSpanElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTitleElement_SVGTitleElement() throws Exception { test("SVGTitleElement", "SVGTitleElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTransform_SVGTransform() throws Exception { test("SVGTransform", "SVGTransform"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTransformList_SVGTransformList() throws Exception { test("SVGTransformList", "SVGTransformList"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGTSpanElement_SVGTSpanElement() throws Exception { test("SVGTSpanElement", "SVGTSpanElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true") @HtmlUnitNYI(FF = "true", FF78 = "true", IE = "true") public void _SVGUnitTypes_SVGUnitTypes() throws Exception { test("SVGUnitTypes", "SVGUnitTypes"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGUseElement_SVGUseElement() throws Exception { test("SVGUseElement", "SVGUseElement"); } /** * @throws Exception if the test fails */ @Test @Alerts("true") public void _SVGViewElement_SVGViewElement() throws Exception { test("SVGViewElement", "SVGViewElement"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", IE = "true") public void _SVGZoomEvent_SVGZoomEvent() throws Exception { test("SVGZoomEvent", "SVGZoomEvent"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "true", IE = "false") public void _Symbol_Symbol() throws Exception { test("Symbol", "Symbol"); } /** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "false", CHROME = "true", EDGE = "true") public void _SyncManager_SyncManager() throws Exception { test("SyncManager", "SyncManager"); } }
def os_wget(fileurl, targetdir, num_tries=3, secsbetweentries=10, wgetparams=""): check_param_type("fileurl", fileurl, str) check_param_type("targetdir", targetdir, str) check_param_type("num_tries", num_tries, int) check_param_type("secsbetweentries", secsbetweentries, int) check_param_type("wgetparams", wgetparams, str) wget_success = False if not os.path.isdir(targetdir): log_error("Download directory {0} does not exist".format(targetdir)) return False wgetoutfile = "{0}/wget.out".format(test_output_get_tmp_dir()) log_debug("Downloading file via wget: {0}".format(fileurl)) cmd = "wget {0} --no-check-certificate -P {1} {2} > {3} 2>&1".\ format(fileurl, targetdir, wgetparams, wgetoutfile) attemptnum = 1 while attemptnum <= num_tries: log_debug("wget Attempt#{0}; cmd={1}".format(attemptnum, cmd)) rtn_value = os.system(cmd) log_debug("wget rtn: {0}".format(rtn_value)) if rtn_value == 0: log_debug("wget download successful") wget_success = True attemptnum = num_tries + 1 continue if os.path.isfile(wgetoutfile): with open(wgetoutfile, "rb") as wgetfile: wgetoutput = "".join(wgetfile.readlines()[1:]) log_debug("wget output:\n{0}".format(wgetoutput)) else: log_debug("wget output: NOT FOUND") log_debug("Download Failed, waiting {0} seconds and trying again...".\ format(secsbetweentries)) attemptnum = attemptnum + 1 time.sleep(secsbetweentries) if not wget_success: log_error("Failed to download via wget {0}".format(fileurl)) return wget_success
import { Component, useEffect, useState } from 'react'; import Head from 'next/head'; import keyGen from '../../utils/key'; import SyntaxHighlighter from 'react-syntax-highlighter'; import SyntaxStyle from 'react-syntax-highlighter/dist/cjs/styles/hljs/vs2015'; import styles from '../../styles/function.key.module.scss'; function Key() { const [output, setOutput] = useState(' '); const handleInput = (e: any) => { setOutput(JSON.stringify(keyGen(e.target.value), null, 2)); }; useEffect(() => { setOutput(JSON.stringify(keyGen(''), null, 2)); }, []); return ( <> <Head> <title>Generator</title> </Head> <div className={styles.wrapper}> <div className={styles.inner + ' pt-10 w-50 flex justify-center'}> <form className='container'> <div className='mb-3'> <label className='form-label'>info.json</label> <input type='text' className='form-control key-input' placeholder='Raw JSON' onKeyUp={handleInput} /> </div> <div className='mb-3'> <label className='form-label'>Item for all.json</label> <SyntaxHighlighter language='json' style={SyntaxStyle}> {output} </SyntaxHighlighter> </div> </form> </div> </div> </> ); } export default Key;
Photo: Bo Rader/The Wichita Eagle/AP During the presidential campaign, some imagined that the more overtly racist elements of Donald Trump’s platform were just talk designed to rile up the base, not anything he seriously intended to act on. But in his first week in office, when he imposed a travel ban on seven majority-Muslim countries, that comforting illusion disappeared fast. Fortunately, the response was immediate: the marches and rallies at airports, the impromptu taxi strikes, the lawyers and local politicians intervening, the judges ruling the bans illegal. The whole episode showed the power of resistance, and of judicial courage, and there was much to celebrate. Some have even concluded that this early slap down chastened Trump, and that he is now committed to a more reasonable, conventional course. That is a dangerous illusion. It is true that many of the more radical items on this administration’s wish list have yet to be realized. But make no mistake, the full agenda is still there, lying in wait. And there is one thing that could unleash it all: a large-scale crisis. Large-scale shocks are frequently harnessed to ram through despised pro-corporate and anti-democratic policies that would never have been feasible in normal times. It’s a phenomenon I have previously called the “Shock Doctrine,” and we have seen it happen again and again over the decades, from Chile in the aftermath of Augusto Pinochet’s coup to New Orleans after Hurricane Katrina. And we have seen it happen recently, well before Trump, in U.S. cities including Detroit and Flint, where looming municipal bankruptcy became the pretext for dissolving local democracy and appointing “emergency managers” who waged war on public services and public education. It is unfolding right now in Puerto Rico, where the ongoing debt crisis has been used to install the unaccountable “Financial Oversight and Management Board,” an enforcement mechanism for harsh austerity measures, including cuts to pensions and waves of school closures. This tactic is being deployed in Brazil, where the highly questionable impeachment of President Dilma Rousseff in 2016 was followed by the installation of an unelected, zealously pro-business regime that has frozen public spending for the next 20 years, imposed punishing austerity, and begun selling off airports, power stations, and other public assets in a frenzy of privatization. As Milton Friedman wrote long ago, “Only a crisis — actual or perceived — produces real change. When that crisis occurs, the actions that are taken depend on the ideas that are lying around. That, I believe, is our basic function: to develop alternatives to existing policies, to keep them alive and available until the politically impossible becomes politically inevitable.” Survivalists stockpile canned goods and water in preparation for major disasters; these guys stockpile spectacularly anti-democratic ideas. Now, as many have observed, the pattern is repeating under Trump. On the campaign trail, he did not tell his adoring crowds that he would cut funds for meals-on-wheels, or admit that he was going to try to take health insurance away from millions of Americans, or that he planned to grant every item on Goldman Sachs’ wish list. He said the very opposite. Since taking office, however, Donald Trump has never allowed the atmosphere of chaos and crisis to let up. Some of the chaos, like the Russia investigations, has been foisted upon him or is simply the result of incompetence, but much appears to be deliberately created. Either way, while we are distracted by (and addicted to) the Trump Show, clicking on and gasping at marital hand-slaps and mysterious orbs, the quiet, methodical work of redistributing wealth upward proceeds apace. This is also aided by the sheer velocity of change. Witnessing the tsunami of executive orders during Trump’s first 100 days, it rapidly became clear his advisers were following Machiavelli’s advice in “The Prince”: “Injuries ought to be done all at one time, so that, being tasted less, they offend less.” The logic is straightforward enough. People can develop responses to sequential or gradual change. But if dozens of changes come from all directions at once, the hope is that populations will rapidly become exhausted and overwhelmed, and will ultimately swallow their bitter medicine. But here’s the thing. All of this is shock doctrine lite; it’s the most that Trump can pull off under cover of the shocks he is generating himself. And as much as this needs to be exposed and resisted, we also need to focus on what this administration will do when they have a real external shock to exploit. Maybe it will be an economic crash like the 2008 subprime mortgage crisis. Maybe a natural disaster like Superstorm Sandy. Or maybe it will be a horrific terrorist attack like the Manchester bombing. Any one such crisis could trigger a very rapid shift in political conditions, making what currently seems unlikely suddenly appear inevitable. So let’s consider a few categories of possible shocks, and how they might be harnessed to start ticking off items on Trump’s toxic to-do list. Police officers join members of the public to view the flowers and messages of support in St. Ann’s Square in Manchester, England, on May 31, 2017, placed in tribute to the victims of the May 22 terror attack at the Manchester Arena. Photo: Oli Scarff/AFP/Getty Images A Terror Shock Recent terror attacks in London, Manchester, and Paris provide some broad hints about how the administration would try to exploit a large-scale attack that took place on U.S. soil or against U.S. infrastructure abroad. After the horrific Manchester bombing last month, the governing Conservatives launched a fierce campaign against Jeremy Corbyn and the Labour Party for suggesting that the failed “war on terror” is part of what is fueling such acts, calling any such suggestion “monstrous” (a clear echo of the “with us or with the terrorists” rhetoric that descended after September 11, 2001). For his part, Trump rushed to link the attack to the “thousands and thousands of people pouring into our various countries” — never mind that the bomber, Salman Abedi, was born in the U.K. Similarly, in the immediate aftermath of the Westminster terror attacks in London in March 2017, when a driver plowed into a crowd of pedestrians, deliberately killing four people and injuring dozens more, the Conservative government wasted no time declaring that any expectation of privacy in digital communications was now a threat to national security. Home Secretary Amber Rudd went on the BBC and declared the end-to-end encryption provided by programs like WhatsApp to be “completely unacceptable.” And she said that they were meeting with the large tech firms “to ask them to work with us” on providing backdoor access to these platforms. She made an even stronger call to crack down on internet privacy after the London Bridge attack. More worrying, in 2015, after the coordinated attacks in Paris that killed 130 people, the government of François Hollande declared a “state of emergency” that banned political protests. I was in France a week after those horrific events and it was striking that, although the attackers had targeted a concert, a football stadium, restaurants, and other emblems of daily Parisian life, it was only outdoor political activity that was not permitted. Large concerts, Christmas markets, and sporting events — the sorts of places that were likely targets for further attacks — were all free to carry on as usual. In the months that followed, the state-of-emergency decree was extended again and again until it had been in place for well over a year. It is currently set to remain in effect until at least July 2017. In France, state-of-emergency is the new normal. This took place under a center-left government in a country with a long tradition of disruptive strikes and protests. One would have to be naive to imagine that Donald Trump and Mike Pence wouldn’t immediately seize on any attack in the United States to go much further down that same road. In all likelihood they would do it swiftly, by declaring protests and strikes that block roads and airports (the kind that responded to the Muslim travel ban) a threat to “national security.” Protest organizers would be targeted with surveillance, arrests, and imprisonment. Indeed we should be prepared for security shocks to be exploited as excuses to increase the rounding up and incarceration of large numbers of people from the communities this administration is already targeting: Latino immigrants, Muslims, Black Lives Matter organizers, climate activists, investigative journalists. It’s all possible. And in the name of freeing the hands of law enforcement to fight terrorism, Attorney General Jeff Sessions would have the excuse he’d been looking for to do away with federal oversight of state and local police, especially those that have been accused of systemic racial abuses. And there is no doubt that the president would seize on any domestic terrorist attack to blame the courts. He made this perfectly clear when he tweeted, after his first travel ban was struck down: “Just cannot believe a judge would put our country in such peril. If something happens blame him and court system.” And on the night of the London Bridge attack, he went even further, tweeting: “We need the courts to give us back our rights. We need the Travel Ban as an extra level of safety!” In a context of public hysteria and recrimination that would surely follow an attack in the U.S., the kind of courage we witnessed from the courts in response to Trump’s travel bans might well be in shorter supply. This April 7, 2017, photo shows the USS Porter launching a tomahawk missile at a Syrian air base. Photo: Mass Communication Specialist 3rd Class Ford Williams/U.S. Navy via AP The Shock of War The most lethal way that governments overreact to terrorist attacks is by exploiting the atmosphere of fear to embark on a full-blown foreign war (or two). It doesn’t necessarily matter if the target has no connection to the original terror attacks. Iraq wasn’t responsible for 9/11, and it was invaded anyway. Trump’s likeliest targets are mostly in the Middle East, and they include (but are by no means limited to) Syria, Yemen, Iraq, and, most perilously, Iran. And then, of course, there’s North Korea, where Secretary of State Rex Tillerson has declared that “all options are on the table,” pointedly refusing to rule out a pre-emptive military strike. There are many reasons why people around Trump, particularly those who came straight from the defense sector, might decide that further military escalation is in order. Trump’s April 2017 missile strike on Syria — ordered without congressional approval and therefore illegal according to some experts — won him the most positive news coverage of his presidency. His inner circle, meanwhile, immediately pointed to the attacks as proof that there was nothing untoward going on between the White House and Russia. But there’s another, less discussed reason why this administration might rush to exploit a security crisis to start a new war or escalate an ongoing conflict: There is no faster or more effective way to drive up the price of oil, especially if the violence interferes with the supply of oil to the world market This would be great news for oil giants like Exxon Mobil, which have seen their profits drop dramatically as a result of the depressed price of oil — and Exxon, of course, is fortunate enough to have its former CEO, Tillerson, currently serving as secretary of state. (Not only was Tillerson at Exxon for 41 years, his entire working life, but Exxon Mobil has agreed to pay him a retirement package worth a staggering $180 million.) Other than Exxon, perhaps the only entity that would have more to gain from an oil price hike fueled by global instability is Vladimir Putin’s Russia, a vast petro-state that has been in economic crisis since the price of oil collapsed. Russia is the world’s leading exporter of natural gas, and the second-largest exporter of oil (after Saudi Arabia). When the price was high, this was great news for Putin: Prior to 2014, fully 50 percent of Russia’s budget revenues came from oil and gas. But when prices plummeted, the government was suddenly short hundreds of billions of dollars, an economic catastrophe with tremendous human costs. According to the World Bank, in 2015 real wages fell in Russia by nearly 10 percent; the Russian ruble depreciated by close to 40 percent; and the population of people classified as poor increased from 3 million to over 19 million. Putin plays the strongman, but this economic crisis makes him vulnerable at home. We’ve also heard a lot about that massive deal between Exxon Mobil and the Russian state oil company Rosneft to drill for oil in the Arctic (Putin bragged that it was worth half a trillion dollars). That deal was derailed by U.S. sanctions against Russia and despite the posturing on both sides over Syria, it is still entirely possible that Trump will decide to lift the sanctions and clear the way for that deal to go ahead, which would quickly boost Exxon Mobil’s flagging fortunes. But even if the sanctions are lifted, there is another factor standing in the way of the project moving forward: the depressed price of oil. Tillerson made the deal with Rosneft in 2011, when the price of oil was soaring at around $110 a barrel. Their first commitment was to explore for oil in the sea north of Siberia, under tough-to-extract, icy conditions. The break-even price for Arctic drilling is estimated to be around $100 a barrel, if not more. So even if sanctions are lifted under Trump, it won’t make sense for Exxon and Rosneft to move ahead with their project unless oil prices are high enough. Which is yet another reason why parties might embrace the kind of instability that would send oil prices shooting back up. If the price of oil rises to $80 or more a barrel, then the scramble to dig up and burn the dirtiest fossil fuels, including those under melting ice, will be back on. A price rebound would unleash a global frenzy in new high-risk, high-carbon fossil fuel extraction, from the Arctic to the tar sands. And if that is allowed to happen, it really would rob us of our last chance of averting catastrophic climate change. So, in a very real sense, preventing war and averting climate chaos are one and the same fight. A screen displays financial data on Jan. 22, 2008. Photo: Cate Gillon/Getty Images Economic Shocks A centerpiece of Trump’s economic project so far has been a flurry of financial deregulation that makes economic shocks and disasters distinctly more likely. Trump has announced plans to dismantle Dodd-Frank, the most substantive piece of legislation introduced after the 2008 banking collapse. Dodd-Frank wasn’t tough enough, but its absence will liberate Wall Street to go wild blowing new bubbles, which will inevitably burst, creating new economic shocks. Trump and his team are not unaware of this, they are simply unconcerned — the profits from those market bubbles are too tantalizing. Besides, they know that since the banks were never broken up, they are still too big to fail, which means that if it all comes crashing down, they will be bailed out again, just like in 2008. (In fact, Trump issued an executive order calling for a review of the specific part of Dodd-Frank designed to prevent taxpayers from being stuck with the bill for another such bailout — an ominous sign, especially with so many former Goldman executives making White House policy.) Some members of the administration surely also see a few coveted policy options opening up in the wake of a good market shock or two. During the campaign, Trump courted voters by promising not to touch Social Security or Medicare. But that may well be untenable, given the deep tax cuts on the way (and the fictional math beneath the claims that they will pay for themselves). His proposed budget already begins the attack on Social Security and an economic crisis would give Trump a handy excuse to abandon those promises altogether. In the midst of a moment being sold to the public as economic Armageddon, Betsy DeVos might even have a shot at realizing her dream of replacing public schools with a system based on vouchers and charters. Trump’s gang has a long wish list of policies that do not lend themselves to normal times. In the early days of the new administration, for instance, Mike Pence met with Wisconsin Gov. Scott Walker to hear how the governor had managed to strip public sector unions of their right to collective bargaining in 2011. (Hint: He used the cover of the state’s fiscal crisis, prompting New York Times columnist Paul Krugman to declare that in Wisconsin “the shock doctrine is on full display.”) Taken together, the picture is clear. We will very likely not see this administration’s full economic barbarism in the first year. That will only reveal itself later, after the inevitable budget crises and market shocks kick in. Then, in the name of rescuing the government and perhaps the entire economy, the White House will start checking off the more challenging items on the corporate wish list. Cattle menaced by a wildfire near Protection, Kansas, on March, 7, 2017. Photo: Bo Rader/Wichita Eagle/TNS/Getty Images Weather Shocks Just as Trump’s national security and economic policies are sure to generate and deepen crises, the administration’s moves to ramp up fossil fuel production, dismantle large parts of the country’s environmental laws, and trash the Paris climate accord all pave the way for more large-scale industrial accidents — not to mention future climate disasters. There is a lag time of about a decade between the release of carbon dioxide into the atmosphere and the full resulting warming, so the very worst climatic effects of the administration’s policies won’t likely be felt until they’re out of office. That said, we’ve already locked in so much warming that no president can complete a term without facing major weather-related disasters. In fact, Trump wasn’t even two months on the job before he was confronted with overwhelming wildfires on the Great Plains, which led to so many cattle deaths that one rancher described the event as “our Hurricane Katrina.” Trump showed no great interest in the fires, not even sparing them a tweet. But when the first superstorm hits a coast, we should expect a very different reaction from a president who knows the value of oceanfront property, has open contempt for the poor, and has only ever been interested in building for the 1 percent. The worry, of course, is a repeat of Katrina’s attacks on public housing and public schools, as well as the contractor free for all that followed the disaster, especially given the central role played by Mike Pence in shaping post-Katrina policy. The biggest Trump-era escalation, however, will most likely be in disaster response services marketed specifically toward the wealthy. When I was writing “The Shock Doctrine,” this industry was still in its infancy, and several early companies didn’t make it. I wrote, for instance, about a short-lived airline called Help Jet, based in Trump’s beloved West Palm Beach. While it lasted, Help Jet offered an array of gold-plated rescue services in exchange for a membership fee. When a hurricane was on its way, Help Jet dispatched limousines to pick up members, booked them into five-star golf resorts and spas somewhere safe, then whisked them away on private jets. “No standing in lines, no hassle with crowds, just a first-class experience that turns a problem into a vacation,” read the company’s marketing materials. “Enjoy the feeling of avoiding the usual hurricane evacuation nightmare.” With the benefit of hindsight, it seems Help Jet, far from misjudging the market for these services, was simply ahead of its time. These days, in Silicon Valley and on Wall Street, the more serious high-end survivalists are hedging against climate disruption and social collapse by buying space in custom-built underground bunkers in Kansas (protected by heavily armed mercenaries) and building escape homes on high ground in New Zealand. It goes without saying that you need your own private jet to get there. What is worrying about the entire top-of-the-line survivalist phenomenon (apart from its general weirdness) is that, as the wealthy create their own luxury escape hatches, there is diminishing incentive to maintain any kind of disaster response infrastructure that exists to help everyone, regardless of income — precisely the dynamic that led to enormous and unnecessary suffering in New Orleans during Katrina. And this two-tiered disaster infrastructure is galloping ahead at alarming speed. In fire-prone states such as California and Colorado, insurance companies provide a “concierge” service to their exclusive clients: When wildfires threaten their mansions, the companies dispatch teams of private firefighters to coat them in re-retardant. The public sphere, meanwhile, is left to further decay. California provides a glimpse of where this is all headed. For its firefighting, the state relies on upwards of 4,500 prison inmates, who are paid a dollar an hour when they’re on the fire line, putting their lives at risk battling wildfires, and about two bucks a day when they’re back at camp. By some estimates, California saves a billion dollars a year through this program — a snapshot of what happens when you mix austerity politics with mass incarceration and climate change. Migrants and refugees gather close to a border crossing near the Greek village of Idomeni, on March 5, 2016, where thousands of people wait to enter Macedonia. Photo: Dimitar Dilkoff/AFP/Getty Images A World of Green Zones and Red Zones The uptick in high-end disaster prep also means there is less reason for the big winners in our economy to embrace the demanding policy changes required to prevent an even warmer and more disaster-prone future. Which might help explain the Trump administration’s determination to do everything possible to accelerate the climate crisis. So far, much of the discussion around Trump’s environmental rollbacks has focused on supposed schisms between the members of his inner circle who actively deny climate science, including EPA head Scott Pruitt and Trump himself, and those who concede that humans are indeed contributing to planetary warming, such as Rex Tillerson and Ivanka Trump. But this misses the point: What everyone who surrounds Trump shares is a confidence that they, their children, and indeed their class will be just fine, that their wealth and connections will protect them from the worst of the shocks to come. They will lose some beachfront property, sure, but nothing that can’t be replaced with a new mansion on higher ground. This insouciance is representative of an extremely disturbing trend. In an age of ever-widening income inequality, a significant cohort of our elites are walling themselves off not just physically but also psychologically, mentally detaching themselves from the collective fate of the rest of humanity. This secessionism from the human species (if only in their own minds) liberates the rich not only to shrug off the urgent need for climate action but also to devise ever more predatory ways to profit from current and future disasters and instability. What we are hurtling toward is a world demarcated into fortified Green Zones for the super-rich, Red Zones for everyone else — and black sites for whoever doesn’t cooperate. Europe, Australia, and North America are erecting increasingly elaborate (and privatized) border fortresses to seal themselves off from people fleeing for their lives. Fleeing, quite often, as a direct result of forces unleashed primarily by those fortressed continents, whether predatory trade deals, wars, or ecological disasters intensified by climate change. In fact, if we chart the locations of the most intense conflict spots in the world right now — from the bloodiest battlefields in Afghanistan and Pakistan, to Libya, Yemen, Somalia, and Iraq — what becomes clear is that these also happen to be some of the hottest and driest places on earth. It takes very little to push these regions into drought and famine, which frequently acts as an accelerant to conflict, which of course drives migration. And the same capacity to discount the humanity of the “other,” which justifies civilian deaths and casualties from bombs and drones in places like Yemen and Somalia, is now being trained on the people in the boats — casting their need for security as a threat, their desperate flight as some sort of invading army. This is the context in which well over 13,000 people have drowned in the Mediterranean trying to reach European shores since 2014, many of them children, toddlers, and babies. It is the context in which the Australian government has sought to normalize the incarceration of refugees in island detention camps on Nauru and Manus, under conditions that numerous humanitarian organizations have described as tantamount to torture. This is also the context in which the massive, recently demolished migrant camp in Calais, France, was nicknamed “the jungle” — an echo of the way Katrina’s abandoned people were categorized in right-wing media as “animals.” The dramatic rise in right-wing nationalism, anti-Black racism, Islamophobia, and straight-up white supremacy over the past decade cannot be pried apart from these larger geopolitical and ecological trends. The only way to justify such barbaric forms of exclusion is to double down on theories of racial hierarchy that tell a story about how the people being locked out of the global Green Zone deserve their fate, whether it’s Trump casting Mexicans as rapists and “bad hombres,” and Syrian refugees as closet terrorists, or prominent Conservative Canadian politician Kellie Leitch proposing that immigrants be screened for “Canadian values,” or successive Australian prime ministers justifying those sinister island detention camps as a “humanitarian” alternative to death at sea. This is what global destabilization looks like in societies that have never redressed their foundational crimes — countries that have insisted slavery and indigenous land theft were just glitches in otherwise proud histories. After all, there is little more Green Zone/Red Zone than the economy of the slave plantation — of cotillions in the master’s house steps away from torture in the fields, all of it taking place on the violently stolen indigenous land on which North America’s wealth was built. And now the same theories of racial hierarchy that justified those violent thefts in the name of building the industrial age are surging to the surface as the system of wealth and comfort they constructed starts to unravel on multiple fronts simultaneously. Trump is just one early and vicious manifestation of that unraveling. He is not alone. He won’t be the last. Residents of the Mangueira ‘favela’ community, foreground, watch fireworks explode over Maracana stadium during opening ceremonies for the 2016 Olympic Games on Aug. 5, 2016, in Rio de Janeiro. Photo: Mario Tama/Getty Images A Crisis of Imagination It seems relevant that the walled city where the wealthy few live in relative luxury while the masses outside war with one another for survival is pretty much the default premise of every dystopian sci-fi movie that gets made these days, from “The Hunger Games,” with the decadent Capitol versus the desperate colonies, to “Elysium,” with its spa-like elite space station hovering above a sprawling and lethal favela. It’s a vision deeply enmeshed with the dominant Western religions, with their grand narratives of great floods washing the world clean and a chosen few selected to begin again. It’s the story of the great fires that sweep in, burning up the unbelievers and taking the righteous to a gated city in the sky. We have collectively imagined this extreme winners-and-losers ending for our species so many times that one of our most pressing tasks is learning to imagine other possible ends to the human story in which we come together in crisis rather than split apart, take down borders rather than erect more of them. Because the point of all that dystopian art was never to act as a temporal GPS, showing us where we are inevitably headed. The point was to warn us, to wake us — so that, seeing where this perilous road leads, we can decide to swerve. “We have it in our power to begin the world over again.” So said Thomas Paine many years ago, neatly summarizing the dream of escaping the past that is at the heart of both the colonial project and the American Dream. The truth, however, is that we do not have this godlike power of reinvention, nor did we ever. We must live with the messes and mistakes we have made, as well as within the limits of what our planet can sustain. But we do have it in our power to change ourselves, to attempt to right past wrongs, and to repair our relationships with one another and with the planet we share. It’s this work that is the bedrock of shock resistance. Adapted from the new book by Naomi Klein, No Is Not Enough: Resisting Trump’s Shock Politics and Winning the World We Need, to be published by Haymarket Books on June 13. www.noisnotenough.org
// Run compiles and executes a statement list. It returns, if applicable, a // RecordSet slice and/or an index and error. // // For more details please see DB.Execute // // Run is safe for concurrent use by multiple goroutines. func (db *DB) Run(ctx *TCtx, ql string, arg ...interface{}) (rs []Recordset, index int, err error) { l, err := Compile(ql) if err != nil { return nil, -1, err } return db.Execute(ctx, l, arg...) }
def ap_extract(data, trace_spl, sigma_spl, apwidth=2, skysep=1, skywidth=2, skydeg=0, sky_subtract=True): y_size, x_size = data.shape y_indices, x_indices = np.indices(data.shape) y_bins = np.arange(y_size) x_bins = np.arange(x_size) x_centers = trace_spl(y_bins) x_sigmas = sigma_spl(y_bins) ap_lows = x_centers - apwidth * x_sigmas ap_highs = x_centers + apwidth * x_sigmas right_sky_lows = x_centers - (apwidth + skysep + skywidth) * x_sigmas right_sky_highs = x_centers - (apwidth + skysep) * x_sigmas left_sky_lows = x_centers + (apwidth + skysep) * x_sigmas left_sky_highs = x_centers + (apwidth + skysep + skywidth) * x_sigmas ap_pixels = np.logical_and(ap_lows < x_indices, x_indices < ap_highs) right_sky_pixels = np.logical_and(right_sky_lows < x_indices, x_indices < right_sky_highs) left_sky_pixels = np.logical_and(left_sky_lows < x_indices, x_indices < left_sky_highs) sky_pixels = np.logical_or(right_sky_pixels, left_sky_pixels) aperture = np.empty(y_size) sky = np.empty(y_size) unc = np.empty(y_size) if not sky_subtract: for i in range(y_size): aperture[i] = np.nansum(data[i, ap_pixels[i]]) return aperture for i in range(y_size): data_slice = data[i] ap_slice = data_slice[ap_pixels[i]] aperture[i] = np.nansum(ap_slice) sky_slice = data_slice[sky_pixels[i]] x_sky = x_bins[sky_pixels[i]] x_ap = x_bins[ap_pixels[i]] if skydeg > 0: pfit = np.polyfit(x_sky, sky_slice, skydeg) sky[i] = np.nansum(np.polyval(pfit, x_ap)) elif skydeg == 0: sky[i] = np.nanmean(sky_slice) * (apwidth * x_sigmas[i] * 2 + 1) coaddN = 1 sigB = np.std(sky_slice) N_B = len(x_sky) N_A = apwidth * x_sigmas[i] * 2. + 1 unc[i] = np.sqrt(np.sum((aperture[i] - sky[i]) / coaddN) + (N_A + N_A**2. / N_B) * (sigB**2.)) return aperture, sky, unc
<filename>packages/trainee/src/modules/module3.ts import m from 'mithril'; import '../../css/module3.css'; import { sessionSvc, state } from '../global'; import help from './components/help'; import hud from './components/hud'; const updateSession = () => sessionSvc.update(state.session); const MODULE3 = { oninit: () => { state.session.activeModule = 'workAgreements'; state.session.activeStepIndex = 0; state.showHelp = true; updateSession(); }, view: () => { return m('div', { class: 'container' }, [ m(hud, { done: state.scenariosModule.show ? '/module4' : '', }), m(interaction), ]); }, }; const interaction = { view: () => { return m('div', { class: 'interactionArea' }, [ m( 'div', { class: 'row' }, state.showHelp ? m(help, { title: 'Title', desc: ['Discuss and enter 3 work agreements.'], }) : [ m('div', { class: 'agreements col s8 offset-s2' }, [ m( 'div', { class: 'row textareaWrap' }, m('textarea', { class: 'col s10 offset-s1', maxlength: 200 }) ), m( 'div', { class: 'row textareaWrap' }, m('textarea', { class: 'col s10 offset-s1', maxlength: 200 }) ), m( 'div', { class: 'row textareaWrap' }, m('textarea', { class: 'col s10 offset-s1', maxlength: 200 }) ), ]), ] ), ]); }, }; export default MODULE3;
#include<bits/stdc++.h> #define pb push_back #define f first #define s second using namespace std; int main() { int n,b,m,b1; cin >> n >> b; vector<int >v,v1; for(int i=0;i<n;i++) { int r; cin >> r; v.pb(r); } cin >> m >> b1; for(int i=0;i<m;i++) { int r; cin >> r; v1.pb(r); } reverse(v.begin(),v.end()); reverse(v1.begin(),v1.end()); long long p=0,k=0; //cout << b << endl; for(int i=0;i<n;i++) { long long a = pow(b,i); // cout << a << endl; long long q = v[i]*a; k += q; //cout << k << endl; } for(int i=0;i<m;i++) { p += v1[i]*pow(b1,i); } //cout << k << endl; //cout << p << endl; if(k==p) cout << "=" << endl; else if(k>p) cout << ">" << endl; else if(k<p) cout << "<" << endl; }
/* Arguments: in starting address of input data on this proc out starting address of where output data for this proc will be placed (can be same as in) flag 1 for forward FFT, -1 for inverse FFT plan plan returned by previous call to fft_3d_create_plan */ void fft_3d(FFT_DATA *in, FFT_DATA *out, int flag, struct fft_plan_3d *plan) { int i,offset,num; double norm; FFT_DATA *data,*copy; if (plan->pre_plan) { if (plan->pre_target == 0) copy = out; else copy = plan->copy; remap_3d((double *) in, (double *) copy, (double *) plan->scratch, plan->pre_plan); data = copy; } else data = in; if (flag == -1) fftw_execute_dft(plan->plan_fast_forward,data,data); else fftw_execute_dft(plan->plan_fast_backward,data,data); if (plan->mid1_target == 0) copy = out; else copy = plan->copy; remap_3d((double *) data, (double *) copy, (double *) plan->scratch, plan->mid1_plan); data = copy; if (flag == -1) fftw_execute_dft(plan->plan_mid_forward,data,data); else fftw_execute_dft(plan->plan_mid_backward,data,data); if (plan->mid2_target == 0) copy = out; else copy = plan->copy; remap_3d((double *) data, (double *) copy, (double *) plan->scratch, plan->mid2_plan); data = copy; if (flag == -1) fftw_execute_dft(plan->plan_slow_forward,data,data); else fftw_execute_dft(plan->plan_slow_backward,data,data); if (plan->post_plan) remap_3d((double *) data, (double *) out, (double *) plan->scratch, plan->post_plan); if (flag == 1 && plan->scaled) { norm = plan->norm; num = plan->normnum; for (i = 0; i < num; i++) { out[i][0] *= norm; out[i][1] *= norm; } } }
// ReloadSchemaShard is part of the vtctlservicepb.VtctldServer interface. func (s *VtctldServer) ReloadSchemaShard(ctx context.Context, req *vtctldatapb.ReloadSchemaShardRequest) (*vtctldatapb.ReloadSchemaShardResponse, error) { logger, getEvents := eventStreamLogger() var sema *sync2.Semaphore if req.Concurrency > 0 { sema = sync2.NewSemaphore(int(req.Concurrency), 0) } s.reloadSchemaShard(ctx, req, sema, logger) return &vtctldatapb.ReloadSchemaShardResponse{ Events: getEvents(), }, nil }
/** * @param storey Apache Jena Resource RDF node that refers to an * #IfcBuildingStorey ifcOWL element * @param ifcOWL The ifcOWL namespace element. * @return The list of all corresponding space ifcOWL elements under the storey * element */ public static List<RDFNode> listStoreySpaces(Resource storey, IfcOWL ifcOWL) { List<RDFNode> ret; ret = RDFUtils.pathQuery(storey, getNextLevelPath(ifcOWL)); RDFStep[] path2 = { new RDFStep(ifcOWL.getProperty("objectPlacement_IfcProduct")), new InvRDFStep(ifcOWL.getProperty("placementRelTo_IfcLocalPlacement")), new InvRDFStep(ifcOWL.getProperty("objectPlacement_IfcProduct")) }; ret.addAll(RDFUtils.pathQuery(storey, path2)); return ret; }
import {CLEAR_CONNECTED_MEMBER, SET_CONNECTED_MEMBER} from './actions'; import {ConnectedMemberState} from './types'; const INITIAL_STATE = null; export default function reducer( state: ConnectedMemberState = INITIAL_STATE, action: any ) { const {type, ...payload} = action; switch (type) { case SET_CONNECTED_MEMBER: return setConnectedMemberReducer(state, payload); case CLEAR_CONNECTED_MEMBER: return clearConnectedMemberReducer(); default: return state; } } function setConnectedMemberReducer( state: Partial<ConnectedMemberState>, payload: Record<string, any> ) { return {...state, ...payload}; } function clearConnectedMemberReducer() { return INITIAL_STATE; }
// API users.list: Lists all users in a Slack team. func (sl *Slack) UsersList() ([]*User, error) { uv := sl.urlValues() body, err := sl.GetRequest(usersListApiEndpoint, uv) if err != nil { return nil, err } res := new(UsersListAPIResponse) err = json.Unmarshal(body, res) if err != nil { return nil, err } if !res.Ok { return nil, errors.New(res.Error) } return res.Members() }
import { assert, IsExact } from 'conditional-type-checks'; import { MultiUint } from './multi'; // 1 * 1 = 1 assert<IsExact<MultiUint<[1], [1]>, [1, 0]>>(true); // 12 * 345 = 4140 assert< IsExact< MultiUint<[0, 0, 1, 1], [1, 0, 0, 1, 1, 0, 1, 0, 1]>, [0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1] > >(true); // 345 * 12 = 4140 assert< IsExact< MultiUint<[1, 0, 0, 1, 1, 0, 1, 0, 1], [0, 0, 1, 1]>, [0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1] > >(true); // 123456789 * 987654321 = 121932631112635269 // prettier-ignore assert< IsExact< MultiUint<[1,0,1,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,0,1,1,1], [1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,0,1,1,1]>, [1,0,1,0,0,0,0,1,1,1,0,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,1,0,0,0,1,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1] > >(true); // 987654321 * 123456789 = 121932631112635260 // prettier-ignore assert< IsExact< MultiUint<[1,0,0,0,1,1,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,0,1,1,1], [1,0,1,0,1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,1,0,1,0,1,1,1]>, [1,0,1,0,0,0,0,1,1,1,0,0,1,0,1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,0,1,0,1,0,0,0,1,0,0,0,1,1,0,0,1,0,0,0,1,1,0,1,1] > >(true);
def check_parent(self): self.all_joints = pm.ls(type="joint") joint_under_world = [] for joint in self.all_joints: if joint == "World": return om.MGlobal.displayError("This file already have world joint under world, please check it") joint_parent = pm.listRelatives(joint, allParents=True) if len(joint_parent) == 0: joint_under_world.append(joint) else: continue return joint_under_world
Republicans like Paul Ryan, Jeb Bush, Grover Norquist, et al. who insist that the House GOP pass Chuck Schumer’s amnesty bill are saying that Obama can be trusted to enforce whatever new immigration laws we come up with. As if there weren’t already abundant evidence of the absurdity of such trust, a Buzzfeed story adds to the pile. Advertisement Advertisement The story is about disagreement between Schumer and the White House over plans to water down enforcement even more. The less-sophisticated among the anti-borders Left are demanding that the ongoing review of deportation policy, designed to make it more “humane,” result in dramatic new curbs on the removal of illegal aliens or, even better, de facto amnesty for all illegals along the lines of Obama’s illegal DREAM Act–style DACA amnesty. Schumer — also part of the anti-borders Left, but smarter than the others — warns that any further curbs on deportation, even minor ones, would doom efforts to get Republicans to sign on to a broad amnesty bill. More interesting, though was this bit from the article: The administration is also reportedly looking at shortening the time an immigrant is considered new, and therefore a removal priority. A recent immigrant would go from someone who entered in the last three years, to someone who entered in the last two weeks. Advertisement Although I disagree as a matter of policy, the idea that an illegal has put down roots here after three years, and thus shouldn’t be deported, at least makes a certain kind of sense. But to exempt an illegal alien from deportation simply because he snuck in at least 15 days ago is surreal. Or, more accurately, it’s proof that the Left has no intention whatsoever of enforcing future immigration laws, even if all the illegals here today get amnesty. The goal of “comprehensive immigration reform” isn’t the fixing of any particular aspect of immigration law. It’s the abolition of immigration law.
#!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '0.0.2' from .loggers import BaseLoggers, Loggers from .datamodule import BaseDataModule, DataModule from .module import Module from .trainer import BaseTrainer, Trainer __all__ = ('__version__', 'Loggers', 'DataModule', 'Module', 'Trainer')
import asyncio import time from aiohttp import web from autorc.nodes import AsyncNode class MjpegStreamer(AsyncNode): ''' Stand alone mjpeg streamer (for testing only) ''' def __init__(self, context, *, inputs=('cam/image-jpeg', ), host='0.0.0.0', port=8888, frame_rate=24, **kwargs): super(MjpegStreamer, self).__init__(context, inputs=inputs, **kwargs) if not inputs or len(inputs) < 1: raise Exception('Input key (jpeg stream) is required') self.host = host self.port = port self.is_run = True self.frame_rate = frame_rate async def start_up(self): app = web.Application(logger=self.logger) self.app = app app.router.add_route('GET', "/", self.index) app.router.add_route('GET', "/image", self.handler) # Blocking run # web.run_app(app, host=self.host, port=self.port) self.runner = web.AppRunner(app) await self.runner.setup() site = web.TCPSite(self.runner, host=self.host, port=self.port) await site.start() async def shutdown(self): super(MjpegStreamer, self).shutdown() self.is_run = False await self.app.shutdown() await self.runner.cleanup() async def index(self, request): return web.Response( text='<img src="/image"/>', content_type='text/html') async def handler(self, request): self.logger.info('Client connected %s', request.raw_headers) boundary = "boundarydonotcross" response = web.StreamResponse(status=200, reason='OK', headers={ 'Content-Type': 'multipart/x-mixed-replace; ' 'boundary=--%s' % boundary, 'Cache-Control': 'no-cache' }) try: await response.prepare(request) max_sleep_time = 1.0 / self.frame_rate while self.is_run: start_time = time.time() frame = self.context.get(self.inputs[0]) if frame is not None: try: # Write header await response.write( '--{}\r\n'.format(boundary).encode('utf-8')) await response.write(b'Content-Type: image/jpeg\r\n') await response.write('Content-Length: {}\r\n'.format( len(frame)).encode('utf-8')) await response.write(b"\r\n") # Write data await response.write(frame) await response.write(b"\r\n") await response.drain() except ConnectionResetError as ex: print('Client connection closed') break except KeyboardInterrupt as ex: print('Keyboard Interrupt') break sleep_time = max_sleep_time - (time.time() - start_time) if sleep_time > 0: await asyncio.sleep(sleep_time) except asyncio.CancelledError: print('Client connection closed') finally: if response is not None: await response.write_eof() return response
<reponame>toshok/echojs<gh_stars>100-1000 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=4 sw=4 et tw=99 ft=cpp: */ #ifndef _ejs_h_ #define _ejs_h_ #include <stdio.h> #include <stdlib.h> #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if __cplusplus #define EJS_BEGIN_DECLS extern "C" { #define EJS_END_DECLS } #else #define EJS_BEGIN_DECLS #define EJS_END_DECLS #endif #define EJS_MACRO_START do { #define EJS_MACRO_END } while (0) #define EJS_STRINGIFY(x) #x #include "ejs-types.h" #include "ejs-log.h" // causes weakmap/weakset to use the inverted representation (as opposed to ephemeron-based weak tables) #define WEAK_COLLECTIONS_USE_INVERTED_REP 1 typedef int32_t EJSBool; #define EJS_TRUE 1 #define EJS_FALSE 0 #ifndef MIN #define MIN(a,b) ((a) > (b) ? (b) : (a)) #endif #ifndef MAX #define MAX(a,b) ((a) > (b) ? (a) : (b)) #endif #if IOS #import <Foundation/Foundation.h> #define LOG(...) NSLog (@__VA_ARGS__) #else #define LOG(...) fprintf (stderr, __VA_ARGS__) #endif #define EJS_NOT_IMPLEMENTED() EJS_MACRO_START \ _ejs_log ("%s:%s:%d not implemented.\n", __PRETTY_FUNCTION__, __FILE__, __LINE__); \ abort(); \ EJS_MACRO_END #define EJS_NOT_REACHED() EJS_MACRO_START \ _ejs_log ("%s:%s:%d should not be reached.\n", __PRETTY_FUNCTION__, __FILE__, __LINE__); \ abort(); \ EJS_MACRO_END #define EJS_ASSERT_VAL(assertion,msg,v) ({ EJS_ASSERT_MSG(assertion,msg); (v); }) #define EJS_ASSERT(assertion) EJS_ASSERT_MSG(assertion,#assertion) #define EJS_ASSERT_MSG(assertion,msg) EJS_MACRO_START \ if (!(assertion)) { \ _ejs_log ("%s:%s:%d assertion failed `%s'.\n", __PRETTY_FUNCTION__, __FILE__, __LINE__, (msg)); \ abort(); \ } \ EJS_MACRO_END typedef struct _EJSPrimString EJSPrimString; typedef struct _EJSPrimSymbol EJSPrimSymbol; typedef struct _EJSClosureEnv EJSClosureEnv; typedef struct _EJSObject EJSObject; #include "ejsval.h" #include "ejs-value.h" void _ejs_init(int argc, char** argv); extern const ejsval _ejs_undefined; extern const ejsval _ejs_null; extern ejsval _ejs_nan; extern const ejsval _ejs_Infinity; extern const ejsval _ejs_true; extern const ejsval _ejs_false; extern const ejsval _ejs_zero; extern const ejsval _ejs_one; extern const ejsval _ejs_false; extern ejsval _ejs_global; #define EJS_ATOM(atom) extern ejsval _ejs_atom_##atom; extern const jschar _ejs_ucs2_##atom[]; #define EJS_ATOM2(atom,atom_name) extern ejsval _ejs_atom_##atom_name; extern const jschar _ejs_ucs2_##atom_name[]; #include "ejs-atoms.h" typedef ejsval (*EJSClosureFunc) (ejsval env, ejsval *_this, uint32_t argc, ejsval* args, ejsval newTarget); #define EJS_NATIVE_FUNC(name) ejsval name (ejsval env, ejsval* _this, uint32_t argc, ejsval *args, ejsval newTarget) #endif // _ejs_h_
#include <stdio.h> #include <stdlib.h> #include <string.h> //#define DEBUG int main(void) { FILE *fpin; #ifdef DEBUG fpin=fopen("input.txt","r"); #else fpin=stdin; #endif while(feof(fpin)==0){ char buf[256]; int data[10]; fscanf(fpin,"%s\n",buf); int i; for(i=0;i<10;i++){ data[i]=buf[i]-'0'; } int n,j; for(n=10;n!=0;n--){ //n is num of data int data_tmp[10]; for(j=0;j<n-1;j++){ data_tmp[j]=(data[j]+data[j+1])%10; } memcpy((int*)data,(int*)data_tmp,sizeof(int)*10); } printf("%d\n",data[0]); } return 0; }