content
stringlengths
10
4.9M
/** * BoundQuery is a query with its bind variables */ @Data public class BoundQuery { // sql is the SQL query to execute private String sql; // bind_variables is a map of all bind variables to expand in the query. // nil values are not allowed. Use NULL_TYPE to express a NULL value. private Map<String, BindVariable> bindVariablesMap; public BoundQuery(String sql, Map<String, BindVariable> bindVariablesMap) { this.sql = sql; this.bindVariablesMap = bindVariablesMap; } public BoundQuery(String sql) { this.sql = sql; } }
using namespace std; #include<bits/stdc++.h> #define ll long long #define pr pair<ll,ll> #define pii pair<int,int> #define fir first #define sec second #define mp make_pair #define pb push_back #define sz(c) ((int)c.size()) #define all(c) (c).begin(),(c).end() #define fn "A" /// ___FILE_NAME_HERE___ #define rep(c,it) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++) #define __rep(c,it) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();it++) ll n,l,r,len=0,ans=0; void bs(ll lef,ll rig,ll k) { if(lef > rig or rig < l or lef > r)return ; ll mid=(lef+rig)/2; if(l<=mid and mid<=r)ans+=k%2; bs(lef,mid-1,k/2); bs(mid+1,rig,k/2); } int main(void) { #ifndef ONLINE_JUDGE freopen(fn".inp","r",stdin); freopen(fn".out","w",stdout); #endif // ONLINE_JUDGE cin>>n>>l>>r; ll k=n,cnt=1,sum=1; while(k > 0) { if(k==2 or k==3)break; sum+=2*cnt; cnt*=2; k/=2; } if(n==1 and l<=1 and 1<=r)puts("1"),exit(0); if(n==0 and l<=1 and 1<=r)puts("0"),exit(0); len=2*cnt+sum; bs(1,len,n); cout<<ans; }
void package___PACKAGE_NAME___register() { }
def find_events(**kwargs): def _build_event(onset, duration, combo): ev = Event(onset=onset, duration=duration, **combo) return ev events = [] prev_onset = 0 old_combo = None duration = 1 for r in xrange(len(kwargs.values()[0])): combo = dict([(k, v[r]) for k, v in kwargs.iteritems()]) if not combo == old_combo: if not old_combo is None: events.append(_build_event(prev_onset, duration, old_combo)) duration = 1 prev_onset = r old_combo = combo else: duration += 1 if not old_combo is None: events.append(_build_event(prev_onset, duration, old_combo)) return events
// Creating the list of regex used to check the expression const std::vector< std::vector <std::regex> > parser::createRegexList() { std::vector< std::vector <std::regex> > regexListReturn; regexListReturn.push_back({ std::regex{ "^[A-Z]" } }); regexListReturn.push_back({ std::regex{ "^(\\s)*=(\\s)*" } }); std::vector <std::regex> temp; for (const std::string gateName : gateNames) { temp.push_back(std::regex{ "^(\\s)*" + gateName + "(\\s)*" }); } regexListReturn.push_back(temp); regexListReturn.push_back({ std::regex{ "^(\\s)*\\((\\s)*" } }); regexListReturn.push_back({ std::regex{ "(\\s)*\\)(\\s)*$" } }); regexListReturn.push_back({ std::regex{ "^(\\s)*[a-z](\\s)*$" } }); return regexListReturn; }
/** * Prepares mapping of VxLan configuration based on device id.<br/> * * @param vxlanInstanceList collection of VxLan configuration * @return mapping of VxLan configuration based on device id. * @since SDNHUB 0.5 */ public static Map<String, List<SbiNeVxlanInstance>> divideVxlanInsByDeviceId(List<SbiNeVxlanInstance> vxlanInstanceList) { Map<String, List<SbiNeVxlanInstance>> deviceIdToVxlanInsMap = new HashMap<>(); for(SbiNeVxlanInstance sbiNeVxlanInstance : vxlanInstanceList) { String deviceId = sbiNeVxlanInstance.getDeviceId(); if(!deviceIdToVxlanInsMap.containsKey(deviceId)) { deviceIdToVxlanInsMap.put(deviceId, new ArrayList<SbiNeVxlanInstance>()); } deviceIdToVxlanInsMap.get(deviceId).add(sbiNeVxlanInstance); } return deviceIdToVxlanInsMap; }
/// Steals from other local queues. /// /// `start` specifies the queue from which to start stealing. pub(crate) fn steal(&self, start: usize) -> Option<Task<T>> { let num_queues = self.cluster.local.len(); for i in 0..num_queues { let i = (start + i) % num_queues; if i == self.index as usize { continue; } // safety: we own the dst queue let ret = unsafe { self.cluster.local[i].steal(self.local()) }; if ret.is_some() { return ret; } } None }
Using a live singer, instrument or even a taped recording, the national anthem is performed numerous times each day to open sporting events, special memorials and dozens of other occasions. Most times, the performance is nothing to write home about, but every so often someone screws up the song so bad that it becomes national news within moments. The very worst national anthem renditions include singers, athletes, actors and ordinary people who have flubbed the lines, put their own (unsuccessful) spin on the song or just messed up so bad that they never ever live it down. Though many will say that the Star Spangled Banner is a difficult song to sing on a vocal level because of its wide range, an octave and a half, of notes, that certainly doesn't make any excuse for forgetting the words. Taken from the 1814 poem titled "Defence of Fort McHenry" by Francis Scott Key, the words to the American anthem have always been the same, except when they're mangled by a performer. We all remember in 1990 when sitcom star Roseanne Barr made a joke of the Star Spangled Banner prior to a baseball game but that disastrous performance was certainly not the worst of the worst. Take for instance one Hamilton County Deputy Sheriff in Tennessee who made a somber memorial service for fallen law enforcement officers overly awkward after completely butchering the lyrics. Many have been criticized for small errors during performances such as when the likes of Christina Aguilera and Keri Hilson missed a few words, only to recover and end the song well. Others have attempted to add their own style to the iconic song but with horrible results. Take Steven Tyler for example. He tried to get the crowd at the 2001 Indianapolis 500 involved by adding the name of the event, plus an awkward harmonica solo, to the song. Veterans groups were far from amused and the Aerosmith crooner apologized. Same thing happened with R&B singer R. Kelly as he opened the Bernard Hopkins vs. Jermain Taylor boxing match in 2005. The crowd at the MGM Grand in Las Vegas as well as the one at home was not into it, especially the part where he urged watchers to clap and dance, leading to a complete failure. As these horrible, awful national anthem performances prove, it's better to perform the Star Spangled Banner well and not be noticed than to murder the song in front of thousands, if not millions of people. Consider yourself warned anthem singers.
/** * Wraps an underlying format element and adds ANSI colours. */ public class Colourizer implements FormatElement.Wrapping { public static final String RESET_COLOR = "\033[0m"; private final transient String ansiColorCode; private transient FormatElement wrapped; public Colourizer(String ansiColorCode, FormatElement wrapped) { this.ansiColorCode = ansiColorCode; this.wrapped = wrapped; } public Colourizer(String ansiColorCode) { this.ansiColorCode = ansiColorCode; } public static Colourizer wrap(FormatElement element, Color c) { return new Colourizer(c.code, element); } @Override public void setWrapped(FormatElement wrapped) { this.wrapped = wrapped; } @Override public boolean isWrapping() { return wrapped != null; } @Override public void appendTo(StringBuilder sb, ProgressMonitor monitor) { if (wrapped != null) { sb.append("\033[").append(ansiColorCode).append("m"); wrapped.appendTo(sb, monitor); sb.append(RESET_COLOR); } } public enum Color { BLACK("30"), RED("31"), GREEN("32"), YELLOW("33"), ; private final String code; Color(String code) { this.code = code; } /** * Parse the string form of the color enum. * @param s string form of color * @return an optional if parsed correctly (empty if not recognised) */ public static Optional<Color> parse(String s) { for (Color c : values()) { if (c.name().equals(s)) { return Optional.of(c); } } return Optional.empty(); } public String getCode() { return code; } } }
<commit_msg>Convert tabs to spaces in ModelSchema<commit_before>import { Tsoa } from './../metadataGeneration/tsoa'; /** * For Swagger, additionalProperties is implicitly allowed. So use this function to clarify that undefined should be associated with allowing additional properties * @param test if this is undefined then you should interpret it as a "yes" */ export function isDefaultForAdditionalPropertiesAllowed(test: TsoaRoute.ModelSchema['additionalProperties']): test is undefined { return test === undefined; } export namespace TsoaRoute { export interface Models { [name: string]: ModelSchema; } export interface ModelSchema { enums?: string[] | number[]; properties?: { [name: string]: PropertySchema }; additionalProperties?: boolean | PropertySchema; } export type ValidatorSchema = Tsoa.Validators; export interface PropertySchema { dataType?: Tsoa.TypeStringLiteral; ref?: string; required?: boolean; array?: PropertySchema; enums?: string[]; subSchemas?: PropertySchema[]; validators?: ValidatorSchema; default?: any; additionalProperties?: boolean | PropertySchema; nestedProperties?: { [name: string]: PropertySchema }; } export interface ParameterSchema extends PropertySchema { name: string; in: string; } export interface Security { [key: string]: string[]; } } <commit_after>import { Tsoa } from './../metadataGeneration/tsoa'; /** * For Swagger, additionalProperties is implicitly allowed. So use this function to clarify that undefined should be associated with allowing additional properties * @param test if this is undefined then you should interpret it as a "yes" */ export function isDefaultForAdditionalPropertiesAllowed(test: TsoaRoute.ModelSchema['additionalProperties']): test is undefined { return test === undefined; } export namespace TsoaRoute { export interface Models { [name: string]: ModelSchema; } export interface ModelSchema { enums?: string[] | number[]; properties?: { [name: string]: PropertySchema }; additionalProperties?: boolean | PropertySchema; } export type ValidatorSchema = Tsoa.Validators; export interface PropertySchema { dataType?: Tsoa.TypeStringLiteral; ref?: string; required?: boolean; array?: PropertySchema; enums?: string[]; subSchemas?: PropertySchema[]; validators?: ValidatorSchema; default?: any; additionalProperties?: boolean | PropertySchema; nestedProperties?: { [name: string]: PropertySchema }; } export interface ParameterSchema extends PropertySchema { name: string; in: string; } export interface Security { [key: string]: string[]; } }
/// Given a result of name lookup that had no viable results, diagnose the /// unviable ones. void FailureDiagnosis::diagnoseUnviableLookupResults( MemberLookupResult &result, Expr *E, Type baseObjTy, Expr *baseExpr, DeclNameRef memberName, DeclNameLoc nameLoc, SourceLoc loc) { SourceRange baseRange = baseExpr ? baseExpr->getSourceRange() : SourceRange(); if (result.UnviableCandidates.empty()) { MissingMemberFailure failure(CS, baseObjTy, memberName, CS.getConstraintLocator(E)); auto diagnosed = failure.diagnoseAsError(); assert(diagnosed && "Failed to produce missing member diagnostic"); (void)diagnosed; return; } auto firstProblem = result.UnviableReasons[0]; bool sameProblem = llvm::all_of( result.UnviableReasons, [&firstProblem](const MemberLookupResult::UnviableReason &problem) { return problem == firstProblem; }); auto instanceTy = baseObjTy; if (auto *MTT = instanceTy->getAs<AnyMetatypeType>()) instanceTy = MTT->getInstanceType(); if (sameProblem) { auto choice = llvm::find_if( result.UnviableCandidates, [&](const OverloadChoice &choice) { return choice.isDecl(); }); if (!choice) return; switch (firstProblem) { case MemberLookupResult::UR_WritableKeyPathOnReadOnlyMember: case MemberLookupResult::UR_ReferenceWritableKeyPathOnMutatingMember: case MemberLookupResult::UR_KeyPathWithAnyObjectRootType: break; case MemberLookupResult::UR_UnavailableInExistential: { InvalidMemberRefOnExistential failure( CS, instanceTy, memberName, CS.getConstraintLocator(E)); failure.diagnoseAsError(); return; } case MemberLookupResult::UR_InstanceMemberOnType: case MemberLookupResult::UR_TypeMemberOnInstance: { auto locatorKind = isa<SubscriptExpr>(E) ? ConstraintLocator::SubscriptMember : ConstraintLocator::Member; AllowTypeOrInstanceMemberFailure failure( CS, baseObjTy, choice->getDecl(), memberName, CS.getConstraintLocator(E, locatorKind)); auto diagnosed = failure.diagnoseAsError(); assert(diagnosed && "Failed to produce missing or extraneous metatype diagnostic"); (void)diagnosed; return; } case MemberLookupResult::UR_MutatingMemberOnRValue: case MemberLookupResult::UR_MutatingGetterOnRValue: { MutatingMemberRefOnImmutableBase failure(CS, choice->getDecl(), CS.getConstraintLocator(E)); (void)failure.diagnose(); return; } case MemberLookupResult::UR_Inaccessible: { If we found an inaccessible member of a protocol extension, it might be declared 'public'. This can only happen if the protocol is not visible to us, but the conforming type is. In this case, we need to clamp the formal access for diagnostics purposes to the formal access of the protocol itself. InaccessibleMemberFailure failure(CS, choice->getDecl(), CS.getConstraintLocator(E)); auto diagnosed = failure.diagnoseAsError(); assert(diagnosed && "failed to produce expected diagnostic"); for (auto cand : result.UnviableCandidates) { if (!cand.isDecl()) continue; auto *candidate = cand.getDecl(); failure is going to highlight candidate given to it, we just need to handle the rest here. if (candidate != choice->getDecl()) diagnose(candidate, diag::decl_declared_here, candidate->getFullName()); } return; } } } Otherwise, we don't have a specific issue to diagnose. Just say the vague 'cannot use' diagnostic. if (!baseObjTy->isEqual(instanceTy)) diagnose(loc, diag::could_not_use_type_member, instanceTy, memberName) .highlight(baseRange).highlight(nameLoc.getSourceRange()); else diagnose(loc, diag::could_not_use_value_member, baseObjTy, memberName) .highlight(baseRange).highlight(nameLoc.getSourceRange()); return; }
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, division, absolute_import import unittest import panphon from panphon import distance feature_model = 'segment' dim = 24 class TestLevenshtein(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_trivial1(self): self.assertEqual(self.dist.levenshtein_distance('pop', 'pʰop'), 1) def test_trivial2(self): self.assertEqual(self.dist.levenshtein_distance('pop', 'pʰom'), 2) class TestDolgoPrime(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_trivial1(self): self.assertEqual(self.dist.dolgo_prime_distance('pop', 'bob'), 0) def test_trivial2(self): self.assertEqual(self.dist.dolgo_prime_distance('pop', 'bab'), 0) class TestUnweightedFeatureEditDist(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_unweighted_substitution_cost(self): self.assertEqual(self.dist.unweighted_substitution_cost([0, 1, -1], [0, 1, 1]) * 3, 1) def test_unweighted_deletion_cost(self): self.assertEqual(self.dist.unweighted_deletion_cost([1, -1, 1, 0]) * 4, 3.5) def test_trivial1(self): self.assertEqual(self.dist.feature_edit_distance('bim', 'pym') * dim, 3) def test_trivial2(self): self.assertEqual(self.dist.feature_edit_distance('ti', 'tʰi') * dim, 1) def test_xsampa(self): self.assertEqual(self.dist.feature_edit_distance('t i', 't_h i', xsampa=True) * dim, 1) def test_xsampa2(self): self.assertEqual(self.dist.feature_edit_distance('p u n', 'p y n', xsampa=True) * dim, 1) def test_xsampa3(self): ipa = self.dist.jt_feature_edit_distance_div_maxlen('kʰin', 'pʰin') xs = self.dist.jt_feature_edit_distance_div_maxlen('k_h i n', 'p_h i n', xsampa=True) self.assertEqual(ipa, xs) class TestWeightedFeatureEditDist(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_trivial1(self): self.assertGreater(self.dist.weighted_feature_edit_distance('ti', 'tʰu'), self.dist.weighted_feature_edit_distance('ti', 'tʰi')) def test_trivial2(self): self.assertGreater(self.dist.weighted_feature_edit_distance('ti', 'te'), self.dist.weighted_feature_edit_distance('ti', 'tḭ')) class TestHammingFeatureEditDistanceDivMaxlen(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_hamming_substitution_cost(self): self.assertEqual(self.dist.hamming_substitution_cost(['+', '-', '0'], ['0', '-', '0']) * 3, 1) def test_trivial1(self): self.assertEqual(self.dist.hamming_feature_edit_distance_div_maxlen('pa', 'ba') * dim * 2, 1) def test_trivial2(self): self.assertEqual(self.dist.hamming_feature_edit_distance_div_maxlen('i', 'pi') * 2, 1) def test_trivial3(self): self.assertEqual(self.dist.hamming_feature_edit_distance_div_maxlen('sɛks', 'ɛɡz'), (1 + (1 / dim) + (1 / dim)) / 4) def test_trivial4(self): self.assertEqual(self.dist.hamming_feature_edit_distance_div_maxlen('k', 'ɡ'), 1 / dim) class TestMany(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) def test_fast_levenshtein_distance(self): self.assertEqual(self.dist.fast_levenshtein_distance('p', 'b'), 1) def test_fast_levenshtein_distance_div_maxlen(self): self.assertEqual(self.dist.fast_levenshtein_distance_div_maxlen('p', 'b'), 1) def test_dolgo_prime_distance(self): self.assertEqual(self.dist.dolgo_prime_distance('p', 'b'), 0) def test_dolgo_prime_div_maxlen(self): self.assertEqual(self.dist.dolgo_prime_distance_div_maxlen('p', 'b'), 0) def test_feature_edit_distance(self): self.assertEqual(self.dist.feature_edit_distance('p', 'b'), 1 / dim) def test_jt_feature_edit_distance(self): self.assertEqual(self.dist.jt_feature_edit_distance('p', 'b'), 1 / dim) def test_feature_edit_distance_div_maxlen(self): self.assertEqual(self.dist.feature_edit_distance_div_maxlen('p', 'b'), 1 / dim) def test_jt_feature_edit_distance_div_maxlen(self): self.assertEqual(self.dist.jt_feature_edit_distance_div_maxlen('p', 'b'), 1 / dim) def test_hamming_feature_edit_distance(self): self.assertEqual(self.dist.hamming_feature_edit_distance('p', 'b'), 1 / dim) def test_jt_hamming_feature_edit_distance(self): self.assertEqual(self.dist.jt_hamming_feature_edit_distance('p', 'b'), 1 / dim) def test_hamming_feature_edit_distance_div_maxlen(self): self.assertEqual(self.dist.hamming_feature_edit_distance_div_maxlen('p', 'b'), 1 / dim) def test_jt_hamming_feature_edit_distance_div_maxlen(self): self.assertEqual(self.dist.jt_hamming_feature_edit_distance_div_maxlen('p', 'b'), 1 / dim) class TestXSampa(unittest.TestCase): def setUp(self): self.dist = distance.Distance(feature_model=feature_model) self.ft = panphon.FeatureTable() def test_feature_edit_distance(self): self.assertEqual(self.dist.feature_edit_distance("p_h", "p", xsampa=True), 1 / dim)
import AnkeBehandlingProsessStegPanelDef from './prosessStegPaneler/AnkeBehandlingProsessStegPanelDef'; import AnkeResultatProsessStegPanelDef from './prosessStegPaneler/AnkeResultatProsessStegPanelDef'; import AnkeMerknaderProsessStegPanelDef from './prosessStegPaneler/AnkeMerknaderProsessStegPanelDef'; const prosessStegPanelDefinisjoner = [ new AnkeBehandlingProsessStegPanelDef(), new AnkeResultatProsessStegPanelDef(), new AnkeMerknaderProsessStegPanelDef(), ]; export default prosessStegPanelDefinisjoner;
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #ifndef CRYINCLUDE_EDITOR_CLIPBOARD_H #define CRYINCLUDE_EDITOR_CLIPBOARD_H #pragma once #include "Include/EditorCoreAPI.h" #include <QTimer> class CImageEx; class QVariant; class QWidget; /** Use this class to put and get stuff from windows clipboard. */ class EDITOR_CORE_API CClipboard { public: CClipboard(QWidget* parent); //! Put xml node into clipboard void Put(XmlNodeRef& node, const QString& title = QString()); //! Get xml node to clipboard. XmlNodeRef Get() const; //! Put string into Windows clipboard. void PutString(const QString& text, const QString& title = QString()); //! Get string from Windows clipboard. QString GetString() const; //! Return name of what is in clipboard now. QString GetTitle() const { return m_title; }; //! Put image into Windows clipboard. void PutImage(const CImageEx& img); //! Get image from Windows clipboard. bool GetImage(CImageEx& img); //! Return true if clipboard is empty. bool IsEmpty() const; private: // Resolves the last request Put operation void SendPendingPut(); AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING static XmlNodeRef m_node; AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING static QString m_title; static QVariant s_pendingPut; QWidget* m_parent; QTimer m_putDebounce; }; #endif // CRYINCLUDE_EDITOR_CLIPBOARD_H
def find_commit(repo, local_repo, version, branch='master'): description_path = local_repo / 'DESCRIPTION' for commit in repo.iter_commits(branch): repo.git.checkout(commit) with open(description_path) as description: description.readline() description = description.readline().strip() description = description.split(': ')[1] print(description) if description == version: sha = commit.hexsha print(f'version {version} was found in the {sha} commit') print('try to build it in the correspondent image') return sha raise ValueError(f'{version} was not found')
// process reads results produced by the checker and distributes them // to the publishers. func (r *Runner) process() { r.log.Debug("process() loop start") for { select { case result := <-r.publishChan: if result == nil { continue } for label, publisher := range r.publishers { go func() { l := r.log.New("check", result.Name, "publisher", label) l.Debug("Publishing check result to publisher") if err := publisher.Publish(result); err != nil { l.Warn("Error publishing check result", "error", err) } else { l.Debug("Check result published") } }() } case <-r.done: return } } r.log.Debug("process() loop end") }
<reponame>snytkine/bind-rest import { IBindRestContext } from '../interfaces/icontext'; export type IControllerMatcher = (ctx: IBindRestContext) => boolean;
<gh_stars>0 /* Driver program; runs compiler to generate a full program from one line */ #include <iostream> #include <fstream> #include <string> #include "compiler.hh" void generate_main (const std::string class_name, std::ofstream& ofs) { std::string object_name("sample_object"); /* int main () { SampleClass sc; sc.run(); sc.dump(); return 0; } */ ofs << "int main () {" << '\n'; ofs << class_name << " " << object_name << ";" << '\n'; ofs << object_name << ".run();" << '\n'; ofs << object_name << ".dump();" << '\n'; ofs << "return 0; }" << '\n'; } int main () { const std::string PROJ_ROOT("/home/ubuntu/workspace/"); std::string class_name("SampleClass"); std::string output_filename("test/src/" + class_name + ".cc"); std::ofstream ofs(output_filename, std::ofstream::out); ds_compiler::Compiler my_compiler(ofs); const std::string PROMPT("Enter the line to be compiled:\n"); std::string input_line = ""; std::cout << PROMPT; std::getline(std::cin, input_line); std::vector<std::string> program; program.push_back(input_line); //wrap in try/catch try { my_compiler.compile_full(program, class_name); generate_main(class_name, ofs); std::cout << class_name << " compiled successfully to " << output_filename << "." << '\n'; std::cout << "Run 'make sample' to build; bin/sample to execute." << '\n'; } catch (std::exception &ex) { std::cerr << ex.what() << '\n'; } return 0; }
// tslint:disable: no-console /// <reference lib="esnext.asynciterable" /> import { google } from 'googleapis' import { default as readline } from 'readline-promise' import { readFile, writeFile, createWriteStream, exists, rename } from 'fs' import { default as fetch } from 'node-fetch' import { mkdirp } from 'mkdirp' import { promisify } from 'util' import { join } from 'path' import { parallelMap, consume, buffer, writeToStream, pipeline, flatMap } from 'streaming-iterables' import { OAuth2Client } from 'google-auth-library' const readFileAsync = promisify(readFile) const writeFileAsync = promisify(writeFile) const mkdirpAsync = path => new Promise((resolve, reject) => mkdirp(path, err => (err ? reject(err) : resolve()))) const existsAsync = promisify(exists) const renameAsync = promisify(rename) const clientCredsPath = './clientCreds.json' const REDIRECT = 'http://localhost' const credCachePath = './auth.json' const PHOTO_SEARCH_URL = 'https://photoslibrary.googleapis.com/v1/mediaItems:search' async function authClient(rlp) { const { CLIENT_ID, CLIENT_SECRET } = await JSON.parse(await readFileAsync(clientCredsPath, { encoding: 'utf8'})) const oAuthClient = new google.auth.OAuth2({ clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, redirectUri: REDIRECT, }) oAuthClient.on('tokens', tokens => { console.log('writing new tokens to disk', JSON.stringify(tokens, null, 2)) writeFileAsync(credCachePath, JSON.stringify(tokens, null, 2)).then(() => console.log('done writing tokens')) }) const creds: string | null = await readFileAsync(credCachePath, { encoding: 'utf8' }).catch(i => null) if (creds) { console.log('Using cached creds') oAuthClient.setCredentials(JSON.parse(creds)) return oAuthClient } const url = oAuthClient.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/photoslibrary.readonly', prompt: 'consent', }) console.log(`Authorize this app by visiting this url: ${url}`) const code = await rlp.questionAsync('Enter the code in the address bar without the "#"(?code=<code>#) ') const { tokens } = await oAuthClient.getToken(code) await writeFileAsync(credCachePath, JSON.stringify(tokens, null, 2)) oAuthClient.setCredentials(tokens) return oAuthClient } interface MediaItem { id: string baseUrl: string mediaMetadata: { photo: boolean video: boolean creationTime?: string width: number height: number } } type SearchResponse = | { error: { status: string; message: string } nextPageToken: undefined mediaItems: undefined } | { error: undefined nextPageToken?: string mediaItems: MediaItem[] } async function* fetchPhotos( albumId: string, oAuthClient: OAuth2Client, pageToken?: string ): AsyncIterable<MediaItem[]> { console.log('getting request metadata') const authHeaders = await oAuthClient.getRequestHeaders() console.log('Fetching photos') const response = await fetch(PHOTO_SEARCH_URL, { headers: { ...authHeaders, 'content-type': 'application/json', }, method: 'POST', body: JSON.stringify({ albumId, pageSize: 100, ...(pageToken && { pageToken }), // trick to only add this if it's truthy }), }) const { mediaItems, nextPageToken, error } = (await response.json()) as SearchResponse if (error) { throw new Error(`${error.status}:${error.message}`) } if (!mediaItems) { throw new Error("This error exists because I don't know enough typescript") } console.log(`${mediaItems.length} Photos fetched`) yield mediaItems // cheap blows the stack way but I love it if (nextPageToken) { yield* fetchPhotos(albumId, oAuthClient, nextPageToken) } } const parseMediaItems = function*(mediaItems: MediaItem[]) { for (const item of mediaItems) { const { id, baseUrl, mediaMetadata } = item const idSlice = (id as string).slice(-4) const createdAtSafe = (mediaMetadata.creationTime || 'unknown').replace(/:/g, '_') const fileName = `${createdAtSafe}-${idSlice}` const { width, height } = mediaMetadata if (mediaMetadata.photo) { yield { fileName: `${fileName}.jpg`, url: `${baseUrl}=w${width}-h${height}`, } } else if (mediaMetadata.video) { yield { fileName: `${fileName}.mp4`, url: `${baseUrl}=dv`, } } else { console.log(item) throw new Error('unknown media type!') } } } const saveMedia = (folder: string) => async (media: { fileName: string; url: string }) => { const start = Date.now() if (!media) { return 'what happened!' + JSON.stringify({ media }) } const { url, fileName } = media const path = join(folder, fileName) if (await existsAsync(path)) { console.log(`File already Exists ${fileName}`) return fileName } const tmpPath = join(folder, `${fileName}-downloading`) const request = await fetch(url, { method: 'GET' }) const file = createWriteStream(tmpPath) await writeToStream(file, request.body) file.close() await new Promise(resolve => file.once('close', resolve)) await renameAsync(tmpPath, path) console.log(`Downloaded ${fileName} in ${Date.now() - start}ms`) return fileName } async function main() { const rlp = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true, }) const albumId = process.argv[2] || (await rlp.questionAsync('albumId? ')) const folderName = process.argv[3] || (await rlp.questionAsync('folder name? [./photos] ')) || './photos' const oAuthClient = await authClient(rlp) rlp.close() await mkdirpAsync(folderName) await pipeline( () => fetchPhotos(albumId, oAuthClient), buffer(2), flatMap(parseMediaItems), parallelMap(10, saveMedia(folderName)), consume ) } main().then( () => process.exit(0), err => { console.error(err.stack) process.exit(1) } )
package billtypeservice import ( "github.com/Samoy/bill_backend/config" "github.com/Samoy/bill_backend/dao" "github.com/Samoy/bill_backend/models" "github.com/stretchr/testify/assert" "os" "testing" ) func setup() { config.Setup("../../app.ini") dao.Setup(config.DatabaseConf.Type, config.DatabaseConf.User, config.DatabaseConf.Password, config.DatabaseConf.Host, config.DatabaseConf.Name, config.DatabaseConf.TablePrefix, ) } var billTypeID uint var ownerID uint = 1 func TestMain(m *testing.M) { setup() code := m.Run() teardown() os.Exit(code) } func TestAddBillType(t *testing.T) { type args struct { billType *models.BillType } tests := []struct { name string args args wantErr bool }{ { "Add Bill Type", args{ &models.BillType{ Name: "Test Bill Type", Image: "/testpath", Owner: ownerID, }, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := AddBillType(tt.args.billType); (err != nil) != tt.wantErr { t.Errorf("AddBillType() error = %v, wantErr %v", err, tt.wantErr) } else { billTypeID = tt.args.billType.ID } }) } } func TestGetBillType(t *testing.T) { type args struct { billTypeID uint } tests := []struct { name string args args wantErr bool }{ { "Get Bill Type", args{ billTypeID, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetBillType(tt.args.billTypeID) if (err != nil) != tt.wantErr { t.Errorf("GetBillType() error = %v, wantErr %v", err, tt.wantErr) return } assert.NotEmpty(t, got, "GetBillType() test not pass") }) } } func TestUpdateBillType(t *testing.T) { type args struct { billTypeID uint data map[string]interface{} } tests := []struct { name string args args wantErr bool }{ { "Update Bill Type", args{ billTypeID, map[string]interface{}{ "name": "After update Bill Type", "owner": ownerID, "image": "/after_update_bill_type_path", }, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if billType, err := UpdateBillType(tt.args.billTypeID, ownerID, tt.args.data); (err != nil) != tt.wantErr { t.Errorf("UpdateBillType() error = %v, wantErr %v", err, tt.wantErr) assert.NotEmpty(t, billType, "Update bill type service not pass") } }) } } func TestGetBillTypeList(t *testing.T) { type args struct { ownerID uint } tests := []struct { name string args args wantErr bool }{ { "Get Bill Type List", args{ ownerID, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetBillTypeList(tt.args.ownerID) if (err != nil) != tt.wantErr { t.Errorf("GetBillTypeList() error = %v, wantErr %v", err, tt.wantErr) return } assert.NotEmpty(t, got, "GetBillTypeList() test not pass") }) } } func TestDeleteBillType(t *testing.T) { type args struct { billTypeID uint ownerID uint } tests := []struct { name string args args wantErr bool }{ { "Delete Bill Type", args{ billTypeID, ownerID, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := DeleteBillType(tt.args.billTypeID, tt.args.ownerID); (err != nil) != tt.wantErr { t.Errorf("DeleteBillType() error = %v, wantErr %v", err, tt.wantErr) } }) } } func teardown() { _ = dao.CloseDB() }
<reponame>daitangio/ahab from fastapi import FastAPI, Depends from pydantic import BaseModel # consider also https://fastapi.tiangolo.com/tutorial/static-files/ app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None amazon_prime: bool = True @app.get("/") def read_root(): return {"Hello": "World!"} # i.e. http://127.0.0.1:8000/items/5?q=somequery @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): """ Try http://127.0.0.1:8000/items/5?q=somequery """ return {"item_id": item_id, "q": q} @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id} def login_data(user: str, api_key: str): return { "api_pass": <PASSWORD>+"@"+api_key} # See https://fastapi.tiangolo.com/tutorial/security/http-basic-auth/ @app.put("/login") def login(login_data: dict = Depends(login_data)): login_data["result"]="logged_in" return login_data ## Slow down alert import logging,time from starlette.requests import Request @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers["X-Process-Time"] = str(process_time) if process_time >0.02: logging.warn(str(request.url) +" Executed into: "+str(process_time)) return response
/* * QEMU PowerPC PowerNV Emulation of some SBE behaviour * * Copyright (c) 2022, IBM Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include "qemu/osdep.h" #include "target/ppc/cpu.h" #include "qapi/error.h" #include "qemu/log.h" #include "qemu/module.h" #include "hw/irq.h" #include "hw/qdev-properties.h" #include "hw/ppc/pnv.h" #include "hw/ppc/pnv_xscom.h" #include "hw/ppc/pnv_sbe.h" #include "trace.h" /* * Most register and command definitions come from skiboot. * * xscom addresses are adjusted to be relative to xscom subregion bases */ /* * SBE MBOX register address * Reg 0 - 3 : Host to send command packets to SBE * Reg 4 - 7 : SBE to send response packets to Host */ #define PSU_HOST_SBE_MBOX_REG0 0x00000000 #define PSU_HOST_SBE_MBOX_REG1 0x00000001 #define PSU_HOST_SBE_MBOX_REG2 0x00000002 #define PSU_HOST_SBE_MBOX_REG3 0x00000003 #define PSU_HOST_SBE_MBOX_REG4 0x00000004 #define PSU_HOST_SBE_MBOX_REG5 0x00000005 #define PSU_HOST_SBE_MBOX_REG6 0x00000006 #define PSU_HOST_SBE_MBOX_REG7 0x00000007 #define PSU_SBE_DOORBELL_REG_RW 0x00000010 #define PSU_SBE_DOORBELL_REG_AND 0x00000011 #define PSU_SBE_DOORBELL_REG_OR 0x00000012 #define PSU_HOST_DOORBELL_REG_RW 0x00000013 #define PSU_HOST_DOORBELL_REG_AND 0x00000014 #define PSU_HOST_DOORBELL_REG_OR 0x00000015 /* * Doorbell register to trigger SBE interrupt. Set by OPAL to inform * the SBE about a waiting message in the Host/SBE mailbox registers */ #define HOST_SBE_MSG_WAITING PPC_BIT(0) /* * Doorbell register for host bridge interrupt. Set by the SBE to inform * host about a response message in the Host/SBE mailbox registers */ #define SBE_HOST_RESPONSE_WAITING PPC_BIT(0) #define SBE_HOST_MSG_READ PPC_BIT(1) #define SBE_HOST_STOP15_EXIT PPC_BIT(2) #define SBE_HOST_RESET PPC_BIT(3) #define SBE_HOST_PASSTHROUGH PPC_BIT(4) #define SBE_HOST_TIMER_EXPIRY PPC_BIT(14) #define SBE_HOST_RESPONSE_MASK (PPC_BITMASK(0, 4) | \ SBE_HOST_TIMER_EXPIRY) /* SBE Control Register */ #define SBE_CONTROL_REG_RW 0x00000000 /* SBE interrupt s0/s1 bits */ #define SBE_CONTROL_REG_S0 PPC_BIT(14) #define SBE_CONTROL_REG_S1 PPC_BIT(15) struct sbe_msg { uint64_t reg[4]; }; static uint64_t pnv_sbe_power9_xscom_ctrl_read(void *opaque, hwaddr addr, unsigned size) { uint32_t offset = addr >> 3; uint64_t val = 0; switch (offset) { default: qemu_log_mask(LOG_UNIMP, "SBE Unimplemented register: Ox%" HWADDR_PRIx "\n", addr >> 3); } trace_pnv_sbe_xscom_ctrl_read(addr, val); return val; } static void pnv_sbe_power9_xscom_ctrl_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { uint32_t offset = addr >> 3; trace_pnv_sbe_xscom_ctrl_write(addr, val); switch (offset) { default: qemu_log_mask(LOG_UNIMP, "SBE Unimplemented register: Ox%" HWADDR_PRIx "\n", addr >> 3); } } static const MemoryRegionOps pnv_sbe_power9_xscom_ctrl_ops = { .read = pnv_sbe_power9_xscom_ctrl_read, .write = pnv_sbe_power9_xscom_ctrl_write, .valid.min_access_size = 8, .valid.max_access_size = 8, .impl.min_access_size = 8, .impl.max_access_size = 8, .endianness = DEVICE_BIG_ENDIAN, }; static void pnv_sbe_set_host_doorbell(PnvSBE *sbe, uint64_t val) { val &= SBE_HOST_RESPONSE_MASK; /* Is this right? What does HW do? */ sbe->host_doorbell = val; trace_pnv_sbe_reg_set_host_doorbell(val); qemu_set_irq(sbe->psi_irq, !!val); } /* SBE Target Type */ #define SBE_TARGET_TYPE_PROC 0x00 #define SBE_TARGET_TYPE_EX 0x01 #define SBE_TARGET_TYPE_PERV 0x02 #define SBE_TARGET_TYPE_MCS 0x03 #define SBE_TARGET_TYPE_EQ 0x04 #define SBE_TARGET_TYPE_CORE 0x05 /* SBE MBOX command class */ #define SBE_MCLASS_FIRST 0xD1 #define SBE_MCLASS_CORE_STATE 0xD1 #define SBE_MCLASS_SCOM 0xD2 #define SBE_MCLASS_RING 0xD3 #define SBE_MCLASS_TIMER 0xD4 #define SBE_MCLASS_MPIPL 0xD5 #define SBE_MCLASS_SECURITY 0xD6 #define SBE_MCLASS_GENERIC 0xD7 #define SBE_MCLASS_LAST 0xD7 /* * Commands are provided in xxyy form where: * - xx : command class * - yy : command * * Both request and response message uses same seq ID, * command class and command. */ #define SBE_CMD_CTRL_DEADMAN_LOOP 0xD101 #define SBE_CMD_MULTI_SCOM 0xD201 #define SBE_CMD_PUT_RING_FORM_IMAGE 0xD301 #define SBE_CMD_CONTROL_TIMER 0xD401 #define SBE_CMD_GET_ARCHITECTED_REG 0xD501 #define SBE_CMD_CLR_ARCHITECTED_REG 0xD502 #define SBE_CMD_SET_UNSEC_MEM_WINDOW 0xD601 #define SBE_CMD_GET_SBE_FFDC 0xD701 #define SBE_CMD_GET_CAPABILITY 0xD702 #define SBE_CMD_READ_SBE_SEEPROM 0xD703 #define SBE_CMD_SET_FFDC_ADDR 0xD704 #define SBE_CMD_QUIESCE_SBE 0xD705 #define SBE_CMD_SET_FABRIC_ID_MAP 0xD706 #define SBE_CMD_STASH_MPIPL_CONFIG 0xD707 /* SBE MBOX control flags */ /* Generic flags */ #define SBE_CMD_CTRL_RESP_REQ 0x0100 #define SBE_CMD_CTRL_ACK_REQ 0x0200 /* Deadman loop */ #define CTRL_DEADMAN_LOOP_START 0x0001 #define CTRL_DEADMAN_LOOP_STOP 0x0002 /* Control timer */ #define CONTROL_TIMER_START 0x0001 #define CONTROL_TIMER_STOP 0x0002 /* Stash MPIPL config */ #define SBE_STASH_KEY_SKIBOOT_BASE 0x03 static void sbe_timer(void *opaque) { PnvSBE *sbe = opaque; trace_pnv_sbe_cmd_timer_expired(); pnv_sbe_set_host_doorbell(sbe, sbe->host_doorbell | SBE_HOST_TIMER_EXPIRY); } static void do_sbe_msg(PnvSBE *sbe) { struct sbe_msg msg; uint16_t cmd, ctrl_flags, seq_id; int i; memset(&msg, 0, sizeof(msg)); for (i = 0; i < 4; i++) { msg.reg[i] = sbe->mbox[i]; } cmd = msg.reg[0]; seq_id = msg.reg[0] >> 16; ctrl_flags = msg.reg[0] >> 32; trace_pnv_sbe_msg_recv(cmd, seq_id, ctrl_flags); if (ctrl_flags & SBE_CMD_CTRL_ACK_REQ) { pnv_sbe_set_host_doorbell(sbe, sbe->host_doorbell | SBE_HOST_MSG_READ); } switch (cmd) { case SBE_CMD_CONTROL_TIMER: if (ctrl_flags & CONTROL_TIMER_START) { uint64_t us = msg.reg[1]; trace_pnv_sbe_cmd_timer_start(us); timer_mod(sbe->timer, qemu_clock_get_us(QEMU_CLOCK_VIRTUAL) + us); } if (ctrl_flags & CONTROL_TIMER_STOP) { trace_pnv_sbe_cmd_timer_stop(); timer_del(sbe->timer); } break; default: qemu_log_mask(LOG_UNIMP, "SBE Unimplemented command: 0x%x\n", cmd); } } static void pnv_sbe_set_sbe_doorbell(PnvSBE *sbe, uint64_t val) { val &= HOST_SBE_MSG_WAITING; sbe->sbe_doorbell = val; if (val & HOST_SBE_MSG_WAITING) { sbe->sbe_doorbell &= ~HOST_SBE_MSG_WAITING; do_sbe_msg(sbe); } } static uint64_t pnv_sbe_power9_xscom_mbox_read(void *opaque, hwaddr addr, unsigned size) { PnvSBE *sbe = PNV_SBE(opaque); uint32_t offset = addr >> 3; uint64_t val = 0; if (offset <= PSU_HOST_SBE_MBOX_REG7) { uint32_t idx = offset - PSU_HOST_SBE_MBOX_REG0; val = sbe->mbox[idx]; } else { switch (offset) { case PSU_SBE_DOORBELL_REG_RW: val = sbe->sbe_doorbell; break; case PSU_HOST_DOORBELL_REG_RW: val = sbe->host_doorbell; break; default: qemu_log_mask(LOG_UNIMP, "SBE Unimplemented register: Ox%" HWADDR_PRIx "\n", addr >> 3); } } trace_pnv_sbe_xscom_mbox_read(addr, val); return val; } static void pnv_sbe_power9_xscom_mbox_write(void *opaque, hwaddr addr, uint64_t val, unsigned size) { PnvSBE *sbe = PNV_SBE(opaque); uint32_t offset = addr >> 3; trace_pnv_sbe_xscom_mbox_write(addr, val); if (offset <= PSU_HOST_SBE_MBOX_REG7) { uint32_t idx = offset - PSU_HOST_SBE_MBOX_REG0; sbe->mbox[idx] = val; } else { switch (offset) { case PSU_SBE_DOORBELL_REG_RW: pnv_sbe_set_sbe_doorbell(sbe, val); break; case PSU_SBE_DOORBELL_REG_AND: pnv_sbe_set_sbe_doorbell(sbe, sbe->sbe_doorbell & val); break; case PSU_SBE_DOORBELL_REG_OR: pnv_sbe_set_sbe_doorbell(sbe, sbe->sbe_doorbell | val); break; case PSU_HOST_DOORBELL_REG_RW: pnv_sbe_set_host_doorbell(sbe, val); break; case PSU_HOST_DOORBELL_REG_AND: pnv_sbe_set_host_doorbell(sbe, sbe->host_doorbell & val); break; case PSU_HOST_DOORBELL_REG_OR: pnv_sbe_set_host_doorbell(sbe, sbe->host_doorbell | val); break; default: qemu_log_mask(LOG_UNIMP, "SBE Unimplemented register: Ox%" HWADDR_PRIx "\n", addr >> 3); } } } static const MemoryRegionOps pnv_sbe_power9_xscom_mbox_ops = { .read = pnv_sbe_power9_xscom_mbox_read, .write = pnv_sbe_power9_xscom_mbox_write, .valid.min_access_size = 8, .valid.max_access_size = 8, .impl.min_access_size = 8, .impl.max_access_size = 8, .endianness = DEVICE_BIG_ENDIAN, }; static void pnv_sbe_power9_class_init(ObjectClass *klass, void *data) { PnvSBEClass *psc = PNV_SBE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); dc->desc = "PowerNV SBE Controller (POWER9)"; psc->xscom_ctrl_size = PNV9_XSCOM_SBE_CTRL_SIZE; psc->xscom_ctrl_ops = &pnv_sbe_power9_xscom_ctrl_ops; psc->xscom_mbox_size = PNV9_XSCOM_SBE_MBOX_SIZE; psc->xscom_mbox_ops = &pnv_sbe_power9_xscom_mbox_ops; } static const TypeInfo pnv_sbe_power9_type_info = { .name = TYPE_PNV9_SBE, .parent = TYPE_PNV_SBE, .instance_size = sizeof(PnvSBE), .class_init = pnv_sbe_power9_class_init, }; static void pnv_sbe_power10_class_init(ObjectClass *klass, void *data) { PnvSBEClass *psc = PNV_SBE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass); dc->desc = "PowerNV SBE Controller (POWER10)"; psc->xscom_ctrl_size = PNV10_XSCOM_SBE_CTRL_SIZE; psc->xscom_ctrl_ops = &pnv_sbe_power9_xscom_ctrl_ops; psc->xscom_mbox_size = PNV10_XSCOM_SBE_MBOX_SIZE; psc->xscom_mbox_ops = &pnv_sbe_power9_xscom_mbox_ops; } static const TypeInfo pnv_sbe_power10_type_info = { .name = TYPE_PNV10_SBE, .parent = TYPE_PNV9_SBE, .class_init = pnv_sbe_power10_class_init, }; static void pnv_sbe_realize(DeviceState *dev, Error **errp) { PnvSBE *sbe = PNV_SBE(dev); PnvSBEClass *psc = PNV_SBE_GET_CLASS(sbe); /* XScom regions for SBE registers */ pnv_xscom_region_init(&sbe->xscom_ctrl_regs, OBJECT(dev), psc->xscom_ctrl_ops, sbe, "xscom-sbe-ctrl", psc->xscom_ctrl_size); pnv_xscom_region_init(&sbe->xscom_mbox_regs, OBJECT(dev), psc->xscom_mbox_ops, sbe, "xscom-sbe-mbox", psc->xscom_mbox_size); qdev_init_gpio_out(DEVICE(dev), &sbe->psi_irq, 1); sbe->timer = timer_new_us(QEMU_CLOCK_VIRTUAL, sbe_timer, sbe); } static void pnv_sbe_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass); dc->realize = pnv_sbe_realize; dc->desc = "PowerNV SBE Controller"; dc->user_creatable = false; } static const TypeInfo pnv_sbe_type_info = { .name = TYPE_PNV_SBE, .parent = TYPE_DEVICE, .instance_size = sizeof(PnvSBE), .class_init = pnv_sbe_class_init, .class_size = sizeof(PnvSBEClass), .abstract = true, }; static void pnv_sbe_register_types(void) { type_register_static(&pnv_sbe_type_info); type_register_static(&pnv_sbe_power9_type_info); type_register_static(&pnv_sbe_power10_type_info); } type_init(pnv_sbe_register_types);
// ParseHSL pulls out the rgb/rgba information from a hsl color format from the // provided string. func ParseHSL(hslData string) (float64, float64, float64) { subs := hsl.FindStringSubmatch(hslData) h := utils.ParseFloat(subs[1]) s := utils.ParseFloat(subs[2]) / 100 l := utils.ParseFloat(subs[3]) / 100 return h, s, l }
/* * Populates examples menu with library folders */ public void populateExamplesMenu(JMenu examplesMenu, ActionListener listener) { Library library; Collection libraries = getBuiltLibraries(); Iterator iterator = libraries.iterator(); JMenu libraryExamples; while(iterator.hasNext()){ library = (Library)iterator.next(); libraryExamples = library.getExamplesMenu(listener); if(null != libraryExamples){ examplesMenu.add(libraryExamples); } } }
/** * Tests {@link AbstractTopic} * * @author Tim Neumann */ class AbstractTopicTest { /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#validateTopicString(java.lang.String)}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validNames") void testValidateTopicString(String name) throws Exception { AbstractTopic.validateTopicString(name); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#validateTopicString(java.lang.String)} * when they are not valid. * * @param name * The name of the topic to test. * */ @ParameterizedTest @MethodSource("invalidNames") void testValidateTopicStringNot(String name) { Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicString(name), "Expected a topic format exception."); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#validateTopicLevels(java.util.List)}. * * @throws Exception * When an error occurs. */ @Test void testValidateTopicLevels() throws Exception { AbstractTopic.validateTopicLevels(toTopicLevels("test", "", "level")); AbstractTopic.validateTopicLevels(toTopicLevels("", "test", "")); AbstractTopic.validateTopicLevels(toTopicLevels("test", "+", "level")); AbstractTopic.validateTopicLevels(toTopicLevels("test", "level", "#")); AbstractTopic.validateTopicLevels(toTopicLevels("+", "+", "#")); AbstractTopic.validateTopicLevels(toTopicLevels("#")); AbstractTopic.validateTopicLevels(toTopicLevels("+")); AbstractTopic.validateTopicLevels(toTopicLevels("", "#")); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#validateTopicLevels(java.util.List)} for * invalid levels. */ @Test void testValidateTopicLevelsNot() { Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("test", "#", "level")), "Expected topic format excpetion"); Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("", "#", "")), "Expected topic format excpetion"); Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("#", "level")), "Expected topic format excpetion"); Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("#", "")), "Expected topic format excpetion"); Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("", "#", "")), "Expected topic format excpetion"); Assertions.assertThrows(TopicFormatException.class, () -> AbstractTopic.validateTopicLevels(toTopicLevels("#", "+")), "Expected topic format excpetion"); } private List<TopicLevel> toTopicLevels(String... names) throws Exception { List<TopicLevel> tlList = new ArrayList<>(); for (String name : names) { tlList.add(new TopicLevelImpl(name)); } return tlList; } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#getStringRepresentation()}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validNames") void testGetStringRepresentation(String name) throws Exception { AbstractTopic t = new TestingTopic(name); Assertions.assertEquals(name, t.getStringRepresentation(), "String representation should be the same as the name."); } /** * Test method for {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#getTopicLevels()}. * * @param levels * The levels to use. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validLevelLists") void testGetTopicLevels(List<String> levels) throws Exception { String topicName = levels.get(0); for (int i = 1; i < levels.size(); i++) { topicName += "/"; topicName += levels.get(i); } AbstractTopic t = new TestingTopic(topicName); String[] topicLevelNames = levels.toArray(new String[levels.size()]); List<TopicLevel> topicLevels = toTopicLevels(topicLevelNames); Assertions.assertEquals(topicLevels, t.getTopicLevels(), "Wrong topic levels."); } /** * Test method for {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#isSpecialTopic()}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("specialNames") void testIsSpecialTopic(String name) throws Exception { AbstractTopic t = new TestingTopic(name); Assertions.assertTrue(t.isSpecialTopic(), "Should be a special topic"); } /** * Test method for {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#toString()}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validNames") void testToString(String name) throws Exception { AbstractTopic t = new TestingTopic(name); Assertions.assertEquals(name, t.toString(), "toString should be the same as the name."); } /** * Test method for {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#hashCode()}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validNames") void testHashCode(String name) throws Exception { AbstractTopic t1 = new TestingTopic(name); AbstractTopic t2 = new TestingTopic(new String(name)); Assertions.assertEquals(t1.hashCode(), t2.hashCode(), "Hashcodes should match."); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#equals(java.lang.Object)}. * * @param name * The name of the topic to test. * * @throws Exception * When an error occurs. */ @ParameterizedTest @MethodSource("validNames") void testEquals(String name) throws Exception { AbstractTopic t1 = new TestingTopic(name); AbstractTopic t2 = new TestingTopic(new String(name)); Assertions.assertTrue(t1.equals(t2), "A topic should be equal to another topic with the same name."); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#equals(java.lang.Object)} when they are * not equal. * * @throws Exception * When an error occurs. */ @Test void testEqualsNot() throws Exception { AbstractTopic t1 = new TestingTopic("home/test"); AbstractTopic t2 = new TestingTopic("Home/Test"); AbstractTopic t3 = new TestingTopic("+/+"); AbstractTopic t4 = new TestingTopic("#"); Assertions.assertFalse(t1.equals(t2), t1 + " and " + t2 + " should not be equal"); Assertions.assertFalse(t1.equals(t3), t1 + " and " + t3 + " should not be equal"); Assertions.assertFalse(t1.equals(t4), t1 + " and " + t4 + " should not be equal"); Assertions.assertFalse(t2.equals(t3), t2 + " and " + t3 + " should not be equal"); Assertions.assertFalse(t2.equals(t4), t2 + " and " + t4 + " should not be equal"); Assertions.assertFalse(t3.equals(t4), t3 + " and " + t4 + " should not be equal"); } /** * Test method for * {@link io.github.amyassist.amy.messagehub.topic.AbstractTopic#equals(java.lang.Object)} when they are * not the same type. * * @throws Exception * When an error occurs. */ @Test void testEqualsNotSameType() throws Exception { AbstractTopic t1 = new TestingTopic("home/test"); AbstractTopic t2 = new TestingTopic("+/+"); AbstractTopic t3 = new TestingTopic("#"); Assertions.assertFalse(t1.equals(new Object()), t1 + " should not be equal to a empty object."); Assertions.assertFalse(t2.equals(new Object()), t2 + " should not be equal to a empty object."); Assertions.assertFalse(t3.equals(new Object()), t3 + " should not be equal to a empty object."); } /** * @return A stream of normal topic names */ static Stream<String> normalNames() { List<String> vars = new ArrayList<>(); vars.add("home"); vars.add("/home"); vars.add("home/topic/test"); vars.add("/"); vars.add("/home/topic/test"); vars.add("home/topic/test/"); vars.add("/home/topic/test/"); vars.add("home/TOPIC/test"); vars.add("LEvel"); vars.add("Test Topic"); vars.add("Test Topic/Level"); vars.add("!\\}][{€@\"§%$&()=?,;.:-_<>|'*"); vars.add("home/+/test"); vars.add("home/+/+"); vars.add("home/#"); vars.add("home/+/#"); vars.add("+"); vars.add("#"); return vars.stream(); } /** * @return A stream of special topic names */ static Stream<String> specialNames() { return AbstractTopicTest.normalNames().filter(s -> !(s.equals("+") || s.equals("#"))).map(s -> "$" + s); } /** * @return A stream of valid topic names */ static Stream<String> validNames() { return Streams.concat(AbstractTopicTest.normalNames(), AbstractTopicTest.specialNames()); } /** * @return A stream of invalid topic names */ static Stream<String> invalidNames() { List<String> vars = new ArrayList<>(); vars.add(""); vars.add("home" + Character.toString((char) 0x0000)); vars.add("ho" + Character.toString((char) 0x0000) + "me/topic/test"); vars.add(StringUtils.leftPad("TestString", 65536, "*")); vars.add(StringUtils.leftPad("TestString", 65546, "*")); return vars.stream(); } /** * @return A stream of valid topic names split into the levels */ static Stream<List<String>> validLevelLists() { return AbstractTopicTest.validNames().map(s -> Arrays.asList(s.split("/", -1))); } }
AGRA/ LUCKNOW: Forty-nine infants died in a month at Farrukhabad’s Ram Manohar Lohia government hospital, most of them due to “perinatal asphyxia”, a condition in which the child cannot breathe properly, officials said on Monday. In a virtual replay of the tragedy in Gorakhpur, where 30 children died in two days at a state-run hospital last month, parents of many of the children in Farrukhabad told officials that there was a delay in providing oxygen and medicines. Soon after the matter came to light, the state government transferred the district magistrate (DM), the chief medical officer (CMO) and the chief medical superintendent (CMS)Principal health and family welfare secretary Prashant Trivedi said a high-level committee will look into the children deaths at the sick newborn care unit (SNCU), clarifying that the facts had been misinterpreted and the deaths were not linked to the Gorakhpur tragedy in any way.According to local officials, the matter came to light after DM Ravindra Kumar ordered a probe on August 30 after, according to some claims, he visited the hospital and interacted with parents of the victims.The hospital recorded 49 deaths — 30 in the neonatal ICU and 19 during delivery — between July 20 and August 21, an official spokesperson said in Lucknow. He added that 468 deliveries took place in the women’s wing of the hospital during the period. Of these, 19 were still births.The DM asked the CMO and the CMS to submit a detailed cause-wise report on the deaths. Finding the report incomplete, the DM deputed the city magistrate to probe the matter. Farrukhabad SP Daya Nand Misra told TOI, “On Sunday evening, based on a written complaint filed by magistrate Jainendra Kumar Jain in Nagar Kotwali police station regarding the deaths of children, we lodged an FIR against CMO Uma Kant Pandey, CMS B P Pushkar and a few doctors of RML hospital.The accused have been booked under IPC sections 176 (omission to give notice or information to public servant by person legally bound to give it), 188 (disobedience to order duly promulgated by public servant) and 304 (punishment for culpable homicide not amounting to murder).”
def activities_list_to_objects(self, activities_list): def create_object(activity): verb = get_verb_by_id(activity['verb']['id']) extra_context = activity['extra_context'] activity_datetime = activity['time'] activity = self.activity_class( activity['actor'], verb, activity['object'], activity['target'], time=activity_datetime, extra_context=extra_context ) return activity return list(map(create_object, activities_list))
package erclog import ( "os" "testing" ) var ( testLog *LogService tokenAddr = "<KEY>" // 币地址 Addr = "0xC56bE5E6B20F6cf225A9ff4412d7cCEcd53e3037" // 目标账户 1-0 fromBlock int64 = 21230135 // 起始块 toBlock int64 = 21230135 // 结束块 ) func TestMain(m *testing.M) { // 创建币查询服务 testLog = NewLogService(nil) os.Exit(m.Run()) } func Test_TransactionLog(t *testing.T) { testLog.TransactionLog(tokenAddr, Addr, fromBlock, toBlock) } /* 交易记录 Log Block Number: 21230135 Log Index: 0 Log Name: Transfer Log Block Number: 21230135 Log Index: 0 Log Hash: 0xbc9fc83d39ce43841325b387f51d17cf56172289c3b56ccefa0c5625a33d5fb0 From: 0xC56bE5E6B20F6cf225A9ff4412d7cCEcd53e3037 To: 0x2D72D0e085447bBf86E098f5A0e644a9F25f64FE Tokens: 100000500000000000000000 */
def update(self, cond = "", rollback = False): if rollback and self._rollback_queue: self._rollback_queue.add_rollback_point(SpuUpdateRollbackPoint(self, cond)) (sql, reset) = self.gen_update_sql(cond) if not sql: return self.execsql(sql) for n, v in reset: v.no_writed() sql = None
package com.quickjs.plugin; import com.quickjs.JSArray; import com.quickjs.JSContext; import com.quickjs.JSFunction; import com.quickjs.JSObject; import com.quickjs.JavaCallback; import com.quickjs.JavaConstructorCallback; import com.quickjs.JavaVoidCallback; import com.quickjs.Plugin; import com.quickjs.QuickJS; import java.io.Closeable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * http://www.ruanyifeng.com/blog/2018/07/web-worker.html */ public abstract class WorkerPlugin extends Plugin { private Map<Long, Worker> workers = new HashMap<>(); @Override protected void setup(JSContext context) { context.registerClass((thisObj, args) -> { String url = args.getString(0); workers.put(thisObj.getTag(), new Worker(WorkerPlugin.this, thisObj, url)); }, "Worker"); } @Override protected void close(JSContext context) { for (Worker worker : workers.values()) { worker.close(); } } abstract String getScript(String moduleName); static class Worker implements Closeable { private final JSObject workerObj; private final QuickJS quickJS; private final JSContext context; Worker(WorkerPlugin workerPlugin, JSObject workerObj, String url) { this.quickJS = QuickJS.createRuntimeWithEventQueue(); this.context = quickJS.createContext(); this.context.addPlugin(new ConsolePlugin()); this.context.addPlugin(new SetTimeoutPlugin()); this.context.registerJavaMethod(new JavaVoidCallback() { @Override public void invoke(JSObject receiver, JSArray args) { String event = args.getString(0); sendMessageReceiver(event); } }, "postMessage"); this.workerObj = workerObj; initWorkerReceiver(); new Thread(new Runnable() { @Override public void run() { context.executeVoidScript(workerPlugin.getScript(url), url); } }).start(); } private void sendMessageReceiver(String event) { workerObj.postEventQueue(() -> { JSObject onmessage = workerObj.getObject("onmessage"); if (onmessage instanceof JSFunction) { JSFunction func = (JSFunction) onmessage; func.call(workerObj, new JSArray(workerObj.getContext()).push(event)); } }); } private void initWorkerReceiver() { workerObj.registerJavaMethod((receiver, args) -> { close(); }, "terminate"); workerObj.registerJavaMethod(new JavaVoidCallback() { @Override public void invoke(JSObject receiver, JSArray args) { postMessage(args.getString(0)); } }, "postMessage"); } private boolean terminate; @Override public void close() { if (terminate) { return; } terminate = true; quickJS.postEventQueue(quickJS::close); } public void postMessage(String msg) { quickJS.postEventQueue(() -> { JSObject func = context.getObject("onmessage"); if (func != null && !func.isUndefined()) { ((JSFunction) func).call(null, new JSArray(context).push(msg)); } }); } } }
# Copyright (c) 2017, IGLU consortium # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # - Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # - Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import os import sys import time import multiprocessing import logging import numpy as np import unittest import matplotlib.pyplot as plt from home_platform.env import BasicEnvironment from panda3d.core import LVector3f TEST_DATA_DIR = os.path.join(os.path.dirname( os.path.realpath(__file__)), "..", "data") TEST_SUNCG_DATA_DIR = os.path.join(os.path.dirname( os.path.realpath(__file__)), "..", "data", "suncg") class TestBasicEnvironment(unittest.TestCase): def testRender(self): env = BasicEnvironment("0004d52d1aeeb8ae6de39d6bd993e992", suncgDatasetRoot=TEST_SUNCG_DATA_DIR, depth=True) env.agent.setPos(LVector3f(42, -39, 1)) env.agent.setHpr(LVector3f(60.0, 0.0, 0.0)) env.step() image = env.renderWorld.getRgbImages()['agent-0'] depth = env.renderWorld.getDepthImages(mode='distance')['agent-0'] fig = plt.figure(figsize=(16, 8)) plt.axis("off") ax = plt.subplot(121) ax.imshow(image) ax = plt.subplot(122) ax.imshow(depth / np.max(depth), cmap='binary') plt.show(block=False) time.sleep(1.0) plt.close(fig) env.destroy() def testGenerateSpawnPositions(self): env = BasicEnvironment("0004d52d1aeeb8ae6de39d6bd993e992", suncgDatasetRoot=TEST_SUNCG_DATA_DIR, depth=False) occupancyMap, occupancyMapCoord, positions = env.generateSpawnPositions( n=10) xmin, ymin = np.min(occupancyMapCoord, axis=(0, 1)) xmax, ymax = np.max(occupancyMapCoord, axis=(0, 1)) fig = plt.figure() plt.axis("on") ax = plt.subplot(111) ax.imshow(occupancyMap, cmap='gray', extent=[xmin, xmax, ymin, ymax]) ax.scatter(positions[:, 0], positions[:, 1], s=40, c=[1.0, 0.0, 0.0]) plt.show(block=False) time.sleep(1.0) plt.close(fig) env.destroy() def testMultiprocessing(self): # Spawn new process with independent simulations using the # multiprocessing module # Not supported in OSX for now if sys.platform == 'darwin': return nbProcesses = 2 nbSteps = 100 def worker(): env = BasicEnvironment("0004d52d1aeeb8ae6de39d6bd993e992", suncgDatasetRoot=TEST_SUNCG_DATA_DIR, depth=False, debug=True) env.agent.setPos(LVector3f(45, -42, 1)) env.agent.setHpr(LVector3f(45.0, 0.0, 0.0)) # Simulation loop for _ in range(nbSteps): env.step() _ = env.getObservation() env.destroy() processes = [] for _ in range(nbProcesses): p = multiprocessing.Process(target=worker) processes.append(p) p.start() for p in processes: p.join() if __name__ == '__main__': logging.basicConfig(level=logging.WARN) np.seterr(all='raise') unittest.main()
<filename>CPP/No140.cc /** * Created by Xiaozhong on 2020/8/13. * Copyright (c) 2020/8/13 Xiaozhong. All rights reserved. */ #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; class Solution { private: unordered_map<int, vector<string>> ans; unordered_set <string> wordSet; public: vector<string> wordBreak(string s, vector<string> &wordDict) { wordSet = unordered_set(wordDict.begin(), wordDict.end()); backtrack(s, 0); return ans[0]; } void backtrack(const string &s, int index) { if (!ans.count(index)) { if (index == s.size()) { ans[index] = {""}; return; } ans[index] = {}; for (int i = index + 1; i <= s.size(); ++i) { string word = s.substr(index, i - index); if (wordSet.count(word)) { backtrack(s, i); for (const string &succ: ans[i]) { ans[index].push_back(succ.empty() ? word : word + " " + succ); } } } } } };
package fr.idarkay.morefeatures.mixin; import fr.idarkay.morefeatures.FeaturesClient; import fr.idarkay.morefeatures.options.screen.MenuButtons; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.option.OptionsScreen; import net.minecraft.text.Text; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /** * File <b>OptionScreenMixin</b> located on fr.idarkay.breaksafe.mixin * OptionScreenMixin is a part of fabric-example-mod. * <p> * Copyright (c) 2020 fabric-example-mod. * <p> * * @author <NAME>. (IDarKay), * Created the 27/07/2020 at 16:40 */ @Mixin(OptionsScreen.class) public abstract class OptionScreenMixin extends Screen { protected OptionScreenMixin(Text title) { super(title); } @Inject(method = "init", at = @At("RETURN")) protected void init(CallbackInfo ci) { if (this.client != null && this.client.world != null) { int x = this.width / 2 - 155; int y = this.height / 6 + 144 - 6; int w = 150; this.addDrawableChild(MenuButtons.FEATURES.createButton(this, FeaturesClient.options(), x, y, w)); } } }
#encoding=utf-8 import os import mmap import struct import socket #“产品线名.业务组名.服务名”组成serviceKey用于标识一个服务,各字段限长30字节 ServiceKeyCap = 92 #"section.key"组成服务的一个配置,各字段限长30字节 ConfKeyCap = 61 #value支持最大200字节 ConfValueCap = 200 ServiceConfLimit = 100 ''' 一个bucket用于存放一个Service的配置,可存多少种Service [版本号:serviceKey长度:serviceKey:配置个数:配置k1长度:配置k1:配置v1长度:配置v1:......] [2:2:92:2:[2:61:2:30]:[2:61:2:30]:...] ''' OneBucketCap = 2 + 2 + ServiceKeyCap + 2 + ServiceConfLimit * (2 + ConfKeyCap + 2 + ConfValueCap) #一个service总共可包含100个配置 ServiceBucketLimit = 100 #配置总内存空间 #[Service1][Service2][Service3]...最多100个 TotalConfMemSize = OneBucketCap * ServiceBucketLimit class SharedMemory(object): def __init__(self, service_key, index): self.fd = os.open('/tmp/sona/cfg.mmap', os.O_RDONLY) self.mmap = mmap.mmap(self.fd, TotalConfMemSize, flags = mmap.MAP_SHARED, prot = mmap.PROT_READ, offset = 0) self.service_key = service_key self.index = index ''' if there are service configures ''' def has_service(self): start = self.index * OneBucketCap self.mmap.seek(start) version_bytes = self.mmap.read(2) version = socket.ntohs(struct.unpack('H', version_bytes)[0]) return version != 0 ''' get service key ''' def get_service_key(self): start = self.index * OneBucketCap + 2 self.mmap.seek(start) len_bytes = self.mmap.read(2) len = socket.ntohs(struct.unpack('H', len_bytes)[0]) sk = self.mmap.read(len) return str(sk) ''' get configure key ''' def get_conf_key(self, pos): start = self.index * OneBucketCap + 6 + ServiceKeyCap + pos * (4 + ConfKeyCap + ConfValueCap) self.mmap.seek(start) len_bytes = self.mmap.read(2) len = socket.ntohs(struct.unpack('H', len_bytes)[0]) conf_key = self.mmap.read(len) return str(conf_key) ''' get configure value ''' def get_conf_value(self, pos): start = self.index * OneBucketCap + 6 + ServiceKeyCap + pos * (4 + ConfKeyCap + ConfValueCap) + 2 + ConfKeyCap self.mmap.seek(start) len_bytes = self.mmap.read(2) len = socket.ntohs(struct.unpack('H', len_bytes)[0]) conf_value = self.mmap.read(len) return str(conf_value) ''' search a config key use binary search ''' def search_one_conf(self, target_key): start = self.index * OneBucketCap + 4 + ServiceKeyCap self.mmap.seek(start) count_bytes = self.mmap.read(2) count = socket.ntohs(struct.unpack('H', count_bytes)[0]) low, high = 0, count while low < high: mid = (low + high) / 2 conf_key = self.get_conf_key(mid) if conf_key > target_key: high = mid elif conf_key < target_key: low = mid + 1 else: return mid, True return -1, False ''' get some key's value (public) ''' def get_conf(self, conf_key): if not self.has_service() or self.get_service_key() != self.service_key: return "" pos, exist = self.search_one_conf(conf_key) if not exist: return "" return self.get_conf_value(pos) ''' memory = SharedMemory('lebron.james.info', 0) print(memory.get_conf("player.team")) print(memory.get_conf("friends.list")) memory = SharedMemory('miliao.milink.pushgateway', 1) print(memory.get_conf("log.level")) '''
/** * Common functions for PathSeq */ public final class PSUtils { public static JavaRDD<GATKRead> primaryReads(final JavaRDD<GATKRead> reads) { return reads.filter(read -> !(read.isSecondaryAlignment() || read.isSupplementaryAlignment())); } public static String[] parseCommaDelimitedArgList(final String arg) { if (arg == null || arg.isEmpty()) { return new String[0]; } return arg.split(","); } /** * Parses command-line option for specifying kmer spacing masks */ public static byte[] parseMask(final String maskArg, final int kSize) { final String[] kmerMaskString = parseCommaDelimitedArgList(maskArg); final byte[] kmerMask = new byte[kmerMaskString.length]; for (int i = 0; i < kmerMaskString.length; i++) { kmerMask[i] = (byte) Integer.parseInt(kmerMaskString[i]); Utils.validateArg(kmerMask[i] >= 0 && kmerMask[i] < kSize, "Invalid kmer mask index: " + kmerMaskString[i]); } return kmerMask; } /** * Prints warning message followed by a list of relevant items */ public static void logItemizedWarning(final Logger logger, final Collection<String> items, final String warning) { if (!items.isEmpty()) { String str = ""; for (final String acc : items) str += acc + ", "; str = str.substring(0, str.length() - 2); logger.warn(warning + " : " + str); } } /** * Writes two objects using Kryo to specified local file path. * NOTE: using setReferences(false), which must also be set when reading the file. Does not work with nested * objects that reference its parent. */ public static void writeKryoTwo(final String filePath, final Object obj1, final Object obj2) { try { final Kryo kryo = new Kryo(); kryo.setReferences(false); Output output = new Output(new FileOutputStream(filePath)); kryo.writeClassAndObject(output, obj1); kryo.writeClassAndObject(output, obj2); output.close(); } catch (final FileNotFoundException e) { throw new UserException.CouldNotCreateOutputFile("Could not serialize objects to file", e); } } /** * Same as GATKSparkTool's getRecommendedNumReducers(), but can specify input BAM path (for when --input is not used) */ public static int pathseqGetRecommendedNumReducers(final String inputPath, final int numReducers, final int targetPartitionSize) { if (numReducers != 0) { return numReducers; } return 1 + (int) (BucketUtils.dirSize(inputPath) / targetPartitionSize); } }
<filename>app/providers/GlobalQuran/services/QuranAyahs.ts import {Injectable, Injector} from '@angular/core'; import {Ayah} from './Ayah'; @Injectable() export class QuranAyahs { ayahs: Array<Ayah>; constructor() { //.... to be continue } }
import React from 'react'; import { Hidden } from '@material-ui/core'; import MobileView from './mobile/MobileView'; import LocationContextProvider from '../context/LocationContext'; import BookingContextProvider from '../context/BookingContext'; import WebView from './web/WebView'; const App: React.FC = () => { return( <> <LocationContextProvider> <BookingContextProvider> <Hidden mdUp> <MobileView /> </Hidden> <Hidden smDown> <WebView /> </Hidden> </BookingContextProvider> </LocationContextProvider> </> ) } export default App;
<reponame>objectrocket/sensu-operator // Copyright 2017 The etcd-operator Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v1beta1 import ( crdutil "github.com/objectrocket/sensu-operator/pkg/util/k8sutil/conversionutil" sensutypes "github.com/sensu/sensu-go/types" k8s_api_extensions_v1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // SensuHandlerList is a list of sensu handlers. type SensuHandlerList struct { metav1.TypeMeta `json:",inline"` // Standard list metadata // More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#metadata metav1.ListMeta `json:"metadata,omitempty"` Items []SensuHandler `json:"items"` } // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:openapi-gen=true // SensuHandler is the type of sensu handlers type SensuHandler struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec SensuHandlerSpec `json:"spec"` Status SensuHandlerStatus `json:"status"` } // SensuHandlerSpec is the spec section of the custom object // +k8s:openapi-gen=true type SensuHandlerSpec struct { Type string `json:"type"` Mutator string `json:"mutator,omitempty"` Command string `json:"command,omitempty"` Timeout uint32 `json:"timeout,omitempty"` Socket HandlerSocket `json:"socket,omitempty"` Handlers []string `json:"handlers,omitempty"` Filters []string `json:"filters,omitempty"` EnvVars []string `json:"envVars,omitempty"` RuntimeAssets []string `json:"runtimeAssets,omitempty"` // Metadata contains the sensu name, sensu namespace, sensu annotations, and sensu labels of the handler SensuMetadata ObjectMeta `json:"sensuMetadata"` // Validation is the OpenAPIV3Schema validation for sensu assets Validation k8s_api_extensions_v1beta1.CustomResourceValidation `json:"validation,omitempty"` } // HandlerSocket is the socket description of a sensu handler. type HandlerSocket struct { Host string `json:"host"` Port uint32 `json:"port"` } // SensuHandlerStatus is the status of the sensu handler type SensuHandlerStatus struct { Accepted bool `json:"accepted"` LastError string `json:"lastError"` } // ToSensuType returns a value of the Handler type from the Sensu API func (a SensuHandler) ToSensuType() *sensutypes.Handler { return &sensutypes.Handler{ ObjectMeta: sensutypes.ObjectMeta{ Name: a.ObjectMeta.Name, Namespace: a.Spec.SensuMetadata.Namespace, Labels: a.ObjectMeta.Labels, Annotations: a.ObjectMeta.Annotations, }, Type: a.Spec.Type, Mutator: a.Spec.Mutator, Command: a.Spec.Command, Timeout: a.Spec.Timeout, Handlers: a.Spec.Handlers, Socket: &sensutypes.HandlerSocket{ Host: a.Spec.Socket.Host, Port: a.Spec.Socket.Port, }, Filters: a.Spec.Filters, EnvVars: a.Spec.EnvVars, RuntimeAssets: a.Spec.RuntimeAssets, } } // GetCustomResourceValidation rreturns the handlers's resource validation func (a SensuHandler) GetCustomResourceValidation() *k8s_api_extensions_v1beta1.CustomResourceValidation { return crdutil.GetCustomResourceValidation("github.com/objectrocket/sensu-operator/pkg/apis/objectrocket/v1beta1.SensuHandler", GetOpenAPIDefinitions) }
import { SchemaField, DataField } from "../../types" interface Config { path: string field: SchemaField<{}> } export class PrimitiveField implements DataField { public name: string public type: string constructor({ path, field: { type } }: Config) { this.name = path this.type = type } async validate(value: any) { return { isValid: true, message: "" } } async hydrate(value: any) { return value } }
The Santa Clara Blues: Corporate Personhood versus Democracy by William Meyers What Corporate Personhood Is Corporate Personhood is a legal fiction. The choice of the word "person" arises from the way the 14th Amendment to the U.S. Constitution was worded and from earlier legal usage of the word person. A corporation is an artificial entity, created by the granting of a charter by a government that grants such charters. Corporation in this essay will be confined to businesses run for profit that have been granted corporate charters by the States of the United States. The Federal Government of the United States usually does not grant corporate charters to businesses (exceptions include the Post Office and Amtrak). Corporations are artificial entities owned by stockholders, who may be humans or other corporations. They are required by law to have officers and a board of directors (in small corporations these may all be the same people). In effect the corporation is a collective of individuals with a special legal status and privileges not given to ordinary unincorporated businesses or groups of individuals. Obviously a corporation is itself no more a person (though it is owned and staffed by persons) than a locomotive or a mob. So why, in the USA, is a corporation considered to be a person under law? In the United States of America all natural persons (actual human beings) are recognized as having inalienable rights. These rights are recognized, among other places, in the Bill of Rights and the 14th Amendment. Corporate personhood is the idea (legal fiction, currently with force of law) that corporations have inalienable rights (sometimes called constitutional rights) just like real, natural, human persons. That this idea has the force of law both resulted from the power and wealth of the class of people who owned corporations, and resulted in their even greater power and wealth. Corporate constitutional rights effectively invert the relationship between the government and the corporations. Recognized as persons, corporations lose much of their status as subjects of the government. Although artificial creations of their owners and the governments, as legal persons they have a degree of immunity to government supervision. Endowed with the court-recognized right to influence both elections and the law-making process, corporations now dominate not just the U. S. economy, but the government itself. The History of Corporate Personhood Corporations were detested by the colonial rebels in 1776 when the Declaration of Independence severed the States from Great Britain. There had been only a few corporations in colonial America, but they had been very powerful. The Dutch West India Company had founded New York. Corporations had effectively governed Virginia, Maryland and the Carolinas. The political history of the colonies up until 1776 was largely one of conflict between citizens trying to establish rule by elected government and the corporations or King ruling through appointed governors. The new nation or confederation of 13 sovereign states had few native business corporations. The corporations that survived the revolution were mainly non-profit institutions such as colleges [Dartmouth College v. Woodward, 17 U.S. 518 (1819)]. There was not a single bank in the United States until 1780. Most of that first bank's stock was owned by the confederate (what we would later call Federal) government, and the bank's charter was revoked in 1785. "The agrarian charges were numerous... the bank was a monstrosity, an artificial creature endowed with powers not possessed by human beings and incompatible with the principles of a democratic social order." [Hammond, Bray , Banks and Politics in America from the Revolution to the Civil War (Princeton: Princeton University Press, 1991), pp. 48-54] By 1790 four banks had been granted corporate charters by states, but these banks were not originally purely private institutions. They served as financial institutions for the states that chartered them. [Ibid. 65-67] The federal Constitution of 1788 did not mention corporations at all. But in the late 1700's and early 1800's corporations began to be chartered by the states. This was not without opposition. Thomas Jefferson said, "I hope we shall crush in its birth the aristocracy of our moneyed corporations which dare already to challenge our government in a trial of strength, and bid defiance to the laws of our country." Like the banks, other early corporations were closely supervised by the state legislatures that granted their charters. When the Supreme Court of the United States in Dartmouth College v. Woodward in 1819, ruled that Dartmouth's charter granted in 1769 by King George III was a contract and could not be revoked by the New Hampshire legislature, a public outcry ensued. State courts and legislatures, supported by the people, declared that state governments had an absolute right to amend or repeal a corporate charter. [Richard L Grossman and Frank T. Adams, Taking Care of Business, Citizenship and the Charter of Incorporation (Cambridge: Charter, Ink., 1993), p. 11-12] Until 1886 corporations were not considered persons. It was clear what they were: artificial creations of their owners and the state legislatures. They were regulated and taxed. They could sue and be sued. They were subject to all of the laws of the land as well as any restrictions placed in their charters. But from 1819 until 1886 the wealthiest business people sought to use the Federal government, particularly the courts, to get their corporations out from under the control of the states and their citizens. During the 1800's the United States went through an enormous economic expansion, sometimes called the Industrial Revolution, but that term is misleading. The United States expanded geographically by grabbing native American Indian territories formerly claimed by France, Great Britain, and Mexico. The population exploded. Farm production exploded, and international trade exploded, with U.S. grain feeding both growing U.S. cities and Europe. Manufacturing in the U.S., protected by tariffs from British competition, also progressed rapidly. The favored form for large businesses became the corporation. And as these corporations came to dominate business life, they also began to dominate America's politicians, lawyers, courts and culture. The Civil War accelerated the growth of manufacturing and the power of the men who owned the corporations. After the war corporations began a campaign to throw off the legal shackles that had held them in check. The systematic bribing of Congress was instituted by Mark Hanna, sugar trust magnate Henry Havemeyer, and Senator Nelson Aldrich and their associates. [Jonathan Shepard Fast and Luzviminda Bartolome Francisco, Conspiracy For Empire, Big Business, Corruption and the Politics of Imperialism in America, 1876-1907 (Quezon City, Foundation for Nationalist Studies, 1985), p. 92-97] Most Supreme Court judges who were appointed were former corporate lawyers. In 1886 the supreme court justices were Samuel F. Miller, Stephen J. Field, Joseph P. Bradley, John M. Harlan, Stanley Matthews, William B. Woods, Samuel Blatchford, Horace Gray, and chief justice Morrison. R. Waite. Never heard of a one of them? These men subjected African Americans to a century of Jim Crow discrimination; they made corporations into a vehicle for the wealthy elite to control the economy and the government; they vastly increased the power of the Supreme Court itself over elected government officials. How quaint they are forgotten names. In all fairness, Justice Harlan dissented from the infamous Plessy v. Ferguson decision [163 U.S. 537 (1896)], which, as he said, effectively denied the protection of the 14th Amendment to the very group of people (former slaves and their descendants) for whom it was designed. In 1868 the 14th Amendment to the United States Constitution had become law. Section 1 of that Amendment states: SECTION 1. All persons born or naturalized in the United States, and subject to the jurisdiction thereof, are citizens of the United States and of the State wherein they reside. No State shall make or enforce any law which shall abridge the privileges or immunities of citizens of the United States; nor shall any State deprive any person of life, liberty, or property, without due process of law; nor deny to any person within its jurisdiction the equal protection of the laws. "The one pervading purpose . . . [of the 14th Amendment] was the freedom of the slave race, the security and firm establishment of that freedom, and the protection of the newly-made freeman and citizen from the oppression of those who had formerly exercised unlimited dominion over him." That is exactly what Justice Samuel F. Miller said in 1873 in one of the first Supreme Court opinions to rule on the 14th Amendment. [83 U.S. 36, 81 (1873)] But the wealthy, powerful men who owned corporations wanted more power for their corporations. Their lawyers came up with the idea that corporations, which might be said to be groups of persons (though one person might in turn belong to (own stock in) many corporations), should have the same constitutional rights as persons themselves. If they could get the courts to agree that corporations were persons, they could assert that the States, which had chartered the corporations, would then be constrained by the 14th Amendment from exercising power over the corporations. Beginning in the 1870's corporate lawyers began asserting that corporations were persons with many of the rights of natural persons. It should be understood that the term "artificial person" was already in long use, with no mistake that corporations were claiming to have the rights of natural persons. "Artificial person" was used because there were certain resemblances, in law, between a natural person and corporations. Both could be parties in a lawsuit; both could be taxed; both could be constrained by law. In fact the corporations had been called artificial persons by courts in England as early as the 16th century because lawyers for the corporations had asserted they could not be convicted under the English laws of the time because the laws were worded "No person shall..." The need to be freed from legislative and judicial constraints, combined with the use of the word "person" in the U.S. Constitution and the concept of the "artificial person," led to the argument that these "artificial persons" were "persons" with an inconsequential "artificial" adjective appended. If it could be made so, if the courts would accept that corporations were among the "persons" talked about by the U.S. Constitution, then the corporations would gain considerably more leverage against legal restraint. These arguments were made by corporate lawyers at the State level, in court after court, and many judges, being former corporate attorneys and usually at least moderately wealthy themselves, were sympathetic to any argument that would strengthen corporations. There was a national campaign to get the legal establishment to accept that corporations were persons. This cumulated in the Santa Clara decision of 1886, which has been used as the precedent for all rulings about corporate personhood since then. Though it is not yet clear who hatched this plan or where the campaign began, the early cases mainly concerned railroads. In the late 1800's railroads were the most powerful corporations in the country. Most of the nation's farmers were dependent on them to haul their produce; even the manufacturing corporations were at their mercy when they needed coal, iron ore, finished iron, or any other materials transported. That the lawyers for the railway corporations had planned a national campaign to make corporations full, unqualified legal persons is demonstrated by the Supreme Court making several decisions in which this was an issue in 1877. In four cases that reached the Supreme Court [94 U.S. 155, 94 U.S. 164, 94 U.S. 179, 94 U.S. 180 (1877)] it was argued by the railroads that they were protected by the 14th Amendment from states regulating the maximum rates they could charge. In each case the Court did not render an opinion as to whether corporations were persons covered by the 14th Amendment. Bypassing that issue, they said that the 14th Amendment was not meant to prevent states from regulating commerce. Similarly, in 1877, in Munn v. Illinois [94 U.S. 113 (1876)], the Supreme Court decided that the 14th Amendment did not prevent the State of Illinois from regulating charges for use of a business's grain elevators, ignoring the question of whether Munn & Scott was a person. Later, in Northwestern Nat Life Ins. Co. v. Riggs [203 U.S. 243 (1906)], having accepted that corporations are people, the court still ruled that the 14th Amendment was not a bar to many state laws that effectively limited a corporations right to contract business as it pleases. Calling silence a victory, from 1877 to 1886 corporate lawyers assumed that corporations were persons, and their opponents argued that they were not. In Santa Clara County v. Southern Pacific Railroad Company [118 U.S. 394 (1886)], at the lower court levels the question of whether corporations were persons had been argued, and these arguments were submitted in writing to the Court. However, before oral argument took place, Chief Justice Waite announced: "The court does not wish to hear argument on the question whether the provision in the Fourteenth Amendment to the Constitution, which forbids a State to deny to any person within its jurisdiction the equal protection of the laws, applies to these corporations. We are all of the opinion that it does." It is not half as strange that the Supreme Court judges would render such an opinion, given their allegiance to the propertied class, as the way that they rendered it. These guys loved to write long-winded, complex opinions; look at any Supreme Court opinion of the time (or any time) and you'll see that. This question had never been covered in a Supreme Court decision; it had been avoided. Here was the perfect chance for any of nine Supreme Court judges to make his place in history. All declined. No one wanted to explain how an amendment about ex-slaves had converted artificial entities into the legal equivalent of natural persons. This opinion without explanation, given before argument had even been heard, became the law of the United States of America. No state or federal legislature passed it or even discussed; no Amendment to the Constitution was deemed necessary; the citizens were simply informed that they had a mistaken view about corporations, if they were informed at all. Future Supreme Courts refused to even consider the question, preferring to build on it, though occasionally future justices would try to raise the question again. Was the 14th Amendment about corporations? One of the 1886 judges, Samuel F. Miller, had not thought so in 1872, only 6 years after the Amendment had become law, when the court was "called upon for the first time to give construction to these articles." In the Slaughterhouse Cases [83 U.S. 36 (1872)], he stated (and I quote at length because it is important not only to the question of corporate personhood, but to the question of civil rights): The most cursory glance at these articles discloses a unity of purpose, when taken in connection with the history of the times, which cannot fail to have an important bearing on any question of doubt concerning their true meaning. Nor can such doubts, when any reasonably exist, be safely and rationally solved without a reference to that history, for in it is found the occasion and the necessity for recurring again to the great source of power in this country, the people of the States, for additional guarantees of human rights, additional powers to the Federal government; additional restraints upon those of the States. Fortunately, that history is fresh within the memory of us all, and its leading features, as they bear upon the matter before us, free from doubt. The institution of African slavery, as it existed in about half the States of the Union, and the contests pervading the public mind for many years between those who desired its curtailment and ultimate extinction and those who desired additional safeguards for its security and perpetuation, culminated in the effort, on the part of most of the States in which slavery existed, to separate from the Federal government and to resist its authority. This constituted the war of the rebellion, and whatever auxiliary causes may have contributed to bring about this war, undoubtedly the overshadowing and efficient cause was African slavery. ... They [Negroes] were in some States forbidden to appear in the towns in any other character than menial servants. They were required to reside on and cultivate the soil without the right to purchase or own it. They were excluded from many occupations of gain, and were not permitted to give testimony in the courts in any case where a white man was a party. It was said that their lives were at the mercy of bad men, either because the laws for their protection were insufficient or were not enforced. These circumstances, whatever of falsehood or misconception may have been mingled with their presentation, forced upon the statesmen who had conducted the Federal government in safety through the crisis of the rebellion, and who supposed that, by the thirteenth article of amendment, they had secured the result of their labors, the conviction that something more was necessary in the way of constitutional protection to the unfortunate race who had suffered so much. They accordingly passed through Congress the proposition for the fourteenth amendment, and they declined to treat as restored to their full participation in the government of the Union the States which had been in insurrection until they ratified that article by a formal vote of their legislative bodies. . . . We repeat, then, in the light of this recapitulation of events, almost too recent to be called history, but which are familiar to us all, and on the most casual examination of the language of these amendments, no one can fail to be impressed with the one pervading purpose found in them all, lying at the foundation of each, and without which none of them would have been even suggested; we mean the freedom of the slave race, the security and firm establishment of that freedom, and the protection of the newly made freeman and citizen from the oppressions of those who had formerly exercised unlimited dominion over him. It has been argued that the men who wrote the 14th Amendment specifically meant for the word person to be a loophole which you could drive a giant corporation through. Apparently in one of the railroad cases an attorney who had been on the committee that drafted the amendment waived a paper before the court claiming that it documented such; but the paper was not entered as evidence, nor apparently was it shown to anyone, nor was it saved. However, careful research has shown that, John A. Bingham the member of Congress who is known to have been chiefly responsible for the phraseology of Section One when it was drafted by the Joint Committee in 1866, had, during the previous decade and as early as 1856-1859, employed not one but all three of the same clauses and concepts he later used in Section One. More important still, Bingham employed these guarantees specifically and in a context which suggested that free Negroes and mulattoes rather than corporations and business enterprise unquestionably were the persons' to which he then referred. [Graham, Howard Jay, Everyman's Constitution, State Historical Society of Wisconsin, 1968][See also Graham, Howard Jay, A The Conspiracy Theory of the Fourteenth Amendment, @ The Yale Law Journal, Vol. 47: 341, 1938] Before the Supreme Court determined that corporations were persons and hence had constitutional rights female citizens had decided that the Fourteenth Amendment should be interpreted to give them the right to vote. In Minor v. Happersett the Supreme Court ruled that "women" were not persons for the purposes of the Fourteenth Amendment. The moral and legal depravity of the Supreme Court during this period (though of course they saw their job as securing the property of those of their class), and the absurdity of treating corporations as persons with natural and constitutionally recognized rights, is illustrated by the deterioration of the legal position of the former slaves and their descendants during this time. A series of Supreme Court judgements [92 U.S. 214 (1875), 92 U.S. 542 (1875), 106 U.S. 629 (1882), 109 U.S. 3 (1883)] of cases where men classified as Negroes sought the protection of the 14th Amendment narrowed the scope of that protection. Finally, in the infamous Plessy v. Ferguson [163 U.S. 537 (1896)] decision, the Supreme Court ruled that a man who was 1 part slave by ancestry and 7/8 of white/free ancestry could be forced to sit in a A separate but equal" section of a passenger train. In effect this decision declared people with non-European ancestors to not be persons with constitutional rights. The decision would not be overruled by a future Supreme Court until Brown v. Board of Education in 1954. Only justice John M. Harlan dissented in Plessy v. Ferguson. Of the justices who had ruled that corporations were people in Santa Clare v. Southern Pacific, three were still justices and rules that natural persons of the wrong skin color were not persons in Plessy v. Ferguson. These infamous three were Stephen J. Field, Samuel Blatchford, and Horace Gray. Two Supreme Court judges, Hugo Black and William O. Douglas, later rendered opinions attacking the doctrine of corporate personhood. I supply here most of justice Black's opinion: But it is contended that the due process clause of the Fourteenth Amendment prohibits California from determining what terms and conditions should be imposed upon this Connecticut corporation to promote the welfare of the people of California. I do not believe the word 'person' in the Fourteenth Amendment includes corporations. 'The doctrine of stare decisis, however appropriate and even necessary at times, has only a limited application in the field of constitutional law.' This Court has many times changed its interpretations of the Constitution when the conclusion was reached that an improper construction had been adopted. Only recently the case of West Coast Hotel Company v. Parrish, 300 U.S. 379, 57 S.Ct. 578, 108 A.L.R. 1330, expressly overruled a previous interpretation of the Fourteenth Amendment which had long blocked state minimum wage legislation. When a statute is declared by this Court to be unconstitutional, the decision until reversed stands as a barrier against the adoption of similar legislation. A constitutional interpretation that is wrong should not stand. I believe this Court should now overrule previous decisions which interpreted the Fourteenth Amendment to include corporations. Neither the history nor the language of the Fourteenth Amendment justifies the belief that corporations are included within its protection [303 U.S. 77, 86]. The historical purpose of the Fourteenth Amendment was clearly set forth when first considered by this Court in the Slaughter House Cases, 16 Wall. 36, decided April, 1873-less than five years after the proclamation of its adoption. Mr. Justice Miller, speaking for the Court, said: 'Among the first acts of legislation adopted by several of the States in the legislative bodies which claimed to be in their normal relations with the Federal government, were laws which imposed upon the colored race onerous disabilities and burdens, and curtailed their rights in the pursuit of life, liberty, and property to such an extent that their freedom was of little value, while they had lost the protection which they had received from their former owners from motives both of interest and humanity. 'These circumstances, whatever of falsehood or misconception may have been mingled with their presentation, forced ... the conviction that something more was necessary in the way of constitutional protection to the unfortunate race who had suffered so much. (Congressional leaders) accordingly passed through Congress the proposition for the fourteenth amendment, and ... declined to treat as restored to their full participation in the government of the Union the States which had been in insurrection, until they ratified that article by a formal vote of their legislative bodies.' 16 Wall. 36, at page 70. Certainly, when the Fourteenth Amendment was submitted for approval, the people were not told that the states of the South were to be denied their normal relationship with the Federal Government unless they ratified an amendment granting new and revolutionary rights to corporations. This Court, when the Slaughter House Cases were decided in 1873, had apparently discovered no such purpose. The records of the time can be searched in vain for evidence that this amendment was adopted for the benefit of corporations. It is true [303 U.S. 77, 87] that in 1882, twelve years after its adoption, and ten years after the Slaughter House Cases, supra, an argument was made in this Court that a journal of the joint Congressional Committee which framed the amendment, secret and undisclosed up to that date, indicated the committee's desire to protect corporations by the use of the word 'person.' Four years later, in 1886, this Court in the case of Santa Clara County v. Southern Pacific Railroad, 118 U.S. 394, 6 S.Ct. 1132, decided for the first time that the word 'person' in the amendment did in some instances include corporations. A secret purpose on the part of the members of the committee, even if such be the fact, however, would not be sufficient to justify any such construction. The history of the amendment proves that the people were told that its purpose was to protect weak and helpless human beings and were not told that it was intended to remove corporations in any fashion from the control of state governments. The Fourteenth Amendment followed the freedom of a race from slavery. Justice Swayne said in the Slaughter Houses Cases, supra, that: 'By 'any person' was meant all persons within the jurisdiction of the State. No distinction is intimated on account of race or color.' Corporations have neither race nor color. He knew the amendment was intended to protect the life, liberty, and property of human beings. The language of the amendment itself does not support the theory that it was passed for the benefit of corporations. The first clause of section 1 of the amendment reads: 'All persons born or naturalized in the United States, and subject to the jurisdiction thereof, are citizens of the United States and of the State wherein they reside.' Certainly a corporation cannot be naturalized and 'persons' here is not broad enough to include 'corporations.' The first clause of the second sentence of section 1 reads: 'No State shall make or enforce any law which shall abridge the privileges or immunities of citizens of the United States.' While efforts have been made to persuade this Court to allow corporations to claim the protection of his clause, these efforts have not been successful. The next clause of the second sentence reads: 'Nor shall any State deprive any person of life, liberty, or property, without due process of law.' It has not been decided that this clause prohibits a state from depriving a corporation of 'life.' This Court has expressly held that 'the liberty guaranteed by the 14th Amendment against deprivation without due process of law is the liberty of natural, not artificial persons.' Thus, the words 'life' and 'liberty' do not apply to corporations, and of course they could not have been so intended to apply. However, the decisions of this Court which the majority follow hold that corporations are included in this clause in so far as the word 'property' is concerned. In other words, this clause is construed to mean as follows: 'Nor shall any State deprive any human being of life, liberty or property without due process of law; nor shall any State deprive any corporation of property without due process of law.' The last clause of this second sentence of section 1 reads: 'Nor deny to any person within its jurisdiction the equal protection of the laws.' As used here, 'person' has been construed to include corporations. [303 U.S. 77, 89] Both Congress and the people were familiar with the meaning of the word 'corporation' at the time the Fourteenth Amendment was submitted and adopted. The judicial inclusion of the word 'corporation' in the Fourteenth Amendment has had a revolutionary effect on our form of government. The states did not adopt the amendment with knowledge of its sweeping meaning under its present construction. No section of the amendment gave notice to the people that, if adopted, it would subject every state law and municipal ordinance, affecting corporations, (and all administrative actions under them) to censorship of the United States courts. No word in all this amendment gave any hint that its adoption would deprive the states of their long-recognized power to regulate corporations. The second section of the amendment informed the people that representatives would be apportioned among the several states 'according to their respective numbers, counting the whole number of persons in each State, excluding Indians not taxed.' No citizen could gather the impression here that while the word 'persons' in the second section applied to human beings, the word 'persons' in the first section in some instances applied to corporations. Section 3 of the amendment said that 'no person shall be a Senator or Representative in Congress,' (who 'engaged in insurrection'). There was no intimation here that the word 'person' in the first section in some instances included corporations. This amendment sought to prevent discrimination by the states against classes or races. We are aware of this from words spoken in this Court within five years after its adoption, when the people and the courts were personally familiar with the historical background of the amendment. 'We doubt very much whether any action of a State not directed by way of discrimination against [303 U.S. 77, 90] the negroes as a class, or on account of their race, will ever be held to come within the purview of this provision.' Yet, of the cases in this Court in which the Fourteenth Amendment was applied during the first fifty years after its adoption, less than one-half of 1 per cent invoked it in protection of the negro race, and more than 50 per cent. asked that its benefits be extended to corporations. If the people of this nation wish to deprive the states of their sovereign rights to determine what is a fair and just tax upon corporations doing a purely local business within their own state boundaries, there is a way provided by the Constitution to accomplish this purpose. That way does not lie along the course of judicial amendment to that fundamental charter. An amendment having that purpose could be submitted by Congress as provided by the Constitution. I do not believe that the Fourteenth Amendment had that purpose, nor that the people believed it had that purpose, nor that it should be construed as having that purpose. B Hugo Black, dissenting, Connecticut General Life Insurance Company v. Johnson [303 U.S. 77, 1938] Justice Black was not alone in his questioning of the legitimacy of corporate personhood. Justice Douglas, dissenting in Wheeling Steel Corp. v. Glander [337 U.S. 562 (1949)], gave an opinion similar to, but shorter than, the one quoted above, to which Justice Black concurred. Why Corporate Constitutional Rights Are Anti-democratic Is corporate personhood (including the whole range of corporate constitutional rights) a bad thing? If you are a wealthy corporate stockholder who doesn't care about the environment or the fate of less wealthy human beings, the answer is no. In fact corporate personhood is right up there with corporations = limited liability as one of the good things in life. For the rest of us corporate personhood is a very bad thing. Corporate personhood changes the relationship between people and corporations and between corporations and the government, and even between government and the people. The effects of this change in relationships range from loss of liberty and income for citizens to the destruction and poisoning of the earth and the corruption of the U.S. governments (including state and local governments). As outlined in the Declaration of Independence, the Articles of Confederation, the Constitution, the Federalist Papers, and the Anti-Federalist Papers, government derives its powers and responsibilities from the people. Corporations, chartered by governments, are subject to the people with the government acting as an intermediary. Corporate personhood allows the wealthiest citizens to use corporations to control the government and use it as an intermediary to impose their will upon the people. It is this basic about-face from democracy that should most concern us. But because of our corrupted legal system, corporate media, and corrupted elected officials, social activists usually focus their efforts on the bad, even horrible, results of corporate control of government and society. Reformers run around trying to get bureaucrats to enforce the minimalist regulations that have been enacted into law, rather than finding a way to prevent the corporate lawyers and lobbyists from writing the laws. Take, for instance, the Environmental Protection Agency (EPA) and its feeble attempts to clean up the most toxic sites in the United States. Almost all of these sites were created by large corporations. Regulation of corporations was traditionally left to State governments; the Federal government regulated only interstate commerce (though in the 20th century it increasingly used its power to regulate interstate commerce as a means to regulate all commerce). Why did the State governments not prevent the creation of toxic sites in the first place? One might claim that there was simply, in the past, a lack of knowledge on everyone's part about the environment and the dangers of toxins. This theory does not stand up to analysis. Poisoning wells was a crime from the earliest of times. Government standards for food purity and safety go back to at least the Middle Ages. Sanitation laws came into common existence in the U.S. during the 19th century. But toxic sites were the result of toxic dumping by large industrial corporations. They dumped toxic byproducts into the air, into waterways, and onto the ground. They continue to do so today with environmental law written to give them permission to pollute up to specified levels, and even at higher levels if they are willing to pay small fines. In addition, they have used their political power to force taxpayers to pay to clean corporate toxic spills. In some cases they have escaped financial liability through the corporate bankruptcy laws, which limit the liability of stockholders. Billions of dollars that were paid out in dividends to stockholders cannot be reclaimed by the people in order to cover the costs of toxic cleanup at taxpayers' expense. After corporations were given personhood and constitutional rights in 1886 state governments began to find that attempts to regulate corporations were thwarted both by Supreme Court decisions and the A race to the bottom." The immediate effect of the Santa Clara decision was the protection of corporations from some (but not all) state regulation; state regulations could be tested in federal courts to see if they violated the corporations constitutional rights. If a state successfully, and with federal court approval, prohibited an industry from dumping waste in streams and rivers (and actually enforced such a law) the industry would simply move to a state that had no such law or enforced it laxly. In recent decades the Supreme Court has ruled that corporations have the Fourth Amendment constitutional right to freedom from random inspection [See v. City of Seattle, 387 U.S 541 (1967) and Marshall v. Barlow = s, Inc., 436 U.S. 307 (1978), among others]. Without random inspections it is virtually impossible to enforce meaningful anti-pollution, health, and safety laws. What would it take to make corporations stop polluting and pay to clean up the messes they have created? They would have to be prohibited from lobbying, they would have to be prohibited from contributing to political campaigns, they would need to lose their limited liability status, they would need to have their charters limited and enforced, they would need to be subject to inspections without warrants, and they would have to have their ability to buy decisions in their favor in the courts ended. In order to remove any of this set of privileges we would need to make it legally clear that they do not have corporate personhood or the constitutional rights the courts pretend go with it. Or consider subsidized corporate timber harvesting on government lands. One might see this as a case of simple, raw economic and political power. The timber companies wish to grab (privatize) the profits in a situation and pawn off (socialize) the costs by charging them to the taxpayers. They do this by writing the laws governing the sale of timber. It is sold cheap, and the government does not take into account its own costs (administration, building roads, etc.) in setting prices. The net result is that taxpayers loose money, the timber industry makes profits, and the environment is managed in an unsound manner. Corporate personhood does not, in itself, cause laws to be written to subsidize the wealthy holders of timber company stock with the income taxes laid on the backs of ordinary wage earners. But it has created the situation is which corporations are free to lobby and corrupt the political process. To prevent them from lobbying and contributing to political campaigns we must revoke their corporate personhood and constitutional rights. Look at the recent consolidation of the media, from bookstores to cable television empires. This is part of the process of putting Americans in chains. Corporations are able to stifle individual liberty by driving out small local businesses and replacing them with cloned outlets. What does that have to do with corporate personhood? Well, some people, realizing that in the long run local communities prosper with locally owned businesses, have tried to limit the corporate chain's right unlimited expansion. In the case of Liggett v. Lee [288 U.S. 517 (1933)] the State of Florida had imposed a filing fee for licenses for stores that was progressive: a person opening one store would pay a $5.00 fee, whereas a large chain was required to pay $30.00 per store. J. C. Penny Company challenged the law and the Supreme Court of the U.S. ruled that this law violated the 14th Amendment's principle of equal protection. This was at a time when the Jim Crow system of discrimination against blacks was at its height; blacks were still not considered persons protected by the 14th Amendment, but corporations were. Judge Brandeis's dissent in the case is well worth reading for anyone interested in a critique of the growth of corporate power up to 1933. If terrorists had tried to bomb independent bookstores out of existence in the 1990's, people would have been demanding police protection for our neighborhood bookstores. Instead the independents, which had survived fairly well against the earlier versions of bookstore chains, were bombed (economically) by Barnes & Noble and Borders. Now independent book publishers, who had long struggled to survive against the big corporate publishing empires, can have their books effectively censored by two A buyers " , one working at each of the chains. Now the dream of owning a small bookstore and carrying the books that you love has been replaced by the nightmare of being a low-paid clerk in a chain bookstore. Corporate personhood offers little or no advantage to small, local stores and businesses: it is of advantage only to the national and international corporations. The book industry is just one segment of the media industry that has consolidated at an accelerating pace at the end of the 20th Century. Laws could have been enacted insuring a multitude of voices on the radio and TV and in newspapers and magazines, but instead we are subjected to one voice: the voice of money. Endowed with corporate personhood, the media corporations have been able to lobby and influence politicians (with campaign contributions) to allow media empires to effectively extinguish meaningful freedom of the press in the United States. Compare the position of most real persons in the U.S. at present. Most real persons are lucky if they can shake their congressperson's hand; few of us have the power to talk to any congressman on any committee that might help our personal interests. Most real persons were not consulted before Congress acted recently to toss out the New Deal era banking laws, allow the consolidation of the media industry, or change the rules for personal bankruptcy. But multinational corporations have unlimited access to Congress. They buy that access with campaign contributions (and often, lucrative jobs for ex-Congresspersons). The public is told what to think by a (almost always) unified media voice. The public is usually not even told when critical anti-democratic or economic changes are being considered by Congress. Because of corporate personhood and corporate constitutional rights, the ordinary, natural person has become a second-class person in the eyes of the law. A person who has to work for wages as a corporate employee loses his Constitutional rights (such as free speech) when he steps onto corporate property, according to the courts. In any dispute he has with a corporate person he is confronted with the economic penalty of having to buy justice from lawyers and courts, which for the corporation is a tax-deductible expense. For an international corporation a million dollars in legal costs hardly affects the bottom line; for a real person, a thousand dollars in legal costs may mean missing a rent or mortgage payment. Even if ordinary people try to work together, as in a labor union, they are not afforded the same privileges as a corporate person. Finally, look at the corporate contributions to politicians and their overall ability to influence political thought through the corporate media. Without ever giving a penny to a politician's campaign the corporate media would have enormous control of the political process through their ability to filter news and opinions. Dependent on other out-of-control corporations for their own advertising income, they have no reason to anger their real clients by impartially reporting the news. When you add to that the enormous amounts of money that corporations are able to use to affect the political process you have the makings of absolute control of government and society. There have been some efforts by states and the federal government to put some mild restrictions on corporate campaign spending. But in First National Bank of Boston v. Bellotti [435 U.S. 765 (1978)] the U.S. Supreme Court declared that corporate persons have the same free speech rights as natural persons, and could spend unlimited sums of money A speaking" in the form of ads and campaign contributions. The Massachusetts Supreme Court had unanimously upheld the validity of the campaign finance reform law in question. Summing up, corporate personhood is bad because it is the basis of corporations being regarding by the Supreme Court with other rights such as equal protection under the law, free speech, the right to remain silent in criminal cases, and protection from searches. These rights in turn have been used by the corporations to corrupt our citizens, government and legal system, to treat workers and small businesses as economic prey, and to destroy the environment we all depend on to sustain life itself. What would change if corporations lost personhood? There are two broad areas that could change if we revoked corporate personhood. One is directly related to corporations not being persons for the purposes of the 1st, 4th, and 14th Amendments. The other is the critically important secondary effect of what can be achieved if we push corporations out of the political process, which can be achieved only if we remove their personhood. Knowing exactly what would or could change has to be based on what changes have been made, or prevented, since the establishment of corporate personhood as a legal principle in 1886. Fortunately we do have a road map of sorts, a mirror image of this issue. In 1896 the U.S. Supreme Court, in Plessy v. Ferguson, effectively declared that A negros" were not protected by the Fourteenth Amendment, were not in fact the persons it was meant to protect. In 1956 in Brown v. Board of Education, the Supreme Court ruled so that suddenly A Negroes" again became full legal persons. I hope I don't need to describe the plight of African-Americans and other people of color during the period from 1896 to 1956, nor will I recount the campaign necessary to get the court to change its mind in 1956. Were African-Americans (and others classified as non-white) suddenly better off the day after the 1956 ruling? Potentially yes, but factually no. It took years of protests, court cases, legislative changes, changes in people's awareness and semantics, and even many people's murders at the hands of those who opposed change, before African-Americans began to be treated, legally, socially, and economically, as citizens and persons. The process is not yet complete. When corporate personhood is terminated, whether it be by a Supreme Court decision, an Amendment to the U.S. Constitution, or by citizens and States recovering the power to govern themselves democratically, the next day it may seem like nothing really has changed. But the potential for change will be as great as it was for people of color after Brown v. Board of Education. Just as in 1956 you could predict that, finally guaranteed the protection of the Federal Government under the Fourteenth Amendment, people of color might soon be able to shop with white people, have the vote, elect people of color to office, and make substantial economic gains, we can predict what can happen after the ending of corporate personhood. But these things will not happen unless there are years of protests, court cases, legislation, and changes in people's awareness. We can't predict the details, but since we know what has been obstructed in the past, we can see what freedoms the people might gain once we begin to end corporate dominance. Corporate personhood is at the root of such Supreme Court rulings as First National Bank of Boston v. Bellotti [435 U.S. 765 (1978)], which equate corporate donations to political campaigns with free speech. They allow corporate money to govern the political process. These rulings can be reversed once the 1886 decision is reversed, since they are directly dependent upon it. Then we should be able to force corporations out of the political process. We could do this through legislation or through the chartering process. Without personhood the corporations are not entitled to 1st Amendment rights; they will have only what privileges the people, through our government, gives them. We can and should prohibit them from making any kind of contribution to politicians, to lobbying groups, or to campaigns involving referenda. Any advertising that does not sell products, that is, any advertising not presenting factual information about the products or services a corporation offers, should be prohibited. Later in this essay the secondary effects of removing corporations and their money from the political decision making (including regulatory) process will be examined. First other changes that are directly dependent upon revoking corporate personhood need examining. Without the protection of the 14th Amendment, corporations could be purposefully discriminated against in legislation. It would even become possible to discriminate against particular types and sizes of corporations. The citizens would thereby gain much greater control over the economy, both nationally and at the local level. For instance, the Supreme Court in the past, based on corporate personhood, has held that States and localities cannot favor small or local businesses over corporate chain stores or out-of-state businesses, as in Liggett v. Lee [288 U.S. 517 (1933)]. Towns that want all business to be local, or even that want to keep out certain chains but allow others, will be able to have that control, if they wish. They could also finally have truly effective "bad boy" laws (which prohibit businesses with criminal records from operating in a community), as opposed to the current ineffective ones (because we'll be able to limit corporations appeals to the courts). Without personhood the due process used for corporations could be different than the due process used for individuals or unincorporated businesses. As an illustration, corporations might only be allowed a single hearing when their actions effect an endangered species, rather than the current system where they can spend millions of dollars of their own money, and of taxpayer money, and of the non-profit environmental groups that oppose them, in an unending series of appeals and diversionary legal filings. Another example would be that corporate charters, granted by the states, might channel certain types of corporate wrongdoing into special courts where justice is swift and stern, including the immediate closing of businesses that violate environmental, consumer safety, or labor laws. Another important constitutional "right" given to corporations is protection under the 4th Amendment, which states, A The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures, shall not be violated, and no warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons to be seized." The key Supreme Court decision here was Hale v. Henkel [201 U.S. 43 (1906)], which established that corporations have protection under the 4th Amendment based in part on their status as persons. It was decided that a subpoena issued by a federal grand jury to the secretary of a corporation, MacAndrews & Forbes Company, amounted to such an unreasonable search and seizure. This ruling made it difficult to enforce the Sherman anti-monopoly act, which naturally required the papers of corporations in order to determine if there existed grounds for an indictment. Oddly the same ruling recognized it would be very hard to give the 5th Amendment right that "nor shall any person ... be compelled in any criminal case to be a witness against himself," because a corporation, not being a natural person, cannot testify at all. It can be represented in court by natural persons, who cannot take the 5th on the corporation's behalf, because you only have the right to not incriminate yourself; you have no immunity to testifying against other persons. The importance of the 4th Amendment right of corporate persons is shown, among other places, in Marshall v. Barlow's, Inc. [436 U.S. 307 (1978)]. The Occupational Safety and Health Act of 1970 (OSHA), enacted to try to get employees safe working environments, allowed for surprise inspections of workplaces. These inspections were struck down by the Supreme Court, which declared that OSHA inspections required either the corporation's permission or a warrant. Apparently the constitutional personhood rights of corporations trump the rights of real persons. Thousands of workers have died, been maimed, or poisoned since 1978, while on the job; many of these accidents were preventable, but the Supreme Court did not consider the liberty of the workers, only the liberty of corporations and their wealthy owners in making this murderous decision. No workplace that follows OSHA safety rules need fear a surprise inspection. Revoking corporate personhood and 4th Amendment rights for corporations would allow the government to make reasonable inspections to insure worker safety, to insure that toxic substances are not being emitted, and to insure that corporations are operating as allowed by their charters and the law. Revoking personhood should not be feared by law-abiding, legitimate businesses and corporations who are obeying the law. We now return to the possible secondary results of ending corporate personhood and getting corporations out of the political process. With corporations out of the political process the whole nature of regulation would change for the better. Whether regarding the environment or food safety, we would not have to compromise with powerful corporate political machines. Do the people want to prohibit clear-cutting? Then the laws will prohibit clear-cutting, because no politician will be on a wood-products corporation's payroll. Do the people want zero emissions into streams and rivers? Then the law will prohibit any and all toxic emissions, because the politicians will rely on people for votes, not on polluting corporations for money to buy votes. The main roadblock to single-payer, national health care has been the enormous amount of lobbying and campaign contributions from those corporations that profit from the current system. By prohibiting corporate-sponsored campaign contributions to politicians and corporate-sponsored propaganda on television, the national consensus in favor of national health care could no longer be thwarted. Ending corporate personhood is no more a magic-bullet than was the Brown v. Ferguson ruling, or the passing of the Fourteenth Amendment itself. As long as there is a society there will be struggle over how resources, including political powers, are allocated. Ending corporate personhood and corporate constitutional rights would result, not in a level playing field, but in a field where We the People have the advantage again, where in any particular issue that is fought out in the public arena, the people are more likely to win than the owners of the corporations. How We Can Revoke Corporate Personhood Corporate personhood and corporate constitutional rights are a lie. How do we get the courts and government to realize that? The simple solution would be to somehow bring a case involving only corporate personhood to the Supreme Court and ask them to rule on it. Hopefully they would take a strict-constructionist line and recognize that the Constitution does not mean corporations when it says persons. This method is unlikely for a variety of reasons, the foremost being that the current Supreme Court is a product of the corporate-dominated legal system and appointees are designated by corporate-dominated presidents and approved by a corporate-dominated Congress. In addition, many roadblocks have been built into the system to prevent such a case from even coming to the Supreme Court. We would need a law in some State or locality specifically denying corporations personhood, but attorneys and judges have so far taken the view that any such law would be outside the allowable bounds for local jurisdictions. They can (and certainly will) advise elected officials that they cannot even allow such a law to come up for a vote or referendum. But neither did the railroad attorneys simply declare corporations persons and a few days later have the Supreme Court agree with them. Powerful as they were, it took them 15 years to get corporate personhood enshrined in the system. We will need a sustained grassroots campaign to abolish corporate personhood. This campaign has barely begun. We can win with education and action. We must try to pass laws abolishing corporate personhood in every local government and in every state. We must argue before the courts so that they become familiar with our ideas. We must pass referenda and then protest when our referenda are struck down by the corrupt judiciary. We must demand that elected representatives take a stand against corporate personhood if they want the votes of environmentalists, workers, and small business owners. And we must argue our points in the law schools where future generations of lawyers and judges are being trained. Supreme Courts do not work in a vacuum. When the public cries out for an issue to be tried the Supreme Court loses its prestige, perhaps even its ability to govern the country, if it refuses to hear the issue. Even if, in the first case, the Supreme Court ruled in favor of corporate personhood, if they at least gave an actual rational to their madness, we would be able to tear it apart. We could focus on each point of their argument and bring suits appropriate to overruling each point. We could, and probably should, clarify our position by an Amendment to the Constitution that clarifies the legal status of corporations. Amending the Constitution is a very difficult process, but it is the ultimate expression of the people = s authority. The corporate media will not be on our side; we must communicate through our natural inter-connectivity as a grassroots campaign. Other tactics are available besides education, legislation, and lawsuits. We can find corporations that will publicly and voluntarily renounce their corporate personhood. We can boycott corporations that lead the fight to retain corporate personhood. We can add civil disobedience and direct action to our campaign. If a State revokes corporate personhood, and the Supreme Court overturns them, we could refuse to participate in the federal government and simply govern ourselves through the State government until the Supreme Court sees the light. The struggle to abolish slavery was long and difficult. Even as abolitionists seemed to have won, by passing the 13th and 14th Amendments, counterattacks were being prepared. Corporations were pronounced persons in 1886, and in 1896 black people were declared to be sub-persons. In the 20th century we have seen the emergence of wage-slavery on a massive scale. We must ask ourselves: Are corporations to be our masters? Or are we to be free? What price are we willing to pay for our freedom, and what price do we pay now for our ongoing subjugation? The Abolition of corporate personhood is part of the abolition of slavery. It is deeply connected to our need to save the earth from environmental destruction. This is not an optional campaign. Hard as it might be to fight now, it is better to fight now than in 20 years when corporations are even more entrenched and the average person has sunk even deeper into our modern style of slavery. Frequently Asked Questions What would be the immediate effect of revoking corporate personhood? The only immediate effect of revoking corporate personhood, either at the state level or by the Supreme Court, would be to cause the legal status of corporations to revert back to that of artificial entities. (We should refuse to use the old terminology of artificial persons.) They could still be represented in courts by attorneys and would be subject to the law and taxation. However, a whole body of Supreme Court decisions would have to be re-examined. The ability of States, when granting or renewing corporate charters, to restrict harmful activities of corporations would be greatly enhanced. New legislation to protect the environment, workers, small businesses, and consumers could be enacted without worrying that it would be struck down by the Supreme Court. How would small businesses be affected? Small, incorporated businesses would become artificial entities under the law. Most small businesses have gained no meaningful advantage from corporate personhood. Small businesses do not have the kind of money it takes to corrupt the political process that large corporations have. Small businesses would be better situated to protect their interests since laws favoring local businesses over national and international corporations would become legal. If corporations can't lobby, how can they get laws that are fair to them? Revoking corporate personhood would not immediately prevent corporations from lobbying, but it would allow laws to be passed (and enforced) that would restrict corporate lobbying and campaign contributions. If a state legislature or Congress is considering legislation that affects a particular industry they would be able to hold hearings and interrogate corporate representatives. If a corporation feels its needs a change in the laws, not for its own profits but in order to insure competition or public safety, it could petition the legislature to hold such a hearing. What about past harms done by corporate personhood? That is an interesting question with no certain answer. The Constitution prohibits ex post facto laws (laws that punish for deeds committed before the law was written), and properly so. However, revoking corporate personhood does not create an ex post facto law. It may be possible to force corporations to rectify damage they did to the environment during the era of corporate personhood. Would the media lose its freedom of the press and free speech? The ruling that corporate ads on political and social issues is free speech could be overturned, but the corporate media would continue to have freedom of the press. New legislation would be needed to restrict corporations to ownership of a single radio or TV station, newspaper, or magazine and to insure that individual and non-corporate voices could be heard as well. How will revoking corporate personhood affect non-profit corporations? Non-profit corporations would continue to operate as the artificial entities that they are. However, it would be possible to restrict for-profit corporations from working for corporate interests. Why don't unions have corporate personhood? Unions don't have corporate personhood, even though they are also, legally, artificial entities, because unions have never fought to get it. Unions have largely avoided the court system, correctly seeing it as the home court of their enemies. Why do you want to restrict the freedom of stockholders and people who work for corporations? This is a trick question. Corporate lawyers and propagandists will try to get people who work for corporations to support corporate personhood by lying to them about the effects of revocation. In fact individuals, whether they work for corporations or not, will retain all of the freedoms recognized in the constitution. In addition, individuals will have their freedom enhanced by not having their liberty overpowered by the rule of corporations. Only the artificial entity of the corporation will be redefined to have restrictions on its liberty. Wouldn't we lose the power to tax and regulate corporations? In the art of lying it is hard to surpass corporate lawyers. They have managed to place in the minds of law students, in the texts of some law books, and in the public mind, the idea that corporate personhood is necessary to bring corporations under rule of law. This is such a big lie it is amazing that they can tell it with a straight face. Corporations were taxed when they were artificial entities, long before they were granted personhood. They were more subject to the rule of law, not less, before receiving personhood. Read up on the history; don't be fooled again. November 13, 2000 This work has been placed in the public domain. It may be reproduced in whole or in part by anyone for any reason. For more information on ending corporate dominance and corporate personhood visit the Redwood Coast Alliance For Democracy web site: http://www.iiipublishing.com/alliance.htm Published by III Publishing POB 1581 Gualala, CA 95445 In addition to reading the opinions of the justices in the Supreme Court cases discussed (which can be found on the Internet at www.findlaw.com or at most public, college and law libraries), for those who want a deeper legal understanding of the issue I highly recommend: "Personalizing the Impersonal: Corporations and the Bill of Rights" by Carl J. Mayer, The Hastings Law Journal, March 1990
__all__ = [ 'CustomFormFieldMixin' ] class CustomFormFieldMixin(object): def set_additional_data(self, data): for key, val in data.items(): if hasattr(self, key): raise Exception('{} クラスにはすでに属性 : {} が存在します'.format( self.__class__.__name__, key)) setattr(self, key, val) def set_new_queryset(self, *args, **kwargs): pass
<filename>Libraries/LibCore/CoreIPCClient.h #pragma once #include <LibCore/CEvent.h> #include <LibCore/CEventLoop.h> #include <LibCore/CLocalSocket.h> #include <LibCore/CNotifier.h> #include <LibCore/CSyscallUtils.h> #include <LibIPC/IMessage.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> //#define CIPC_DEBUG namespace IPC { namespace Client { class Event : public CEvent { public: enum Type { Invalid = 2000, PostProcess, }; Event() {} explicit Event(Type type) : CEvent(type) { } }; class PostProcessEvent : public Event { public: explicit PostProcessEvent(int client_id) : Event(PostProcess) , m_client_id(client_id) { } int client_id() const { return m_client_id; } private: int m_client_id { 0 }; }; template<typename ServerMessage, typename ClientMessage> class Connection : public CObject { public: Connection(const StringView& address) : m_connection(CLocalSocket::construct(this)) , m_notifier(CNotifier::construct(m_connection->fd(), CNotifier::Read, this)) { // We want to rate-limit our clients m_connection->set_blocking(true); m_notifier->on_ready_to_read = [this] { drain_messages_from_server(); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); }; int retries = 100000; while (retries) { if (m_connection->connect(CSocketAddress::local(address))) { break; } dbgprintf("Client::Connection: connect failed: %d, %s\n", errno, strerror(errno)); usleep(10000); --retries; } ASSERT(m_connection->is_connected()); } virtual void handshake() = 0; virtual void event(CEvent& event) override { if (event.type() == Event::PostProcess) { postprocess_bundles(m_unprocessed_bundles); } else { CObject::event(event); } } void set_server_pid(pid_t pid) { m_server_pid = pid; } pid_t server_pid() const { return m_server_pid; } void set_my_client_id(int id) { m_my_client_id = id; } int my_client_id() const { return m_my_client_id; } template<typename MessageType> bool wait_for_specific_event(MessageType type, ServerMessage& event) { // Double check we don't already have the event waiting for us. // Otherwise we might end up blocked for a while for no reason. for (ssize_t i = 0; i < m_unprocessed_bundles.size(); ++i) { if (m_unprocessed_bundles[i].message.type == type) { event = move(m_unprocessed_bundles[i].message); m_unprocessed_bundles.remove(i); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); return true; } } for (;;) { fd_set rfds; FD_ZERO(&rfds); FD_SET(m_connection->fd(), &rfds); int rc = CSyscallUtils::safe_syscall(select, m_connection->fd() + 1, &rfds, nullptr, nullptr, nullptr); if (rc < 0) { perror("select"); } ASSERT(rc > 0); ASSERT(FD_ISSET(m_connection->fd(), &rfds)); bool success = drain_messages_from_server(); if (!success) return false; for (ssize_t i = 0; i < m_unprocessed_bundles.size(); ++i) { if (m_unprocessed_bundles[i].message.type == type) { event = move(m_unprocessed_bundles[i].message); m_unprocessed_bundles.remove(i); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); return true; } } } } bool post_message_to_server(const ClientMessage& message, const ByteBuffer&& extra_data = {}) { #if defined(CIPC_DEBUG) dbg() << "C: -> S " << int(message.type) << " extra " << extra_data.size(); #endif if (!extra_data.is_empty()) const_cast<ClientMessage&>(message).extra_size = extra_data.size(); struct iovec iov[2]; int iov_count = 1; iov[0].iov_base = const_cast<ClientMessage*>(&message); iov[0].iov_len = sizeof(message); if (!extra_data.is_empty()) { iov[1].iov_base = const_cast<u8*>(extra_data.data()); iov[1].iov_len = extra_data.size(); ++iov_count; } int nwritten; for (;;) { nwritten = writev(m_connection->fd(), iov, iov_count); if (nwritten < 0) { if (errno == EAGAIN) { sched_yield(); continue; } perror("writev"); ASSERT_NOT_REACHED(); } break; } ASSERT((size_t)nwritten == sizeof(message) + extra_data.size()); return true; } template<typename MessageType> ServerMessage sync_request(const ClientMessage& request, MessageType response_type) { bool success = post_message_to_server(request); ASSERT(success); ServerMessage response; success = wait_for_specific_event(response_type, response); ASSERT(success); return response; } template<typename RequestType, typename... Args> typename RequestType::ResponseType send_sync(Args&&... args) { bool success = post_message_to_server(RequestType(forward<Args>(args)...)); ASSERT(success); ServerMessage response; success = wait_for_specific_event(RequestType::ResponseType::message_type(), response); ASSERT(success); return response; } protected: struct IncomingMessageBundle { ServerMessage message; ByteBuffer extra_data; }; virtual void postprocess_bundles(Vector<IncomingMessageBundle>& new_bundles) { dbg() << "Client::Connection: " << " warning: discarding " << new_bundles.size() << " unprocessed bundles; this may not be what you want"; new_bundles.clear(); } private: bool drain_messages_from_server() { for (;;) { ServerMessage message; ssize_t nread = recv(m_connection->fd(), &message, sizeof(ServerMessage), MSG_DONTWAIT); if (nread < 0) { if (errno == EAGAIN) { return true; } perror("read"); exit(1); return false; } if (nread == 0) { dbgprintf("EOF on IPC fd\n"); exit(1); return false; } ASSERT(nread == sizeof(message)); ByteBuffer extra_data; if (message.extra_size) { extra_data = ByteBuffer::create_uninitialized(message.extra_size); int extra_nread = read(m_connection->fd(), extra_data.data(), extra_data.size()); if (extra_nread < 0) { perror("read"); ASSERT_NOT_REACHED(); } ASSERT((size_t)extra_nread == message.extra_size); } #if defined(CIPC_DEBUG) dbg() << "C: <- S " << int(message.type) << " extra " << extra_data.size(); #endif m_unprocessed_bundles.append({ move(message), move(extra_data) }); } } RefPtr<CLocalSocket> m_connection; RefPtr<CNotifier> m_notifier; Vector<IncomingMessageBundle> m_unprocessed_bundles; int m_server_pid { -1 }; int m_my_client_id { -1 }; }; template<typename Endpoint> class ConnectionNG : public CObject { public: ConnectionNG(const StringView& address) : m_connection(CLocalSocket::construct(this)) , m_notifier(CNotifier::construct(m_connection->fd(), CNotifier::Read, this)) { // We want to rate-limit our clients m_connection->set_blocking(true); m_notifier->on_ready_to_read = [this] { drain_messages_from_server(); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); }; int retries = 100000; while (retries) { if (m_connection->connect(CSocketAddress::local(address))) { break; } dbgprintf("Client::Connection: connect failed: %d, %s\n", errno, strerror(errno)); usleep(10000); --retries; } ASSERT(m_connection->is_connected()); } virtual void handshake() = 0; virtual void event(CEvent& event) override { if (event.type() == Event::PostProcess) { postprocess_messages(m_unprocessed_messages); } else { CObject::event(event); } } void set_server_pid(pid_t pid) { m_server_pid = pid; } pid_t server_pid() const { return m_server_pid; } void set_my_client_id(int id) { m_my_client_id = id; } int my_client_id() const { return m_my_client_id; } template<typename MessageType> OwnPtr<MessageType> wait_for_specific_message() { // Double check we don't already have the event waiting for us. // Otherwise we might end up blocked for a while for no reason. for (ssize_t i = 0; i < m_unprocessed_messages.size(); ++i) { if (m_unprocessed_messages[i]->id() == MessageType::static_message_id()) { auto message = move(m_unprocessed_messages[i]); m_unprocessed_messages.remove(i); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); return message; } } for (;;) { fd_set rfds; FD_ZERO(&rfds); FD_SET(m_connection->fd(), &rfds); int rc = CSyscallUtils::safe_syscall(select, m_connection->fd() + 1, &rfds, nullptr, nullptr, nullptr); if (rc < 0) { perror("select"); } ASSERT(rc > 0); ASSERT(FD_ISSET(m_connection->fd(), &rfds)); bool success = drain_messages_from_server(); if (!success) return nullptr; for (ssize_t i = 0; i < m_unprocessed_messages.size(); ++i) { if (m_unprocessed_messages[i]->id() == MessageType::static_message_id()) { auto message = move(m_unprocessed_messages[i]); m_unprocessed_messages.remove(i); CEventLoop::current().post_event(*this, make<PostProcessEvent>(m_connection->fd())); return message; } } } } bool post_message_to_server(const IMessage& message) { auto buffer = message.encode(); int nwritten = write(m_connection->fd(), buffer.data(), (size_t)buffer.size()); if (nwritten < 0) { perror("write"); ASSERT_NOT_REACHED(); return false; } ASSERT(nwritten == buffer.size()); return true; } template<typename RequestType, typename... Args> OwnPtr<typename RequestType::ResponseType> send_sync(Args&&... args) { bool success = post_message_to_server(RequestType(forward<Args>(args)...)); ASSERT(success); auto response = wait_for_specific_message<typename RequestType::ResponseType>(); ASSERT(response); return response; } protected: virtual void postprocess_messages(Vector<OwnPtr<IMessage>>& new_bundles) { new_bundles.clear(); } private: bool drain_messages_from_server() { for (;;) { u8 buffer[4096]; ssize_t nread = recv(m_connection->fd(), buffer, sizeof(buffer), MSG_DONTWAIT); if (nread < 0) { if (errno == EAGAIN) { return true; } perror("read"); exit(1); return false; } if (nread == 0) { dbg() << "EOF on IPC fd"; exit(1); return false; } auto message = Endpoint::decode_message(ByteBuffer::wrap(buffer, sizeof(buffer))); ASSERT(message); m_unprocessed_messages.append(move(message)); } } RefPtr<CLocalSocket> m_connection; RefPtr<CNotifier> m_notifier; Vector<OwnPtr<IMessage>> m_unprocessed_messages; int m_server_pid { -1 }; int m_my_client_id { -1 }; }; } // Client } // IPC
<gh_stars>0 import React, {useCallback} from 'react'; import {Song} from '../Types'; import {breakpoints, colors} from '../theme'; interface Props { setSongData(songs: Array<Song>): void; } const FileUploader: React.FC<Props> = ({setSongData}) => { const handleDrop = useCallback(e => { const reader = new FileReader(); reader.onload = () => { if (typeof reader.result !== 'string') return; const jsonIsLineDelimited = reader.result.indexOf('},') === -1; const songs = JSON.parse( jsonIsLineDelimited ? `[${reader.result.replace(/\n/g, ',')}]` : reader.result ); setSongData(songs); }; reader.readAsText(e.target.files[0]); }, []); return ( <div className='container'> <label htmlFor='upload-input'>UPLOAD</label> <span className='small-text'>(EndSong.json only please)</span> <input id='upload-input' type='file' accept='application/json,.json' onChange={handleDrop} /> <style jsx> {` .container { align-items: center; display: flex; flex-direction: column; margin: 2rem auto 0; width: fit-content; } @media screen and (min-width: ${breakpoints.sm}) .container { margin: initial; } input { background: ${colors.green}; border: none; border-radius: 1rem; color: white; padding: 0.5rem; } .small-text { font-size: 0.8rem; } `} </style> </div> ); }; export default FileUploader;
/** * Parses a buffer looking for an LDAP request message. * * @author Middleware Services */ public class RequestParser { /** Bind request DER path. */ private static final DERPath BIND_PATH = new DERPath("/SEQ/APP(0)"); /** Unbind request DER path. */ private static final DERPath UNBIND_PATH = new DERPath("/SEQ/APP(2)"); /** Search request DER path. */ private static final DERPath SEARCH_PATH = new DERPath("/SEQ/APP(3)"); /** Modify request DER path. */ private static final DERPath MODIFY_PATH = new DERPath("/SEQ/APP(6)"); /** Add request DER path. */ private static final DERPath ADD_PATH = new DERPath("/SEQ/APP(8)"); /** Delete request DER path. */ private static final DERPath DELETE_PATH = new DERPath("/SEQ/APP(10)"); /** Modify DN request DER path. */ private static final DERPath MODIFY_DN_PATH = new DERPath("/SEQ/APP(12)"); /** Compare request DER path. */ private static final DERPath COMPARE_PATH = new DERPath("/SEQ/APP(14)"); /** Abandon request DER path. */ private static final DERPath ABANDON_PATH = new DERPath("/SEQ/APP(16)"); /** Extended request DER path. */ private static final DERPath EXTENDED_PATH = new DERPath("/SEQ/APP(23)"); /** Parser for decoding LDAP messages. */ private final DERParser parser = new DERParser(); /** Message produced from parsing a DER buffer. */ private Request message; /** * Creates a new request parser. */ public RequestParser() { parser.registerHandler(BIND_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(UNBIND_PATH, (p, e) -> { e.clear(); message = new UnbindRequest(); }); parser.registerHandler(SEARCH_PATH, (p, e) -> { e.clear(); // note that no decoding is occurring here message = new SearchRequest(); }); parser.registerHandler(MODIFY_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(ADD_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(DELETE_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(MODIFY_DN_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(COMPARE_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(ABANDON_PATH, (p, e) -> { e.clear(); message = null; }); parser.registerHandler(EXTENDED_PATH, (p, e) -> { e.clear(); message = null; }); } /** * Examines the supplied buffer and parses an LDAP request message if one is found. * * @param buffer to parse * * @return optional LDAP message */ public Optional<Request> parse(final DERBuffer buffer) { parser.parse(buffer); return Optional.ofNullable(message); } }
<filename>mayan/apps/documents/links/trashed_document_links.py from django.utils.translation import ugettext_lazy as _ from mayan.apps.navigation.classes import Link from ..icons import ( icon_document_trash_send, icon_trash_can_empty, icon_trashed_document_delete, icon_trashed_document_list, icon_trashed_document_restore ) from ..permissions import ( permission_trashed_document_delete, permission_trashed_document_restore, permission_document_trash, permission_trash_empty ) link_document_delete = Link( args='resolved_object.id', icon=icon_trashed_document_delete, permissions=(permission_trashed_document_delete,), tags='dangerous', text=_('Delete'), view='documents:document_delete' ) link_document_trash = Link( args='resolved_object.id', icon=icon_document_trash_send, permissions=(permission_document_trash,), tags='dangerous', text=_('Move to trash'), view='documents:document_trash' ) link_document_list_deleted = Link( icon=icon_trashed_document_list, text=_('Trash can'), view='documents:document_list_deleted' ) link_document_restore = Link( args='object.pk', icon=icon_trashed_document_restore, permissions=(permission_trashed_document_restore,), text=_('Restore'), view='documents:document_restore' ) link_document_multiple_trash = Link( icon=icon_document_trash_send, tags='dangerous', text=_('Move to trash'), view='documents:document_multiple_trash' ) link_document_multiple_delete = Link( icon=icon_trashed_document_delete, tags='dangerous', text=_('Delete'), view='documents:document_multiple_delete' ) link_document_multiple_restore = Link( icon=icon_trashed_document_restore, text=_('Restore'), view='documents:document_multiple_restore' ) link_trash_can_empty = Link( icon=icon_trash_can_empty, permissions=(permission_trash_empty,), text=_('Empty trash'), view='documents:trash_can_empty' )
We already had confirmation that Torment: Tides of Numenera [Official Site] would launch day-1 on Linux here on GOL from an email chat with inXile, but it's always good to see fully public confirmation. Some additional good news to report; I am told that Torment will be available on Linux and Mac on the same day as all other formats. — Brian Fargo (@BrianFargo) February 14, 2017 The game will launch for everyone on February 28th, so not long to go! It's a shame it didn't get a Linux release during Early Access for Linux gamers to help test, so here's to hoping it's a polished experience for us. This is one game I expect great things from! Also, see the latest trailer below if you missed it: Thanks for tagging me in the tweet Martin!
<filename>services/preview/storage/mgmt/2015-05-01-preview/storage/storageapi/interfaces.go package storageapi // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/azure-sdk-for-go/services/preview/storage/mgmt/2015-05-01-preview/storage" "github.com/Azure/go-autorest/autorest" ) // AccountsClientAPI contains the set of methods on the AccountsClient type. type AccountsClientAPI interface { CheckNameAvailability(ctx context.Context, accountName storage.AccountCheckNameAvailabilityParameters) (result storage.CheckNameAvailabilityResult, err error) Create(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountCreateParameters) (result storage.AccountsCreateFuture, err error) Delete(ctx context.Context, resourceGroupName string, accountName string) (result autorest.Response, err error) GetProperties(ctx context.Context, resourceGroupName string, accountName string) (result storage.Account, err error) List(ctx context.Context) (result storage.AccountListResultPage, err error) ListComplete(ctx context.Context) (result storage.AccountListResultIterator, err error) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result storage.AccountListResultPage, err error) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result storage.AccountListResultIterator, err error) ListKeys(ctx context.Context, resourceGroupName string, accountName string) (result storage.AccountKeys, err error) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, regenerateKey storage.AccountRegenerateKeyParameters) (result storage.AccountKeys, err error) Update(ctx context.Context, resourceGroupName string, accountName string, parameters storage.AccountUpdateParameters) (result storage.Account, err error) } var _ AccountsClientAPI = (*storage.AccountsClient)(nil) // UsageClientAPI contains the set of methods on the UsageClient type. type UsageClientAPI interface { List(ctx context.Context) (result storage.UsageListResult, err error) } var _ UsageClientAPI = (*storage.UsageClient)(nil)
/** * Parse the given string representation of the type into an instance. * * @param queueType the type of queue as a string value * @return The type of queue as a {@link DocumentQueueType} instance. */ public static DocumentQueueType parse(final String queueType) { try { return valueOf(queueType.toUpperCase(Locale.ROOT)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("\"%s\" is not a valid queue type.", queueType)); } }
#include <babylon/postprocesses/renderpipeline/post_process_render_effect.h> #include <babylon/babylon_stl_util.h> #include <babylon/cameras/camera.h> #include <babylon/materials/effect.h> #include <babylon/materials/textures/render_target_texture.h> #include <babylon/postprocesses/post_process.h> namespace BABYLON { PostProcessRenderEffect::PostProcessRenderEffect( Engine* engine, const std::string& name, const std::function<std::vector<PostProcessPtr>()>& getPostProcesses, bool singleInstance) : _name{name} , _engine{engine} , isSupported{this, &PostProcessRenderEffect::get_isSupported} , _getPostProcesses{getPostProcesses} , _singleInstance{singleInstance} { } PostProcessRenderEffect::~PostProcessRenderEffect() = default; bool PostProcessRenderEffect::get_isSupported() const { for (auto& item : _postProcesses) { for (auto& pps : item.second) { if (!pps->isSupported()) { return false; } } } return true; } void PostProcessRenderEffect::_update() { } void PostProcessRenderEffect::_attachCameras(const std::vector<CameraPtr>& cameras) { std::string cameraKey; auto cams = cameras.empty() ? stl_util::extract_values(_cameras) : cameras; if (cams.empty()) { return; } for (auto& camera : cams) { if (!camera) { continue; } const auto& cameraName = camera->name; if (_singleInstance) { cameraKey = "0"; } else { cameraKey = cameraName; } if (!stl_util::contains(_postProcesses, cameraKey) || _postProcesses[cameraKey].empty()) { auto postProcess = _getPostProcesses(); if (!postProcess.empty()) { _postProcesses[cameraKey] = postProcess; } } if (!stl_util::contains(_indicesForCamera, cameraName)) { _indicesForCamera[cameraName].clear(); } for (auto& postProcess : _postProcesses[cameraKey]) { auto index = camera->attachPostProcess(postProcess); _indicesForCamera[cameraName].emplace_back(index); } if (!stl_util::contains(_cameras, cameraName)) { _cameras[cameraName] = camera; } } } void PostProcessRenderEffect::_detachCameras(const std::vector<CameraPtr>& cameras) { auto cams = cameras.empty() ? stl_util::extract_values(_cameras) : cameras; if (cams.empty()) { return; } for (auto& camera : cams) { auto cameraName = camera->name; const auto cameraKey = _singleInstance ? "0" : cameraName; const auto& postProcesses = _postProcesses[cameraKey]; if (!postProcesses.empty()) { for (auto& postProcess : postProcesses) { camera->detachPostProcess(postProcess); } } if (stl_util::contains(_cameras, cameraName)) { // _indicesForCamera.erase(cameraName); _cameras.erase(cameraName); } } } void PostProcessRenderEffect::_enable(const std::vector<CameraPtr>& cameras) { auto cams = cameras.empty() ? stl_util::extract_values(_cameras) : cameras; if (cams.empty()) { return; } for (auto& camera : cams) { auto cameraName = camera->name; for (auto& j : _indicesForCamera[cameraName]) { auto index = _indicesForCamera[cameraName][j]; if (index >= camera->_postProcesses.size() || camera->_postProcesses[index] == nullptr) { const auto cameraKey = _singleInstance ? "0" : cameraName; for (auto& postProcess : _postProcesses[cameraKey]) { camera->attachPostProcess(postProcess, static_cast<int>(_indicesForCamera[cameraName][j])); } } } } } void PostProcessRenderEffect::_disable(const std::vector<CameraPtr>& cameras) { auto cams = cameras.empty() ? stl_util::extract_values(_cameras) : cameras; if (cams.empty()) { return; } for (auto& camera : cams) { auto cameraName = camera->name; const auto cameraKey = _singleInstance ? "0" : cameraName; for (auto& postProcess : _postProcesses[cameraKey]) { camera->detachPostProcess(postProcess); } } } std::vector<PostProcessPtr> PostProcessRenderEffect::getPostProcesses(Camera* camera) { if (_singleInstance) { return _postProcesses["0"]; } else { if (!camera) { return {}; } return _postProcesses[camera->name]; } } } // end of namespace BABYLON
<gh_stars>0 import * as BS from 'browser-search'; import { StoreId } from 'browser-search'; import { useCallback, useContext, useEffect, useReducer, Reducer } from 'react'; import { BrowserSearchContext } from './provider'; type IndexId = string; export type IdleState = { status: 'idle', } export type LoadingQueryState = { status: 'loading', indexId: IndexId; storeId: StoreId; } export type SuccessQueryState<T> = { status: 'success', indexId: IndexId; storeId: StoreId; response: T[]; } export type ErrorQueryState = { status: 'error', indexId: IndexId; storeId: StoreId; } export type QueryState<T> = IdleState | LoadingQueryState | SuccessQueryState<T> | ErrorQueryState; type Action<T> = | { type: 'requestStarted'; indexId: IndexId; storeId: StoreId;} | { type: 'requestCompleted'; response: T[]; indexId: IndexId; storeId: StoreId;} | { type: 'requestFailed'; indexId: IndexId; storeId: StoreId;} type QueryReducer<T> = Reducer<QueryState<T>, Action<T>>; const initialState: IdleState = { status: 'idle', }; const reducer = <T extends IDBValidKey>(state: QueryState<T>, action: Action<T>): QueryState<T> => { switch (action.type) { case 'requestStarted': { return { status: 'loading', indexId: action.indexId, storeId: action.storeId, } } case 'requestCompleted': { return state.status === 'loading' && state.indexId === action.indexId && state.storeId === action.storeId ? { status: 'success', indexId: action.indexId, response: action.response, storeId: action.storeId, } : state; } case 'requestFailed': { return state.status === 'loading' && state.indexId === action.indexId && state.storeId === action.storeId ? { status: 'error', indexId: action.indexId, storeId: action.storeId, } : state; } default: return state; } } export const useIndexValues = <T extends IDBValidKey>(storeId: StoreId, indexId: IndexId): QueryState<T> => { const queryClient = useContext(BrowserSearchContext); const [state, dispatch] = useReducer<QueryReducer<T>>( reducer, initialState, ); const runQuery = useCallback( (): void => { const responsePromise = BS.getAllValuesOfProperty(storeId)(indexId); dispatch({type: 'requestStarted', indexId, storeId}) responsePromise .then(response => { dispatch({type: 'requestCompleted', response: response as T[], indexId, storeId}) }) .catch(e => { console.log(e); dispatch({type: 'requestFailed', indexId, storeId}) }) }, [storeId, indexId]); useEffect(() => { queryClient.subscribeToStoreChange(storeId)(runQuery); return () => { queryClient.unsubscribeToStoreChange(storeId)(runQuery); }; }, [storeId, queryClient, runQuery]); useEffect(() => { runQuery(); }, [runQuery]); return state; }
def slug_pre_save(signal, instance, sender, **kwargs): if not instance.slug: slug = slugify(instance.titulo) novo_slug = slug contador = 0 while sender.objects.filter(slug=novo_slug).exclude(id=instance.id).count() > 0: contador += 1 novo_slug = '%s-%d'%(slug, contador) instance.slug = novo_slug
<gh_stars>0 package com.itranswarp.learnjava; /** * Learn Java from https://www.liaoxuefeng.com/ * * @author liaoxuefeng */ public class Main { public static void main(String[] args) { new Thread1().start(); new Thread2().start(); for (int i = 0; i < 100; i++) { System.out.println("main: running..."); try { Thread.sleep(1); } catch (InterruptedException e) { } } } } class Thread1 extends Thread { public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread-1: running..."); try { Thread.sleep(1); } catch (InterruptedException e) { } } } } class Thread2 extends Thread { public void run() { for (int i = 0; i < 100; i++) { System.out.println("Thread-2: running..."); try { Thread.sleep(1); } catch (InterruptedException e) { } } } }
<reponame>kokizzu/genqlient<filename>graphql/client.go package graphql import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strings" "github.com/vektah/gqlparser/v2/gqlerror" ) // Client is the interface that the generated code calls into to actually make // requests. type Client interface { // MakeRequest must make a request to the client's GraphQL API. // // ctx is the context that should be used to make this request. If context // is disabled in the genqlient settings, this will be set to // context.Background(). // // req contains the data to be sent to the GraphQL server. Typically GraphQL // APIs will expect it to simply be marshalled as JSON, but MakeRequest may // customize this. // // resp is the Response object into which the server's response will be // unmarshalled. Typically GraphQL APIs will return JSON which can be // unmarshalled directly into resp, but MakeRequest can customize it. // If the response contains an error, this must also be returned by // MakeRequest. The field resp.Data will be prepopulated with a pointer // to an empty struct of the correct generated type (e.g. MyQueryResponse). MakeRequest( ctx context.Context, req *Request, resp *Response, ) error } type client struct { httpClient Doer endpoint string method string } // NewClient returns a Client which makes requests to the given endpoint, // suitable for most users. // // The client makes POST requests to the given GraphQL endpoint using standard // GraphQL HTTP-over-JSON transport. It will use the given http client, or // http.DefaultClient if a nil client is passed. // // The typical method of adding authentication headers is to wrap the client's // Transport to add those headers. See example/caller.go for an example. func NewClient(endpoint string, httpClient Doer) Client { return newClient(endpoint, httpClient, http.MethodPost) } // NewClientUsingGet returns a Client which makes requests to the given endpoint, // suitable for most users. // // The client makes GET requests to the given GraphQL endpoint using a GET query, // with the query, operation name and variables encoded as URL parameters. // It will use the given http client, or http.DefaultClient if a nil client is passed. // // The client does not support mutations, and will return an error if passed a request // that attempts one. // // The typical method of adding authentication headers is to wrap the client's // Transport to add those headers. See example/caller.go for an example. func NewClientUsingGet(endpoint string, httpClient Doer) Client { return newClient(endpoint, httpClient, http.MethodGet) } func newClient(endpoint string, httpClient Doer, method string) Client { if httpClient == nil || httpClient == (*http.Client)(nil) { httpClient = http.DefaultClient } return &client{httpClient, endpoint, method} } // Doer encapsulates the methods from *http.Client needed by Client. // The methods should have behavior to match that of *http.Client // (or mocks for the same). type Doer interface { Do(*http.Request) (*http.Response, error) } // Request contains all the values required to build queries executed by // the graphql.Client. // // Typically, GraphQL APIs will accept a JSON payload of the form // {"query": "query myQuery { ... }", "variables": {...}}` // and Request marshals to this format. However, MakeRequest may // marshal the data in some other way desired by the backend. type Request struct { // The literal string representing the GraphQL query, e.g. // `query myQuery { myField }`. Query string `json:"query"` // A JSON-marshalable value containing the variables to be sent // along with the query, or nil if there are none. Variables interface{} `json:"variables,omitempty"` // The GraphQL operation name. The server typically doesn't // require this unless there are multiple queries in the // document, but genqlient sets it unconditionally anyway. OpName string `json:"operationName"` } // Response that contains data returned by the GraphQL API. // // Typically, GraphQL APIs will return a JSON payload of the form // {"data": {...}, "errors": {...}} // It may additionally contain a key named "extensions", that // might hold GraphQL protocol extensions. Extensions and Errors // are optional, depending on the values returned by the server. type Response struct { Data interface{} `json:"data"` Extensions map[string]interface{} `json:"extensions,omitempty"` Errors gqlerror.List `json:"errors,omitempty"` } func (c *client) MakeRequest(ctx context.Context, req *Request, resp *Response) error { var httpReq *http.Request var err error if c.method == http.MethodGet { httpReq, err = c.createGetRequest(req) } else { httpReq, err = c.createPostRequest(req) } if err != nil { return err } httpReq.Header.Set("Content-Type", "application/json") if ctx != nil { httpReq = httpReq.WithContext(ctx) } httpResp, err := c.httpClient.Do(httpReq) if err != nil { return err } defer httpResp.Body.Close() if httpResp.StatusCode != http.StatusOK { var respBody []byte respBody, err = io.ReadAll(httpResp.Body) if err != nil { respBody = []byte(fmt.Sprintf("<unreadable: %v>", err)) } return fmt.Errorf("returned error %v: %s", httpResp.Status, respBody) } err = json.NewDecoder(httpResp.Body).Decode(resp) if err != nil { return err } if len(resp.Errors) > 0 { return resp.Errors } return nil } func (c *client) createPostRequest(req *Request) (*http.Request, error) { body, err := json.Marshal(req) if err != nil { return nil, err } httpReq, err := http.NewRequest( c.method, c.endpoint, bytes.NewReader(body)) if err != nil { return nil, err } return httpReq, nil } func (c *client) createGetRequest(req *Request) (*http.Request, error) { parsedURL, err := url.Parse(c.endpoint) if err != nil { return nil, err } queryParams := parsedURL.Query() queryUpdated := false if req.Query != "" { if strings.HasPrefix(strings.TrimSpace(req.Query), "mutation") { return nil, errors.New("client does not support mutations") } queryParams.Set("query", req.Query) queryUpdated = true } if req.OpName != "" { queryParams.Set("operationName", req.OpName) queryUpdated = true } if req.Variables != nil { variables, variablesErr := json.Marshal(req.Variables) if variablesErr != nil { return nil, variablesErr } queryParams.Set("variables", string(variables)) queryUpdated = true } if queryUpdated { parsedURL.RawQuery = queryParams.Encode() } httpReq, err := http.NewRequest( c.method, parsedURL.String(), http.NoBody) if err != nil { return nil, err } return httpReq, nil }
import tensorflow as tf import os import umap import matplotlib.pyplot as plt import pandas as pd import numpy as np def train(model, epochs, train_dataset): # Define the checkpoint directory to store the checkpoints checkpoint_dir = './training_checkpoints' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}") callbacks = [ tf.keras.callbacks.TensorBoard(log_dir='./logs'), tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_prefix, save_weights_only=True) ] model.fit(train_dataset, epochs=epochs, callbacks=callbacks) model.load_weights(tf.train.latest_checkpoint(checkpoint_dir)) def test(model, eval_dataset, save_path="embedding"): # Get latent space encoding res = np.array(model.encode(eval_dataset)) res_df = pd.DataFrame(res) res_df.to_csv(save_path + ".csv") # Reduce with UMAP reducer = umap.UMAP(random_state=42) embedding = reducer.fit_transform(res) df = pd.DataFrame(embedding, columns=['PC1', 'PC2']) plt.scatter(df['PC1'], df['PC2']) plt.savefig(save_path + ".png") return save_path
/** * @brief Lock SPI bus for exclusive access * * On SPI buses where there are multiple devices, it will be necessary to lock * SPI to have exclusive access to the buses for a sequence of transfers. * The bus should be locked before the chip is selected. After locking the SPI * bus, the caller should then also call the setfrequency(), setbits() , and * setmode() methods to make sure that the SPI is properly configured for the * device. If the SPI buses is being shared, then it may have been left in an * incompatible state. * * @param dev pointer to structure of device data * @return 0 on success, negative errno on error */ static int tsb_spi_lock(struct device *dev) { struct tsb_spi_info *info = NULL; int ret = 0; if (!dev || !device_get_private(dev)) { return -EINVAL; } info = device_get_private(dev); ret = sem_wait(&info->bus); if (ret != OK) { return -get_errno(); } info->state = TSB_SPI_STATE_LOCKED; return 0; }
/* signal number to freq-index and code --------------------------------------*/ static int sig2idx(int sat, int sig, const char *opt, uint8_t *code) { int idx,sys=satsys(sat,NULL),nex=NEXOBS; if (sig<0||sig>SBF_MAXSIG||sig_tbl[sig][0]!=sys) return -1; *code=sig_tbl[sig][1]; idx=code2idx(sys,*code); if (sys==SYS_GPS) { if (strstr(opt,"-GL1W")&&idx==0) return (*code==CODE_L1W)?0:-1; if (strstr(opt,"-GL1L")&&idx==0) return (*code==CODE_L1L)?0:-1; if (strstr(opt,"-GL2L")&&idx==1) return (*code==CODE_L2L)?1:-1; if (*code==CODE_L1W) return (nex<1)?-1:NFREQ; if (*code==CODE_L2L) return (nex<2)?-1:NFREQ+1; if (*code==CODE_L1L) return (nex<3)?-1:NFREQ+2; } else if (sys==SYS_GLO) { if (strstr(opt,"-RL1P")&&idx==0) return (*code==CODE_L1P)?0:-1; if (strstr(opt,"-RL2C")&&idx==1) return (*code==CODE_L2C)?1:-1; if (*code==CODE_L1P) return (nex<1)?-1:NFREQ; if (*code==CODE_L2C) return (nex<2)?-1:NFREQ+1; } else if (sys==SYS_QZS) { if (strstr(opt,"-JL1L")&&idx==0) return (*code==CODE_L1L)?0:-1; if (strstr(opt,"-JL1Z")&&idx==0) return (*code==CODE_L1Z)?0:-1; if (*code==CODE_L1L) return (nex<1)?-1:NFREQ; if (*code==CODE_L1Z) return (nex<2)?-1:NFREQ+1; } else if (sys==SYS_CMP) { if (strstr(opt,"-CL1P")&&idx==0) return (*code==CODE_L1P)?0:-1; if (*code==CODE_L1P) return (nex<1)?-1:NFREQ; } return (idx<NFREQ)?idx:-1; }
<filename>source/slang/slang-ir-spirv-legalize.cpp // slang-ir-spirv-legalize.cpp #include "slang-ir-spirv-legalize.h" #include "slang-ir-glsl-legalize.h" #include "slang-ir.h" #include "slang-ir-insts.h" #include "slang-emit-base.h" #include "slang-glsl-extension-tracker.h" namespace Slang { // // Legalization of IR for direct SPIRV emit. // struct SPIRVLegalizationContext : public SourceEmitterBase { SPIRVEmitSharedContext* m_sharedContext; IRModule* m_module; // We will use a single work list of instructions that need // to be considered for specialization or simplification, // whether generic, existential, etc. // OrderedHashSet<IRInst*> workList; void addToWorkList(IRInst* inst) { if (workList.Add(inst)) { addUsersToWorkList(inst); } } void addUsersToWorkList(IRInst* inst) { for (auto use = inst->firstUse; use; use = use->nextUse) { auto user = use->getUser(); addToWorkList(user); } } SPIRVLegalizationContext(SPIRVEmitSharedContext* sharedContext, IRModule* module) : m_sharedContext(sharedContext), m_module(module) { } void processGlobalParam(IRGlobalParam* inst) { // If the global param is not a pointer type, make it so and insert explicit load insts. auto ptrType = as<IRPtrTypeBase>(inst->getDataType()); if (!ptrType) { SpvStorageClass storageClass = SpvStorageClassPrivate; // Figure out storage class based on var layout. if (auto layout = getVarLayout(inst)) { if (auto systemValueAttr = layout->findAttr<IRSystemValueSemanticAttr>()) { String semanticName = systemValueAttr->getName(); semanticName = semanticName.toLower(); if (semanticName == "sv_dispatchthreadid") { storageClass = SpvStorageClassInput; } } } // Make a pointer type of storageClass. IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); ptrType = builder.getPtrType(kIROp_PtrType, inst->getFullType(), storageClass); inst->setFullType(ptrType); // Insert an explicit load at each use site. List<IRUse*> uses; for (auto use = inst->firstUse; use; use = use->nextUse) { uses.add(use); } for (auto use : uses) { builder.setInsertBefore(use->getUser()); auto loadedValue = builder.emitLoad(inst); use->set(loadedValue); } } processGlobalVar(inst); } void processGlobalVar(IRInst* inst) { auto oldPtrType = as<IRPtrTypeBase>(inst->getDataType()); if (!oldPtrType) return; // If the pointer type is already qualified with address spaces (such as // lowered pointer type from a `HLSLStructuredBufferType`), make no // further modifications. if (oldPtrType->hasAddressSpace()) { addUsersToWorkList(inst); return; } auto varLayout = getVarLayout(inst); if (!varLayout) return; SpvStorageClass storageClass = SpvStorageClassPrivate; for (auto rr : varLayout->getOffsetAttrs()) { switch (rr->getResourceKind()) { case LayoutResourceKind::Uniform: case LayoutResourceKind::ShaderResource: case LayoutResourceKind::DescriptorTableSlot: storageClass = SpvStorageClassUniform; break; case LayoutResourceKind::VaryingInput: storageClass = SpvStorageClassInput; break; case LayoutResourceKind::VaryingOutput: storageClass = SpvStorageClassOutput; break; case LayoutResourceKind::UnorderedAccess: storageClass = SpvStorageClassStorageBuffer; break; case LayoutResourceKind::PushConstantBuffer: storageClass = SpvStorageClassPushConstant; break; default: break; } } auto rate = inst->getRate(); if (as<IRGroupSharedRate>(rate)) { storageClass = SpvStorageClassWorkgroup; } IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); auto newPtrType = builder.getPtrType(oldPtrType->getOp(), oldPtrType->getValueType(), storageClass); inst->setFullType(newPtrType); addUsersToWorkList(inst); return; } void processCall(IRCall* inst) { auto funcValue = inst->getOperand(0); if (auto targetIntrinsic = Slang::findBestTargetIntrinsicDecoration( funcValue, m_sharedContext->m_targetRequest->getTargetCaps())) { SpvSnippet* snippet = m_sharedContext->getParsedSpvSnippet(targetIntrinsic); if (!snippet) return; if (snippet->resultStorageClass != SpvStorageClassMax) { auto ptrType = as<IRPtrTypeBase>(inst->getDataType()); if (!ptrType) return; IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); auto qualPtrType = builder.getPtrType( ptrType->getOp(), ptrType->getValueType(), snippet->resultStorageClass); List<IRInst*> args; for (UInt i = 0; i < inst->getArgCount(); i++) args.add(inst->getArg(i)); auto newCall = builder.emitCallInst(qualPtrType, funcValue, args); inst->replaceUsesWith(newCall); inst->removeAndDeallocate(); addUsersToWorkList(newCall); } } } void processGetElementPtr(IRGetElementPtr* inst) { if (auto ptrType = as<IRPtrTypeBase>(inst->getBase()->getDataType())) { if (!ptrType->hasAddressSpace()) return; auto oldResultType = as<IRPtrTypeBase>(inst->getDataType()); if (oldResultType->getAddressSpace() != ptrType->getAddressSpace()) { IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); auto newPtrType = builder.getPtrType( oldResultType->getOp(), oldResultType->getValueType(), ptrType->getAddressSpace()); auto newInst = builder.emitElementAddress(newPtrType, inst->getBase(), inst->getIndex()); inst->replaceUsesWith(newInst); inst->removeAndDeallocate(); addUsersToWorkList(newInst); } } } void processFieldAddress(IRFieldAddress* inst) { if (auto ptrType = as<IRPtrTypeBase>(inst->getBase()->getDataType())) { if (!ptrType->hasAddressSpace()) return; auto oldResultType = as<IRPtrTypeBase>(inst->getDataType()); if (oldResultType->getAddressSpace() != ptrType->getAddressSpace()) { IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); auto newPtrType = builder.getPtrType( oldResultType->getOp(), oldResultType->getValueType(), ptrType->getAddressSpace()); auto newInst = builder.emitFieldAddress(newPtrType, inst->getBase(), inst->getField()); inst->replaceUsesWith(newInst); inst->removeAndDeallocate(); addUsersToWorkList(newInst); } } } void processStructuredBufferType(IRHLSLStructuredBufferTypeBase* inst) { IRBuilder builder; builder.sharedBuilder = &m_sharedContext->m_sharedIRBuilder; builder.setInsertBefore(inst); auto arrayType = builder.getUnsizedArrayType(inst->getElementType()); auto structType = builder.createStructType(); auto arrayKey = builder.createStructKey(); builder.createStructField(structType, arrayKey, arrayType); auto ptrType = builder.getPtrType(kIROp_PtrType, structType, SpvStorageClassStorageBuffer); StringBuilder nameSb; switch (inst->getOp()) { case kIROp_HLSLRWStructuredBufferType: nameSb << "RWStructuredBuffer"; break; case kIROp_HLSLAppendStructuredBufferType: nameSb << "AppendStructuredBuffer"; break; case kIROp_HLSLConsumeStructuredBufferType: nameSb << "ConsumeStructuredBuffer"; break; default: nameSb << "StructuredBuffer"; break; } builder.addNameHintDecoration(structType, nameSb.getUnownedSlice()); builder.addDecoration(structType, kIROp_SPIRVBufferBlockDecoration); inst->replaceUsesWith(ptrType); inst->removeAndDeallocate(); addUsersToWorkList(ptrType); } void processModule() { addToWorkList(m_module->getModuleInst()); while (workList.Count() != 0) { IRInst* inst = workList.getLast(); workList.removeLast(); switch (inst->getOp()) { case kIROp_GlobalParam: processGlobalParam(as<IRGlobalParam>(inst)); break; case kIROp_GlobalVar: processGlobalVar(as<IRGlobalVar>(inst)); break; case kIROp_Call: processCall(as<IRCall>(inst)); break; case kIROp_getElementPtr: processGetElementPtr(as<IRGetElementPtr>(inst)); break; case kIROp_FieldAddress: processFieldAddress(as<IRFieldAddress>(inst)); break; case kIROp_HLSLStructuredBufferType: case kIROp_HLSLRWStructuredBufferType: processStructuredBufferType(as<IRHLSLStructuredBufferTypeBase>(inst)); break; default: for (auto child = inst->getLastChild(); child; child = child->getPrevInst()) { addToWorkList(child); } break; } } } }; void legalizeSPIRV(SPIRVEmitSharedContext* sharedContext, IRModule* module) { SPIRVLegalizationContext context(sharedContext, module); context.processModule(); } void legalizeIRForSPIRV( SPIRVEmitSharedContext* context, IRModule* module, const List<IRFunc*>& entryPoints, DiagnosticSink* sink) { SLANG_UNUSED(sink); GLSLExtensionTracker extensionTracker; legalizeEntryPointsForGLSL(module->getSession(), module, entryPoints, sink, &extensionTracker); legalizeSPIRV(context, module); } } // namespace Slang
from sys import stdin,stdout from bisect import bisect_right input = stdin.readline n,v = map(int, input().split()) ans = min(v,n-1); left=0 for i in range(2,n): if n-v-i >= 0: ans += i print(ans)
// If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called. @Override public void onCreate(SQLiteDatabase db) { String CREATE_POSTS_TABLE = "CREATE TABLE " + TABLE_GROCERIES + "(" + KEY_GROCERIES_ID + " INTEGER PRIMARY KEY," + KEY_GROCERIES_NAME + " TEXT, " + KEY_GROCERIES_IMAGE + " TEXT" + ")"; String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "(" + KEY_PRODUCTS_ID + " INTEGER PRIMARY KEY," + KEY_PRODUCTS_NAME + " TEXT," + KEY_PRODUCTS_IMAGE + " TEXT," + KEY_PRODUCTS_GROUP + " TEXT," + KEY_PRODUCTS_PRICE + " TEXT" + ")"; String CREATE_CART_TABLE = "CREATE TABLE " + TABLE_CART + "(" + KEY_CART_ID + " INTEGER PRIMARY KEY," + KEY_CART_NAME + " TEXT," + KEY_CART_IMAGE + " TEXT," + KEY_CART_PRICE + " TEXT," + KEY_CART_QUANTITY + " TEXT" + ")"; db.execSQL(CREATE_POSTS_TABLE); db.execSQL(CREATE_USERS_TABLE); db.execSQL(CREATE_CART_TABLE); addTableData(db); }
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #include<string.h> #include<math.h> #define mprint(x) printf(FORMATCONVERSION(x),(x)) #define FORMATCONVERSION(x) _Generic((x),\ int:"%d",unsigned int:"%u",\ double:"%lf",long long int:"%lld",\ unsigned long long int:"%llu",\ unsigned long : "%lu",\ long int : "%ld",\ char :"%c",char*:"%s") int main(void){ int n; char str[n]; scanf("%d",&n); scanf("%s",str); int count = 0; for(int i = 2;i < n;i++){ if(str[i] == 'C' && str[i - 1] == 'B' && str[i - 2] == 'A')count++; } mprint(count); }
/* * A quick util to know whether or not this report contains information * about a specific equipmentId. * */ @JsonIgnore public boolean seesEquipment(long equipmentId) { if (managedNeighbours != null) { for (List<ManagedNeighbourEquipmentInfo> list : managedNeighbours.values()) { for (ManagedNeighbourEquipmentInfo managedInfo : list) { if (managedInfo.getEquipmentId() == equipmentId) { return true; } } } } return false; }
/// Whether to include specialized methods for specific encodings. pub fn with_encodings<I>(mut self, encodings: I) -> Self where I: IntoIterator<Item = Encoding>, { self.encodings = encodings.into_iter().collect(); self }
<filename>lib/__tests__/fixtures/events.ts import {WDIO_TEST_STATUS} from "../../constants"; export const suiteStartEvent = () => ({ uid: "FooBarSuite", cid: "0-0", title: "foo", runner: {"0-0": {}} }); export const suiteEndEvent = () => ({ uid: "FooBarSuite", cid: "0-0", title: "foo", tests: [{ state: WDIO_TEST_STATUS.PASSED, }] }); export const testStartEvent = () => ({ uid: "FooBarTest", fullTitle: "fullTitle", type: 'test', cid: "0-0", title: "foo", runner: {"0-0": {}} });
‘The Joyous Light of Day’: New Year’s Day Music in Leipzig, 1781–1847 Unlike other European cities, where the rise of the public concert in the eighteenth century diminished the church’s prominent role in musical life, Leipzig was a city in which the church maintained a strong influence over public concert institutions. On 25 November 1781, Leipzig’s new concert hall, the Gewandhaus, was inaugurated as the home for the subscription series directed by Johann Adam Hiller. Launched along with the hall was a tradition of performing one of the subscription concerts on New Year’s Day, a practice that may well have been the first of its kind on the continent. At first, the New Year’s concert was like any other of the season, comprising a variety of musical genres, including symphonies, concerti, and operatic fare. Quickly, however, concert organizers attempted to give this particular programme a distinct identity. Sacred music became a tradition in these concerts, which soon came to resemble the New Year’s Day music at the Thomaskirche and Nikolaikirche. Despite its sacred bent, the New Year’s Day concert was also infused with strong political overtones. Indeed, it was the sacred components of the concert that became the vehicle for praising political figures. New Year’s Day music in Leipzig was not sacred or political, it was often sacred and political simultaneously—not surprising for a city in which sacred and civic music institutions had such blurred boundaries. Vestiges of this tradition continued into Felix Mendelssohn’s Gewandhaus directorship, during which he composed at least two psalm cantatas for New Year’s Day performance.
#include <iostream> #include<limits.h> #include<algorithm> using namespace std; typedef long long ll; ll n,*a; ll func() { if(n==2) return 0; else if(n==1) return 0; ll *dp; dp= new ll[n]; dp[n-1]= a[n-1]; dp[n-2]= a[n-2]; dp[n-3]= a[n-3]; for(ll i=n-4;i>=0;i--) { dp[i]= a[i]+ min(dp[i+1],min(dp[i+2],dp[i+3])); } return min(dp[0],min(dp[1],dp[2])); } int main() { cin>>n; a= new ll[n]; for(ll i=0;i<n;i++) cin>>a[i]; cout<<func()<<endl; return 0; }
How Much Zoom is the Right Zoom from the Perspective of Super-Resolution? Constructing a high-resolution (HR) image from low-resolution (LR) image(s) has been a very active research topic recently with focus shifting from multi-frames to learning based single-frame super-resolution (SR). Multi-frame SR algorithms attempt the exact reconstruction of reality, but are limited to small magnification factors. Learning based SR algorithms learn the correspondences between LR and HR patches. Accurate replacements or revealing the exact underlying information is not guaranteed in many scenarios. In this paper we propose an alternate solution. We propose to capture images at right zoom such that it has just sufficient amount of information so that further resolution enhancements can be easily achieved using any off the shelf single-frame SR algorithm. This is true under the assumption that such a zoom factor is not very high, which is true for most man-made structures. The low-resolution image is divided into small patches and ideal resolution is predicted for every patch. The contextual information is incorporated using a Markov Random Field based prior. Training data is generated from high-quality images and can use any single-frame SR algorithm. Several constraints are proposed to minimize the extent of zoom-in. We validate the proposed approach on synthetic data and real world images to show the robustness.
Get the latest news and videos for this game daily, no spam, no fuss. Microsoft has filed a new trademark application for Battletoads, suggesting--but absolutely not confirming--that the Xbox company may be planning to revive the series in some fashion. The trademark application, spotted by NeoGAF, was filed with the United States Patent & Trademark Office (USPTO) on November 5. It covers "game software" and "online video games." The Battletoads series was created by British developer Rare, and was originally released for the NES in 1991. Microsoft acquired Rare in 2002, and the Battletoads series has been dormant for years. Could the trademark application mean Microsoft is looking to bring Battletoads back to modern consoles? Maybe, but Microsoft has not announced any plans to date. Filing a trademark application doesn't guarantee a future game release, as Microsoft could just be protecting the name, should it want to make a new game some day. A Microsoft representative told GameSpot, "Microsoft often acquires various trademarks as part of its ongoing business strategy, but beyond that we have no comment." If the Battletoads series were to return, what would you like to see? Let us know in the comments below.
def mdct(signals, frame_length, window_fn=window_ops.vorbis_window, pad_end=False, norm=None, name=None): with ops.name_scope(name, 'mdct', [signals, frame_length]): signals = ops.convert_to_tensor(signals, name='signals') signals.shape.with_rank_at_least(1) frame_length = ops.convert_to_tensor(frame_length, name='frame_length') frame_length.shape.assert_has_rank(0) frame_length_static = tensor_util.constant_value(frame_length) if frame_length_static is not None: if frame_length_static % 4 != 0: raise ValueError('The frame length must be a multiple of 4.') frame_step = ops.convert_to_tensor(frame_length_static // 2, dtype=frame_length.dtype) else: frame_step = frame_length // 2 framed_signals = shape_ops.frame( signals, frame_length, frame_step, pad_end=pad_end) if window_fn is not None: window = window_fn(frame_length, dtype=framed_signals.dtype) framed_signals *= window else: framed_signals *= 1.0 / np.sqrt(2) split_frames = array_ops.split(framed_signals, 4, axis=-1) frame_firsthalf = -array_ops.reverse(split_frames[2], [-1]) - split_frames[3] frame_secondhalf = split_frames[0] - array_ops.reverse(split_frames[1], [-1]) frames_rearranged = array_ops.concat((frame_firsthalf, frame_secondhalf), axis=-1) return dct_ops.dct(frames_rearranged, type=4, norm=norm)
# MongoDB MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 DBS_NAME = 'GroupB' STORAGE_COLLECTION = 'totalStorage' FARMERS_COLLECTION = 'farmers' # SQLITE DB = 'network.db'
<gh_stars>10-100 package org.jetbrains.emacs4ij.jelisp.elisp; import junit.framework.Assert; import org.jetbrains.emacs4ij.jelisp.elisp.text.Action; import org.jetbrains.emacs4ij.jelisp.elisp.text.TextPropertiesInterval; import org.junit.Test; import java.util.List; public class TextPropertiesHolderTest { @Test public void testAddProperties() { LispString holder = new LispString("hello world"); Assert.assertTrue(holder.getTextPropertiesHolder().actOnTextProperties(0, 11, LispList.list(new LispSymbol("one"), new LispInteger(1)), Action.ADD)); List<TextPropertiesInterval> intervals = holder.getTextPropertiesHolder().getIntervals(); Assert.assertEquals(1, intervals.size()); Assert.assertTrue(intervals.get(0).getRange().equals(0, 11)); Assert.assertEquals("#(\"hello world\" 0 11 (one 1))", holder.toString()); Assert.assertTrue(holder.getTextPropertiesHolder().actOnTextProperties(4, 6, LispList.list(new LispSymbol("two"), new LispInteger(2)), Action.ADD)); intervals = holder.getTextPropertiesHolder().getIntervals(); Assert.assertEquals(3, intervals.size()); Assert.assertTrue(intervals.get(0).getRange().equals(0, 4)); Assert.assertTrue(intervals.get(1).getRange().equals(4, 6)); Assert.assertTrue(intervals.get(2).getRange().equals(6, 11)); Assert.assertEquals("#(\"hello world\" 0 4 (one 1) 4 6 (one 1 two 2) 6 11 (one 1))", holder.toString()); Assert.assertTrue(holder.getTextPropertiesHolder().actOnTextProperties(4, 6, LispList.list(new LispSymbol("two"), new LispInteger(2), new LispSymbol("three"), new LispInteger(3)), Action.ADD)); intervals = holder.getTextPropertiesHolder().getIntervals(); Assert.assertEquals(3, intervals.size()); Assert.assertTrue(intervals.get(0).getRange().equals(0, 4)); Assert.assertTrue(intervals.get(1).getRange().equals(4, 6)); Assert.assertTrue(intervals.get(2).getRange().equals(6, 11)); Assert.assertEquals("#(\"hello world\" 0 4 (one 1) 4 6 (one 1 two 2 three 3) 6 11 (one 1))", holder.toString()); } }
FLASHBACK 1987 Tascam Porta Two Cassette Four-Track Tape Recorder BACKGROUND The Porta Two is a portable cassette four-track tape recorder manufactured by Tascam in 1987. Teac/Tascam are a huge influence in home recording. The Teac 144, the first cassette four-track recorder, was released in 1979. The 144 kicked off the cassette recording revolution. The Tascam Porta One was released in 1984 offering battery power. In 1987, The Tascam Porta Two offered a six-channel mixer, an fx loop, and battery power. HOW IT WAS USED The cassette four-track allowed any musician to make quality home recordings at an affordable price. The media, cassettes, is cheap, so you could record lots of music. You had four mono tracks to work with. A typical format was to record drums or drum machine on track one, bass on track two, guitar on track three, and vocals on track four. If you needed more than four tracks you could record tracks one, two, and three with music and bounce/mix them onto track four. Now committing to your mix on track four, you record over tracks one, two, and three for a total of six tracks. Recording with four tracks forces you to commit to performances and mixes early on in the creative process. LESSONS LEARNED Today’s engineers and artists can learn the fundamentals of music production with a four-track cassette recorder. The transport controls on the Porta Two are laid out just like a modern DAW. Recording with a four-track, you learn about microphone placement, how to achieve optimum recording levels and decision making. The Porta Two also allows you to learn about fx loops, graphic EQ, preamps, signal flow, problem solving, bouncing tracks, and mixing music. Lastly, a cassette four-track teaches you about analog recording and sound, tape machine maintenance, and how to have fun with a pencil and a cassette tape. HISTORICAL NOTES Bruce Springsteen recorded Nebraska on a Teac 144. Cassette four-track recording is often referred to as the “lo-fi” movement. Other notable artists who recorded with cassette four-track machines include Guided By Voices and Ween. CAN BE HEARD ON I recorded Roland drum machine and synth bass parts onto my Tascam Porta Two for the song “BP Oil Rap (How Can You)” from For Real by Aslan King. ABOUT THE AUTHOR Torbin Harding is a graduate of Berklee College of Music, B.A. in Music Synthesis Production 1995, and founded Lo-ZRecords in 1997. He currently works in both the analog tape and digital recording mediums. For more info visit www.Lo-ZRecords.com.
import React, { useState } from 'react' import { hot } from 'react-hot-loader/root' import '../components/button/style' import '../components/switch/style' import '../components/spin/style' import { Button, DingAuth, Switch, Spin, Icon } from '../components' const App = () => { const [checked, setChecked] = useState<boolean>(false) const handleSiwtch = (check: boolean) => { setChecked(check) } return ( <div> <Button type="primary" danger> primary </Button> <Button type="dashed" danger> dashed </Button> <Button type="primary" disabled> disabled </Button> <DingAuth appId="xxxx" redirectUri="xxx" width={240} height={300} state="xxx" className="test-dingding" onSuccess={() => { console.log('onSuccess') }} /> <Switch defaultChecked checked={checked} onChange={handleSiwtch} /> <Spin /> <br /> <Spin size="large" /> <Icon icon="ad" size="2x" theme="primary" /> </div> ) } export default hot(App)
<gh_stars>0 package rcustomer import ( "database/sql" "encoding/json" mcustomer "github.com/project.go.standard/project-web/fiber/postgres/crud-dao/models/customer" ) func GetUuid(db *sql.DB, uuid string) (string, error) { var customer mcustomer.CustomerPost sqlexec := ` SELECT imp_id, imp_uuid, imp_status, imp_nome FROM ad_customer WHERE imp_uuid=$1 AND imp_status =$2` row := db.QueryRow(sqlexec, uuid, 1) //aju_status = 1 ativo, = 2 desativado err := row.Scan( &customer.ImpId, &customer.ImpUuid, &customer.ImpStatus, &customer.ImpNome, ) if err != nil { return "", err } json, err := json.Marshal(customer) return string(json), nil }
#include <stdio.h> typedef struct _Player { int no; double time; }Player; Player ExtractTop(Player player[], int from, int to) { int i; int minNo=from; Player top; for(i=from+1; i<=to; i++) { if(player[i].time < player[minNo].time) minNo = i; } top.no = player[minNo].no; top.time = player[minNo].time; player[minNo].time = 999; return top; } void ExtractTop2(Player player[], int from, int to, Player top[2]) { top[0] = ExtractTop(player, from, to); top[1] = ExtractTop(player, from, to); } int main(void) { //FILE* f=fopen("in.txt", "r"); int i, cls, minNo; Player player[24]; Player top[4][2]; for(i=0; i<24; i++) { //fscanf(f, "%d %lf", &player[i].no, &player[i].time); scanf("%d %lf", &player[i].no, &player[i].time); } for(cls=0; cls<3; cls++) ExtractTop2(player, cls*8, cls*8 +7, top[cls]); ExtractTop2(player, 0, 23, top[3]); for(cls=0; cls<4; cls++) for(i=0; i<2; i++) { printf("%d %.2f\n", top[cls][i].no, top[cls][i].time); } //fclose(f); return 0; }
def parse(self, payload): remediation_entry = json.loads(payload) notification_info = remediation_entry.get("notificationInfo", None) finding_info = notification_info.get("FindingInfo", None) source_bucket = finding_info.get("ObjectId", None) object_chain = remediation_entry["notificationInfo"]["FindingInfo"][ "ObjectChain" ] object_chain_dict = json.loads(object_chain) cloud_account_id = object_chain_dict["cloudAccountId"] region = finding_info.get("Region") logging.info(f"cloud_account_id: {cloud_account_id}") logging.info(f"region: {region}") target_bucket = f"vss-logging-target-{cloud_account_id}-{region}" if source_bucket is None: raise Exception( "Missing parameters for 'payload.notificationInfo.ObjectId'." ) logging.info("parsed params") logging.info(f" source_bucket: {source_bucket}") target_prefix = source_bucket return_dict = { "region": region, "source_bucket": source_bucket, "target_bucket": target_bucket, "target_prefix": f"s3bucket/{target_prefix}", } logging.info(return_dict) return return_dict
Seriously. These people are concerned that the statue -- which specifically paid tribute to a past, dead Apple CEO and not the one who publicly and bravely acknowledged his sexuality in a Bloomberg Businessweek piece last week -- could erode the hearty Russian familial structure. Won't someone please think of the children? Oh wait, the Russian government has, and that's why its been trying to limit the "propaganda of homosexuality and other sexual perversions" minors should have access to. The location of the statue didn't help matters much, either -- its proximity to a school sparked concerns that it could lead bright youngsters passing by down a path of sin, because apparently laying your eyes on a statue is all it takes to completely rewrite your sexual preferences. Some future we live in, huh?
The 2018 Winter Olympics in Pyeongchang, South Korea won’t feature active NHL players, but a legendary recent NHL player could take part. That would be 45-year-old Czech winger Jaromir Jagr (seen above during the 2010 Olympics), who had 16 goals and 46 points for the Florida Panthers last season, but is currently without a NHL contract. As Yahoo’s Greg Wyshynski writes, Jagr told Czech TV he wants to return to the NHL, but playing or training in Europe is a possibility as well: In an interview with Czech TV, Jagr made it clear that he wants to return to the NHL, and that remains the priority. “I love hockey in the NHL, so I’m able to wait, how many people would give everything to NHL at least one match?,” he said. “I’m so fond of everything around the NHL that I want to extend my career there.” But if there’s no NHL team offering a contract, then there’s no return to the NHL. So Jagr said there are a couple of options for next season, without an NHL deal: Signing with a European league team with an out clause to return to the NHL during the 2017-18 season if the offer arrives; or “stay in Kladno and focus on training and see how I feel.” Staying in Europe to train or play also would likely let Jagr compete in the Olympics if he wanted to, and Czech TV’s Zdenek Matejovsky notes that Jagr mentioned that: If Jaromir Jagr will not sign in the NHL he told the Czech TV in Prague today that there is a chance he may play for Czechs at the Olympics! — Zdenek Matejovsky (@zedmat) September 5, 2017 As Wyshynski writes, this isn’t the first time Jagr has brought up playing in the 2018 Games: Please also recall that around the 2014 Sochi Games, Jagr said that playing for the 2018 national team wasn’t out of the question. “I understand that. It’s funny, but don’t forget that by then I’ll be playing in Europe on the big ice and there probably won’t be NHL players,” Jagr said back in 2013. “I would have to stay healthy and I would have to have the same desire.” We’ll see if this happens. The NHL still seems to be the focus for Jagr, and it’s quite possible he could pick up a North American deal by then; players who notched 16 goals and 30 assists last season aren’t exactly common, and injuries to their roster or a slow start in the standings might overcome teams’ concerns about his age. However, if no one bites, playing in Europe and heading to the Olympics might be a good option for him, and his presence would certainly seem to boost the Czechs’ chances of winning gold. It could make for yet another compelling chapter in the already-remarkable story of his career, too. [Puck Daddy]
/** * the layered encryptors * * @since 1.0.0 */ public class LayeredEncryptors { private static RootKeyManager rootKeyManager = new RootKeyManager(); private static WorkingKeyManager workingKeyManager = new WorkingKeyManager(); /** * encrypted data, use Two-layer encryption * * @param clearText clear text * @param keyStr use keyStr to find the cipher text of working key * @return encrypted data string */ public static String encrypt(String clearText, String keyStr) { String rootKey = rootKeyManager.getRootKey(); String workingKey = workingKeyManager.getOrCreateWorkingKey(keyStr, rootKey); return SymmetricEncryptors.getInstance().encrypt(clearText, workingKey); } /** * decrypted data, use Two-layer decryption * * @param cipherText cipher text of data * @param keyStr use keyStr to find the cipher text of working key * @return decrypted data string */ public static String decrypt(String cipherText, String keyStr) { String rootKey = rootKeyManager.getRootKey(); if (StringUtil.stringIsEmpty(rootKey)) { return ""; } String workingKey = workingKeyManager.getOrCreateWorkingKey(keyStr, rootKey); if (StringUtil.stringIsEmpty(rootKey) || StringUtil.stringIsEmpty(workingKey)) { return ""; } return SymmetricEncryptors.getInstance().decrypt(cipherText, workingKey); } }
/** * Used by test code to obtain Spring beans when auto-wiring is not available. */ @SuppressWarnings("WeakerAccess") public class TestSpringBeans { /** Context used to obtain Spring beans. */ private static ApplicationContext context; /** * Because of some wiring issues experienced, the {@link #context} field is initialized statically * from {@link AbstractIntegrationTest#initSystem()}. */ public static void setApplicationContext(@NotNull ApplicationContext ctx) throws BeansException { context = ctx; } public static @NotNull ApplicationContext getApplicationContext() { return Objects.requireNonNull(context, "Spring application context could not be determined."); } public static @NotNull <T> T getBean(Class<T> clazz) { return getApplicationContext().getBean(clazz); } public static @NotNull RepositoryService getCacheRepositoryService() { return getApplicationContext() .getBean("cacheRepositoryService", RepositoryService.class); } public static @NotNull MidpointConfiguration getMidpointConfiguration() { return getBean(MidpointConfiguration.class); } /** * We assume that only a single instance of the object importer exists. * * TODO What about tests running below AbstractModelIntegrationTest level? */ public static @NotNull ObjectImporter getObjectImporter() { return getApplicationContext() .getBean(ObjectImporter.class); } }
const enum RemoteButton { A = 0xA2, B = 0x62, C = 0xE2, D = 0x22, E = 0xC2, F = 0xB0, UP = 0x02, DOWN = 0x98, LEFT = 0xE0, RIGHT = 0x90, STOP = 0xA8, NUM0 = 0x68, NUM1 = 0x30, NUM2 = 0x18, NUM3 = 0x7A, NUM4 = 0x10, NUM5 = 0x38, NUM6 = 0x5A, NUM7 = 0x42, NUM8 = 0x4A, NUM9 = 0x52 } //% color=#00A6F0 weight=19 icon="\uf1eb" block="KSRobot_IR" namespace KSRobot_IR { let IRCommand = 0; let IRReceived_cnt = 0; let IRReceived_word = 0; let IR_Init = 0; const REMOTE_NEC_EVENT = 562; const REMOTE_PRESSED_EVENT = 563; const REMOTE_RELEASED_EVENT = 564; const REMOTE_COMPLETE_EVENT = 565; const INCOMPLETE_STATE = 0xF1; const COMPLETE_STATE = 0xF2; const WAIT_TIME = 0x7F; function remote_decode(head: number): number { IRReceived_cnt += 1; if (head < 1584) { //low IRReceived_word = (IRReceived_word << 1) + 0; if (IRReceived_cnt < 32) { return INCOMPLETE_STATE; } if (IRReceived_cnt === 32) { IRCommand = IRReceived_word & 0xffff; return COMPLETE_STATE; } } else if (head < 2688) { //high IRReceived_word = (IRReceived_word << 1) + 1; if (IRReceived_cnt < 32) { return INCOMPLETE_STATE; } if (IRReceived_cnt === 32) { IRCommand = IRReceived_word & 0xffff; return COMPLETE_STATE; } } IRReceived_cnt = 0; return INCOMPLETE_STATE; } //% blockId="ir_init" //% block="connect ir receiver to %pin" export function init( pin: DigitalPin ): void { let head = 0; let wait_time = 0; let newCommand = 0; let nowCommand = -1; let now_status = 0; if (IR_Init) { return; } IR_Init = 1; pins.setPull(pin, PinPullMode.PullNone); pins.onPulsed(pin, PulseValue.Low, () => { head = pins.pulseDuration(); }); pins.onPulsed(pin, PulseValue.High, () => { head = head + pins.pulseDuration(); now_status = remote_decode(head); if (now_status !== INCOMPLETE_STATE) { control.raiseEvent(REMOTE_NEC_EVENT, now_status); } }); control.onEvent( REMOTE_NEC_EVENT, EventBusValue.MICROBIT_EVT_ANY, () => { now_status = control.eventValue(); if (now_status === COMPLETE_STATE) { wait_time = input.runningTime() + WAIT_TIME; control.raiseEvent(REMOTE_COMPLETE_EVENT, 0); newCommand = IRCommand >> 8; if (newCommand !== nowCommand) { if (nowCommand >= 0) { control.raiseEvent( REMOTE_RELEASED_EVENT, nowCommand ); } nowCommand = newCommand; control.raiseEvent( REMOTE_PRESSED_EVENT, newCommand ); } } } ); control.inBackground(() => { while (true) { if (nowCommand === -1) { // wait basic.pause(2 * WAIT_TIME); } else { const now = input.runningTime(); if (now > wait_time) { control.raiseEvent( REMOTE_RELEASED_EVENT, nowCommand ); nowCommand = -1; } else { basic.pause(WAIT_TIME); } } } }); } //% blockId=ir_received_left_event //% block="on |%btn| button pressed" export function onPressEvent( btn: RemoteButton, handler: () => void ) { control.onEvent( REMOTE_PRESSED_EVENT, btn, () => { handler(); } ); } }
/** * Hilfsobjekt, Macht aus einem String ein JSON Objekt * */ public class ObjectMapperService implements IObjectMapperService { private static final Logger LOGGER = LoggerFactory.getLogger(ObjectMapperService.class); private final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public ObjectMapperService() { // FORMATTER:OFF final SimpleModule module = new SimpleModule() .addSerializer(LocalDate.class, new LocalDateSerializer()) .addDeserializer(LocalDate.class, new LocalDateDeserializer()); // FORMATTER:ON OBJECT_MAPPER.registerModule(module); } /** * Macht aus einem übergebenen Object ein JSON String * * @return json string oder "" */ public String createJsonString(final Object list) { String jsonString = ""; try { jsonString = OBJECT_MAPPER.writer().writeValueAsString(list); return jsonString; } catch (final JsonProcessingException e) { LOGGER.warn("Could not serialize bean into JSON string", e); } return ""; } /** * macht aus einem JSON String und einer Übergebenen Klasse ein neues Objekt * @param json * @param resultClass * @return */ public <T> Object createObject(final String json, final Class<T> resultClass) { try { final T result = OBJECT_MAPPER.readValue(json, resultClass); return result; } catch (final JsonMappingException e) { LOGGER.error("Error: ", e); } catch (final JsonParseException e) { LOGGER.error("Error: ", e); } catch (final IOException e) { LOGGER.error("Error: ", e); } return null; } }
What is this ? How to write a genome f : draw f orward in the direction I'm currently facing. : draw orward in the direction I'm currently facing. n : step forward with n o drawing. : step forward with o drawing. - : step backward with no drawing. : step backward with no drawing. c : draws a filled c ircle. : draws a filled ircle. l : turn l eft. : turn eft. r : turn r ight. : turn ight. d : d uplicate - create a child in my direction. : uplicate - create a child in my direction. b : b ranch - 50% chance of creating a child in my direction. : ranch - 50% chance of creating a child in my direction. s : s tep - either draw forward or do nothing, at random. : tep - either draw forward or do nothing, at random. t : t urn : turn left or right, at random. : urn : turn left or right, at random. ? : turn left or right or not at all, at random. : turn left or right or not at all, at random. m : mirror - 50% chance that turning left and right are inverted. a:*; : defines the a ngle of a turn to * degrees. 90 gives square angles. : defines the ngle of a turn to * degrees. 90 gives square angles. g:*; : defines the maximum amount of g enerations to *. Keep it small or your browser might crash ! : defines the maximum amount of enerations to *. Keep it small or your browser might crash ! s:*; : defines the s tarting angle to * degrees. : defines the tarting angle to * degrees. b:*; : defines the b ranching symmetry to * branches. : defines the ranching symmetry to * branches. c:*; : defines the size of the c ircles to * (this is affected by the ratio). : defines the size of the ircles to * (this is affected by the ratio). d:*; : defines the d istance travelled by a step forward to * pixels (when the ratio is 1). Basically, this sets the size of the drawing. : defines the istance travelled by a step forward to * pixels (when the ratio is 1). Basically, this sets the size of the drawing. r:*; : defines the ratio to * (a number between 0 and 2). A ratio of 0.5 means that each generation is half the size of its parent. This is a fractal toy that generates a picture according to a set of instructions stored in a simple string of characters (the genome).It can be used to generate trees, squiggles and other shapes.The algorithm used is related to L-systems and turtle graphics It is coded in javascript and uses html5 canvas.A genome is a chain of operations executed by bots. A bot draws a line as it goes forward. It can also turn and duplicate itself.A bot executes a specific operation for every character that appears in the genome.
<filename>index.ts<gh_stars>1-10 import { Decimal } from "decimal.js"; import { Asset, asset_to_number, Sym as Symbol, Sym, asset } from "eos-common"; export type EosAccount = string; export interface TokenSymbol { contract: EosAccount; symbol: Symbol; } export interface BaseRelay { contract: EosAccount; smartToken: TokenSymbol; isMultiContract: boolean; } export interface DryRelay extends BaseRelay { reserves: TokenSymbol[]; } export interface v1Relay extends DryRelay { isMultiContract: false; } export interface HydratedRelay extends BaseRelay { reserves: TokenAmount[]; fee: number; } export interface TokenAmount { contract: EosAccount; amount: Asset; } export interface ConvertPath { account: string; symbol: string; multiContractSymbol?: string; } export interface ChoppedRelay { contract: string; reserves: TokenSymbol[]; } export const compareString = (stringOne: string, stringTwo: string) => { const strings = [stringOne, stringTwo]; if (!strings.every(str => typeof str == "string")) throw new Error( `String one: ${stringOne} String two: ${stringTwo} one of them are falsy or not a string` ); return stringOne.toLowerCase() == stringTwo.toLowerCase(); }; export function calculateReturn( balanceFrom: Asset, balanceTo: Asset, amount: Asset ) { if (!balanceFrom.symbol.isEqual(amount.symbol)) throw new Error("From symbol does not match amount symbol"); if (amount.amount >= balanceFrom.amount) throw new Error("Impossible to buy the entire reserve or more"); Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN }); const balanceFromNumber = new Decimal(asset_to_number(balanceFrom)); const balanceToNumber = new Decimal(asset_to_number(balanceTo)); const amountNumber = new Decimal(asset_to_number(amount)); const reward = amountNumber .div(balanceFromNumber.plus(amountNumber)) .times(balanceToNumber); const rewardAsset = new Asset( reward .times(Math.pow(10, balanceTo.symbol.precision())) .toDecimalPlaces(0, Decimal.ROUND_DOWN) .toNumber(), balanceTo.symbol ); const slippage = asset_to_number(amount) / asset_to_number(balanceFrom); return { reward: rewardAsset, slippage }; } export function calculateCost( balanceFrom: Asset, balanceTo: Asset, amountDesired: Asset ) { if (!balanceTo.symbol.isEqual(amountDesired.symbol)) throw new Error("From symbol does not match amount symbol"); if (amountDesired.amount >= balanceTo.amount) throw new Error("Impossible to buy the entire reserve or more"); const balanceFromNumber = new Decimal(asset_to_number(balanceFrom)); const balanceToNumber = new Decimal(asset_to_number(balanceTo)); const amountNumber = new Decimal(asset_to_number(amountDesired)); const oneNumber = new Decimal(1); Decimal.set({ precision: 15, rounding: Decimal.ROUND_UP }); const reward = balanceFromNumber .div(oneNumber.minus(amountNumber.div(balanceToNumber))) .minus(balanceFromNumber); const rewardAsset = new Asset( reward .times(Math.pow(10, balanceFrom.symbol.precision())) .toDecimalPlaces(0, Decimal.ROUND_FLOOR) .toNumber(), balanceFrom.symbol ); const slippage = asset_to_number(amountDesired) / asset_to_number(balanceTo); return { reward: rewardAsset, slippage }; } export function concatAffiliate( memo: string, affiliateAccount: string, percentNumber: number | string ) { return memo.concat(`,${affiliateAccount},${percentNumber}`); } export function composeMemo( converters: ConvertPath[], minReturn: string, destAccount: string, version = 1, feeAccount?: string, feePercent?: number ): string { const receiver = converters .map(({ account, symbol, multiContractSymbol }) => { return `${account}${ multiContractSymbol ? `:${multiContractSymbol}` : "" } ${symbol}`; }) .join(" "); const base = `${version},${receiver},${minReturn},${destAccount}`; if (feeAccount && feePercent) { return concatAffiliate(base, feeAccount, feePercent); } return base; } export function relaysToConvertPaths( from: Symbol, relays: DryRelay[] ): ConvertPath[] { return relays .map(relay => relay.reserves.map(token => { const base = { account: relay.contract, symbol: token.symbol.code().to_string() }; return relay.isMultiContract ? { ...base, multiContractSymbol: relay.smartToken.symbol.code().to_string() } : base; }) ) .reduce((prev, curr) => prev.concat(curr)) .filter(converter => converter.symbol !== from.code().to_string()) .reduce((accum: ConvertPath[], item: ConvertPath) => { return accum.find( (converter: ConvertPath) => converter.symbol == item.symbol ) ? accum : [...accum, item]; }, []); } const tokenToSymbolName = (token: TokenSymbol) => token.symbol.code().to_string(); const symbolToSymbolName = (symbol: Sym) => symbol.code().to_string(); export function relayHasBothSymbols( symbol1: Symbol, symbol2: Symbol ): (choppedRelay: ChoppedRelay) => boolean { return function(relay: ChoppedRelay) { return relay.reserves.every( token => tokenToSymbolName(token) == symbolToSymbolName(symbol1) || tokenToSymbolName(token) == symbolToSymbolName(symbol2) ); }; } const zip = (arr1: any[], arr2: any[]) => { if (arr1.length !== arr2.length) throw new Error("These arrays aren't the same"); return arr1.map((item, index) => [item, arr2[index]]); }; const reservesAreSame = (one: TokenSymbol, two: TokenSymbol): boolean => { return one.contract == two.contract && one.symbol == two.symbol; }; const relaysAreSame = (one: ChoppedRelay, two: ChoppedRelay): boolean => { const zippedReserves = zip(one.reserves, two.reserves); const matchingReserves = zippedReserves.every(([reserve, opposingReserve]) => reservesAreSame(reserve, opposingReserve) ); const matchingContract = one.contract == two.contract; return matchingContract && matchingReserves; }; export function removeChoppedRelay( relays: ChoppedRelay[], departingRelay: ChoppedRelay ): ChoppedRelay[] { const res = relays.filter(relay => !relaysAreSame(relay, departingRelay)); if (res.length + 1 !== relays.length) throw new Error("Failed to remove chopped relay"); return res; } export const chopRelay = (item: DryRelay): ChoppedRelay[] => { return [ { contract: item.contract, reserves: [item.reserves[0], item.smartToken] }, { contract: item.contract, reserves: [item.reserves[1], item.smartToken] } ]; }; export const chopRelays = (relays: DryRelay[]) => { return relays.reduce((accum: ChoppedRelay[], item: DryRelay) => { const [relay1, relay2] = chopRelay(item); return [...accum, relay1, relay2]; }, []); }; export function getOppositeSymbol(relay: ChoppedRelay, symbol: Symbol): Symbol { const oppositeToken = relay.reserves.find( token => !token.symbol.isEqual(symbol) )!!; return oppositeToken.symbol; } function relayOffersSymbols(symbol1: Symbol, symbol2: Symbol) { return function(relay: DryRelay) { const inReserves = relay.reserves.every( token => token.symbol.isEqual(symbol1) || token.symbol.isEqual(symbol2) ); if (inReserves) return inReserves; const inReserve = relay.reserves.some( token => token.symbol.isEqual(symbol1) || token.symbol.isEqual(symbol2) ); const inSmartToken = relay.smartToken.symbol.isEqual(symbol1) || relay.smartToken.symbol.isEqual(symbol2); return inReserve && inSmartToken; }; } export function unChopRelays( choppedRelays: ChoppedRelay[], relays: DryRelay[] ) { return choppedRelays.reduce( (accum: DryRelay[], choppedRelay: ChoppedRelay) => { const relayOfInterest = relayOffersSymbols( choppedRelay.reserves[0].symbol, choppedRelay.reserves[1].symbol ); const alreadyExistingRelay = accum.find(relayOfInterest); return alreadyExistingRelay ? accum : [...accum, relays.find(relayOfInterest)!]; }, [] ); } export function chargeFee( asset: Asset, decimalFee: number, magnitude: number = 1 ): Asset { Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN }); const assetAmount = new Decimal(asset_to_number(asset)); const one = new Decimal(1); const totalFee = assetAmount.times( one.minus(Decimal.pow(one.minus(decimalFee), magnitude)) ); const newAmount = assetAmount.minus(totalFee); return new Asset( newAmount .times(Math.pow(10, asset.symbol.precision())) .toDecimalPlaces(0, Decimal.ROUND_FLOOR) .toNumber(), asset.symbol ); } export function addFee( asset: Asset, decimalFee: number, magnitude: number = 1 ): Asset { Decimal.set({ precision: 15, rounding: Decimal.ROUND_DOWN }); const assetAmount = new Decimal(asset_to_number(asset)); const one = new Decimal(1); const totalFee = assetAmount.times( one.minus(Decimal.pow(one.minus(decimalFee), magnitude)) ); const newAmount = assetAmount.plus(totalFee); return new Asset( newAmount .times(Math.pow(10, asset.symbol.precision())) .toDecimalPlaces(0, Decimal.ROUND_FLOOR) .toNumber(), asset.symbol ); } const sortReservesByAsset = (asset: Asset, reserves: TokenAmount[]) => { if (!reserves.some(reserve => reserve.amount.symbol.isEqual(asset.symbol))) throw new Error("Asset does not exist in these reserves"); return reserves.sort((a, b) => a.amount.symbol.isEqual(asset.symbol) ? -1 : 1 ); }; const highestNumber = (number1: number, number2: number) => number1 > number2 ? number1 : number2; export const findReturn = (amount: Asset, relaysPath: HydratedRelay[]) => relaysPath.reduce( ({ amount, highestSlippage }, relay) => { const [fromReserve, toReserve] = sortReservesByAsset( amount, relay.reserves ); const { reward, slippage } = calculateReturn( fromReserve.amount, toReserve.amount, amount ); return { amount: chargeFee(reward, relay.fee, 2), highestSlippage: highestNumber(highestSlippage, slippage) }; }, { amount, highestSlippage: 0 } ); export const findCost = (amount: Asset, relaysPath: HydratedRelay[]) => relaysPath.reverse().reduce( ({ amount, highestSlippage }, relay) => { const [toReserve, fromReserve] = sortReservesByAsset( amount, relay.reserves ); const { reward, slippage } = calculateCost( fromReserve.amount, toReserve.amount, amount ); return { amount: addFee(reward, relay.fee, 2), highestSlippage: highestNumber(highestSlippage, slippage) }; }, { amount, highestSlippage: 0 } ); export function fund( smartTokens: Asset, reserveBalance: Asset, smartSupply: Asset ) { Decimal.set({ precision: 18, rounding: Decimal.ROUND_HALF_EVEN }); const cost = new Decimal(reserveBalance.amount.toString()) .times(smartTokens.amount.toString()) .div(smartSupply.amount.toString()); const assetAmount = cost.ceil().toNumber(); return asset(assetAmount, reserveBalance.symbol); } export function calculateFundReturn( reserveTokens: Asset, reserveBalance: Asset, smartSupply: Asset ) { Decimal.set({ precision: 18, rounding: Decimal.ROUND_HALF_EVEN }); const one = new Decimal(1); // y(s+1) + 1 / r const reward = new Decimal(reserveTokens.amount.toString()) .times(new Decimal(smartSupply.amount.toString())) .plus(one) .div(reserveBalance.amount.toString()); const rewardAmount = reward.floor().toNumber(); return asset(rewardAmount, smartSupply.symbol); }
/** * List of two elements. * * @author John Whaley <[email protected]> * @version $Id: Pair.java,v 1.2 2005/04/29 02:32:24 joewhaley Exp $ */ public class Pair extends AbstractList implements Serializable, Textualizable { /** * Version ID for serialization. */ private static final long serialVersionUID = 3545236912383078965L; /** * The elements of the pair. */ public Object left, right; /** * Construct a new Pair. * * @param left first element * @param right second element */ public Pair(Object left, Object right) { this.left = left; this.right = right; } /* (non-Javadoc) * @see java.util.Collection#size() */ public int size() { return 2; } /* (non-Javadoc) * @see java.util.List#get(int) */ public Object get(int index) { switch(index) { case 0: return this.left; case 1: return this.right; default: throw new IndexOutOfBoundsException(); } } /* (non-Javadoc) * @see java.util.List#set(int, java.lang.Object) */ public Object set(int index, Object element) { Object prev; switch(index) { case 0: prev=this.left; this.left=element; return prev; case 1: prev=this.right; this.right=element; return prev; default: throw new IndexOutOfBoundsException(); } } /* (non-Javadoc) * @see jwutil.io.Textualizable#write(jwutil.io.Textualizer) */ public void write(Textualizer t) throws IOException { } /* (non-Javadoc) * @see jwutil.io.Textualizable#writeEdges(jwutil.io.Textualizer) */ public void writeEdges(Textualizer t) throws IOException { t.writeEdge("left", (Textualizable) left); t.writeEdge("right", (Textualizable) right); } /* (non-Javadoc) * @see jwutil.io.Textualizable#addEdge(java.lang.String, jwutil.io.Textualizable) */ public void addEdge(String edge, Textualizable t) { if (edge.equals("left")) this.left = t; else if (edge.equals("right")) this.right = t; else throw new InternalError(); } }
<gh_stars>1-10 package commands; import java.util.ArrayList; import java.util.List; public class ApplicationInfo { final List<Application> applications; public ApplicationInfo(List<Application> apps) { applications = new ArrayList<Application>(); applications.addAll(apps); } public List<Application> getApplications() { return applications; } }
//----------------------------------------------------------------------------- // Purpose: There's no guarantee that your interface pointer will persist across level transitions, // so this function will update your interface. //----------------------------------------------------------------------------- ISteamGameStats* CSteamWorksGameStatsUploader::GetInterface( void ) { HSteamUser hSteamUser = 0; HSteamPipe hSteamPipe = 0; #ifdef GAME_DLL if ( steamgameserverapicontext && steamgameserverapicontext->SteamGameServer() && steamgameserverapicontext->SteamGameServerUtils() ) { m_UserID = steamgameserverapicontext->SteamGameServer()->GetSteamID().ConvertToUint64(); m_iAppID = steamgameserverapicontext->SteamGameServerUtils()->GetAppID(); hSteamUser = SteamGameServer_GetHSteamUser(); hSteamPipe = SteamGameServer_GetHSteamPipe(); } if ( g_pSteamClientGameServer && engine && ( engine->IsDedicatedServer()) ) { return (ISteamGameStats*)g_pSteamClientGameServer->GetISteamGenericInterface( hSteamUser, hSteamPipe, STEAMGAMESTATS_INTERFACE_VERSION ); } #elif CLIENT_DLL if ( steamapicontext && steamapicontext->SteamUser() && steamapicontext->SteamUtils() ) { m_UserID = steamapicontext->SteamUser()->GetSteamID().ConvertToUint64(); m_iAppID = steamapicontext->SteamUtils()->GetAppID(); hSteamUser = steamapicontext->SteamUser()->GetHSteamUser(); hSteamPipe = GetHSteamPipe(); } #endif if ( SteamClient() ) { return (ISteamGameStats*)SteamClient()->GetISteamGenericInterface( hSteamUser, hSteamPipe, STEAMGAMESTATS_INTERFACE_VERSION ); } return NULL; }
def solveSimultaneousEqs(eq): eq = [sympify(expr) for expr in eq] freesym = [expr.free_symbols for expr in eq] freevar = list() for freeset in freesym: for sym in freeset: freevar.append(sym) freevar=list(set(freevar)) for sym in freevar: exec(f"{sym.name}=symbols('{sym.name}')") solutions = solve_poly_system(eq, freevar) solutionList = list() freevar = [str(var) for var in freevar] for possibility in solutions: possibility = [float(num) for num in possibility] solutionList.append(dict(zip(freevar,possibility))) return solutionList
In theory, CS:GO brought along a great mechanism for weapon balance by tweaking the monetary value awarded to the player after landing a frag. In practice however, the values chosen for the rewards were too extreme and also did not accurately take competitive play into account. I believe that this idea can be tweaked to perfection over time and provide more balance and incentive to each gun without decimating the intricacies of the economy system in competitive gameplay. The original intent Valve’s original intent of altering the kill rewards was to provide more incentive for the team strapped for cash to invest in weapons rather than just performing a full save round. If the team was able to get two or three kills but still lose, they would be able to recoup much of their expenses and not fall too far behind economically while giving them a larger chance to win the round at hand. Also, guns that were typically neglected would become more appealing. The problem As it stands now, guns that have always been used on anti-eco rounds now reward the player a whopping $900 per kill. This allows the winning team to further snowball their advantage. There are a few reasons SMG’s are so effective on anti-eco rounds: SMG’s have a fast rate of fire SMG’s are great against unarmored targets and significantly weaker against armored targets SMG’s are inexpensive These weapon traits mean that players using SMG’s can mow down unarmored targets with ease. Should a player from the winning team die, there isn’t much of a risk of their team losing the round due to the enemy getting their hands on the SMG which is ineffective against armored targets. If it were a rifle that made its way into the hands of the other team, their chances of winning the round increase tremendously. Also, the dying player’s bankroll isn’t damaged as severely as it would have been if they had lost a rifle instead of an SMG. Working towards a solution As we can see, there are a several factors working contrary to Valve’s initial intent given the current implementation of the kill reward system. Below, I attempt to create suitable monetary kill rewards to make the weapons in the game appealing and balanced without altering current weapon behavior and prices. By having extra monetary incentives based on the weapon used, the player has more factors to consider when making a weapon purchase. Weapon reward guidelines Rate of fire Accuracy $ Spent/Kill Ratio Damage Efficiency vs armored and unarmored targets Frequency of use compared to similar guns New Kill Rewards Team Kill Penalty The penalty for killing a teammate should simply be the inverse of the kill reward. An AK-47 would award the player $300 for a kill and -$300 for a team kill. Very straightforward and easy to understand Players are not excessively punished for team killing in a competitive match since killing their teammate is punishment enough Retains the economic variables of team killing in a much less extreme manner Guns with the highest kill reward also have the highest team kill penalty Pistols The side specific pistols award the player with $450 which provides these pistols a unique benefit to make up for their lack of appeal when compared with other pistols such as the P250 The reward for pistols is not greater than $450 as that would greatly skew the amount of money players have in the second round Extra layer of complexity in weapon strategy as players can use their sidearm to finish off a helpless or wounded foe to earn $450 instead of using their primary weapon The P250 has a slight reduction in kill reward as it is already an extremely powerful pistol at a low price of $500 SMG’s The most effective SMG’s at winning anti-eco rounds do not reward the player with extra money Low cost SMG’s that the losing team can afford offer a slight bonus to cash reward Keeping an SMG that awards extra cash is very dangerous vs rifles and deagles Heavy Shotguns provide extra cash since they are risky to use for the winning team on anti-eco rounds The MAG-7 is the most powerful and versatile of the shotguns so it provides the least kill reward. The XM1014 is an underused and expensive shotgun so it provides the largest kill reward The M249 currently makes very little sense to buy compared to the Negev so it is given a large kill reward bonus to add extra incentive The Negev has a slightly larger than standard kill reward since it is the most expensive gun in the game and purchasing it will quickly drain a player’s funds Rifles The standard four rifles remain unchanged The SSG 08 (scout) awards the player $900 per kill and can be utilized for low money/surprise buys since the player can recoup a lot of their costs with a kill or two The SG 553 provides $150 more per kill than the AUG since the price discrepancy between the SG 553 and AK-47 is twice the price discrepancy between the M4A4 and AUG The AWP kill reward was tripled to $150 which should suffice as the AWP is an extremely cost effective gun The kill reward for the autosnipers was increased to $450 since they are the most expensive rifles and are also underused Miscellaneous Knife kills were reduced to $600 since they are typically the most common in pistol rounds or when a team already has a large lead The Molotov kill reward was bumped up to compensate for their large cost and low probability of getting a kill Decoys, flashes and smoke kill rewards were increased to $600 since they are so uncommon that a player should be rewarded for getting a kill with one of these grenades Final Thoughts This is a first pass at these values and will likely require some further tweaking. I believe that these new kill rewards are a step in the right direction as they attempt to balance the weapons while providing the player with more interesting decisions than the current kill rewards in CS:GO.
<filename>packages/node-utils/src/cli-utils.ts import dotenv from 'dotenv'; import { registerRequireHooks } from './'; import path from 'path'; export function cliInit(projectPath: string): void { dotenv.config(); registerRequireHooks(projectPath); } export const defaultMetaGlob = 'src/**/*.meta.ts?(x)'; export function getWebpackConfigPath(projectPath: string): string { return path.join(projectPath, '.autotools/webpack.config.js'); }
<reponame>brunocodutra/steady import React from 'react'; import { connect } from 'react-redux'; import { State } from 'state'; import removable, { Props as PropsBase } from 'container/removable'; import Element from 'component/element'; import Status from 'component/status'; import Tile from 'component/tile'; import { Shunt } from 'lib/element'; import { Unit } from 'lib/unit'; import { prefix } from 'lib/util'; export const Icon = require('icon/shunt.svg'); const Wire = require('icon/wire.svg'); const Knee = require('icon/knee.svg'); interface Props extends PropsBase<Shunt> { readonly essential: boolean, } const mapState = ({ active }: State, props: PropsBase<Shunt>) => ({ essential: prefix(props.id, active), }); export default removable<Shunt>(connect(mapState)( ({ id, element: { kind, branch, subcircuits, vi: [v, i] }, active, activate, essential, remove }: Props): JSX.Element => { const fill = Array.from({ length: subcircuits - branch.subcircuits - 1 }, (_, k) => <Wire key={k} />); return ( <Tile> <Tile activate={activate} active={active} remove={essential ? undefined : remove} className={kind}> <Icon /> {fill} <Knee /> <Status value={v} unit={Unit.volt} /> <Status value={i} unit={Unit.ampere} /> </Tile> <Tile className={'branch'}> <Element id={id} element={branch} /> </Tile> </Tile> ); }, ));
Flipped Quartification and a composite $b$-quark An alternative"flipped"version of the quartification model is obtained by rearrangement of the particle assignments. The model has two standard (trinification) families and one flipped quartification family. An interesting phenomenological implication is that the model allows for a composite $b$-quark. I. INTRODUCTION The model presented here, which we call "Flipped Quartification," is an extension of the standard model (SM) that singles out the b quark as different from all the rest of the SM fermions in that just above the electro-weak (EW) scale the EW singlet b R can be in a nontrivial irreducible representation (irrep) of a new gauge group SU(2) ℓ while all the other fermions are in SU(2) ℓ singlets. This can happen within the model in two ways: (i) the SU(2) ℓ symmetry breaks just above the EW scale where now the b R falls into its usual SM irrep, but with slightly different phenomenology due to nearby SU(2) ℓ effects that the other fermions do not have. This is a fairly conventional scheme for introducing new physics into the SM. More interesting is (ii) where SU(2) ℓ becomes confining just above the EW scale. This is possible for a range parameters chosen at the unification scale of quartification where all gauge symmetries are restored. All quartification models contain a leptonic color sector to realize a manifest quarklepton symmetry and must contain at least three families to be phenomenologically viable, plus they contain the new fermions needed to symmetrize the quark and lepton particle content at high energies. Instead of fully quartified models, where all families are quartification families are given by we will consider only hybrid models where n > 0 families are trinification families and the the remaining 3 − n are quartification families. In particular, we concentrate on the n = 2 case . One can derive three family models with appropriate scalar content to permit gauge symmetry breaking to the standard model and ultimately to SU(3) C × U EM (1) from orbifolded AdS ⊗ S 5 (for a review see ). In two of us carried out a global search for Γ = Z n trinification models with three or more families, and in quartification models of this type were derived from a Γ = Z 8 orbifolded AdS ⊗ S 5 . We leave the study of the UV completion of this model for later work. We now "flip" the R and l designations such that We are free to cyclically permute the groups and to reverse their order without changing the physics. Thus we let which allows us to write our new 2 + 1 flipped quartification model in a form that conforms with the notation of earlier work. Symmetry breaking can easily be arranged with a single adjoint scalar VEV for each of SU(3) L and SU(3) l and a pair of adjoints for SU(3) R such that where the charge operator A, C and D are of the form diag(1, 1, −2) and B is of the form diag(1, −1, 0). Their weighting in forming weak hypercharge will be provided below. Under the remaining symmetry group Using the relation where Q is the electric charge, T 3 is the third component of isospin, and Y is the hypercharge, we can determine the hypercharge in terms of the U(1) charges (designated by A, B, C, and D) as Charged singlets can be used to break for the first two families, where as usual, each trinification family contains a SM family plus the following vector-like states The third family (11) This leads to some interesting phenomenological consequences, as we will discuss in the next section. For this particle to be in a hadron we must confine it again via color SU(3) C . Hence there is a double confinement process and a double hadronization, first (assuming Λ l > Λ QCD ) via SU(2) ℓ and then via SU(3) C . (In standard quartification, none of the SM fermions need leptonic confinement or leptonic hadronization.) Note that there are only four fermionic SU(2) ℓ doublets, so the SU(2) ℓ beta function indicates that it is a confining gauge theory as required, and if it starts off with a coupling g l >> g 3 at the SU(3) 4 scale, then it is possible for SU(2) ℓ to confine before SU(3) C . Likewise the fermionic spectrum is also consistent with SU(3) C being confining. Similar remarks apply to the SU(2) l doublet leptons which must be confined for large g l . Hence their natural mass scale is around Λ l . III. PHENOMENOLOGICAL IMPLICATIONS AND SUMMARY We now discuss the phenomenology of our two models. A. SSB Phenomenology For case (i), with spontaneous symmetry breaking of SU(2) l , we find a phenomenology that is a straightforward extension of the SM: it contains the normal SM particle content in the first two families plus their trinification extension. The third quartified family contains a third normal family, its extended trinification content plus the remaining extended quartification content composed of two SU(2) L singlet unit electric charged leptons and five Weyl neutrinos some of which can be pair up after SSB. While this model is potentially interesting, it is not particularly novel and further analysis and predictions would proceed along standard lines for the SM plus additional particle content. What is most interesting is the case when SU(2) l becomes confining as we now discuss. B. SU (2) l Confinement Phenomenology Our case (ii) model contains the fundamental charge -1 3 quark in a doublet of the strong SU(2) l group. If this particle binds with a charge neutral scalar SU(2) l doublet, as assumed herein for definiteness, then a composite particle in an SU(2) l singlet can form with standard b R quark quantum numbers. This composite object should behave like a point particle up to some energy scale. There are high-energy scatterings that set a lower bound on this scale such as e + e − → bb which have shown b R to behave like point particles up to M Z , but above that scale anomalies could appear directly, or below M Z indirectly. Since SU(2) l is confining, the model is expected to have both SU(2) l mesons and baryons, where as usual, the mesons are composed of an SU(2) l doublet and a conjugate doublet, while the baryons are composed of two SU(2) l doublets (only two quarks for Muster Mark this time!), but since the doublet is a pseudoreal irrep, the distinction between mesons and baryons is blurred. There can also be SU(2) l glueballs in the model. All these states should be near the SU(2) l confinement scale. The model's phenomenology divides according to the energy transfer which probes the composite nature of the b R . We will consider the two cases where the probe energy compared to the binding energy of the composite b R is small or large. (The third case of a probe energy comparable in magnitude to the binding energy is a more subtle proposition, and not considered here.) If the probe energy is small, then (unknown) form factors govern the process. These form factors may present themselves as BSM physics. (In an alternative approach , the CP properties of the B states are emphasized, and it is unclear to these authors how a composite b R -quark would enhance effects.) If the probe energy exceeds the unknown binding energy, then the composite b R -quark is resolved into its constituents, the fundamental precursor to the b-quark and the scalar. The binding energy would naturally be the order of the the confinement scale Λ l , possibly as low as a few GeV as governed by upsilon phenomenology, but probably of order of 100 GeV, much like the conventional Higgs doublet. What is different from the usual SM case is that there is no light left-over fundamental SU(2) l Higgs in this case. The b c L state is the charge conjugate of the right handed component of the b quark. Since any free particle must be a singlet of SU(2) l below its confinement scale, then in any b-onium state the b c L must be bound to a state with opposite lepton color charge below that scale. The standard Υ is taken to be bb, but within the present model it could be formed from the binding of two pairs of bound objects: the b R now will form a composite from binding with a (112) scalar, and then together they combine with the anti-b c L and anti-(112) scalar (along with the left handed piece and its anti-left pair) to form a lepton colorless particle. The additional structure could then be probed with energies exceeding binding energy of the b+scalar composite. Recently, a number of anomalous results in B decays (and so by implication, b decays at a more fundamental level) have been reported. None of these observations are convincing on their own, but taken together as a whole it does appear that they imply new physics beyond the standard model (BSM) is required to explain these new results. These results indicate a violation of Lepton flavor universality (LFU) of the coupling of electroweak gauge bosons to all three families of leptons, a consequence of the Standard Model (SM) . Global analyses and reviews of these B anomalies include , and references therein. One possible explanation for the B anomalies is through partial compositeness, which can provide violation of LFU (see, for example ). These models typically have a composite Higgs which leads to degrees of compositeness for mutliple quarks, as well as mediators and muons. In contrast, the flipped quartification model in the present work does provide compositeness for only the b R -quark, but through a new confining gauge group. While we are not ready to provide an explanation of the anomalies here, we have presented a model that has the potential of eventually doing so, i.e., our Flipped Quartification model, is able to single out the b R quark as the only fermion among the three families that differs from its designation in the SM. There are two viable phenomenological options in the model, the b R must either (i) couple to a new low scale gauge group SU(2) l that breaks in a way so that the b acquires its usual SM quantum numbers and remains a fundamental particle, or (ii) the new SU(2) l gauge group becomes confining and the b R becomes a composite upon binding with a scalar. While the model we have presented focuses on B physics, other models in this class can be used to single out one or more right handed charge − 1 3 quarks. Then right handed quarks are made to fall into flipped quartification families, while the remaining right handed charge − 1 3 quarks remain in trinification families. Future work potentially leads to a whole class of models similar to Flipped Quartification where one or more fermions are singled out to differ from other normal family members, hence providing a rich and interesting BSM phenomenology.
For three years, 50 percent of the evaluations of many D.C. public school teachers were based on students standardized test scores, a key part of the ground-breaking IMPACT assessment system introduced by Michelle Rhee. Kaya Henderson, left and Michelle Rhee (Ricky Carioti/WASHINGTON POST) Sounds reasonable, right? It isn’t. When Rhee set the percentage at 50 percent back in 2009, after spending millions of dollars to create the assessment system, she based it on absolutely nothing grounded in research. The 35 percent? Also based on no research. In fact, there is no research to show that even 1 percent would be a valid way to assess teachers, because standardized tests that are being used in a number states — where officials followed Rhee’s example — are not designed to evaluate teachers. There are enough questions about how valid they are in evaluating students to make it unfair to use the scores in any high-stakes decisions for kids, much less teachers. What will take the place of that lost 15 percent? Apparently other measures of student achievement, including student performance on final exams or early literacy tests. More evaluation based on testing. Why did Henderson institute this and other changes in IMPACT? She said the revisions are in part a response to complaints that the system was too rigid and dependent on test scores. She told Brown: “I’m not stuck with what we thought was right in ’08, or too stubborn to ignore what we’ve learned over the last three years.” There’s no reason to think Henderson doesn’t want to improve the evaluation system. She’s smart and certainly sees some of its flaws. But too bad she hasn’t read, or taken to heart if she did read it, the comprehensive 2011 report by the National Research Council, the research arm of the National Academies (which include the National Academy of Sciences, the National Academy of Engineering and the Institute of Medicine), that says that standardized test scores are of limited value in determining causes of improvements in student performance. “Looking at test scores should be only a first step – not an end point – in considering questions about student achievement, or even more broadly, about student learning,” it says. There are other changes to IMPACT, too, in what is really the biggest revision since it was implemented. Though only some teachers were evaluated in part by test scores, all teachers have been evaluated in part by classroom observations — done by principals and master teachers. At first, teachers were judged by five half-hour observations over the course of a year, and in each of those observations, they had to show 22 separate teaching competencies. These included tailoring instruction to at least three “learning styles,” and demonstrating that they were instilling student belief in success through “affirmation chants, poems and cheer.” This was so off the wall that the 22 were whittled down to nine different teaching elements in 30 minutes. Now, under the new revisions, only four of the five observations will be included in the evaluation and the fifth will be strictly for feedback. Teachers with consistently high ratings will only get three formal observations. Still, it is artificial to ask a teacher to prove nine different teaching competencies in the space of every 30 minutes; it’s not the way classrooms work. As a result, some D.C. teachers find out beforehand when they will be observed and have a ready-made lesson that will pass the IMPACT test ready to pull off the shelf. Besides, it is bordering on ludicrous to judge a teacher based on two hours of teaching a year. Ninety eight teachers were just fired as a result of their IMPACT evaluations. Maybe all of them were ineffective teachers; maybe not. It's impossible to know with a flawed teacher evaluation system. -0- Follow The Answer Sheet every day by bookmarking www.washingtonpost.com/blogs/answer-sheet .
def serialize_token(token): return { 'apiURL': local_site_reverse( 'oauth-token-resource', local_site=token.application.local_site, kwargs={ 'oauth_token_id': token.pk, }, ), 'application': token.application.name, }
<reponame>ss-jugg/YCAssistivePlugin // // YCAssistiveNetworkFlowDataView.h // YCAssistivePlugin // // Created by shenweihang on 2019/9/25. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface YCAssistiveNetworkFlowDataView : UIView @end NS_ASSUME_NONNULL_END
<reponame>JuanEmus/transito { 'name': 'Productos en tránsito', 'version': '172.16.17.32.0', 'author': 'JuanEmus', 'depends': [ 'purchase', 'purchase_stock', ], 'data': [ # security # data # demo # reports # views 'views/productostransito.xml', ], }
<reponame>essafikhadija/ManagmentBooks<filename>src/books/bookDto.ts import {IsInt, IsString, Max, Min} from 'class-validator'; import {ApiProperty} from '@nestjs/swagger'; export class BookDto { @IsString() @ApiProperty() name: string; @IsInt({message: 'le prix doit etre un entier'}) @ApiProperty() @Min(10, {message: 'le prix doit etre supérieur à 10'}) @Max(500, {message: 'le prix doit etre inférieur à 500'}) price: number; }
DEBUG = True LOCAL_TEST_SERVER = "192.168.198.242" class DbConfig(object): @staticmethod def get_db_info(): redis_host, redis_port = DbConfig.get_redis_info() mongo_server, mongo_port = DbConfig.get_mongo_info() return mongo_server, mongo_port, redis_host, redis_port @staticmethod def get_redis_info(): redis_host = 'localhost' redis_port = 6379 return redis_host, redis_port @staticmethod def get_mongo_info(): if DEBUG is False: mongo_server = ["10.19.136.122", "10.19.63.98", "10.19.87.123"] mongo_port = 5010 else: mongo_server = LOCAL_TEST_SERVER mongo_port = 27017 return mongo_server, mongo_port
#include<bits/stdc++.h> using namespace std; double arr[100009]; int main() { int n,a,b; double s1=0,s2=0; scanf("%d%d%d",&n,&a,&b); if(b>a) swap(a,b); for(int i=0; i<n; i++) scanf("%lf",&arr[i]); sort(arr,arr+n); for(int i=0; i<n; i++) if(i>=n-a-b) { if(i>=n-b) s2+=arr[i]; else s1+=arr[i]; } printf("%.9lf\n",s2/b+s1/a); return 0; }
The 25IQ blog posts below have been rewritten and are now part of a new book that will benefit the author’s chosen charity: No Kid Hungry. The author will be directing his share of the profits from both hardcover and Kindle sales to this charity. Steve Blank (“Customer Development” methodology) Bill Campbell (“The Coach”) Eric Ries (Lean Startup) Sam Altman (Y Combinator) Steve Anderson (Baseline Ventures) Marc Andreessen (Andreessen Horowitz) Rich Barton (Expedia, Zillow, Glassdoor) Roelof Botha (Sequoia Capital) Jim Breyer (Breyer Capital) Chris Dixon (Andreessen Horowitz) John Doerr (Kleiner Perkins Caufield & Byers) Peter Fenton (Benchmark Capital) Jim Goetz (Sequoia Capital) Paul Graham (Y Combinator) Bill Gurley (Benchmark Capital) Reid Hoffman (Greylock Partners) Ben Horowitz (Andreessen Horowitz) Vinod Khosla (Khosla Ventures) Josh Kopelman (First Round) Jenny Lee (GGV Capital) Dan Levitan (Maveron) Doug Leone (Sequoia Capital) Jessica Livingston (Y Combinator) Mary Meeker (Kleiner Perkins Caufield & Byers) Mike Moritz (Sequoia Capital) Chamath Palihapitiya (Social Capital) Keith Rabois (Khosla Ventures) Andy Rachleff (Benchmark Capital) Naval Ravikant (AngelList) Heidi Roizen (Draper Fisher Jurvetson) Mark Suster (Upfront Ventures) Peter Thiel (Founders Fund) Fred Wilson (Union Square Ventures) Ann Winblad (Hummer Winblad Venture Partners) – More on A Dozen Lessons for Entrepreneurs – A Dozen Lessons for Entrepreneurs shows how the insights of leading venture capitalists can teach readers to create a unique approach to building a successful business. Through profiles and interviews of figures such as Bill Gurley of Benchmark Capital, Marc Andreesen and Ben Horowitz of Andreesen Horowitz, and Jenny Lee of GGV Capital, Tren Griffin draws out the fundamental lessons from their ideas and experiences. Entrepreneurs should learn from past successes but also be prepared to break new ground. While there are best practices, there is no single recipe they should follow. By better understanding the views and experiences of a wide range of successful venture capitalists and entrepreneurs, readers can discern which of many possible paths will lead to success. With insight and verve, Griffin argues that innovation and best practices are discovered by the experimentation of entrepreneurs as they establish the evolutionary fitness of their business. The products and services created through this experimentation that have greater fitness survive, and less-fit products and services die. Entrepreneurs have always experimented when creating or altering a business. What is different today is the existence of modern tools and systems that allow experiments to be conducted more cheaply and rapidly than ever before. Griffin shows that listening to what the best venture capitalists have to say is invaluable for entrepreneurs. Their experiences, if studied carefully, teach bedrock methods and guiding principles for approaching business. Save Share this: Twitter Facebook
<reponame>mremolt/dets<gh_stars>1-10 export class Foo { get foo() { return 5; } set foo(value: number) {} }