content
stringlengths
10
4.9M
// RUN: %libomp-compile-and-run // RUN: %libomp-run | %python %S/check.py -c 'CHECK' %s #include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #define XSTR(x) #x #define STR(x) XSTR(x) #define streqls(s1, s2) (!strcmp(s1, s2)) #define check(condition) \ if (!(condition)) { \ fprintf(stderr, "error: %s: %d: " STR(condition) "\n", __FILE__, \ __LINE__); \ exit(1); \ } #define BUFFER_SIZE 1024 int main(int argc, char** argv) { char buf[BUFFER_SIZE]; size_t needed; omp_set_affinity_format("0123456789"); needed = omp_get_affinity_format(buf, BUFFER_SIZE); check(streqls(buf, "0123456789")); check(needed == 10) // Check that it is truncated properly omp_get_affinity_format(buf, 5); check(streqls(buf, "0123")); #pragma omp parallel { char my_buf[512]; size_t needed = omp_capture_affinity(my_buf, 512, NULL); check(streqls(my_buf, "0123456789")); check(needed == 10); // Check that it is truncated properly omp_capture_affinity(my_buf, 5, NULL); check(streqls(my_buf, "0123")); } #pragma omp parallel num_threads(4) { omp_display_affinity(NULL); } return 0; } // CHECK: num_threads=4 0123456789
// TestUnitValidateExpirationNoExpirationSet - Verify that when 'expires' isn't set // on the store, it is set in validateExpiration func TestUnitValidateExpirationNoExpirationSet(t *testing.T) { initConfig() Convey("Given I have an session store with expires set to 0", t, func() { s := NewStore(nil) data := map[string]interface{}{ "expires": uint32(0), "signin_info": map[string]interface{}{ "access_token": map[string]interface{}{ "expires_in": uint16(123), }, }, } s.Data = data Convey("Given I call validate expiration on the store", func() { err := s.validateExpiration() Convey("Then no errors are returned and expires has been set", func() { So(err, ShouldBeNil) So(s.Expires, ShouldNotEqual, uint64(0)) }) }) }) cleanupConfig() }
<filename>src/main/java/com/naharoo/commons/mapstruct/MappingsRegistrationBeanPostProcessor.java package com.naharoo.commons.mapstruct; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.annotation.Primary; import org.springframework.core.GenericTypeResolver; @PrivateApi final class MappingsRegistrationBeanPostProcessor implements BeanPostProcessor { @PrivateApi @Override public Object postProcessBeforeInitialization(final Object bean, final String beanName) { if (!(bean instanceof Mapper)) { return bean; } if (bean instanceof BidirectionalMapper) { processBidirectionalMapper(bean); } else if (bean instanceof UnidirectionalMapper) { processUnidirectionalMapper(bean); } return bean; } private void processBidirectionalMapper(final Object bean) { @SuppressWarnings("unchecked") final BidirectionalMapper<Object, Object> castedBean = (BidirectionalMapper<Object, Object>) bean; final Class<?> beanClass = bean.getClass(); final Class<?>[] genericClasses = extractGenericParameters(beanClass, BidirectionalMapper.class); final Class<?> source = genericClasses[0]; final Class<?> destination = genericClasses[1]; final MappingIdentifier directMappingIdentifier = MappingIdentifier.from(source, destination); if (!MappingsRegistry.exists(directMappingIdentifier) || beanClass.isAnnotationPresent(Primary.class)) { MappingsRegistry.register(directMappingIdentifier, castedBean::map); MappingsRegistry.register(MappingIdentifier.from(destination, source), castedBean::mapReverse); } } private void processUnidirectionalMapper(final Object bean) { @SuppressWarnings("unchecked") final UnidirectionalMapper<Object, Object> castedBean = (UnidirectionalMapper<Object, Object>) bean; final Class<?> beanClass = bean.getClass(); final Class<?>[] genericClasses = extractGenericParameters(beanClass, UnidirectionalMapper.class); final Class<?> source = genericClasses[0]; final Class<?> destination = genericClasses[1]; final MappingIdentifier directMappingIdentifier = MappingIdentifier.from(source, destination); if (!MappingsRegistry.exists(directMappingIdentifier) || beanClass.isAnnotationPresent(Primary.class)) { MappingsRegistry.register(directMappingIdentifier, castedBean::map); } } private Class<?>[] extractGenericParameters(final Class<?> beanClass, final Class<?> genericInterface) { final Class<?>[] classes = GenericTypeResolver.resolveTypeArguments(beanClass, genericInterface); if (classes == null || classes.length < 2) { throw new IllegalArgumentException("Failed to extract Generic Parameters from " + beanClass.getName()); } return classes; } }
primes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] normal = [x for x in primes[:15]] squares = [x ** 2 for x in primes[:4]] # print(squares, normal) for n in squares: print(n) ans = input() if "yes" in ans: exit(print("composite")) ans = 0 for n in normal: print(n) a = input() if a == "yes": ans += 1 print(["composite", "prime"][ans < 2])
/** * Validate a given IP Address against a list of comma separated list of addresses. */ public class IpAddressValidator { /** * The parsed list of ip addresses */ private ArrayList<String> ipaddr = new ArrayList<>(); /** * IP addresses from the ipaddr list that contain a wildcard character '*' */ private ArrayList<String> wildCardIPs = new ArrayList<>(); /** * Optimization based on empty IP address list or an explicit '*' wildcard */ private boolean anyIP = true; /** * ctor - initialize an instance with the given ip address list * @param commaSeparatedIpAddresses - comma separated list of ip addresses */ public IpAddressValidator(String commaSeparatedIpAddresses) { if (commaSeparatedIpAddresses == null) { anyIP = true; return; } parseIpAddesses(commaSeparatedIpAddresses); } private void parseIpAddesses(String commaSeparatedIpAddresses) { String[] ips = commaSeparatedIpAddresses.split(","); ipaddr = new ArrayList<>(); wildCardIPs = new ArrayList<>(); Collections.addAll(ipaddr, ips); if (!ipaddr.contains("*")) { anyIP = false; // check whether there are any wildcarded ip's - example: 192.* or 192.168.* or 192.168.1.* for (String addr : ipaddr) { if (addr.contains("*")) { wildCardIPs.add(addr.substring(0, addr.lastIndexOf('*'))); } } } } public boolean validateIpAddress(String addr) { boolean valid = false; if (addr == null) { // LJM TODO: log as possible programming error return false; } if (anyIP) { valid = true; } else { if (ipaddr.contains(addr)) { valid = true; } else { // check for wildcards if there are wildcardIP acls configured if (!wildCardIPs.isEmpty()) { for (String ip : wildCardIPs) { if (addr.startsWith(ip)) { valid = true; break; } } } } } return valid; } public boolean allowsAnyIP() { return anyIP; } public ArrayList<String> getIPAddresses() { return ipaddr; } }
package org.goblinframework.monitor.module.monitor; import org.goblinframework.api.annotation.Install; import org.goblinframework.api.function.Ordered; import org.goblinframework.core.conversion.ConversionUtils; import org.goblinframework.core.event.GoblinEventChannel; import org.goblinframework.core.event.GoblinEventContext; import org.goblinframework.core.event.GoblinEventListener; import org.goblinframework.core.monitor.Flight; import org.goblinframework.core.monitor.FlightEvent; import org.goblinframework.monitor.flight.FlightImpl; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Install @GoblinEventChannel("/goblin/monitor") final public class FlightPrettyPrinterListener implements GoblinEventListener, Ordered { private static final Logger logger = LoggerFactory.getLogger(FlightPrettyPrinterListener.class); public static final FlightPrettyPrinterListener INSTANCE = new FlightPrettyPrinterListener(); private FlightPrettyPrinterListener() { } @Override public int getOrder() { return HIGHEST_PRECEDENCE; } @Override public boolean accept(@NotNull GoblinEventContext context) { return context.getEvent() instanceof FlightEvent; } @Override public void onEvent(@NotNull GoblinEventContext context) { FlightEvent event = (FlightEvent) context.getEvent(); Flight flight = event.getFlight(); if (ConversionUtils.toBoolean(flight.attribute("flight.silence"))) { return; } if (flight instanceof FlightImpl) { String message = FlightRecorderPrinter.generatePrettyLog((FlightImpl) flight); logger.info("\n{}", message); } } }
Article continues below ... Don’t worry — this doesn’t mean a butt fumble will never happen again. It just means Mark Sanchez won’t be taken down by the same rear end that felled him last Thanksgiving. Jets guard Brandon Moore is retiring from the NFL, Adam Caplan reports. Moore played 144 games in his career, starting 137 in a row. But his most-remembered moment will not be the consistent protection he provided the likes of Sanchez, Kellen Clemens, Chad Pennington, Brooks Bollinger, Vinny Testaverde, Quincy Carter and even Brett Favre. It will be this legendary moment in history . . . In the aftermath of last season’s Thanksgiving night disaster, Moore was not pleased about becoming the butt of jokes around football. He particularly did not enjoy being mocked on national television by NBC analyst Cris Collinsworth, saying the following week: "I’ve never really been a big fan of his." Hey, at least Jets fans didn’t hate on him. May retirement treat you better than Mark Sanchez, Brandon Moore. Oh, and just because, enjoy the play again in black and white. Sorry, Brandon.
<gh_stars>0 package notifier import ( "github.com/pkg/errors" "github.com/rancher/norman/types" "github.com/sirupsen/logrus" ) func Formatter(apiContext *types.APIContext, resource *types.RawResource) { /* resource.Actions["update"] = apiContext.URLBuilder.Action("update", resource) resource.Actions["remove"] = apiContext.URLBuilder.Action("remove", resource) resource.Actions["approve"] = apiContext.URLBuilder.Action("approve", resource) resource.Actions["deny"] = apiContext.URLBuilder.Action("deny", resource) resource.Actions["rerun"] = apiContext.URLBuilder.Action("rerun", resource) resource.Actions["stop"] = apiContext.URLBuilder.Action("stop", resource) */ } func CollectionFormatter(apiContext *types.APIContext, collection *types.GenericCollection) { collection.AddAction(apiContext, "send") } func ActionHandler(actionName string, action *types.Action, apiContext *types.APIContext) error { logrus.Infof("do activity action:%s", actionName) switch actionName { case "send": return testNotifier(actionName, action, apiContext) } return errors.Errorf("bad action %v", actionName) } func testNotifier(actionName string, action *types.Action, apiContext *types.APIContext) error { return nil }
import { Component } from "@angular/core"; import { MessageboxService } from "../../shared/messagebox/messagebox.service"; import { SecurityService } from "../../security/shared/security.service"; import { VisitService } from "../../appointments/shared/visit.service"; import { PatientService } from "../../patients/shared/patient.service"; import { NursingBLService } from "../shared/nursing.bl.service"; import { Router } from "@angular/router"; import { ADT_BLService } from "../../adt/shared/adt.bl.service"; import { DanpheHTTPResponse } from "../../shared/common-models"; @Component({ templateUrl: "./nursing-transfer.html", }) export class NursingTransferComponent { public showTransferInPopUp: boolean = false; public showTransferPage: boolean = false; public selectedBedInfo: { PatientAdmissionId; PatientId; PatientVisitId; MSIPAddressInfo; PatientCode; DischargedDate; Name; AdmittingDoctor; BedInformation: { BedId; PatientBedInfoId; Ward; BedFeature; BedCode; BedNumber; BedFeatureId; AdmittedDate; WardId; StartedOn; }; }; patientId: any; visitId: any; //constructor of class constructor( public securityServ: SecurityService, public visitservice: VisitService, public patientservice: PatientService, public msgBoxServ: MessageboxService, public nursingBlService: NursingBLService, public admissionBLService: ADT_BLService, public router: Router ) { this.patientId = this.patientservice.globalPatient.PatientId; this.visitId = this.visitservice.globalVisit.PatientVisitId; } ngOnInit() { this.GetADTPatientByPatVisitId(); } GetADTPatientByPatVisitId() { this.nursingBlService.GetADTDataByVisitId(this.visitId).subscribe( (res) => { if (res.Status == "OK") { this.selectedBedInfo = res.Results; this.showTransferPage = true; } else { this.msgBoxServ.showMessage("error", [res.ErrorMessage]); } }, (err) => { this.msgBoxServ.showMessage("error", [err.ErrorMessage]); } ); } TransferUpgrade($event) { this.router.navigate(["/Nursing/InPatient"]); } public allDepartments: Array<any> = []; public LoadDepartments() { this.admissionBLService.GetDepartments() .subscribe((res: DanpheHTTPResponse) => { this.allDepartments = res.Results; }); } }
def __calcThreshold(self, targets, predictions): self.threshold = np.max(mse(targets,predictions, multioutput="raw_values"))
/** * Reuses internal backing store whenever possible * <strong>NOT THREAD SAFE.</strong> * @author mnasser */ public class MutableByteBuilder extends ByteBuilder { public MutableByteBuilder(){ super();} public MutableByteBuilder(int size){ super(size); } public MutableByteBuilder(byte[] original){ super(original); } /** * Returns the entire backing store - not a copy of the * representative sequence of bytes. * If you augment this backing store - you must manually * increment the internal length using incrLength(). * * @return The backing store for this sequence of bytes by * reference (NOT A COPY) * @see MutableByteBuilder.incrLength() */ @Override public byte[] getContent() { return this.b; } /** * Increments the current length of the sequence. * This is needed if you are manually filling the content * of the backing store using <code>getContent()</code>. * @param p * @see MutableByteBuilder.getContent() */ @Override public void incrLength(int p) { if( position + p > capacity ) throw new IndexOutOfBoundsException( (position + p) + " > " + capacity); position += p; } //Seems there is no significant speed advantage in doing it this way Arrays.copyOf() is just fine @Override public void reset(byte[] bb) { int p = 0; if ( b.length >= bb.length ){ for(byte bite : bb ){ b[p] = bite; p++; } }else{ b = bb; p = b.length; } //b = bb; position = p; capacity = b.length; } }
/** * Created by MattyG on 6/8/17. */ @Service public class SongServiceImpl implements SongService{ @Autowired SongDao songDao; @Autowired Util util; @Override @Transactional public void add(Song song) { songDao.add(song); } @Override public List<Song> findAllByUsername(String username){ return songDao.findAllByUsername(username); } @Override public List<Song> findAllByUsername(){ //All songs for logged in user. Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName(); return songDao.findAllByUsername(currentPrincipalName); } @Transactional public void add(String title, String key, String genre){ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String currentPrincipalName = authentication.getName(); List<String> songChords= util.songChordsFromGenre(genre, key); Song song = new Song(); song.setTitle(title); song.setKey(key); song.setGenre(genre); song.setUsername(currentPrincipalName); song.setChords(songChords); songDao.add(song); } @Transactional public void delete(int id){ songDao.delete(id); } @Transactional public void update(int id, String title){ songDao.update(id, title); } }
<gh_stars>0 #include <bits/stdc++.h> #define watch(x) std::cout << (#x) << " is " << (x) << std::endl using LL = long long; int main() { //freopen("in", "r", stdin); std::cin.tie(nullptr)->sync_with_stdio(false); int cas = 1; std::cin >> cas; while (cas--) { int n; std::cin >> n; std::vector<int> a(n), b(n); for (auto &x : a) std::cin >> x; for (auto &x : b) std::cin >> x; LL s = std::accumulate(b.begin(), b.end(), 0LL); std::vector<std::vector<LL>> e(n + 1), c(n + 1); for (int i = 0; i < n; ++i) e[a[i]].emplace_back(b[i]); for (int i = 1; i <= n; ++i) if (e[i].size() > 1) std::sort(e[i].begin(), e[i].end(), std::greater<>()); for (int i = 1; i <= n; ++i) if (int sz = e[i].size(); sz > 0) { c[sz].resize(sz); for (int j = 0; j < sz; ++j) c[sz][j] += e[i][j]; } for (int i = 1; i <= n; ++i) if (c[i].size()) { for (int j = 1; j < i; ++j) c[i][j] += c[i][j - 1]; } std::vector<LL> ans(n + 1); for (int i = 1; i <= n; ++i) if (c[i].size()) { for (int j = 1; j <= i; ++j) { ans[j] += c[i][i / j * j - 1]; } } for (int i = 1; i <= n; ++i) std::cout << ans[i] << " \n"[i == n]; } return 0; }
// New creates a new TMP102 connection. The I2C bus must already be configured. func New(bus machine.I2C) Device { return Device{ bus: bus, } }
package com.slife.enums; /** * Created by chenjianan on 2017/3/1-19:16. * <p> * Describe:数据权限范围 * DATA_SCOPE_ALL("所有数据"), * DATA_SCOPE_COMPANY_AND_CHILD("所在公司及以下数据"), * DATA_SCOPE_COMPANY("所在公司数据"), * DATA_SCOPE_OFFICE_AND_CHILD("所在部门及以下数据"), * DATA_SCOPE_OFFICE("所在部门数据"), * DATA_SCOPE_SELF("仅本人数据"), * DATA_SCOPE_CUSTOM("按明细设置"); */ public enum DataScopeEnum { /** * 所有数据 */ DATA_SCOPE_ALL("所有数据"), /** * 所在公司及以下数据 */ DATA_SCOPE_COMPANY_AND_CHILD("所在公司及以下数据"), /** * 所在公司数据 */ DATA_SCOPE_COMPANY("所在公司数据"), /** * 所在部门及以下数据 */ DATA_SCOPE_OFFICE_AND_CHILD("所在部门及以下数据"), /** * 所在部门数据 */ DATA_SCOPE_OFFICE("所在部门数据"), /** * 仅本人数据 */ DATA_SCOPE_SELF("仅本人数据"), /** * 按明细设置 */ DATA_SCOPE_CUSTOM("按明细设置"); private final String value; DataScopeEnum(final String value){ this.value=value; } /** * 传入name,返回对应value * @return Returns the value. */ public String getValue(){ return value; } /** * 传入value,返回对应name * @param name 中文名 * @return Returns the name. */ public static DataScopeEnum getNameByValue(String name){ for (DataScopeEnum scopeEnum:DataScopeEnum.values()){ if (scopeEnum.getValue().equals(name)){ return scopeEnum; } } return null; } }
def session_timestamp_ms(self): return time.to_utc_ms(self.session_timestamp)
package com.baeldung.zoneddatetime; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; public class OffsetDateTimeExample { public OffsetDateTime getCurrentTimeByZoneOffset(String region) { LocalDateTime now = LocalDateTime.now(); ZoneId zone = ZoneId.of(region); ZoneOffset zoneOffSet= zone.getRules().getOffset(now); OffsetDateTime date = OffsetDateTime.now(zoneOffSet); return date; } }
export interface IMyStruct__Args { field1: Array<Array<string>>; } export class MyStruct { public field1: Array<Array<string>>; constructor(args: IMyStruct__Args) { if (args != null && args.field1 != null) { this.field1 = args.field1; } else { throw new thrift.Thrift.TProtocolException(thrift.Thrift.TProtocolExceptionType.UNKNOWN, "Required field[field1] is unset!"); } } public write(output: thrift.TProtocol): void { output.writeStructBegin("MyStruct"); if (this.field1 != null) { output.writeFieldBegin("field1", thrift.Thrift.Type.LIST, 1); output.writeListBegin(thrift.Thrift.Type.LIST, this.field1.length); this.field1.forEach((value_1: Array<string>): void => { output.writeListBegin(thrift.Thrift.Type.STRING, value_1.length); value_1.forEach((value_2: string): void => { output.writeString(value_2); }); output.writeListEnd(); }); output.writeListEnd(); output.writeFieldEnd(); } output.writeFieldStop(); output.writeStructEnd(); return; } public static read(input: thrift.TProtocol): MyStruct { input.readStructBegin(); let _args: any = {}; while (true) { const ret: thrift.TField = input.readFieldBegin(); const fieldType: thrift.Thrift.Type = ret.ftype; const fieldId: number = ret.fid; if (fieldType === thrift.Thrift.Type.STOP) { break; } switch (fieldId) { case 1: if (fieldType === thrift.Thrift.Type.LIST) { const value_3: Array<Array<string>> = new Array<Array<string>>(); const metadata_1: thrift.TList = input.readListBegin(); const size_1: number = metadata_1.size; for (let i_1: number = 0; i_1 < size_1; i_1++) { const value_4: Array<string> = new Array<string>(); const metadata_2: thrift.TList = input.readListBegin(); const size_2: number = metadata_2.size; for (let i_2: number = 0; i_2 < size_2; i_2++) { const value_5: string = input.readString(); value_4.push(value_5); } input.readListEnd(); value_3.push(value_4); } input.readListEnd(); _args.field1 = value_3; } else { input.skip(fieldType); } break; default: { input.skip(fieldType); } } input.readFieldEnd(); } input.readStructEnd(); if (_args.field1 !== undefined) { return new MyStruct(_args); } else { throw new thrift.Thrift.TProtocolException(thrift.Thrift.TProtocolExceptionType.UNKNOWN, "Unable to read MyStruct from input"); } } }
//---------------------------------------------------------------------------------------------------------------------- // // Copyright(c) 2018 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files(the "Software"), to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the // Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //---------------------------------------------------------------------------------------------------------------------- #include <algorithm> #include <cmath> #include <cstdint> #include <exception> #include <iostream> #include <list> #include <memory> #include <map> #include <random> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <vector> //---------------------------------------------------------------------------------------------------------------------- struct bar { bool operator<(const bar& rhs) const { return id < rhs.id; } int id; int percent_current; int percent_min; int percent_max; }; struct depletion { int percent = 1; }; namespace std { template<> struct hash<bar> { std::size_t operator()(const bar& rhs) const { return rhs.id; } }; } //---------------------------------------------------------------------------------------------------------------------- int main() { try { if(SDL_Init(SDL_INIT_VIDEO) != 0 || SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3) != 0 || SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3) != 0 || SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) != 0 || SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24) != 0 || TTF_Init() != 0) { throw std::runtime_error(SDL_GetError()); } constexpr int WINDOW_WIDTH = 1024; constexpr int WINDOW_HEIGHT = 768; constexpr int WINDOW_HPOS = SDL_WINDOWPOS_UNDEFINED; constexpr int WINDOW_VPOS = SDL_WINDOWPOS_UNDEFINED; constexpr int WINDOW_FLAGS = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN/* | SDL_WINDOW_RESIZABLE*/; constexpr const char* WINDOW_TITLE = "100 Days of Code 2018"; const std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> window(SDL_CreateWindow( WINDOW_TITLE, WINDOW_HPOS, WINDOW_VPOS, WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_FLAGS), SDL_DestroyWindow); if(!window) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<void, void(*)(SDL_GLContext)> context( SDL_GL_CreateContext(window.get()), SDL_GL_DeleteContext); if(!context) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<SDL_Renderer, void(*)(SDL_Renderer*)> renderer( SDL_CreateRenderer(window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE), SDL_DestroyRenderer); if(!renderer) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<TTF_Font, void(*)(TTF_Font*)> font( TTF_OpenFont("../asset/font/saxmono.ttf", 16), TTF_CloseFont); if(!font) { throw std::runtime_error(SDL_GetError()); } constexpr const char* key_string = "Press x key to start / stop depletion of bar, z key to refill bar, q key to quit"; const std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> key_string_surface( TTF_RenderText_Solid(font.get(), key_string, { 255, 255, 255, 255 }), SDL_FreeSurface); if(!key_string_surface) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> key_string_texture( SDL_CreateTextureFromSurface(renderer.get(), key_string_surface.get()), SDL_DestroyTexture); if(!key_string_texture) { throw std::runtime_error(SDL_GetError()); } int key_string_width = 0; int key_string_height = 0; SDL_QueryTexture(key_string_texture.get(), NULL, NULL, &key_string_width, &key_string_height); SDL_Rect key_string_rect = { 10, 10, key_string_width, key_string_height }; constexpr const char* frames_string = "Average frames per second: "; const std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> frames_string_surface( TTF_RenderText_Solid(font.get(), frames_string, { 255, 255, 255, 255 }), SDL_FreeSurface); if(!frames_string_surface) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> frames_string_texture( SDL_CreateTextureFromSurface(renderer.get(), frames_string_surface.get()), SDL_DestroyTexture); if(!frames_string_texture) { throw std::runtime_error(SDL_GetError()); } int frames_string_width = 0; int frames_string_height = 0; SDL_QueryTexture(frames_string_texture.get(), NULL, NULL, &frames_string_width, &frames_string_height); SDL_Rect frames_string_rect = { 10, 20 + key_string_height, frames_string_width, frames_string_height }; int renderer_width = 0; int renderer_height = 0; SDL_GetRendererOutputSize(renderer.get(), &renderer_width, &renderer_height); SDL_Event event; bool quit = false; std::list<bar> bars({{ 0, 90, 0, 100 }}); std::map<std::reference_wrapper<bar>, depletion, std::less<bar>> depletions; const SDL_Rect outer_rect { static_cast<int>(std::floor(renderer_width / 2 - 200 + 0.5)), static_cast<int>(std::floor(renderer_height / 2 - 40 + 0.5)), 400, 80 }; SDL_Rect inner_rect { outer_rect.x + 10, outer_rect.y + 10, outer_rect.w - 10, outer_rect.h - 20 }; int frames = 0; double start_time = SDL_GetTicks(); double last_frame_time = 0.0; double cycles_left_over = 0.0; double average_frames_per_second = 0.0; while(!quit) { while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: quit = true; break; case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_x: if(depletions.empty()) { depletions[bars.front()] = { 1 }; } else { depletions.clear(); } break; case SDLK_z: bars.front().percent_current = bars.front().percent_max; break; case SDLK_q: quit = true; break; } break; default: break; } } //constexpr int MAXIMUM_FRAME_RATE = 120; constexpr int MAXIMUM_FRAME_RATE = 30; constexpr int MINIMUM_FRAME_RATE = 15; constexpr double UPDATE_INTERVAL = 1.0 / MAXIMUM_FRAME_RATE; constexpr double MAX_CYCLES_PER_FRAME = MAXIMUM_FRAME_RATE / MINIMUM_FRAME_RATE; double current_time = SDL_GetTicks(); double update_iterations = ((current_time - last_frame_time) + cycles_left_over); if(update_iterations > (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL)) { update_iterations = (MAX_CYCLES_PER_FRAME * UPDATE_INTERVAL); } while(update_iterations > UPDATE_INTERVAL) { update_iterations -= UPDATE_INTERVAL; for(auto iterator = depletions.begin(); iterator != depletions.end(); ++iterator) { iterator->first.get().percent_current -= iterator->second.percent; if(iterator->first.get().percent_current < iterator->first.get().percent_min) { iterator = depletions.erase(iterator); if(iterator == depletions.end()) { break; } } } } average_frames_per_second = frames / ((SDL_GetTicks() - start_time) / 1000.0); cycles_left_over = update_iterations; last_frame_time = current_time; if(average_frames_per_second > 2000000) { average_frames_per_second = 0; } const std::unique_ptr<SDL_Surface, void(*)(SDL_Surface*)> afps_string_surface( TTF_RenderText_Solid(font.get(), std::to_string(average_frames_per_second).c_str(), { 255, 255, 255, 255 }), SDL_FreeSurface); if(!afps_string_surface) { throw std::runtime_error(SDL_GetError()); } const std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> afps_string_texture( SDL_CreateTextureFromSurface(renderer.get(), afps_string_surface.get()), SDL_DestroyTexture); if(!afps_string_texture) { throw std::runtime_error(SDL_GetError()); } int afps_string_width = 0; int afps_string_height = 0; SDL_QueryTexture(afps_string_texture.get(), NULL, NULL, &afps_string_width, &afps_string_height); SDL_Rect afps_string_rect = { 10 + frames_string_width, 20 + key_string_height, afps_string_width, afps_string_height }; SDL_SetRenderDrawColor(renderer.get(), 0, 0, 0, 255); SDL_RenderClear(renderer.get()); SDL_RenderCopy(renderer.get(), key_string_texture.get(), nullptr, &key_string_rect); SDL_RenderCopy(renderer.get(), frames_string_texture.get(), nullptr, &frames_string_rect); SDL_RenderCopy(renderer.get(), afps_string_texture.get(), nullptr, &afps_string_rect); SDL_SetRenderDrawColor(renderer.get(), 50, 100, 200, 255); SDL_RenderFillRect(renderer.get(), &outer_rect); inner_rect.w = static_cast<int>(std::floor( 380 * bars.front().percent_current / bars.front().percent_max + 0.5)); if(inner_rect.w > 0) { SDL_SetRenderDrawColor(renderer.get(), 20, 70, 170, 255); SDL_RenderFillRect(renderer.get(), &inner_rect); } SDL_RenderPresent(renderer.get()); ++frames; } } catch(const std::runtime_error& exception) { std::cout << "Oh no, something bad happened! Exception: " << exception.what() << std::endl; } if(TTF_WasInit()) { TTF_Quit(); } SDL_Quit(); return 0; } //----------------------------------------------------------------------------------------------------------------------
<reponame>lastweek/source-freebsd /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2002, 2003, 2004, 2005 <NAME> <<EMAIL>> * Copyright (c) 2004, 2005 <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * $FreeBSD$ * */ /* * uma.h - External definitions for the Universal Memory Allocator * */ #ifndef _VM_UMA_H_ #define _VM_UMA_H_ #include <sys/param.h> /* For NULL */ #include <sys/malloc.h> /* For M_* */ #include <sys/_smr.h> /* User visible parameters */ #define UMA_SMALLEST_UNIT 8 /* Smallest item allocated */ /* Types and type defs */ struct uma_zone; /* Opaque type used as a handle to the zone */ typedef struct uma_zone * uma_zone_t; /* * Item constructor * * Arguments: * item A pointer to the memory which has been allocated. * arg The arg field passed to uma_zalloc_arg * size The size of the allocated item * flags See zalloc flags * * Returns: * 0 on success * errno on failure * * Discussion: * The constructor is called just before the memory is returned * to the user. It may block if necessary. */ typedef int (*uma_ctor)(void *mem, int size, void *arg, int flags); /* * Item destructor * * Arguments: * item A pointer to the memory which has been allocated. * size The size of the item being destructed. * arg Argument passed through uma_zfree_arg * * Returns: * Nothing * * Discussion: * The destructor may perform operations that differ from those performed * by the initializer, but it must leave the object in the same state. * This IS type stable storage. This is called after EVERY zfree call. */ typedef void (*uma_dtor)(void *mem, int size, void *arg); /* * Item initializer * * Arguments: * item A pointer to the memory which has been allocated. * size The size of the item being initialized. * flags See zalloc flags * * Returns: * 0 on success * errno on failure * * Discussion: * The initializer is called when the memory is cached in the uma zone. * The initializer and the destructor should leave the object in the same * state. */ typedef int (*uma_init)(void *mem, int size, int flags); /* * Item discard function * * Arguments: * item A pointer to memory which has been 'freed' but has not left the * zone's cache. * size The size of the item being discarded. * * Returns: * Nothing * * Discussion: * This routine is called when memory leaves a zone and is returned to the * system for other uses. It is the counter-part to the init function. */ typedef void (*uma_fini)(void *mem, int size); /* * Import new memory into a cache zone. */ typedef int (*uma_import)(void *arg, void **store, int count, int domain, int flags); /* * Free memory from a cache zone. */ typedef void (*uma_release)(void *arg, void **store, int count); /* * What's the difference between initializing and constructing? * * The item is initialized when it is cached, and this is the state that the * object should be in when returned to the allocator. The purpose of this is * to remove some code which would otherwise be called on each allocation by * utilizing a known, stable state. This differs from the constructor which * will be called on EVERY allocation. * * For example, in the initializer you may want to initialize embedded locks, * NULL list pointers, set up initial states, magic numbers, etc. This way if * the object is held in the allocator and re-used it won't be necessary to * re-initialize it. * * The constructor may be used to lock a data structure, link it on to lists, * bump reference counts or total counts of outstanding structures, etc. * */ /* Function proto types */ /* * Create a new uma zone * * Arguments: * name The text name of the zone for debugging and stats. This memory * should not be freed until the zone has been deallocated. * size The size of the object that is being created. * ctor The constructor that is called when the object is allocated. * dtor The destructor that is called when the object is freed. * init An initializer that sets up the initial state of the memory. * fini A discard function that undoes initialization done by init. * ctor/dtor/init/fini may all be null, see notes above. * align A bitmask that corresponds to the requested alignment * eg 4 would be 0x3 * flags A set of parameters that control the behavior of the zone. * * Returns: * A pointer to a structure which is intended to be opaque to users of * the interface. The value may be null if the wait flag is not set. */ uma_zone_t uma_zcreate(const char *name, size_t size, uma_ctor ctor, uma_dtor dtor, uma_init uminit, uma_fini fini, int align, uint32_t flags); /* * Create a secondary uma zone * * Arguments: * name The text name of the zone for debugging and stats. This memory * should not be freed until the zone has been deallocated. * ctor The constructor that is called when the object is allocated. * dtor The destructor that is called when the object is freed. * zinit An initializer that sets up the initial state of the memory * as the object passes from the Keg's slab to the Zone's cache. * zfini A discard function that undoes initialization done by init * as the object passes from the Zone's cache to the Keg's slab. * * ctor/dtor/zinit/zfini may all be null, see notes above. * Note that the zinit and zfini specified here are NOT * exactly the same as the init/fini specified to uma_zcreate() * when creating a master zone. These zinit/zfini are called * on the TRANSITION from keg to zone (and vice-versa). Once * these are set, the primary zone may alter its init/fini * (which are called when the object passes from VM to keg) * using uma_zone_set_init/fini()) as well as its own * zinit/zfini (unset by default for master zone) with * uma_zone_set_zinit/zfini() (note subtle 'z' prefix). * * master A reference to this zone's Master Zone (Primary Zone), * which contains the backing Keg for the Secondary Zone * being added. * * Returns: * A pointer to a structure which is intended to be opaque to users of * the interface. The value may be null if the wait flag is not set. */ uma_zone_t uma_zsecond_create(const char *name, uma_ctor ctor, uma_dtor dtor, uma_init zinit, uma_fini zfini, uma_zone_t master); /* * Create cache-only zones. * * This allows uma's per-cpu cache facilities to handle arbitrary * pointers. Consumers must specify the import and release functions to * fill and destroy caches. UMA does not allocate any memory for these * zones. The 'arg' parameter is passed to import/release and is caller * specific. */ uma_zone_t uma_zcache_create(const char *name, int size, uma_ctor ctor, uma_dtor dtor, uma_init zinit, uma_fini zfini, uma_import zimport, uma_release zrelease, void *arg, int flags); /* * Definitions for uma_zcreate flags * * These flags share space with UMA_ZFLAGs in uma_int.h. Be careful not to * overlap when adding new features. */ #define UMA_ZONE_ZINIT 0x0002 /* Initialize with zeros */ #define UMA_ZONE_CONTIG 0x0004 /* * Physical memory underlying an object * must be contiguous. */ #define UMA_ZONE_NOTOUCH 0x0008 /* UMA may not access the memory */ #define UMA_ZONE_MALLOC 0x0010 /* For use by malloc(9) only! */ #define UMA_ZONE_NOFREE 0x0020 /* Do not free slabs of this type! */ #define UMA_ZONE_MTXCLASS 0x0040 /* Create a new lock class */ #define UMA_ZONE_VM 0x0080 /* * Used for internal vm datastructures * only. */ #define UMA_ZONE_NOTPAGE 0x0100 /* allocf memory not vm pages */ #define UMA_ZONE_SECONDARY 0x0200 /* Zone is a Secondary Zone */ #define UMA_ZONE_NOBUCKET 0x0400 /* Do not use buckets. */ #define UMA_ZONE_MAXBUCKET 0x0800 /* Use largest buckets. */ #define UMA_ZONE_MINBUCKET 0x1000 /* Use smallest buckets. */ #define UMA_ZONE_CACHESPREAD 0x2000 /* * Spread memory start locations across * all possible cache lines. May * require many virtually contiguous * backend pages and can fail early. */ #define UMA_ZONE_NODUMP 0x4000 /* * Zone's pages will not be included in * mini-dumps. */ #define UMA_ZONE_PCPU 0x8000 /* * Allocates mp_maxid + 1 slabs of * PAGE_SIZE */ #define UMA_ZONE_FIRSTTOUCH 0x10000 /* First touch NUMA policy */ #define UMA_ZONE_ROUNDROBIN 0x20000 /* Round-robin NUMA policy. */ #define UMA_ZONE_SMR 0x40000 /* * Safe memory reclamation defers * frees until all read sections * have exited. This flag creates * a unique SMR context for this * zone. To share contexts see * uma_zone_set_smr() below. * * See sys/smr.h for more details. */ /* In use by UMA_ZFLAGs: 0xffe00000 */ /* * These flags are shared between the keg and zone. Some are determined * based on physical parameters of the request and may not be provided by * the consumer. */ #define UMA_ZONE_INHERIT \ (UMA_ZONE_NOTOUCH | UMA_ZONE_MALLOC | UMA_ZONE_NOFREE | \ UMA_ZONE_VM | UMA_ZONE_NOTPAGE | UMA_ZONE_PCPU | \ UMA_ZONE_FIRSTTOUCH | UMA_ZONE_ROUNDROBIN) /* Definitions for align */ #define UMA_ALIGN_PTR (sizeof(void *) - 1) /* Alignment fit for ptr */ #define UMA_ALIGN_LONG (sizeof(long) - 1) /* "" long */ #define UMA_ALIGN_INT (sizeof(int) - 1) /* "" int */ #define UMA_ALIGN_SHORT (sizeof(short) - 1) /* "" short */ #define UMA_ALIGN_CHAR (sizeof(char) - 1) /* "" char */ #define UMA_ALIGN_CACHE (0 - 1) /* Cache line size align */ #define UMA_ALIGNOF(type) (_Alignof(type) - 1) /* Alignment fit for 'type' */ #define UMA_ANYDOMAIN -1 /* Special value for domain search. */ /* * Destroys an empty uma zone. If the zone is not empty uma complains loudly. * * Arguments: * zone The zone we want to destroy. * */ void uma_zdestroy(uma_zone_t zone); /* * Allocates an item out of a zone * * Arguments: * zone The zone we are allocating from * arg This data is passed to the ctor function * flags See sys/malloc.h for available flags. * * Returns: * A non-null pointer to an initialized element from the zone is * guaranteed if the wait flag is M_WAITOK. Otherwise a null pointer * may be returned if the zone is empty or the ctor failed. */ void *uma_zalloc_arg(uma_zone_t zone, void *arg, int flags); /* Allocate per-cpu data. Access the correct data with zpcpu_get(). */ void *uma_zalloc_pcpu_arg(uma_zone_t zone, void *arg, int flags); /* Use with SMR zones. */ void *uma_zalloc_smr(uma_zone_t zone, int flags); /* * Allocate an item from a specific NUMA domain. This uses a slow path in * the allocator but is guaranteed to allocate memory from the requested * domain if M_WAITOK is set. * * Arguments: * zone The zone we are allocating from * arg This data is passed to the ctor function * domain The domain to allocate from. * flags See sys/malloc.h for available flags. */ void *uma_zalloc_domain(uma_zone_t zone, void *arg, int domain, int flags); /* * Allocates an item out of a zone without supplying an argument * * This is just a wrapper for uma_zalloc_arg for convenience. * */ static __inline void *uma_zalloc(uma_zone_t zone, int flags); static __inline void *uma_zalloc_pcpu(uma_zone_t zone, int flags); static __inline void * uma_zalloc(uma_zone_t zone, int flags) { return uma_zalloc_arg(zone, NULL, flags); } static __inline void * uma_zalloc_pcpu(uma_zone_t zone, int flags) { return uma_zalloc_pcpu_arg(zone, NULL, flags); } /* * Frees an item back into the specified zone. * * Arguments: * zone The zone the item was originally allocated out of. * item The memory to be freed. * arg Argument passed to the destructor * * Returns: * Nothing. */ void uma_zfree_arg(uma_zone_t zone, void *item, void *arg); /* Use with PCPU zones. */ void uma_zfree_pcpu_arg(uma_zone_t zone, void *item, void *arg); /* Use with SMR zones. */ void uma_zfree_smr(uma_zone_t zone, void *item); /* * Frees an item back to the specified zone's domain specific pool. * * Arguments: * zone The zone the item was originally allocated out of. * item The memory to be freed. * arg Argument passed to the destructor */ void uma_zfree_domain(uma_zone_t zone, void *item, void *arg); /* * Frees an item back to a zone without supplying an argument * * This is just a wrapper for uma_zfree_arg for convenience. * */ static __inline void uma_zfree(uma_zone_t zone, void *item); static __inline void uma_zfree_pcpu(uma_zone_t zone, void *item); static __inline void uma_zfree(uma_zone_t zone, void *item) { uma_zfree_arg(zone, item, NULL); } static __inline void uma_zfree_pcpu(uma_zone_t zone, void *item) { uma_zfree_pcpu_arg(zone, item, NULL); } /* * Wait until the specified zone can allocate an item. */ void uma_zwait(uma_zone_t zone); /* * Backend page supplier routines * * Arguments: * zone The zone that is requesting pages. * size The number of bytes being requested. * pflag Flags for these memory pages, see below. * domain The NUMA domain that we prefer for this allocation. * wait Indicates our willingness to block. * * Returns: * A pointer to the allocated memory or NULL on failure. */ typedef void *(*uma_alloc)(uma_zone_t zone, vm_size_t size, int domain, uint8_t *pflag, int wait); /* * Backend page free routines * * Arguments: * item A pointer to the previously allocated pages. * size The original size of the allocation. * pflag The flags for the slab. See UMA_SLAB_* below. * * Returns: * None */ typedef void (*uma_free)(void *item, vm_size_t size, uint8_t pflag); /* * Reclaims unused memory * * Arguments: * req Reclamation request type. * Returns: * None */ #define UMA_RECLAIM_DRAIN 1 /* release bucket cache */ #define UMA_RECLAIM_DRAIN_CPU 2 /* release bucket and per-CPU caches */ #define UMA_RECLAIM_TRIM 3 /* trim bucket cache to WSS */ void uma_reclaim(int req); void uma_zone_reclaim(uma_zone_t, int req); /* * Sets the alignment mask to be used for all zones requesting cache * alignment. Should be called by MD boot code prior to starting VM/UMA. * * Arguments: * align The alignment mask * * Returns: * Nothing */ void uma_set_align(int align); /* * Set a reserved number of items to hold for M_USE_RESERVE allocations. All * other requests must allocate new backing pages. */ void uma_zone_reserve(uma_zone_t zone, int nitems); /* * Reserves the maximum KVA space required by the zone and configures the zone * to use a VM_ALLOC_NOOBJ-based backend allocator. * * Arguments: * zone The zone to update. * nitems The upper limit on the number of items that can be allocated. * * Returns: * 0 if KVA space can not be allocated * 1 if successful * * Discussion: * When the machine supports a direct map and the zone's items are smaller * than a page, the zone will use the direct map instead of allocating KVA * space. */ int uma_zone_reserve_kva(uma_zone_t zone, int nitems); /* * Sets a high limit on the number of items allowed in a zone * * Arguments: * zone The zone to limit * nitems The requested upper limit on the number of items allowed * * Returns: * int The effective value of nitems */ int uma_zone_set_max(uma_zone_t zone, int nitems); /* * Sets a high limit on the number of items allowed in zone's bucket cache * * Arguments: * zone The zone to limit * nitems The requested upper limit on the number of items allowed */ void uma_zone_set_maxcache(uma_zone_t zone, int nitems); /* * Obtains the effective limit on the number of items in a zone * * Arguments: * zone The zone to obtain the effective limit from * * Return: * 0 No limit * int The effective limit of the zone */ int uma_zone_get_max(uma_zone_t zone); /* * Sets a warning to be printed when limit is reached * * Arguments: * zone The zone we will warn about * warning Warning content * * Returns: * Nothing */ void uma_zone_set_warning(uma_zone_t zone, const char *warning); /* * Sets a function to run when limit is reached * * Arguments: * zone The zone to which this applies * fx The function ro run * * Returns: * Nothing */ typedef void (*uma_maxaction_t)(uma_zone_t, int); void uma_zone_set_maxaction(uma_zone_t zone, uma_maxaction_t); /* * Obtains the approximate current number of items allocated from a zone * * Arguments: * zone The zone to obtain the current allocation count from * * Return: * int The approximate current number of items allocated from the zone */ int uma_zone_get_cur(uma_zone_t zone); /* * The following two routines (uma_zone_set_init/fini) * are used to set the backend init/fini pair which acts on an * object as it becomes allocated and is placed in a slab within * the specified zone's backing keg. These should probably not * be changed once allocations have already begun, but only be set * immediately upon zone creation. */ void uma_zone_set_init(uma_zone_t zone, uma_init uminit); void uma_zone_set_fini(uma_zone_t zone, uma_fini fini); /* * The following two routines (uma_zone_set_zinit/zfini) are * used to set the zinit/zfini pair which acts on an object as * it passes from the backing Keg's slab cache to the * specified Zone's bucket cache. These should probably not * be changed once allocations have already begun, but only be set * immediately upon zone creation. */ void uma_zone_set_zinit(uma_zone_t zone, uma_init zinit); void uma_zone_set_zfini(uma_zone_t zone, uma_fini zfini); /* * Replaces the standard backend allocator for this zone. * * Arguments: * zone The zone whose backend allocator is being changed. * allocf A pointer to the allocation function * * Returns: * Nothing * * Discussion: * This could be used to implement pageable allocation, or perhaps * even DMA allocators if used in conjunction with the OFFPAGE * zone flag. */ void uma_zone_set_allocf(uma_zone_t zone, uma_alloc allocf); /* * Used for freeing memory provided by the allocf above * * Arguments: * zone The zone that intends to use this free routine. * freef The page freeing routine. * * Returns: * Nothing */ void uma_zone_set_freef(uma_zone_t zone, uma_free freef); /* * Associate a zone with a smr context that is allocated after creation * so that multiple zones may share the same context. */ void uma_zone_set_smr(uma_zone_t zone, smr_t smr); /* * Fetch the smr context that was set or made in uma_zcreate(). */ smr_t uma_zone_get_smr(uma_zone_t zone); /* * These flags are setable in the allocf and visible in the freef. */ #define UMA_SLAB_BOOT 0x01 /* Slab alloced from boot pages */ #define UMA_SLAB_KERNEL 0x04 /* Slab alloced from kmem */ #define UMA_SLAB_PRIV 0x08 /* Slab alloced from priv allocator */ /* 0x02, 0x10, 0x40, and 0x80 are available */ /* * Used to pre-fill a zone with some number of items * * Arguments: * zone The zone to fill * itemcnt The number of items to reserve * * Returns: * Nothing * * NOTE: This is blocking and should only be done at startup */ void uma_prealloc(uma_zone_t zone, int itemcnt); /* * Used to determine if a fixed-size zone is exhausted. * * Arguments: * zone The zone to check * * Returns: * Non-zero if zone is exhausted. */ int uma_zone_exhausted(uma_zone_t zone); /* * Returns the bytes of memory consumed by the zone. */ size_t uma_zone_memory(uma_zone_t zone); /* * Common UMA_ZONE_PCPU zones. */ extern uma_zone_t pcpu_zone_int; extern uma_zone_t pcpu_zone_64; /* * Exported statistics structures to be used by user space monitoring tools. * Statistics stream consists of a uma_stream_header, followed by a series of * alternative uma_type_header and uma_type_stat structures. */ #define UMA_STREAM_VERSION 0x00000001 struct uma_stream_header { uint32_t ush_version; /* Stream format version. */ uint32_t ush_maxcpus; /* Value of MAXCPU for stream. */ uint32_t ush_count; /* Number of records. */ uint32_t _ush_pad; /* Pad/reserved field. */ }; #define UTH_MAX_NAME 32 #define UTH_ZONE_SECONDARY 0x00000001 struct uma_type_header { /* * Static per-zone data, some extracted from the supporting keg. */ char uth_name[UTH_MAX_NAME]; uint32_t uth_align; /* Keg: alignment. */ uint32_t uth_size; /* Keg: requested size of item. */ uint32_t uth_rsize; /* Keg: real size of item. */ uint32_t uth_maxpages; /* Keg: maximum number of pages. */ uint32_t uth_limit; /* Keg: max items to allocate. */ /* * Current dynamic zone/keg-derived statistics. */ uint32_t uth_pages; /* Keg: pages allocated. */ uint32_t uth_keg_free; /* Keg: items free. */ uint32_t uth_zone_free; /* Zone: items free. */ uint32_t uth_bucketsize; /* Zone: desired bucket size. */ uint32_t uth_zone_flags; /* Zone: flags. */ uint64_t uth_allocs; /* Zone: number of allocations. */ uint64_t uth_frees; /* Zone: number of frees. */ uint64_t uth_fails; /* Zone: number of alloc failures. */ uint64_t uth_sleeps; /* Zone: number of alloc sleeps. */ uint64_t uth_xdomain; /* Zone: Number of cross domain frees. */ uint64_t _uth_reserved1[1]; /* Reserved. */ }; struct uma_percpu_stat { uint64_t ups_allocs; /* Cache: number of allocations. */ uint64_t ups_frees; /* Cache: number of frees. */ uint64_t ups_cache_free; /* Cache: free items in cache. */ uint64_t _ups_reserved[5]; /* Reserved. */ }; void uma_reclaim_wakeup(void); void uma_reclaim_worker(void *); unsigned long uma_limit(void); /* Return the amount of memory managed by UMA. */ unsigned long uma_size(void); /* Return the amount of memory remaining. May be negative. */ long uma_avail(void); #endif /* _VM_UMA_H_ */
<filename>src/main/java/com/g10/ssm/mapper/MenuQueryMapper.java package com.g10.ssm.mapper; import java.util.List; import com.g10.ssm.po.Menu; public interface MenuQueryMapper { List<Menu> selectAllMenu(); }
def umbrella_matrix( R, z, triangles, ignore_boundary=True, inverse_distance_weighting=True, normalised=False, sparse_format="csr", ): triangle_edges, edge_vertices, edge_map = build_edge_map(triangles) if ignore_boundary: boundary_edges = [i for i in range(len(edge_map)) if len(edge_map[i]) == 1] boundary_vertex_set = {edge_vertices[i, 0] for i in boundary_edges} | { edge_vertices[i, 1] for i in boundary_edges } verts = {i for i in range(R.size)} - boundary_vertex_set else: verts = range(R.size) row_inds_list = [] col_inds_list = [] entry_vals_list = [] for i in verts: inds = ((edge_vertices[:, 0] == i) | (edge_vertices[:, 1] == i)).nonzero()[0] col_inds = [i] col_inds.extend([j for j in edge_vertices[inds, :].flatten() if i != j]) col_inds = array(col_inds, dtype=int) distances = sqrt((R[i] - R[col_inds[1:]]) ** 2 + (z[i] - z[col_inds[1:]]) ** 2) row_inds = full(col_inds.size, fill_value=i, dtype=int) weights = full(col_inds.size, fill_value=-1.0) if inverse_distance_weighting: inv_distances = 1.0 / distances weights[1:] = inv_distances / inv_distances.sum() else: weights[1:] = 1.0 / (col_inds.size - 1.0) if normalised: weights /= 2.6 * distances.mean() ** 2 row_inds_list.append(row_inds) col_inds_list.append(col_inds) entry_vals_list.append(weights) row_indices = concatenate(row_inds_list) col_indices = concatenate(col_inds_list) entry_values = concatenate(entry_vals_list) shape = (R.size, R.size) if sparse_format == "csr": return csr_matrix((entry_values, (row_indices, col_indices)), shape=shape) elif sparse_format == "csc": return csc_matrix((entry_values, (row_indices, col_indices)), shape=shape)
n, m = tuple(map(int, raw_input().split())) data = list(map(int, raw_input().split())) data.sort() data = data[:min(n,m)] ans = 0 for i in data: if i<0: ans -= i else: break print ans
package main import ( "bytes" "context" "flag" "fmt" "net" "os" "os/user" "time" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/terminal" ) var ( private = flag.String("private", "", "The path to the SSH private key for this connection") ) func main() { flag.Parse() if len(os.Args) != 3 { fmt.Println("Error: command must be 2 args, [host] [command]") os.Exit(1) } _, _, err := net.SplitHostPort(os.Args[1]) if err != nil { os.Args[1] = os.Args[1] + ":22" _, _, err = net.SplitHostPort(os.Args[1]) if err != nil { fmt.Println("Error: problem with host passed: ", err) os.Exit(1) } } var auth ssh.AuthMethod if *private == "" { fi, _ := os.Stdin.Stat() if (fi.Mode() & os.ModeCharDevice) == 0 { fmt.Println("-private not set, cannot use password when STDIN is a pipe") os.Exit(1) } auth, err = passwordFromTerm() if err != nil { fmt.Println(err) os.Exit(1) } } else { auth, err = publicKey(*private) if err != nil { fmt.Println(err) os.Exit(1) } } u, err := user.Current() if err != nil { fmt.Println("Error: problem getting current user: ", err) os.Exit(1) } config := &ssh.ClientConfig{ User: u.Username, Auth: []ssh.AuthMethod{auth}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), Timeout: 5 * time.Second, } conn, err := ssh.Dial("tcp", os.Args[1], config) if err != nil { fmt.Println("Error: could not dial host: ", err) os.Exit(1) } defer conn.Close() ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() out, err := combinedOutput(ctx, conn, os.Args[2]) if err != nil { fmt.Println("command error: ", err) os.Exit(1) } fmt.Println(out) } func passwordFromTerm() (ssh.AuthMethod, error) { fmt.Printf("SSH Passsword: ") p, err := terminal.ReadPassword(int(os.Stdin.Fd())) if err != nil { return nil, err } fmt.Println("") // Show the return if len(bytes.TrimSpace(p)) == 0 { return nil, fmt.Errorf("password was an empty string") } return ssh.Password(string(p)), nil } func publicKey(privateKeyFile string) (ssh.AuthMethod, error) { k, err := os.ReadFile(privateKeyFile) if err != nil { return nil, err } signer, err := ssh.ParsePrivateKey(k) if err != nil { return nil, err } return ssh.PublicKeys(signer), nil } // combinedOutput runs a command on an SSH client. The context can be cancelled, however // SSH does not always honor the kill signals we send, so this might not break. So closing // the session does nothing. So depending on what the server is doing, cancelling the context // may do nothing and it may still block. func combinedOutput(ctx context.Context, conn *ssh.Client, cmd string) (string, error) { sess, err := conn.NewSession() if err != nil { return "", err } defer sess.Close() if v, ok := ctx.Deadline(); ok { t := time.NewTimer(v.Sub(time.Now())) defer t.Stop() go func() { x := <-t.C if !x.IsZero() { sess.Signal(ssh.SIGKILL) } }() } b, err := sess.Output(cmd) if err != nil { return "", err } return string(b), nil }
/** * A template builder for a metadata node. * * @author Carl Harris */ class MetaNodeViewTemplateBuilder extends ValueNodeViewTemplateBuilder { private UnconfigurableNodeSupport delegate; MetaNodeViewTemplateBuilder(AbstractViewTemplateBuilder parent, AbstractContainerNode target, AbstractViewNode node) { super(parent, target, node); delegate = new UnconfigurableNodeSupport(node); } @Override public ViewTemplateBuilder discriminator() { return delegate.discriminator(); } @Override public ViewTemplateBuilder discriminator(Class<? extends DiscriminatorStrategy> discriminatorClass, Object... configuration) { return delegate.discriminator(discriminatorClass, configuration); } @Override public ViewTemplateBuilder discriminator(Class<? extends DiscriminatorStrategy> discriminatorClass, Map configuration) { return delegate.discriminator(discriminatorClass, configuration); } @Override public ViewTemplateBuilder discriminator(DiscriminatorStrategy discriminator) { return delegate.discriminator(discriminator); } @Override public ViewTemplateBuilder source(String name) { return delegate.source(name); } @Override public ViewTemplateBuilder accessType(AccessType accessType) { return delegate.accessType(accessType); } @Override public ViewTemplateBuilder allow(AccessMode mode, AccessMode... modes) { return delegate.allow(mode, modes); } @Override public ViewTemplateBuilder allow(EnumSet<AccessMode> modes) { return delegate.allow(modes); } @Override public ViewTemplateBuilder converter(Class<? extends ValueTypeConverter> converterClass, Object... configuration) { return delegate.converter(converterClass, configuration); } @Override public ViewTemplateBuilder converter(Class<? extends ValueTypeConverter> converterClass, Map configuration) { return delegate.converter(converterClass, configuration); } @Override public ViewTemplateBuilder converter(ValueTypeConverter converter) { return delegate.converter(converter); } }
package com.example.rh.ui.banner; import android.support.v7.widget.AppCompatImageView; import android.view.View; import com.bigkoo.convenientbanner.holder.Holder; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.example.rh.core.app.MyApp; import com.example.rh_core.R; /** * @author RH * @date 2018/10/26 */ public class ImageHolder extends Holder<String> { /** * 控件不能赋值空 */ private AppCompatImageView mImageView; private static final RequestOptions BANNER_OPTIONS = new RequestOptions() .diskCacheStrategy(DiskCacheStrategy.ALL) .dontAnimate() .centerCrop(); public ImageHolder(View itemView) { super(itemView); } @Override protected void initView(View itemView) { mImageView = (AppCompatImageView) itemView.findViewById(R.id.banner_image); } @Override public void updateUI(String data) { //该处不能使用itemView,只能使用全局Context,否则会报错 //java.lang.IllegalArgumentException: You cannot start a load for a destroyed activity Glide.with(MyApp.getApplicationContext()) .load(data) .apply(BANNER_OPTIONS) .into(mImageView); } }
#!/usr/bin/env python3 ############################################################################## # EVOLIFE http://evolife.telecom-paris.fr <NAME> # # Telecom Paris 2021 www.dessalles.fr # # -------------------------------------------------------------------------- # # License: Creative Commons BY-NC-SA # ############################################################################## ############################################################################## # Basic implementation of Turing's reaction-diffusion model # ############################################################################## """ Basic implementation of Turing's reaction-diffusion model """ import sys import random sys.path.append('..') sys.path.append('../../..') import Evolife.Ecology.Observer as EO import Evolife.Scenarii.Parameters as EPar import Evolife.QtGraphics.Evolife_Window as EW import Evolife.QtGraphics.Curves as EC import Landscapes # global functions Quantify = lambda x, Step: int(x / Step) * Step if Step else x def Limitate(x, Min=0, Max=1, Step=0): " returns a quantified version of x cut to fit an interval " if Step == 0: Step = Gbl.P('Precision') return Quantify(x, Step) return min(max(Quantify(x, Step),Min), Max) # return min(max(round(x, 3),Min), Max) class LandCell(Landscapes.LandCell): " Defines what is stored at a given location " def __init__(self): # Cell content is defined as a couple (ConcentrationA, ConcentrationB) Landscapes.LandCell.__init__(self, (0, 0), VoidCell=(0, 0)) self.Colour = 2 # white == invisible self.OldColour = None def activated(self, Future=False): " tells whether a cell is active " return self.Content(Future=Future)[1] > 0 def Update(self): self.Present = self.Future # erases history return not self.activated() def getColour(self, product=1, Max=1): " return color corresponding to content, but only if it has changed " # self.Colour = EC.Shade(self.Content()[0], BaseColour='red', Max=Max, darkToLight=False) self.Colour = '#%02X%02XFF' % ((int(255 * (1 - self.Content()[product-1])),) * 2) Col = None if self.Colour != self.OldColour: Col = self.Colour self.OldColour = self.Colour return Col #------------------------# # Reaction # #------------------------# # Gray-Scott model # #------------------------# def Reaction(self, F, k, Noise=0): " Reaction between local products A and B " (Ca0, Cb0) = self.Content() deltaB = Ca0 * Cb0 * Cb0 if Noise: deltaB *= (1 - Noise * (1 - random.random())) deltaA = F * (1 - Ca0) - deltaB deltaB -= (F + k) * Cb0 return ((Limitate(Ca0 + deltaA, Max=Gbl.P('MaxA'))), Limitate(Cb0 + deltaB, Max=Gbl.P('MaxB'))) class Landscape(Landscapes.Landscape): " Defines a 2D square grid " def __init__(self, Size, DiffusionCoefficients, MaxValues, NeighbourhoodRadius, Precision): Landscapes.Landscape.__init__(self, Width=Size, CellType=LandCell) # calls local LandCell definition # Computing actual diffusion coefficients self.NeighbourhoodRadius = NeighbourhoodRadius self.DcA, self.DcB = DiffusionCoefficients self.MaxA, self.MaxB = MaxValues self.Precision = Precision def Seed(self, Center, Value, Radius=5): " Creation of a blob " for Pos1 in self.neighbours(Center, Radius): # immediate neighbours self.Modify(Pos1, Value, Future=False) #------------------------# # Diffusion # #------------------------# def activate(self, Pos0): " Cell located at position 'Pos0' produces its effect on neighbouring cells " (Ca0, Cb0) = self.Cell(Pos0).Content() # actual concentration values # NL = self.neighbourhoodLength(Radius=self.NeighbourhoodRadius) # Neighbours = self.neighbours(Pos0, self.NeighbourhoodRadius) Neighbours = self.neighbours(Pos0, Radius=1) # deltaA = (self.DcA * Ca0)/NL # contribution to neighbouring cells # deltaB = (self.DcB * Cb0)/NL # contribution to neighbouring cells NeighbourhoodInfluenceA, NeighbourhoodInfluenceB = (0,0) for Pos1 in Neighbours: # immediate neighbours (Ca1, Cb1) = self.Content(Pos1) # current concentration values NeighbourhoodInfluenceA += Ca1 NeighbourhoodInfluenceB += Cb1 self.Modify(Pos0, ( Limitate(Ca0 + self.DcA * (NeighbourhoodInfluenceA - 4 * Ca0), Max=self.MaxA, Step=self.Precision), Limitate(Cb0 + self.DcB * (NeighbourhoodInfluenceB - 4 * Cb0), Max=self.MaxB, Step=self.Precision)), Future=True) import cProfile def One_Step1(): print(Observer.StepId) if Observer.StepId % 5 == 0: cProfile.run("One_Step1()") return True else: return One_Step1() def One_Step(): """ This function is repeatedly called by the simulation thread. One agent is randomly chosen and decides what it does """ Observer.season() # increments StepId dotSize = Gbl.P('DotSize') maxA = Gbl.P('MaxA') maxB = Gbl.P('MaxB') if Observer.Visible(): # for (Position, Cell) in Land.travel(): for Position in Land.ActiveCells: Cell = Land.Cell(Position) # displaying concentrations Colour1 = Cell.getColour(1, Max=maxA) # quantity of A Colour2 = Cell.getColour(2, Max=maxB) # quantity of B if Colour1 is not None: Observer.record(('C%d_%d' % Position, Position + (Colour1, -dotSize, 'shape=rectangle'))) if Colour2 is not None: Observer.record(('C%d_%d' % Position, Position + (Colour2, -dotSize, 'shape=rectangle')), Window='Trajectories') ############# # Diffusion # ############# for (Position, Cell) in Land.travel(): Land.activate(Position) # diffusion Land.update() # Let's update concentrations ############# # Reaction # ############# for (Position, Cell) in Land.travel(): Land.Modify(Position, Cell.Reaction(Gbl.P('F'), Gbl.P('k'), Noise=Gbl.P('Noise')), Future=False) # for Cell in Land.ActiveCells: # Cell.Reaction(Gbl.P('F'), Gbl.P('k')) if len(Land.ActiveCells) == 0: return False return True if __name__ == "__main__": print(__doc__) ############################# # Global objects # ############################# Gbl = EPar.Parameters(CfgFile='_Params.evo') Gbl.P = lambda x: Gbl.Parameter(x) # to shorten writings Observer = EO.Experiment_Observer(Gbl) # Observer contains statistics # Observer.recordInfo('Background', 'white') # Observer.recordInfo('FieldWallpaper', 'white') Observer.recordInfo('Background', 'white') PhysicalSize = Gbl.P('DotSize') * Gbl.P('LandSize') Observer.recordInfo('DefaultViews', [('Field', PhysicalSize, PhysicalSize),('Trajectories', PhysicalSize, PhysicalSize)]) Observer.record([(0, Gbl.P('LandSize'),2,0), (Gbl.P('LandSize'), 0, 2,0)]) # to resize Observer.record([(0, Gbl.P('LandSize'),2,0), (Gbl.P('LandSize'), 0, 2,0)], Window='Trajectories') # to resize Land = Landscape( Gbl.P('LandSize'), (Gbl.P('Da'), Gbl.P('Db')), (Gbl.P('MaxA'), Gbl.P('MaxB')), Gbl.P('NeighbourhoodRadius'), Gbl.P('Precision') ) # 2D square grid Land.Seed((Gbl.P('LandSize')//3, Gbl.P('LandSize')//3), (0.4, 0.9), Radius=4) Land.Seed((2*Gbl.P('LandSize')//3, 2*Gbl.P('LandSize')//3), (0.4, 0.9), Radius=4) # print len(Land.ActiveCells) # Land.setAdmissible(range(101)) # max concentration EW.Start(One_Step, Observer, Capabilities='RPT') print("Bye.......") __author__ = 'Dessalles'
/** \file * Alter implementation. */ #include "alter.h" namespace ql { namespace pass { namespace map { namespace qubits { namespace map { namespace detail { /** * This should only be called after a virgin construction and not after * cloning a path. */ void Alter::initialize(const ir::compat::KernelRef &k, const OptionsRef &opt) { QL_DOUT("Alter::initialize(number of qubits=" << k->platform->qubit_count); platform = k->platform; kernel = k; options = opt; nq = platform->qubit_count; ct = platform->cycle_time; // total, fromSource and fromTarget start as empty vectors past.initialize(kernel, options); // initializes past to empty score_valid = false; // will not print score for now } /** * Print path as s followed by path of the form [0->1->2]. */ static void partial_print( const utils::Str &s, const utils::Vec<utils::UInt> &path ) { if (!path.empty()) { std::cout << s << path.to_string("[", "->", "]"); } } /** * Prints the state of this Alter, prefixed by s. */ void Alter::print(const utils::Str &s) const { // std::cout << s << "- " << targetgp->qasm(); std::cout << s << "- " << target_gate->qasm(); if (from_source.empty() && from_target.empty()) { partial_print(", total path:", total); } else { partial_print(", path from source:", from_source); partial_print(", from target:", from_target); } if (score_valid) { std::cout << ", score=" << score; } // past.Print("past in Alter"); std::cout << std::endl; } /** * Prints the state of this Alter, prefixed by s, only when the logging * verbosity is at least debug. */ void Alter::debug_print(const utils::Str &s) const { if (utils::logger::log_level >= utils::logger::LogLevel::LOG_DEBUG) { print(s); } } /** * Prints a state of a whole list of Alters, prefixed by s. */ void Alter::print(const utils::Str &s, const utils::List<Alter> &la) { utils::Int started = 0; for (auto &a : la) { if (started == 0) { started = 1; std::cout << s << "[" << la.size() << "]={" << std::endl; } a.print(""); } if (started == 1) { std::cout << "}" << std::endl; } } /** * Prints a state of a whole list of Alters, prefixed by s, only when the * logging verbosity is at least debug. */ void Alter::debug_print(const utils::Str &s, const utils::List<Alter> &la) { if (utils::logger::log_level >= utils::logger::LogLevel::LOG_DEBUG) { print(s, la); } } /** * Adds a node to the path in front, extending its length with one. */ void Alter::add_to_front(utils::UInt q) { total.insert(total.begin(), q); // hopelessly inefficient } /** * Add swap gates for the current path to the given past, up to the maximum * specified by the swap selection mode. This past can be a path-local one * or the main past. After having added them, schedule the result into that * past. */ void Alter::add_swaps(Past &past, SwapSelectionMode mode) const { // QL_DOUT("Addswaps " << mapselectswapsopt); if (mode == SwapSelectionMode::ONE || mode == SwapSelectionMode::ALL) { utils::UInt num_added = 0; utils::UInt max_num_to_add = (mode == SwapSelectionMode::ONE ? 1 : ir::compat::MAX_CYCLE); utils::UInt from_source_qubit; utils::UInt to_source_qubit; from_source_qubit = from_source[0]; for (utils::UInt i = 1; i < from_source.size() && num_added < max_num_to_add; i++) { to_source_qubit = from_source[i]; past.add_swap(from_source_qubit, to_source_qubit); from_source_qubit = to_source_qubit; num_added++; } utils::UInt from_target_qubit; utils::UInt to_target_qubit; from_target_qubit = from_target[0]; for (utils::UInt i = 1; i < from_target.size() && num_added < max_num_to_add; i++) { to_target_qubit = from_target[i]; past.add_swap(from_target_qubit, to_target_qubit); from_target_qubit = to_target_qubit; num_added++; } } else { QL_ASSERT(mode == SwapSelectionMode::EARLIEST); if (from_source.size() >= 2 && from_target.size() >= 2) { if (past.is_first_swap_earliest(from_source[0], from_source[1], from_target[0], from_target[1])) { past.add_swap(from_source[0], from_source[1]); } else { past.add_swap(from_target[0], from_target[1]); } } else if (from_source.size() >= 2) { past.add_swap(from_source[0], from_source[1]); } else if (from_target.size() >= 2) { past.add_swap(from_target[0], from_target[1]); } } past.schedule(); } /** * Compute cycle extension of the current alternative in curr_past relative * to the given base past. * * extend can be called in a deep exploration where pasts have been * extended, each one on top of a previous one, starting from the base past. * The curr_past here is the last extended one, i.e. on top of which this * extension should be done; the base_past is the ultimate base past * relative to which the total extension is to be computed. * * Do this by adding the swaps described by this alternative to an * alternative-local copy of the current past. Keep this resulting past in * the current alternative (for later use). Compute the total extension of * all pasts relative to the base past, and store this extension in the * alternative's score for later use. */ void Alter::extend(const Past &curr_past, const Past &base_past) { // QL_DOUT("... clone past, add swaps, compute overall score and keep it all in current alternative"); past = curr_past; // explicitly clone currPast to an alternative-local copy of it, Alter.past // QL_DOUT("... adding swaps to alternative-local past ..."); add_swaps(past, SwapSelectionMode::ALL); // QL_DOUT("... done adding/scheduling swaps to alternative-local past"); if (options->heuristic == Heuristic::MAX_FIDELITY) { QL_FATAL("Mapper option maxfidelity has been disabled"); // score = quick_fidelity(past.lg); } else { score = past.get_max_free_cycle() - base_past.get_max_free_cycle(); } score_valid = true; } /** * Split the path. Starting from the representation in the total attribute, * generate all split path variations where each path is split once at any * hop in it. The intention is that the mapped two-qubit gate can be placed * at the position of that hop. All result paths are added/appended to the * given result list. * * When at the hop of a split a two-qubit gate cannot be placed, the split * is not done there. This means at the end that, when all hops are * inter-core, no split is added to the result. * * distance=5 means length=6 means 4 swaps + 1 CZ gate, e.g. * index in total: 0 1 2 length-3 length-2 length-1 * qubit: 2 -> 5 -> 7 -> 3 -> 1 CZ 4 */ void Alter::split(utils::List<Alter> &result) const { // QL_DOUT("Split ..."); utils::UInt length = total.size(); QL_ASSERT (length >= 2); // distance >= 1 so path at least: source -> target for (utils::UInt rightopi = length - 1; rightopi >= 1; rightopi--) { utils::UInt leftopi = rightopi - 1; QL_ASSERT (leftopi >= 0); // QL_DOUT("... leftopi=" << leftopi); // leftopi is the index in total that holds the qubit that becomes the left operand of the gate // rightopi is the index in total that holds the qubit that becomes the right operand of the gate // rightopi == leftopi + 1 if (platform->topology->is_inter_core_hop(total[leftopi], total[rightopi])) { // an inter-core hop cannot execute a two-qubit gate, so is not a valid alternative // QL_DOUT("... skip inter-core hop from qubit=" << total[leftopi] << " to qubit=" << total[rightopi]); continue; } Alter na = *this; // na is local copy of the current path, including total // na = *this; // na is local copy of the current path, including total // na.DPRINT("... copy of current alter"); // fromSource will contain the path with qubits at indices 0 to leftopi // fromTarget will contain the path with qubits at indices rightopi to length-1, reversed // reversal of fromTarget is done since swaps need to be generated starting at the target utils::UInt fromi, toi; na.from_source.resize(leftopi + 1); // QL_DOUT("... fromSource size=" << na.fromSource.size()); for (fromi = 0, toi = 0; fromi <= leftopi; fromi++, toi++) { // QL_DOUT("... fromSource: fromi=" << fromi << " toi=" << toi); na.from_source[toi] = na.total[fromi]; } na.from_target.resize(length - leftopi - 1); // QL_DOUT("... fromTarget size=" << na.fromTarget.size()); for (fromi = length-1, toi = 0; fromi > leftopi; fromi--, toi++) { // QL_DOUT("... fromTarget: fromi=" << fromi << " toi=" << toi); na.from_target[toi] = na.total[fromi]; } // na.DPRINT("... copy of alter after split"); result.push_back(na); // QL_DOUT("... added to result list"); // DPRINT("... current alter after split"); } } } // namespace detail } // namespace map } // namespace qubits } // namespace map } // namespace pass } // namespace ql
<filename>migrations/versions/79dcf9aa4f15_.py<gh_stars>0 """add UserID to article_papers primary key Revision ID: 79dcf9aa4f15 Revises: 451512b7ee9b Create Date: 2018-04-03 10:58:52.939561 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '451512b7ee9b' branch_labels = None depends_on = None def upgrade(): # delete foreign keys op.drop_constraint("article_papers_ibfk_1", 'article_papers', type_='foreignkey') op.drop_constraint("article_papers_ibfk_2", 'article_papers', type_='foreignkey') op.drop_constraint("article_papers_ibfk_3", 'article_papers', type_='foreignkey') # change primary key over to new format op.execute("ALTER TABLE article_papers DROP PRIMARY KEY") op.create_primary_key("pk_article_papers", "article_papers", ["article_id","paper_id","user_id" ]) #recreate primary keys op.create_foreign_key("article_papers_ibfk_1", 'article_papers', 'articles', ['article_id'], ['article_id']) op.create_foreign_key("article_papers_ibfk_2", 'article_papers', 'papers', ['paper_id'], ['paper_id']) op.create_foreign_key("article_papers_ibfk_3", 'article_papers', 'user', ['user_id'], ['id']) def downgrade(): # delete foreign keys op.drop_constraint("article_papers_ibfk_1", 'article_papers', type_='foreignkey') op.drop_constraint("article_papers_ibfk_2", 'article_papers', type_='foreignkey') op.drop_constraint("article_papers_ibfk_3", 'article_papers', type_='foreignkey') # revert primary key back to the way it was before op.execute("ALTER TABLE article_papers DROP PRIMARY KEY") op.create_primary_key("pk_article_papers", "article_papers", ["article_id","paper_id"]) #recreate primary keys op.create_foreign_key("article_papers_ibfk_1", 'article_papers', 'article_id', ['article_id'], ['article_id']) op.create_foreign_key("article_papers_ibfk_2", 'article_papers', 'papers', ['paper_id'], ['paper_id']) op.create_foreign_key("article_papers_ibfk_3", 'article_papers', 'user', ['user_id'], ['id'])
def selectedNodes(self, layer=None, filterOn=False, extend=None, deep=True): return [self.nodes(layer, extend, deep)[nid] for nid in self.selectedNodeIndices(filterOn, deep)]
Degradation mechanism of perovskite CH3NH3PbI3 diode devices studied by electroluminescence and photoluminescence imaging spectroscopy We investigate the degradation behavior of non-sealed perovskite CH3NH3PbI3 diode devices in air at room temperature by means of electroluminescence (EL) and photoluminescence (PL) imaging techniques. From the comparison of these images, we determine that the spatial fluctuation of the EL intensity is mainly due to fluctuations in the luminescence efficiency of the perovskite layer itself. By applying a constant voltage for tens of minutes, the EL intensity decreases gradually. It is observed that the temporal evolution of the EL intensity is governed by the degradation of the perovskite layer and the carrier injection at the interface.
/** * @param p {@link MavenProject} * @throws MojoExecutionException in case of an error. */ protected void packageSources( MavenProject p ) throws MojoExecutionException { if ( !"pom".equals( p.getPackaging() ) ) { packageSources( Collections.singletonList( p ) ); } }
Application of Structural Equation Model and AMOS Software The Amos 17 is the structural equation model (Structural Equation Modeling, SEM), which is one of the important software analysis. With the application of SEM technology in depth, analysis of multi group structural equation model (Multiple-Group Analysis) has gradually attracted researcher’s attention.. Stability of deep test theoretical model by examining the effect of its regulating variable, and the method is not only suitable for fitting degree test theoretical models in the regulation of variables of different level, but also for the fitting problem to test the tracking data and theoretical model. Through a case study of their own, using Amos 17 software as the basis introduces the basic principle of multi group structural equation model analysis technique and its use method in the study of Applied Linguistics to domestic applied linguistics intends to use the method which will provide examples of reference.
Dallas Mavericks guard J.J. Barea has been hired as the head coach of Indios de Mayaguez in the Puerto Rican league for the remainder of the season, which runs through June 27. "I didn't know it was going to happen now, but I always wanted to coach later on when I finished playing," Barea told ESPN. "This is my hometown team, where I played when I was getting started. I think it's going to be a great experience for myself and see if I really like this and see what I learn and if it can help me out for the future." Barea replaces coach Bobby Porrata, who was fired with Indios de Mayaguez in last place with a 7-14 record. Barea will run one practice before making his coaching debut Thursday. He said he received clearance from Mavericks owner Mark Cuban, head coach Rick Carlisle and the NBA office before accepting the job. Carlisle texted Barea his five favorite plays from the Mavs' playbook. "Great opportunity for J.J. and he will do a tremendous job," Carlisle said via text message. Barea, 32, a Puerto Rican national team star who played a key role on Dallas' 2010-11 championship team, is under contract with the Mavs through 2018-19 and hopes to get at least one more NBA contract. He averaged 10.9 points and 5.5 assists for the Mavs last season but was limited to 35 games due to a series of calf injuries. Barea has entertained the thought of trying to begin his coaching career as an NBA or college assistant once he retires as a player. "I haven't thought too much that far yet," Barea said. "I still want to play four or five more years, and then we'll go from there."
/** * Very simple xml inheritance for devices. */ static XMLElement inheritXML(XMLElement parent, XMLElement child, String parentName) { inheritanceConstInit(); if (parent == null) { return child; } parent.setContent(child.getContent()); for (Enumeration ena = child.enumerateAttributeNames(); ena.hasMoreElements();) { String key = (String) ena.nextElement(); parent.setAttribute(key, child.getAttribute(key)); } for (Enumeration enc = child.enumerateChildren(); enc.hasMoreElements();) { XMLElement c = (XMLElement) enc.nextElement(); String fullName = (parentName + "/" + c.getName()).toUpperCase(Locale.ENGLISH); boolean inheritWithName = false; if (c.getStringAttribute("name") != null) { inheritWithName = true; } else { inheritWithName = ((child.getChildCount(c.getName()) > 1) || (parent.getChildCount(c.getName()) > 1)); } XMLElement p; if (inheritWithName) { String[] equalAttributes = (String[]) specialInheritanceAttributeSet.get(fullName); if (equalAttributes != null) { p = parent.getChild(c.getName(), c.getStringAttributes(equalAttributes)); } else { p = parent.getChild(c.getName(), c.getStringAttribute("name")); } } else { p = parent.getChild(c.getName()); } if (p == null) { parent.addChild(c); } else { inheritXML(p, c, fullName); } } return parent; }
/** * The inner representation of the SearchArgument. Most users should not * need this interface, it is only for file formats that need to translate * the SearchArgument into an internal form. */ class ExpressionTree { public: enum class Operator { OR, AND, NOT, LEAF, CONSTANT }; ExpressionTree(Operator op); ExpressionTree(Operator op, std::initializer_list<TreeNode> children); ExpressionTree(size_t leaf); ExpressionTree(TruthValue constant); ExpressionTree(const ExpressionTree& other); ExpressionTree& operator=(const ExpressionTree&) = delete; Operator getOperator() const; const std::vector<TreeNode>& getChildren() const; std::vector<TreeNode>& getChildren(); const TreeNode getChild(size_t i) const; TreeNode getChild(size_t i); TruthValue getConstant() const; size_t getLeaf() const; void setLeaf(size_t leaf); void addChild(TreeNode child); std::string toString() const; TruthValue evaluate(const std::vector<TruthValue>& leaves) const; private: Operator mOperator; std::vector<TreeNode> mChildren; size_t mLeaf; TruthValue mConstant; }
// Set sets commit value from records func (commit *Commit) Set(record []string) { commit.CommitHash.Abbreviated = record[0] commit.CommitHash.Full = record[1] commit.Author.Name = record[2] commit.Author.Email = record[3] commit.Subject = record[5] commit.Body = record[6] }
<filename>src/hexagon/domain/user/commands/CreateUserCommand.ts /// <reference path="../../../boundary/index.ts" /> import ICreateUserCommand = Microservice.Authentication.Struct.ICreateUserCommand import { CommandBase } from '../../core/CommandBase' export class CreateUserCommand extends CommandBase implements ICreateUserCommand { private username: string private email: string private password: string private constructor() { super() } getUsername(): string { return this.username } getEmail(): string { return this.email } getPassword(): string { return this.password } static Builder = class extends CommandBase.BuilderBase { setUsername() { // const command = new CreateUserCommand() } setEmail() {} setPassword() {} } }
/** * @param state The {@link BlockState} to check. Non null. * * @throws IllegalArgumentException If the state doesn't have a TileEntity */ private static void ensureCorrectClass(BlockState state) { if (!isValidClass(state)) { throw new IllegalArgumentException("The state is not a TileEntity. Valid is e.g. a Chest or a Furnace."); } }
// AlgoliaSyncSetStatus updates the status. If hash or jsonBytes are set, then // it will update those as well func AlgoliaSyncSetStatus(db *sql.Connection, id int, status string, hash *string, jsonBytes []byte) (err error) { ub := db.Update(AlgoliaSyncTableName). Where("algolia_sync_id=?", id). Set("algolia_sync_status", status). Set("updated_on", "now()") if hash != nil { ub = ub.Set("algolia_sync_item_hash", *hash) } if jsonBytes != nil { ub = ub.Set("algolia_sync_item", jsonBytes) } if err := db.ExecUpdate(ub); err != nil { return e.Wrap(err, e.Code0507, "01") } return nil }
/** * Removes the registered SAX driver. */ public void cleanup() { if (oldProperty != null) { System.setProperty(SAX_DRIVER_PROPERTY, oldProperty); } else { System.clearProperty(SAX_DRIVER_PROPERTY); } }
/** * 14/03/2017. Given a collection of candidate numbers (C) and a * target number (T), find all unique combinations in C where the candidate numbers sums to T. * * <p>Each number in C may only be used once in the combination. * * <p>Note: All numbers (including target) will be positive integers. The solution set must not * contain duplicate combinations. For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and * target 8, A solution set is: [ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ] */ public class CombinationSumII { /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int[] candidates = {1, 1, 2, 2}; List<List<Integer>> result = new CombinationSumII().combinationSum2(candidates, 4); } public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<>(); combination(0, target, candidates, new ArrayList<>(), result); return result; } private void combination( int i, int target, int[] candidates, List<Integer> row, List<List<Integer>> result) { if (target == 0) { result.add(new ArrayList<>(row)); } else if (target > 0) { for (int j = i, l = candidates.length; j < l; j++) { if (j > i && candidates[j] == candidates[j - 1]) continue; row.add(candidates[j]); combination(j + 1, target - candidates[j], candidates, row, result); row.remove(row.size() - 1); } } } }
/** * Dynamic implementation of a strongly typed workflow interface that can be used to start, signal * and query workflows from external processes. */ class WorkflowInvocationHandler implements InvocationHandler { public enum InvocationType { SYNC, START, EXECUTE, SIGNAL_WITH_START, } interface SpecificInvocationHandler { InvocationType getInvocationType(); void invoke( POJOWorkflowInterfaceMetadata workflowMetadata, WorkflowStub untyped, Method method, Object[] args) throws Throwable; <R> R getResult(Class<R> resultClass); } private static final ThreadLocal<SpecificInvocationHandler> invocationContext = new ThreadLocal<>(); /** Must call {@link #closeAsyncInvocation()} if this one was called. */ static void initAsyncInvocation(InvocationType type) { initAsyncInvocation(type, null); } /** Must call {@link #closeAsyncInvocation()} if this one was called. */ static <T> void initAsyncInvocation(InvocationType type, T value) { if (invocationContext.get() != null) { throw new IllegalStateException("already in start invocation"); } if (type == InvocationType.START) { invocationContext.set(new StartWorkflowInvocationHandler()); } else if (type == InvocationType.EXECUTE) { invocationContext.set(new ExecuteWorkflowInvocationHandler()); } else if (type == InvocationType.SIGNAL_WITH_START) { @SuppressWarnings("unchecked") SignalWithStartBatchRequest batch = (SignalWithStartBatchRequest) value; invocationContext.set(new SignalWithStartWorkflowInvocationHandler(batch)); } else { throw new IllegalArgumentException("Unexpected InvocationType: " + type); } } @SuppressWarnings("unchecked") static <R> R getAsyncInvocationResult(Class<R> resultClass) { SpecificInvocationHandler invocation = invocationContext.get(); if (invocation == null) { throw new IllegalStateException("initAsyncInvocation wasn't called"); } return invocation.getResult(resultClass); } /** Closes async invocation created through {@link #initAsyncInvocation(InvocationType)} */ static void closeAsyncInvocation() { invocationContext.remove(); } private final WorkflowStub untyped; private final POJOWorkflowInterfaceMetadata workflowMetadata; WorkflowInvocationHandler( Class<?> workflowInterface, WorkflowClientOptions clientOptions, GenericWorkflowClientExternal genericClient, WorkflowExecution execution) { workflowMetadata = POJOWorkflowInterfaceMetadata.newInstance(workflowInterface); Optional<String> workflowType = workflowMetadata.getWorkflowType(); WorkflowStub stub = new WorkflowStubImpl(clientOptions, genericClient, workflowType, execution); for (WorkflowClientInterceptor i : clientOptions.getInterceptors()) { stub = i.newUntypedWorkflowStub(execution, workflowType, stub); } this.untyped = stub; } WorkflowInvocationHandler( Class<?> workflowInterface, WorkflowClientOptions clientOptions, GenericWorkflowClientExternal genericClient, WorkflowOptions options) { Objects.requireNonNull(options, "options"); workflowMetadata = POJOWorkflowInterfaceMetadata.newInstance(workflowInterface); Optional<POJOWorkflowMethodMetadata> workflowMethodMetadata = workflowMetadata.getWorkflowMethod(); if (!workflowMethodMetadata.isPresent()) { throw new IllegalArgumentException( "Method annotated with @WorkflowMethod is not found in " + workflowInterface); } Method workflowMethod = workflowMethodMetadata.get().getWorkflowMethod(); MethodRetry methodRetry = workflowMethod.getAnnotation(MethodRetry.class); CronSchedule cronSchedule = workflowMethod.getAnnotation(CronSchedule.class); WorkflowOptions mergedOptions = WorkflowOptions.merge(methodRetry, cronSchedule, options); String workflowType = workflowMethodMetadata.get().getName(); WorkflowStub stub = new WorkflowStubImpl(clientOptions, genericClient, workflowType, mergedOptions); for (WorkflowClientInterceptor i : clientOptions.getInterceptors()) { stub = i.newUntypedWorkflowStub(workflowType, mergedOptions, stub); } this.untyped = stub; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (method.equals(Object.class.getMethod("toString"))) { // TODO: workflow info return "WorkflowInvocationHandler"; } } catch (NoSuchMethodException e) { throw new Error("unexpected", e); } // Implement StubMarker if (method.getName().equals(StubMarker.GET_UNTYPED_STUB_METHOD)) { return untyped; } if (!method.getDeclaringClass().isInterface()) { throw new IllegalArgumentException( "Interface type is expected: " + method.getDeclaringClass()); } SpecificInvocationHandler handler = invocationContext.get(); if (handler == null) { handler = new SyncWorkflowInvocationHandler(); } handler.invoke(this.workflowMetadata, untyped, method, args); if (handler.getInvocationType() == InvocationType.SYNC) { return handler.getResult(method.getReturnType()); } return Defaults.defaultValue(method.getReturnType()); } private static void startWorkflow(WorkflowStub untyped, Object[] args) { Optional<WorkflowOptions> options = untyped.getOptions(); if (untyped.getExecution() == null || (options.isPresent() && options.get().getWorkflowIdReusePolicy() == WorkflowIdReusePolicy.AllowDuplicate)) { try { untyped.start(args); } catch (DuplicateWorkflowException e) { // We do allow duplicated calls if policy is not AllowDuplicate. Semantic is to wait for // result. if (options.isPresent() && options.get().getWorkflowIdReusePolicy() == WorkflowIdReusePolicy.AllowDuplicate) { throw e; } } } } static void checkAnnotations( Method method, WorkflowMethod workflowMethod, QueryMethod queryMethod, SignalMethod signalMethod) { int count = (workflowMethod == null ? 0 : 1) + (queryMethod == null ? 0 : 1) + (signalMethod == null ? 0 : 1); if (count > 1) { throw new IllegalArgumentException( method + " must contain at most one annotation " + "from @WorkflowMethod, @QueryMethod or @SignalMethod"); } } private static class StartWorkflowInvocationHandler implements SpecificInvocationHandler { private Object result; @Override public InvocationType getInvocationType() { return InvocationType.START; } @Override public void invoke( POJOWorkflowInterfaceMetadata workflowMetadata, WorkflowStub untyped, Method method, Object[] args) { WorkflowMethod workflowMethod = method.getAnnotation(WorkflowMethod.class); if (workflowMethod == null) { throw new IllegalArgumentException( "WorkflowClient.start can be called only on a method annotated with @WorkflowMethod"); } result = untyped.start(args); } @Override @SuppressWarnings("unchecked") public <R> R getResult(Class<R> resultClass) { return (R) result; } } private static class SyncWorkflowInvocationHandler implements SpecificInvocationHandler { private Object result; @Override public InvocationType getInvocationType() { return InvocationType.SYNC; } @Override public void invoke( POJOWorkflowInterfaceMetadata workflowMetadata, WorkflowStub untyped, Method method, Object[] args) { POJOWorkflowMethodMetadata methodMetadata = workflowMetadata.getMethodMetadata(method); WorkflowMethodType type = methodMetadata.getType(); if (type == WorkflowMethodType.WORKFLOW) { result = startWorkflow(untyped, method, args); } else if (type == WorkflowMethodType.QUERY) { result = queryWorkflow(methodMetadata, untyped, method, args); } else if (type == WorkflowMethodType.SIGNAL) { signalWorkflow(methodMetadata, untyped, method, args); result = null; } else { throw new IllegalArgumentException( method + " is not annotated with @WorkflowMethod or @QueryMethod"); } } @Override @SuppressWarnings("unchecked") public <R> R getResult(Class<R> resultClass) { return (R) result; } private void signalWorkflow( POJOWorkflowMethodMetadata methodMetadata, WorkflowStub untyped, Method method, Object[] args) { if (method.getReturnType() != Void.TYPE) { throw new IllegalArgumentException("Signal method must have void return type: " + method); } String signalName = methodMetadata.getName(); untyped.signal(signalName, args); } private Object queryWorkflow( POJOWorkflowMethodMetadata methodMetadata, WorkflowStub untyped, Method method, Object[] args) { if (method.getReturnType() == Void.TYPE) { throw new IllegalArgumentException("Query method cannot have void return type: " + method); } String queryType = methodMetadata.getName(); return untyped.query(queryType, method.getReturnType(), method.getGenericReturnType(), args); } @SuppressWarnings("FutureReturnValueIgnored") private Object startWorkflow(WorkflowStub untyped, Method method, Object[] args) { WorkflowInvocationHandler.startWorkflow(untyped, args); return untyped.getResult(method.getReturnType(), method.getGenericReturnType()); } } private static class ExecuteWorkflowInvocationHandler implements SpecificInvocationHandler { private Object result; @Override public InvocationType getInvocationType() { return InvocationType.EXECUTE; } @Override public void invoke( POJOWorkflowInterfaceMetadata workflowMetadata, WorkflowStub untyped, Method method, Object[] args) { WorkflowMethod workflowMethod = method.getAnnotation(WorkflowMethod.class); if (workflowMethod == null) { throw new IllegalArgumentException( "WorkflowClient.execute can be called only on a method annotated with @WorkflowMethod"); } WorkflowInvocationHandler.startWorkflow(untyped, args); result = untyped.getResultAsync(method.getReturnType(), method.getGenericReturnType()); } @Override @SuppressWarnings("unchecked") public <R> R getResult(Class<R> resultClass) { return (R) result; } } private static class SignalWithStartWorkflowInvocationHandler implements SpecificInvocationHandler { private final SignalWithStartBatchRequest batch; public SignalWithStartWorkflowInvocationHandler(SignalWithStartBatchRequest batch) { this.batch = batch; } @Override public InvocationType getInvocationType() { return InvocationType.SIGNAL_WITH_START; } @Override public void invoke( POJOWorkflowInterfaceMetadata workflowMetadata, WorkflowStub untyped, Method method, Object[] args) { POJOWorkflowMethodMetadata methodMetadata = workflowMetadata.getMethodMetadata(method); switch (methodMetadata.getType()) { case QUERY: throw new IllegalArgumentException( "SignalWithStart batch doesn't accept methods annotated with @QueryMethod"); case WORKFLOW: batch.start(untyped, args); break; case SIGNAL: batch.signal(untyped, methodMetadata.getName(), args); break; } } @Override public <R> R getResult(Class<R> resultClass) { throw new IllegalStateException("No result is expected"); } } }
package org.hzero.feign.interceptor; import javax.annotation.PostConstruct; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext; import feign.RequestTemplate; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.jwt.JwtHelper; import org.springframework.security.jwt.crypto.sign.MacSigner; import org.springframework.security.jwt.crypto.sign.Signer; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; import io.choerodon.core.oauth.CustomUserDetails; import io.choerodon.core.oauth.DetailsHelper; import org.hzero.core.properties.CoreProperties; import org.hzero.core.variable.RequestVariableHolder; /** * 拦截feign请求,为requestTemplate加上oauth token请求头 * * @author bojiangzhou 2019/08/22 */ public class JwtRequestInterceptor implements FeignRequestInterceptor { private static final Logger LOGGER = LoggerFactory.getLogger(JwtRequestInterceptor.class); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String OAUTH_TOKEN_PREFIX = "Bearer "; private Signer signer; private CoreProperties coreProperties; public JwtRequestInterceptor(CoreProperties coreProperties) { this.coreProperties = coreProperties; } @PostConstruct private void init() { signer = new MacSigner(coreProperties.getOauthJwtKey()); } @Override public int getOrder() { return -1000; } @Override public void apply(RequestTemplate template) { String token = null; try { if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication.getDetails() instanceof OAuth2AuthenticationDetails) { OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails(); if (StringUtils.isNoneBlank(details.getTokenType(), details.getTokenValue())) { token = details.getTokenType() + " " + details.getTokenValue(); } else if (details.getDecodedDetails() instanceof CustomUserDetails) { token = OAUTH_TOKEN_PREFIX + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(details.getDecodedDetails()), signer).getEncoded(); } } else if (authentication.getPrincipal() instanceof CustomUserDetails) { token = OAUTH_TOKEN_PREFIX + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(authentication.getPrincipal()), signer).getEncoded(); } } if (token == null) { LOGGER.debug("Feign request set Header Jwt_Token, no member token found, use AnonymousUser default."); token = OAUTH_TOKEN_PREFIX + JwtHelper.encode(OBJECT_MAPPER.writeValueAsString(DetailsHelper.getAnonymousDetails()), signer).getEncoded(); } } catch(Exception e){ LOGGER.error("generate jwt token failed {}", e.getMessage()); } template.header(RequestVariableHolder.HEADER_JWT, token); setLabel(template); } private void setLabel(RequestTemplate template) { if (HystrixRequestContext.isCurrentThreadInitialized()) { String label = RequestVariableHolder.LABEL.get(); if (label != null) { template.header(RequestVariableHolder.HEADER_LABEL, label); } } } }
def add(self, path, value): if len(path) == 0: raise ValueError() if len(path) == 1: self.root = Node(path[0], value) return if self.root is None: self.root = Node(path[0]) self.root.add_leaf(path, value)
// Delete func remove client from client pool func (p *Pool) Delete(id string) (uuid.UUID, error) { p.mu.RLock() defer p.mu.RUnlock() exists, index := p.IsExists(id) if !exists { return uuid.Nil, errors.New("invalid id") } p.IDs = append(p.IDs[:index], p.IDs[index+1:]...) return uuid.FromStringOrNil(id), nil }
/** * Simple tests to check the method for factorial calculation. * * @author Tomislav Bozuric */ public class FactorialTest { @Test public void calculateFactorialOfSmallPositiveNumber() { Assert.assertEquals(120L, Factorial.calculateFactorial(5)); } @Test public void calculateFactorialOfBiggerPositiveNumber() { Assert.assertEquals(1307674368000L, Factorial.calculateFactorial(15)); } @Test(expected = IllegalArgumentException.class) public void calculateFactorialOfNegativeNumber() { Factorial.calculateFactorial(-5); } @Test public void calculateFactorialOfZero() { Assert.assertEquals(1, Factorial.calculateFactorial(0)); } @Test(expected = IllegalArgumentException.class) public void calculateFactorialOfBigNumber() { Factorial.calculateFactorial(40); } }
def run(self, **args): arguments = PexoArguments(args) command = "{} pexo.R {}".format(self.Rscript, str(arguments)) self._print("Running PEXO with:\n$ " + "".join(command) + "\n") code_dir = os.path.join(self.pexodir, "code") if self.verbose: rc = call(command, cwd=code_dir, shell=True) else: with open(os.devnull, "w") as FNULL: rc = call(command, cwd=code_dir, shell=True, stdout=FNULL, stderr=FNULL) if rc != 0: errormessage = "Underlying PEXO code return non-zero exit status {}.".format(rc) raise ChildProcessError(errormessage) self._print("Done.") if arguments.mode == "fit": output = FitOutput(arguments.out) else: output = EmulationOutput(arguments.out) arguments.clear_temp() return output
The security services are facing questions over the cover-up of a Westminster paedophile ring as it emerged that files relating to official requests for media blackouts in the early 1980s were destroyed. Two newspaper executives have told the Observer that their publications were issued with D-notices – warnings not to publish intelligence that might damage national security – when they sought to report on allegations of a powerful group of men engaging in child sex abuse in 1984. One executive said he had been accosted in his office by 15 uniformed and two non-uniformed police over a dossier on Westminster paedophiles passed to him by the former Labour cabinet minister Barbara Castle. The other said that his newspaper had received a D-notice when a reporter sought to write about a police investigation into Elm Guest House, in southwest London, where a group of high-profile paedophiles was said to have operated and may have killed a child. Now it has emerged that these claims are impossible to verify or discount because the D-notice archives for that period “are not complete”. Officials running the D-notice system, which works closely with MI5 and MI6 and the Ministry of Defence, said that files “going back beyond 20 years are not complete because files are reviewed and correspondence of a routine nature with no historical significance destroyed”. The spokesman added: “I cannot believe that past D-notice secretaries would have countenanced the destruction of any key documents. I can only repeat that while any attempted cover-up of this incident might have been attributed to a D-notice the truth would be that it was not.” Theresa May, home secretary, this month told the Commons that an official review into whether there had been a cover-up of the Home Office’s handling of child-abuse allegations in the 1980s had returned a verdict of “not proven”. The review, by Peter Wanless, the chief executive of the National Society for the Prevention of Cruelty to Children, was prompted by the discovery that 114 Home Office files related to child abuse in the 1980s had gone missing. On Saturday night the Labour MP for Rochdale, Simon Danczuk, whose book Smile for the Camera exposed the child sex abuse of the late Liberal MP Cyril Smith, said it was a matter of deep concern that D-notice correspondence had also disappeared, presumed destroyed. D-notices to media outlets are rare, with just five sent in 2009 and 10 in 2010, according to a freedom of information response from Air Vice-Marshal Andrew Vallance, secretary of the defence, press and broadcasting advisory committee, which oversees the system. Danczuk said: “There are clearly questions to be answered as to why these documents were destroyed. They issue very few of them – where was the need to destroy correspondence? “It feels like just another example of key documents from that period going missing. We need to know more about what has happened. The journalists who have said that D-notices were issued are respected people with no reason to lie.” The two journalists, Don Hale, the former editor of the Bury Messenger, and Hilton Tims, news editor of the Surrey Comet between 1980 and 1988, both recall their publications being issued with D-notices around 1984. Tims, a veteran of the Daily Mail and BBC, where he was head of publicity for the launch of colour TV, said that his chief reporter had informed him that a D-notice had been issued to him after he tried to report on a police investigation into events at Elm Guest House, where Smith is said to have been a regular visitor. Tims, 82, said: “One of the reporters on routine calls to the police learned that there was something going down at the guest house in Barnes. It was paedophilia, although that wasn’t the fashionable phrase at the time, it was ‘knocking up young boys’, or something like that. “The reporter was told that there were a number of high-profile people involved and they were getting boys from a care home in the Richmond area. So I put someone on to it, the chief reporter I think, to make inquiries. It was the following day that we had a D-notice slapped on us; the reporter came over and told me. It was the only time in my career.” Hale, who was awarded an OBE for his successful campaign to overturn the murder conviction of Stephen Downing, a victim of one of the longest-known miscarriages of justice, said he was issued with a D-notice when editor of the Bury Messenger. He had been given a file by Castle, by then an MEP, which had details of a Home Office investigation into allegations made by the Tory MP Geoffrey Dickens of the existence of a Westminster paedophile ring. The files contained the name of 16 MPs said to be involved and another 40 who were supportive of the goals of the Paedophile Information Exchange, which sought to reduce the age of consent. Hale said he asked the Home Office for guidance on the dossier and the progress of the investigation but was stonewalled. Hale said: “Then shortly after Cyril Smith bullied his way into my office. I thought he was going to punch me. He was sweating and aggressive and wanted to take the files away, saying it was a load of nonsense and that Barbara Castle just had a bee in her bonnet about homosexuals. I refused to give him the files. “The very next day two non-uniformed officers, about 15 uniformed officers and another non-uniformed person, who didn’t introduce himself, came to the office waving a D-notice and said that I would be damaging national security if I reported on the file.” A spokesman for the D-notice system said: “If Don Hale was ‘served’ with anything purporting to be a ‘D-notice’, it was quite obviously a fabrication.”
def creationTimestamp(self, creationTimestamp): self._creationTimestamp = creationTimestamp
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "PerformanceMark.h" #include "MainThreadUtils.h" #include "nsContentUtils.h" #include "Performance.h" #include "mozilla/dom/MessagePortBinding.h" #include "mozilla/dom/PerformanceBinding.h" #include "mozilla/dom/PerformanceMarkBinding.h" using namespace mozilla::dom; PerformanceMark::PerformanceMark(nsISupports* aParent, const nsAString& aName, DOMHighResTimeStamp aStartTime, const JS::Handle<JS::Value>& aDetail, DOMHighResTimeStamp aUnclampedStartTime) : PerformanceEntry(aParent, aName, u"mark"_ns), mStartTime(aStartTime), mDetail(aDetail), mUnclampedStartTime(aUnclampedStartTime) { mozilla::HoldJSObjects(this); } already_AddRefed<PerformanceMark> PerformanceMark::Constructor( const GlobalObject& aGlobal, const nsAString& aMarkName, const PerformanceMarkOptions& aMarkOptions, ErrorResult& aRv) { const nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports()); return PerformanceMark::Constructor(aGlobal.Context(), global, aMarkName, aMarkOptions, aRv); } already_AddRefed<PerformanceMark> PerformanceMark::Constructor( JSContext* aCx, nsIGlobalObject* aGlobal, const nsAString& aMarkName, const PerformanceMarkOptions& aMarkOptions, ErrorResult& aRv) { RefPtr<Performance> performance = Performance::Get(aCx, aGlobal); if (!performance) { // This is similar to the message that occurs when accessing `performance` // from outside a valid global. aRv.ThrowTypeError( "can't access PerformanceMark constructor, performance is null"); return nullptr; } if (performance->IsGlobalObjectWindow() && performance->IsPerformanceTimingAttribute(aMarkName)) { aRv.ThrowSyntaxError("markName cannot be a performance timing attribute"); return nullptr; } DOMHighResTimeStamp startTime = aMarkOptions.mStartTime.WasPassed() ? aMarkOptions.mStartTime.Value() : performance->Now(); // We need to get the unclamped start time to be able to add profiler markers // with precise time/duration. This is not exposed to web and only used by the // profiler. // If a mStartTime is passed by the user, we will always have a clamped value. DOMHighResTimeStamp unclampedStartTime = aMarkOptions.mStartTime.WasPassed() ? startTime : performance->NowUnclamped(); if (startTime < 0) { aRv.ThrowTypeError("Expected startTime >= 0"); return nullptr; } JS::Rooted<JS::Value> detail(aCx); if (aMarkOptions.mDetail.isNullOrUndefined()) { detail.setNull(); } else { StructuredSerializeOptions serializeOptions; JS::Rooted<JS::Value> valueToClone(aCx, aMarkOptions.mDetail); nsContentUtils::StructuredClone(aCx, aGlobal, valueToClone, serializeOptions, &detail, aRv); if (aRv.Failed()) { return nullptr; } } return do_AddRef(new PerformanceMark(aGlobal, aMarkName, startTime, detail, unclampedStartTime)); } PerformanceMark::~PerformanceMark() { mozilla::DropJSObjects(this); } NS_IMPL_CYCLE_COLLECTION_CLASS(PerformanceMark) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(PerformanceMark, PerformanceEntry) tmp->mDetail.setUndefined(); mozilla::DropJSObjects(tmp); NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(PerformanceMark, PerformanceEntry) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(PerformanceMark, PerformanceEntry) NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mDetail) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_IMPL_ISUPPORTS_CYCLE_COLLECTION_INHERITED_0(PerformanceMark, PerformanceEntry) JSObject* PerformanceMark::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) { return PerformanceMark_Binding::Wrap(aCx, this, aGivenProto); } void PerformanceMark::GetDetail(JSContext* aCx, JS::MutableHandle<JS::Value> aRetval) { // Return a copy so that this method always returns the value it is set to // (i.e. it'll return the same value even if the caller assigns to it). Note // that if detail is an object, its contents can be mutated and this is // expected. aRetval.set(mDetail); } size_t PerformanceMark::SizeOfIncludingThis( mozilla::MallocSizeOf aMallocSizeOf) const { return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); }
<gh_stars>0 use super::super::domain::money::MoneyHolder; use super::super::usecase::create::{CreateInputData, CreateOutputData}; use super::super::usecase::delete::{DeleteInputData, DeleteOutputData}; use super::super::usecase::get::{GetInputData, GetOutputData}; use super::methodtype::{CreateMethod, DeleteMethod, GetMethod, Method}; use super::service::walletgrpc::{ CreateRequest, CreateResponse, DeleteRequest, DeleteResponse, GetRequest, GetResponse, Wallet, }; pub trait Converter<M: Method> { type Req: std::fmt::Debug; type Res: std::fmt::Debug; type InputData; type OutputData; fn decode(req: &Self::Req) -> Self::InputData; fn encode(out: Self::OutputData) -> Self::Res; } pub struct ConverterImpl<M: Method> { _phantom: std::marker::PhantomData<M>, } impl Converter<CreateMethod> for ConverterImpl<CreateMethod> { type Req = CreateRequest; type Res = CreateResponse; type InputData = CreateInputData; type OutputData = CreateOutputData; fn decode(_: &CreateRequest) -> CreateInputData { CreateInputData {} } fn encode(out: CreateOutputData) -> CreateResponse { let w = out.wallet; CreateResponse { wallet: Some(Wallet { id: w.id.to_string(), deposit: w.amount(), currency: w.currency().to_string(), }), } } } impl Converter<GetMethod> for ConverterImpl<GetMethod> { type Req = GetRequest; type Res = GetResponse; type InputData = GetInputData; type OutputData = GetOutputData; fn decode(req: &GetRequest) -> GetInputData { GetInputData { id: req.id.clone() } } fn encode(out: GetOutputData) -> GetResponse { let w = out.wallet; GetResponse { wallet: Some(Wallet { id: w.id.to_string(), deposit: w.amount(), currency: w.currency().to_string(), }), } } } impl Converter<DeleteMethod> for ConverterImpl<DeleteMethod> { type Req = DeleteRequest; type Res = DeleteResponse; type InputData = DeleteInputData; type OutputData = DeleteOutputData; fn decode(req: &DeleteRequest) -> DeleteInputData { DeleteInputData { id: req.id.clone() } } fn encode(_: DeleteOutputData) -> DeleteResponse { DeleteResponse {} } }
def can_convert(fromext: str, toext: str): good = (".nii", ".nii.gz", ".nrrd",) return (HAS_SITK or HAS_ITK) and fromext.lower() in good and toext.lower() in good
// GetActorTypeEnumStringValues Enumerates the set of values in String for ActorTypeEnum func GetActorTypeEnumStringValues() []string { return []string{ "CLOUD_GUARD_SERVICE", "CORRELATION", "RESPONDER", "USER", } }
/** * getGameHighScores * Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects. * <p> * This method will currently return scores for the target user, plus two of his closest neighbors on each side. Will also return the top three users if the user and his neighbors are not among them. Please note that this behavior is subject to change. */ @NoArgsConstructor @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class GetGameHighScores implements MethodObject { /** * Target user id */ @JsonProperty(value = "user_id", required = true) private Integer userId; /** * Required if inline_message_id is not specified. Unique identifier for the target chat */ @JsonProperty(value = "chat_id", required = false) private Integer chatId; /** * Required if inline_message_id is not specified. Identifier of the sent message */ @JsonProperty(value = "message_id", required = false) private Integer messageId; /** * Required if chat_id and message_id are not specified. Identifier of the inline message */ @JsonProperty(value = "inline_message_id", required = false) private String inlineMessageId; public static GetGameHighScores create() { return new GetGameHighScores(); } @Override @JsonIgnore public String getPathMethod() { return "getGameHighScores"; } public GetGameHighScores userId(Integer userId) { this.userId = userId; return this; } public GetGameHighScores chatId(Integer chatId) { this.chatId = chatId; return this; } public GetGameHighScores messageId(Integer messageId) { this.messageId = messageId; return this; } public GetGameHighScores inlineMessageId(String inlineMessageId) { this.inlineMessageId = inlineMessageId; return this; } }
<reponame>fossabot/cpace package cpace import ( "bytes" "fmt" "github.com/bytemare/cryptotools/encoding" ) func ExampleCPace() { serverID := []byte("server") username := []byte("client") password := []byte("password") var ad []byte = nil clientParams := &Parameters{ ID: username, PeerID: serverID, Secret: password, SID: nil, AD: ad, Encoding: encoding.Gob, } // Set up the initiator, let's call it the client client, err := Client(clientParams, nil) if err != nil { panic(err) } // Start the protocol. // message1 must then be sent to the responder message1, err := client.Authenticate(nil) if err != nil { panic(err) } serverParams := &Parameters{ ID: serverID, PeerID: username, Secret: password, SID: nil, AD: ad, Encoding: encoding.Gob, } // Set up the responder, let's call it the server server, err := Server(serverParams, nil) if err != nil { panic(err) } // Handle the initiator's message, and send back message2. At this point the session key can already be derived. message2, err := server.Authenticate(message1) if err != nil { panic(err) } // Give the initiator the responder's answer. Since we're in implicit authentication, no message comes out here. // After this, the initiator can derive the session key. _, err = client.Authenticate(message2) if err != nil { panic(err) } // The protocol is finished, and both parties now share the same secret session key if bytes.Equal(client.SessionKey(), server.SessionKey()) { fmt.Println("Success ! Both parties share the same secret session key !") } else { fmt.Println("Failed. Client and server keys are different.") } // Output: Success ! Both parties share the same secret session key ! }
/** * @author : liaozikai * file : Test2.java */ public class Test2 { public static void main(String[] args) { /** * 第一次配置(eden 2 = from 1 + to 1) * 特殊说明:from和to的空间大小一般是一样的,并且设置from和to的原因是由于新生代可能采用 复制 算法来进行垃圾回收, * 故而需要保留一个空闲空间作为有效对象复制后进行存放 * 从日志可看出,space存放的内容大小比值中,eden:from为2:1 */ // -Xms20m -Xmx20m -Xmn1m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC // 第二次配置 // -Xms20m -Xmx20m -Xmn7m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC /** * 第三次配置 * -XX:NewRatio=老年代/新生代 * -Xms20m -Xmx20m -XX:NewRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC * 从日志可以看出,total中老年代/新生代为 2:1 */ byte[] b = null; // 连续向系统申请10MB空间 for (int i = 0; i < 10; i++) { b = new byte[1 * 1024 * 1024]; } } }
/** * Launch nagbar to indicate errors in the configuration file. */ void start_config_error_nagbar(const char *configpath, bool has_errors) { char *editaction, *pageraction; sasprintf(&editaction, "i3-sensible-editor \"%s\" && i3-msg reload\n", configpath); sasprintf(&pageraction, "i3-sensible-pager \"%s\"\n", errorfilename); char *argv[] = { NULL, "-f", (config.font.pattern ? config.font.pattern : "fixed"), "-t", (has_errors ? "error" : "warning"), "-m", (has_errors ? "You have an error in your i3 config file!" : "Your config is outdated. Please fix the warnings to make sure everything works."), "-b", "edit config", editaction, (errorfilename ? "-b" : NULL), (has_errors ? "show errors" : "show warnings"), pageraction, NULL}; start_nagbar(&config_error_nagbar_pid, argv); free(editaction); free(pageraction); }
/* * Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version. */ #include "ReviveFromCorpseAction.h" #include "Event.h" #include "FleeManager.h" #include "GameGraveyard.h" #include "MapMgr.h" #include "Playerbots.h" #include "PlayerbotFactory.h" #include "ServerFacade.h" bool ReviveFromCorpseAction::Execute(Event event) { Player* master = botAI->GetGroupMaster(); Corpse* corpse = bot->GetCorpse(); // follow master when master revives WorldPacket& p = event.getPacket(); if (!p.empty() && p.GetOpcode() == CMSG_RECLAIM_CORPSE && master && !corpse && bot->IsAlive()) { if (sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "master target"), sPlayerbotAIConfig->farDistance)) { if (!botAI->HasStrategy("follow", BOT_STATE_NON_COMBAT)) { botAI->TellMasterNoFacing("Welcome back!"); botAI->ChangeStrategy("+follow,-stay", BOT_STATE_NON_COMBAT); return true; } } } if (!corpse) return false; if (corpse->GetGhostTime() + bot->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP) > time(nullptr)) return false; if (master) { if (!GET_PLAYERBOT_AI(master) && master->isDead() && master->GetCorpse() && sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "master target"), sPlayerbotAIConfig->farDistance)) return false; } if (!botAI->HasRealPlayerMaster()) { uint32 dCount = AI_VALUE(uint32, "death count"); if (dCount >= 5) { return botAI->DoSpecificAction("spirit healer"); } } LOG_INFO("playerbots", "Bot {} {}:{} <{}> revives at body", bot->GetGUID().ToString().c_str(), bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->getLevel(), bot->GetName().c_str()); bot->GetMotionMaster()->Clear(); bot->StopMoving(); WorldPacket packet(CMSG_RECLAIM_CORPSE); packet << bot->GetGUID(); bot->GetSession()->HandleReclaimCorpseOpcode(packet); return true; } bool FindCorpseAction::Execute(Event event) { if (bot->InBattleground()) return false; Player* master = botAI->GetGroupMaster(); Corpse* corpse = bot->GetCorpse(); if (!corpse) return false; if (master) { if (!GET_PLAYERBOT_AI(master) && sServerFacade->IsDistanceLessThan(AI_VALUE2(float, "distance", "master target"), sPlayerbotAIConfig->farDistance)) return false; } uint32 dCount = AI_VALUE(uint32, "death count"); if (!botAI->HasRealPlayerMaster()) { if (dCount >= 5) { LOG_INFO("playerbots", "Bot {} {}:{} <{}>: died too many times and was sent to an inn", bot->GetGUID().ToString().c_str(), bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->getLevel(), bot->GetName().c_str()); context->GetValue<uint32>("death count")->Set(0); sRandomPlayerbotMgr->RandomTeleportForRpg(bot); return true; } } WorldPosition botPos(bot); WorldPosition corpsePos(corpse); WorldPosition moveToPos = corpsePos; WorldPosition masterPos(master); float reclaimDist = CORPSE_RECLAIM_RADIUS - 5.0f; float corpseDist = botPos.distance(corpsePos); int64 deadTime = time(nullptr) - corpse->GetGhostTime(); bool moveToMaster = master && master != bot && masterPos.fDist(corpsePos) < reclaimDist; //Should we ressurect? If so, return false. if (corpseDist < reclaimDist) { if (moveToMaster) //We are near master. { if (botPos.fDist(masterPos) < sPlayerbotAIConfig->spellDistance) return false; } else if (deadTime > 8 * MINUTE) //We have walked too long already. return false; else { GuidVector units = AI_VALUE(GuidVector, "possible targets no los"); if (botPos.getUnitsAggro(units, bot) == 0) //There are no mobs near. return false; } } // If we are getting close move to a save ressurrection spot instead of just the corpse. if (corpseDist < sPlayerbotAIConfig->reactDistance) { if (moveToMaster) moveToPos = masterPos; else { FleeManager manager(bot, reclaimDist, 0.0, urand(0, 1), moveToPos); if (manager.isUseful()) { float rx, ry, rz; if (manager.CalculateDestination(&rx, &ry, &rz)) moveToPos = WorldPosition(moveToPos.getMapId(), rx, ry, rz, 0.0); else if (!moveToPos.GetReachableRandomPointOnGround(bot, reclaimDist, urand(0, 1))) moveToPos = corpsePos; } } } //Actual mobing part. bool moved = false; if (!botAI->AllowActivity(ALL_ACTIVITY)) { uint32 delay = sServerFacade->GetDistance2d(bot, corpse) / bot->GetSpeed(MOVE_RUN); //Time a bot would take to travel to it's corpse. delay = std::min(delay, uint32(10 * MINUTE)); //Cap time to get to corpse at 10 minutes. if (deadTime > delay) { bot->GetMotionMaster()->Clear(); bot->TeleportTo(moveToPos.getMapId(), moveToPos.getX(), moveToPos.getY(), moveToPos.getZ(), 0); } moved = true; } else { if (bot->isMoving()) moved = true; else { if (deadTime < 10 * MINUTE && dCount < 5) // Look for corpse up to 30 minutes. { moved = MoveTo(moveToPos.getMapId(), moveToPos.getX(), moveToPos.getY(), moveToPos.getZ(), false, false); } if (!moved) { moved = botAI->DoSpecificAction("spirit healer"); } } } return moved; } bool FindCorpseAction::isUseful() { if (bot->InBattleground()) return false; return bot->GetCorpse(); } GraveyardStruct const* SpiritHealerAction::GetGrave(bool startZone) { GraveyardStruct const* ClosestGrave = nullptr; GraveyardStruct const* NewGrave = nullptr; ClosestGrave = sGraveyard->GetClosestGraveyard(bot, bot->GetTeamId()); if (!startZone && ClosestGrave) return ClosestGrave; if (botAI->HasStrategy("follow", BOT_STATE_NON_COMBAT) && botAI->GetGroupMaster() && botAI->GetGroupMaster() != bot) { Player* master = botAI->GetGroupMaster(); if (master && master != bot) { ClosestGrave = sGraveyard->GetClosestGraveyard(master, bot->GetTeamId()); if (ClosestGrave) return ClosestGrave; } } else if(startZone && AI_VALUE(uint8, "durability")) { TravelTarget* travelTarget = AI_VALUE(TravelTarget*, "travel target"); if (travelTarget->getPosition()) { WorldPosition travelPos = *travelTarget->getPosition(); if (travelPos.GetMapId() != uint32(-1)) { uint32 areaId = 0; uint32 zoneId = 0; sMapMgr->GetZoneAndAreaId(bot->GetPhaseMask(), zoneId, areaId, travelPos.getMapId(), travelPos.getX(), travelPos.getY(), travelPos.getZ()); ClosestGrave = sGraveyard->GetClosestGraveyard(travelPos.getMapId(), travelPos.getX(), travelPos.getY(), travelPos.getZ(), bot->GetTeamId(), areaId, zoneId, bot->getClass() == CLASS_DEATH_KNIGHT); if (ClosestGrave) return ClosestGrave; } } } std::vector<uint32> races; if (bot->GetTeamId() == TEAM_ALLIANCE) races = { RACE_HUMAN, RACE_DWARF, RACE_GNOME, RACE_NIGHTELF }; else races = { RACE_ORC, RACE_TROLL, RACE_TAUREN, RACE_UNDEAD_PLAYER }; float graveDistance = -1; WorldPosition botPos(bot); for (auto race : races) { for (uint32 cls = 0; cls < MAX_CLASSES; cls++) { PlayerInfo const* info = sObjectMgr->GetPlayerInfo(race, cls); if (!info) continue; uint32 areaId = 0; uint32 zoneId = 0; sMapMgr->GetZoneAndAreaId(bot->GetPhaseMask(), zoneId, areaId, info->mapId, info->positionX, info->positionY, info->positionZ); NewGrave = sGraveyard->GetClosestGraveyard(info->mapId, info->positionX, info->positionY, info->positionZ, bot->GetTeamId(), areaId, zoneId, cls == CLASS_DEATH_KNIGHT); if (!NewGrave) continue; WorldPosition gravePos(NewGrave->Map, NewGrave->x, NewGrave->y, NewGrave->z); float newDist = botPos.fDist(gravePos); if (graveDistance < 0 || newDist < graveDistance) { ClosestGrave = NewGrave; graveDistance = newDist; } } } return ClosestGrave; } bool SpiritHealerAction::Execute(Event event) { Corpse* corpse = bot->GetCorpse(); if (!corpse) { botAI->TellError("I am not a spirit"); return false; } uint32 dCount = AI_VALUE(uint32, "death count"); int64 deadTime = time(nullptr) - corpse->GetGhostTime(); GraveyardStruct const* ClosestGrave = GetGrave(dCount > 10 || deadTime > 15 * MINUTE || AI_VALUE(uint8, "durability") < 10); if (bot->GetDistance2d(ClosestGrave->x, ClosestGrave->y) < sPlayerbotAIConfig->sightDistance) { GuidVector npcs = AI_VALUE(GuidVector, "nearest npcs"); for (GuidVector::iterator i = npcs.begin(); i != npcs.end(); i++) { Unit* unit = botAI->GetUnit(*i); if (unit && unit->HasFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPIRITHEALER)) { LOG_INFO("playerbots", "Bot {} {}:{} <{}> revives at spirit healer", bot->GetGUID().ToString().c_str(), bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->getLevel(), bot->GetName()); PlayerbotChatHandler ch(bot); bot->ResurrectPlayer(0.5f); bot->SpawnCorpseBones(); bot->SaveToDB(false, false); context->GetValue<Unit*>("current target")->Set(nullptr); bot->SetTarget(); botAI->TellMaster("Hello"); if (dCount > 20) context->GetValue<uint32>("death count")->Set(0); return true; } } } if (!ClosestGrave) { return false; } bool moved = false; if (bot->IsWithinLOS(ClosestGrave->x, ClosestGrave->y, ClosestGrave->z)) moved = MoveNear(ClosestGrave->Map, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, 0.0); else moved = MoveTo(ClosestGrave->Map, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, false, false); if (moved) return true; if (!botAI->HasActivePlayerMaster()) { context->GetValue<uint32>("death count")->Set(dCount + 1); return bot->TeleportTo(ClosestGrave->Map, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, 0.f); } LOG_INFO("playerbots", "Bot {} {}:{} <{}> can't find a spirit healer", bot->GetGUID().ToString().c_str(), bot->GetTeamId() == TEAM_ALLIANCE ? "A" : "H", bot->getLevel(), bot->GetName().c_str()); botAI->TellError("Cannot find any spirit healer nearby"); return false; } bool SpiritHealerAction::isUseful() { return bot->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST); }
<gh_stars>1-10 package main import( "fmt" "net/http" "io/ioutil" "encoding/json" "strings" ) func main() { resp, err := http.Get("https://freegeoip.net/json/www.netdungeon.com") if err != nil { fmt.Println(err) } defer resp.Body.Close() // Read response body in to string body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) } //fmt.Printf("Body is of type %T\n%v\n%s", body, body, body) // Create a map of strings to the raw json messages var objmap map[string]*json.RawMessage err = json.Unmarshal(body, &objmap) if err != nil { fmt.Println(err) } fmt.Println(string(*objmap["city"])) // The above is OK, but it prints the city with quotes "Houston" // We COULD use strings.Trim() to trim the quotes fmt.Println(strings.Trim(string(*objmap["city"]), "\"")) // But it would be better to properly Unmarshal the data to a var var city string err = json.Unmarshal(*objmap["city"], &city) if err != nil { fmt.Println(err) } fmt.Println(city) // Prints a nice clean string with no quotes }
<reponame>haibbo/go-exercises package KBYEB const { KB = 1000 MB = KB*1000 GB = MB*1000 TB = GB*1000 PB = TB*1000 RB = PB*1000 ZB = PB*1000 YB = ZB*1000 }
// Deletes the user attributes in a user pool as an administrator. Works on // any user. func (c *CognitoIdentityProvider) AdminDeleteUserAttributes(input *AdminDeleteUserAttributesInput) (*AdminDeleteUserAttributesOutput, error) { req, out := c.AdminDeleteUserAttributesRequest(input) err := req.Send() return out, err }
Do journalists need to learn computer code? It's a question which has raised passionate debate in the US – with typically polarised responses. As yet in the UK it elicits little more than bemused curiosity. But it's an increasingly important question as media adapts to the volatile requirements of digital technology and changing consumer expectations. It's about more than data journalism, although that certainly sits at the heart of the issue. New digital platforms and applications offer new means of illustrating and disseminating information – but should technical development simply be the province of technologists or should modern journalists take an active role in shaping these new opportunities? Last year, the Atlantic stirred the debate with an article by Olga Khazan, its health correspondent, arguing that young journalists should concentrate on internships and freelancing to win a first job and leave coding to the technologists. The concern was that learning coding would be a distraction from core journalism skills. In one sense she's right. Not every journalist should know, or needs to learn, how a website works. But protecting the routines of the past at the expense of adapting to the future is seldom a good idea. The US has always taken journalism education more seriously than the UK, and many of those who responded to the Atlantic saw the future of news media as depending on young journalists being taught how to understand and lead digital development. In the US several university courses combine journalism and computer science skills – here there are just two, one at Goldsmiths in London and, from September, a new cross-disciplinary course at Cardiff University. Industry increasingly recognises the need to recruit graduates with both computer science and journalism skills. As online and mobile more clearly become the future of media, recruits are needed who can combine editorial judgment and sensibility with a technical understanding of what's possible. They also require a more entrepreneurial mindset in new graduates who will be developing the digital services on which major media brands will rest in future. It's a new area of expertise which is opening up – and a major source of creative energy. In the US, journalists are spinning out their expertise into new enterprises such as Vox, which seeks to provide context to the news, or Nate Silver's data-led FiveThirtyEight. Less innovation is visible in Britain – but major players such as the BBC, the Financial Times, and of course the Guardian have planted their flags in an online future. Groups such as Trinity Mirror are investing in data innovation with sites such as UsVsTh3m and Ammp3d. In doing so they too need technologists who understand journalism, and journalists who understand technology. There's nothing new in that. Each generation of journalists has to absorb new skills. Today's trainees are able to shoot and edit video, before that it was adapting from typewriters to computers. Tomorrow, familiarity with HTML, JavaScript or Python will be a career advantage. In a sector which is undergoing rapid and turbulent adaptation more skills can only be an advantage. However, it's more fundamental than future-proofing skills. The media sector, defined in the UK in economic development terms as part of the "creative industries", is enjoying a period of rapid growth relative to other sectors. Creative industries account for 6% of UK GDP and achieve a higher value of exports than any sectors other than financial services and advanced manufacturing. Beyond the UK, a number of other countries have attached high priority to the growth of creative industries, including emerging major economies such as China and India. If the UK is to continue to be recognised as a world leader in media – with key players in demand by global firms – it has to develop a cadre of graduates with the cross-disciplinary skills that are shaping the industry. Beyond even that, journalism has much to learn from the disciplines of computer and data science. In a world awash with opinion there is an emerging premium on evidence-led journalism and the expertise required to properly gather, analyse and present data that informs rather than simply offers a personal view. The empirical approach of science offers a new grounding for journalism at a time when trust is at a premium. Not every journalism student or mid-career professional seeking to protect their future should turn to coding. It's not a binary question. But some understanding of what technology development entails will be increasingly important. And the digital innovation, on which the UK's strong and admired media sector depends, requires this new and expanding area of expertise to be embraced. Richard Sambrook is professor of journalism at Cardiff University
/** * This class handles the states of sidebars. * It gives default sidebars on every player join * and removes any type of sidebar on every player * quit. * * This avoids useless calculation for the server. * * @author pxav */ @Singleton public class SidebarStateListener { private SidebarRepository sidebarRepository; @Inject public SidebarStateListener(SidebarRepository sidebarRepository) { this.sidebarRepository = sidebarRepository; } /** * This event is triggered when a player joins the server. * In this case it gives the player the default sidebar, * if there has been defined one (with 'setOnJoin' to true * in the {@code @CreateSidebar} annotation). * * @param event Instance of the current event. */ @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); // if a scoreboard has 'setOnJoin' set to true, it will be shown to the player if (!sidebarRepository.getDefaultScoreboard().equalsIgnoreCase("NONE")) { sidebarRepository.openSidebar(sidebarRepository.getDefaultScoreboard(), player); } } /** * This event is triggered when a player quits the server. * In this case it removes the sidebar for every player so * that the server does not do useless updates on their * sidebar. * * @param event Instance of the current event. */ @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { Player player = event.getPlayer(); sidebarRepository.removeSidebar(player); } }
#include <libyuv.h> #include "rotate.h" using namespace libyuv; using namespace libyuv::jniutil; extern "C" { // Rotate I420 frame. PLANES_3_TO_3_R(I420Rotate, y, u, v, y, u, v); // Rotate I444 frame. PLANES_3_TO_3_R(I444Rotate, y, u, v, y, u, v); // Rotate NV12 input and store in I420. PLANES_2_TO_3_R(NV12ToI420Rotate, y, uv, y, u ,v); // Convert Android420 to I420 with rotation. "rotation" can be 0, 90, 180 or 270. PLANES_4_TO_3_R(Android420ToI420Rotate, y, u, v, uv, y, u, v); // Rotate a plane by 0, 90, 180, or 270. PLANES_1_TO_1_R(RotatePlane, p, p); // Rotate UV and split into planar. // width and height expected to be half size for NV12 PLANES_1_TO_2_R(SplitRotateUV, uv, u, v); // The 90 and 270 functions are based on transposes. Deprecated PLANES_1_TO_1_V(TransposePlane, p, p); PLANES_1_TO_2_V(SplitTransposeUV, p, a, b); static int rotateNV12RotateInternal( const uint8_t *src_y, int src_stride_y, const uint8_t *src_uv, int src_stride_uv, uint8_t *dst_y, const int dst_stride_y, uint8_t *dst_uv, const int dst_stride_uv, uint8_t *plane_u, uint8_t *plane_v, const int width, const int height, const int half_width, const int half_height, const int mode) { switch (mode) { case kRotate90: RotatePlane90(src_y, src_stride_y, dst_y, dst_stride_y, width, height); SplitRotateUV90(src_uv, src_stride_uv, plane_u, half_height, plane_v, half_height, half_width, half_height); MergeUVPlane(plane_u, half_height, plane_v, half_height, dst_uv, dst_stride_uv, half_height, half_width); break; case kRotate270: RotatePlane270(src_y, src_stride_y, dst_y, dst_stride_y, width, height); SplitRotateUV270(src_uv, src_stride_uv, plane_u, half_height, plane_v, half_height, half_width, half_height); MergeUVPlane(plane_u, half_height, plane_v, half_height, dst_uv, dst_stride_uv, half_height, half_width); break; case kRotate180: RotatePlane180(src_y, src_stride_y, dst_y, dst_stride_y, width, height); SplitRotateUV180(src_uv, src_stride_uv, plane_u, half_width, plane_v, half_width, half_width, half_height); MergeUVPlane(plane_u, half_width, plane_v, half_width, dst_uv, dst_stride_uv, half_width, half_height); break; default: break; } return 0; } JNI_DEFINE_METHOD(void, rotateNV12Rotate, const jobject j_src_y, const jint j_src_stride_y, jobject j_src_uv, const jint j_src_stride_uv, jobject j_dst_y, const jint j_dst_stride_y, jobject j_dst_uv, const jint j_dst_stride_uv, const jint width, jint height, const jint mode) { SRC_PLANE(y); SRC_PLANE(uv); DST_PLANE(y); DST_PLANE(uv); if (width <= 0 || height == 0) { return; } if (mode == kRotate0) { // copy frame CopyPlane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); CopyPlane(src_uv, src_stride_uv, dst_uv, dst_stride_uv, width, height); return; } int halfwidth = (width + 1) >> 1; int halfheight = (height + 1) >> 1; // Negative height means invert the image. if (height < 0) { height = -height; halfheight = (height + 1) >> 1; src_y = src_y + (height - 1) * src_stride_y; src_uv = src_uv + (halfheight - 1) * src_stride_uv; src_stride_y = -src_stride_y; src_stride_uv = -src_stride_uv; } // Allocate u and v buffers align_buffer_64(plane_u, halfwidth * halfheight * 2); uint8_t* plane_v = plane_u + halfwidth * halfheight; rotateNV12RotateInternal(src_y, src_stride_y, src_uv, src_stride_uv, dst_y, dst_stride_y, dst_uv, dst_stride_uv, plane_u, plane_v, width, height, halfwidth, halfheight, mode); free_aligned_buffer_64(plane_u); } JNI_DEFINE_METHOD(void, rotateNV21Rotate, const jobject j_src_y, const jint j_src_stride_y, const jobject j_src_vu, const jint j_src_stride_vu, jobject j_dst_y, const jint j_dst_stride_y, jobject j_dst_vu, const jint j_dst_stride_vu, const jint width, jint height, const jint mode) { SRC_PLANE(y); SRC_PLANE(vu); DST_PLANE(y); DST_PLANE(vu); if (width <= 0 || height == 0) { return; } if (mode == kRotate0) { // copy frame CopyPlane(src_y, src_stride_y, dst_y, dst_stride_y, width, height); CopyPlane(src_vu, src_stride_vu, dst_vu, dst_stride_vu, width, height); return; } int halfwidth = (width + 1) >> 1; int halfheight = (height + 1) >> 1; // Negative height means invert the image. if (height < 0) { height = -height; halfheight = (height + 1) >> 1; src_y = src_y + (height - 1) * src_stride_y; src_vu = src_vu + (halfheight - 1) * src_stride_vu; src_stride_y = -src_stride_y; src_stride_vu = -src_stride_vu; } // Allocate v and u buffers align_buffer_64(plane_v, halfwidth * halfheight * 2); uint8_t* plane_u = plane_v + halfwidth * halfheight; rotateNV12RotateInternal(src_y, src_stride_y, src_vu, src_stride_vu, dst_y, dst_stride_y, dst_vu, dst_stride_vu, plane_v, plane_u, width, height, halfwidth, halfheight, mode); free_aligned_buffer_64(plane_v); } }
/** * Created with IntelliJ IDEA. * User: ? * Date: 12/6/12 * Time: 6:18 PM * To change this template use File | Settings | File Templates. */ public class ISSNFunction implements Function { private DocstoreClientLocator docstoreClientLocator; private static final Logger LOG = Logger.getLogger(ISSNFunction.class); @Override public Object invoke(Object... arguments) { DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE); String existingDocstoreField = (String)(arguments[0]); String issn = (String)(arguments[1]); LOG.info(" ------------------> issn ------------------> " + issn); if(issn != null) { boolean normalizedISSN = false; try { ISSNUtil validIssn = new ISSNUtil(issn); normalizedISSN = validIssn.hasCorrectChecksum(); } catch (Exception e) { e.printStackTrace(); } List list = new ArrayList(); if(normalizedISSN) { //list = getDiscoveryHelperService().getResponseFromSOLR(existingDocstoreField, issn); // List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(); SearchParams searchParams=new SearchParams(); searchParams.getSearchConditions().add(searchParams.buildSearchCondition("", searchParams.buildSearchField(DocType.BIB.getCode(),"ISSN",issn), "AND")); searchParams.getSearchResultFields().add(searchParams.buildSearchResultField("bibliographic", "bibIdentifier")); try { SearchResponse searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams); List<SearchResult> searchResults=searchResponse.getSearchResults(); LOG.info(" ---------------> list.size ------------> " + list.size()); if(searchResults.size() >=1){ LOG.info(" inside if condition of list --------------------> "); for (SearchResult searchResult:searchResults){ HashMap<String, Object> bibMap=new HashMap<>(); for(SearchResultField searchResultField:searchResult.getSearchResultFields()){ if(searchResultField.getFieldValue()!=null && !searchResultField.getFieldValue().isEmpty() && searchResultField.getFieldName().equalsIgnoreCase("bibIdentifier")){ bibMap.put(OLEConstants.BIB_UNIQUE_ID,searchResultField.getFieldValue()); } } list.add(bibMap); } } }catch(Exception ex){ throw new RuntimeException(ex); } } if(list != null && list.size() >= 1){ dataCarrierService.addData(OLEConstants.BIB_INFO_LIST_FROM_SOLR_RESPONSE, list); return true; } } return false; } public DocstoreClientLocator getDocstoreClientLocator() { if (null == docstoreClientLocator) { return SpringContext.getBean(DocstoreClientLocator.class); } return docstoreClientLocator; } public void setDocstoreClientLocator(DocstoreClientLocator docstoreClientLocator) { this.docstoreClientLocator = docstoreClientLocator; } }
<reponame>basnijholt/HASS-data-detective<filename>detective/functions.py """ Helper functions. """ import json import pandas as pd UNKNOWN = "unknown" def get_device_class(attributes: dict): """Return the device class.""" return attributes.get("device_class", UNKNOWN) def get_unit_of_measurement(attributes: dict): """Return the unit_of_measurement.""" return attributes.get("unit_of_measurement", UNKNOWN) def get_friendly_name(attributes: dict): """Return the friendly_name.""" return attributes.get("friendly_name", UNKNOWN) def generate_features(df: pd.DataFrame) -> pd.DataFrame: """Generate features from the attributes.""" df["attributes"] = df["attributes"].apply(json.loads) df["device_class"] = df["attributes"].apply(get_device_class) df["unit_of_measurement"] = df["attributes"].apply(get_unit_of_measurement) df["friendly_name"] = df["attributes"].apply(get_friendly_name) return df def format_dataframe(df: pd.DataFrame) -> pd.DataFrame: """Convert states to numeric where possible and format the last_changed.""" df["state"] = pd.to_numeric(df["state"], errors="coerce") df["last_changed"] = pd.to_datetime( df["last_changed"].values, errors="ignore", utc=True ).tz_localize(None) df = df.dropna() return df
/* * Copyright (C) 2016 <NAME> * * 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 org.granite.base; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.google.common.base.CharMatcher; import java.util.List; import java.util.Map; import org.junit.Test; public class StringToolsTest { @Test public void testIsNullOrEmpty() throws Exception { String test1 = null; String test2 = " "; String test3 = " askjdh"; String test4 = "test "; assertTrue(StringTools.isNullOrEmpty(test1)); assertTrue(StringTools.isNullOrEmpty(test2)); assertFalse(StringTools.isNullOrEmpty(test3)); assertFalse(StringTools.isNullOrEmpty(test4)); } @Test public void testAnyNullOrEmpty() { assertTrue(StringTools.anyNullOrEmpty("test", "", "test2", " ")); assertTrue(StringTools.anyNullOrEmpty("test1", null, "tet")); assertFalse(StringTools.anyNullOrEmpty("test1", "Test2", "test3")); } @Test public void testTruncate() { final String test1 = "hello"; assertEquals("h", StringTools.truncate(test1, 1)); assertEquals("hell", StringTools.truncate(test1, 4)); assertEquals("hello", StringTools.truncate(test1, 900)); } @Test public void testStringToMap() { final String test1 = "k1=v1,k2=v2,k2=,k3=v3,k3=v4,k4=,k5=k4="; final Map<String, String> resultNoEmpty = StringTools.convertStringsToMap( test1, CharMatcher.is(','), CharMatcher.is('='), true ); assertEquals(4, resultNoEmpty.size()); final Map<String, String> resultEmpty = StringTools.convertStringsToMap( test1, CharMatcher.is(','), CharMatcher.is('='), false ); assertEquals(5, resultEmpty.size()); assertEquals("v1", resultNoEmpty.get("k1")); assertEquals("v2", resultNoEmpty.get("k2")); assertEquals("v4", resultNoEmpty.get("k3")); assertEquals("v1", resultEmpty.get("k1")); assertEquals("", resultEmpty.get("k2")); assertEquals("v4", resultEmpty.get("k3")); assertEquals("", resultEmpty.get("k4")); assertEquals("k4=", resultEmpty.get("k5")); } @Test public void testLevenshtein() { assertEquals(4, StringTools.levenshtein("book", "")); assertEquals(2, StringTools.levenshtein("book", "back")); assertEquals(1, StringTools.levenshtein("pins", "pines")); assertEquals(4, StringTools.levenshtein("emit", "time")); assertEquals(8, StringTools.levenshtein("emit", "sauvignon")); } @Test public void testQualifiedSplit() { checkSplits( "\"hello\",world,\"yep\"", new String[]{"hello","world","yep"} ); checkSplits( "\"hello,\",world,\",yep\"", new String[]{"hello,","world",",yep"} ); checkSplits("", new String[]{}); checkSplits(",", new String[]{"",""}); checkSplits("\",\"", new String[]{","}); checkSplits("Y,Y,Y", new String[]{"Y","Y","Y"}); checkSplits( "\"hello\",world,,again,", new String[]{"hello","world","","again",""} ); try { List<String> parts = StringTools .textQualifiedStringSplit( ",\"", CharMatcher.is(','), CharMatcher.is('"'), false); assertTrue(false); } catch (Exception e){ assertTrue(e instanceof IllegalStateException); } } private static void checkSplits(String testLine, String[] expected){ List<String> parts = StringTools .textQualifiedStringSplit( testLine, CharMatcher.is(','), CharMatcher.is('"'), false); assertEquals(expected.length, parts.size()); for(int index = 0; index < expected.length; index++){ assertEquals(expected[index],parts.get(index)); } } @Test public void testContainsAny(){ String test = "the quick brown fox jumped over the lazy dog"; assertTrue(StringTools.containsAny(test, "tree","dog","cat")); assertFalse(StringTools.containsAny(test, "","burger","mouse")); assertFalse(StringTools.containsAny(test, "")); } }
<reponame>jbermudezcabrera/ControlDePacientes<filename>gui/forms/MainWindow.py import os from PyQt4 import uic from PyQt4.QtCore import pyqtSlot from PyQt4.QtGui import QMainWindow from gui.forms.PatientForm import PatientForm from gui.forms.SearchPatientForm import SearchPatientForm __author__ = '<NAME>' class MainWindow(QMainWindow): def __init__(self, *args): super(MainWindow, self).__init__(*args) uic.loadUi(os.path.join('resources', 'uis', 'MainWindow.ui'), self) self.addPatientAction.triggered.connect(self.on_add_patient) self.searchAction.triggered.connect(self.on_search_patient) self.searchAction.trigger() @pyqtSlot() def on_add_patient(self): central = self.centralWidget() if not (isinstance(central, PatientForm) and central.isVisible()): self.setCentralWidget(PatientForm()) @pyqtSlot() def on_search_patient(self): central = self.centralWidget() if not isinstance(central, SearchPatientForm) or not central.isVisible(): self.setCentralWidget(SearchPatientForm())
<gh_stars>0 import {Component, ViewChild} from '@angular/core'; import {IActionMapping, TREE_ACTIONS, TreeComponent, TreeNode} from 'angular-tree-component'; import * as CodeMirror from 'codemirror'; import {ToastyService} from 'ng2-toasty'; import {CodeService, CONTEXT_ALL} from '../code.service'; import {Landmark} from '../landmark'; import {SemanticNodeType, StructuralNodeType, TreeBuilder} from '../tree-builder'; import {UIStateStore} from '../ui-state.service'; import {Utility} from '../utility'; const actionMapping: IActionMapping = { mouse: { dblClick: (tree, node, $event) => { if (node.hasChildren) { TREE_ACTIONS.TOGGLE_EXPANDED(tree, node, $event); } } } }; @Component({ selector: 'app-line-values', templateUrl: 'line-values.component.html', styleUrls: ['line-values.component.css'] }) export class LineValuesComponent { @ViewChild(TreeComponent) tree: TreeComponent; contexts: DescribedContext[]; filteredContexts: DescribedContext[]; lineValueNodes: any[] = []; filteredLineValueNodes: any[] = []; nodeType = StructuralNodeType; currentFile: FileID; currentPosition: CodeMirror.Position; contextFilterQuery: string; private _context: DescribedContext; lineValueKinds: { value: LineValueKind, name: string, checked: boolean }[] = [ {value: 'VARIABLE', name: 'Variable', checked: true}, {value: 'REGISTER', name: 'Register', checked: true}, {value: 'FIXED_PROPERTY', name: 'Fixed property', checked: true}, {value: 'DYNAMIC_PROPERTY', name: 'Dynamic property', checked: true}, {value: 'UNKNOWN', name: 'Unknown', checked: true} ]; treeOptions = { actionMapping, getChildren: (n) => this.getChildren(n), idField: 'uuid', useVirtualScroll: true, nodeHeight: 23 }; constructor(private codeService: CodeService, private uiStateStore: UIStateStore, private toastyService: ToastyService) { this.uiStateStore.file.subscribe((file: FileDescription) => this.currentFile = file.id); this.uiStateStore.context.subscribe((context: DescribedContext) => this.selectedContext = context); this.uiStateStore.cursorPosition.subscribe((position: CodeMirror.Position) => { this.drillAt(position); this.currentPosition = position; }); } set selectedContext(context: DescribedContext) { this._context = context; this.uiStateStore.changeContext(context); this.filterValues(); } get selectedContext(): DescribedContext { return this._context; } drillAt(position: CodeMirror.Position, context?: DescribedContext) { if (!this.currentFile) { return; } const promises = []; promises.push(this.codeService.getContexts(this.currentFile, position.line + 1) .then(cs => this.contexts = this.filteredContexts = cs)); promises.push(this.getLineValuesAsTree(this.currentFile, position.line + 1).then(n => this.lineValueNodes = n)); Promise.all(promises).then(() => { if (this.contexts.length !== 0) { this.selectedContext = (context) ? (this.contexts.find(c => c.id === context.id)) : this.contexts[0]; } }); this.refresh(); } jumpTo(file: FileID, line: number, context: DescribedContext) { this.uiStateStore.addToJumpHistory(new Landmark(this.currentFile, this.currentPosition.line , `lineValue (origin), ${this.selectedContext.rendering}`)); this.uiStateStore.addToJumpHistory(new Landmark(file, line, `lineValue (destination), ${context.rendering}`)); this.uiStateStore.changeFileAndPosition(file, {line: line - 1, ch: 0}); this.selectedContext = context; } filterContextsSemantically(expression: string): void { if (expression.length === 0) { this.filteredContexts = this.contexts; return; } this.codeService.getPositionalLocationID(this.currentFile, this.currentPosition.line + 1, this.currentPosition.ch) .then((opt: Optional<DescribedLocation>) => { if (!opt.value) { this.toastyService.info('No location available at line'); return; } this.codeService.getFilteredContexts(opt.value.id, expression) .then((cts: DescribedContext[]) => this.filteredContexts = cts) .catch(err => { this.filteredContexts = this.contexts; this.toastyService.warning('API failed on filtering query. Recovering contexts.'); console.log(err); }); }); } filterValues() { if (!this.selectedContext) { return; } // Filter by fileID context if (this.selectedContext === CONTEXT_ALL) { this.filteredLineValueNodes = this.lineValueNodes.filter(n => !n.location.hasOwnProperty('context')); } else { this.filteredLineValueNodes = this.lineValueNodes .filter(n => n.location.hasOwnProperty('context') && n.location['context'].id === this.selectedContext.id); } // Filter by fileID kinds const selectedKinds = this.lineValueKinds.filter(k => k.checked).map(k => k.value); this.filteredLineValueNodes = this.filteredLineValueNodes.filter(v => (selectedKinds.indexOf(v.kind) > -1)); } getChildren(node: TreeNode): Promise<TreeNode[]> { const objectID = node.parent.data.id; let res: Promise<any[]>; switch (node.data.nodeTypeChildren) { case SemanticNodeType.Allocation: res = this.codeService.getAllocationLocations(objectID) .then((ls: any[]) => ls.map(l => Object.assign(l, {nodeType: StructuralNodeType.Jump}))); break; case SemanticNodeType.Call: res = this.codeService.getCallLocations(objectID) .then((ls: any[]) => ls.map(l => Object.assign(l, {nodeType: StructuralNodeType.Jump}))); break; case SemanticNodeType.AsyncListener: res = this.codeService.getEventHandlerRegistrationLocations(objectID) .then((ls: any[]) => ls.map(l => Object.assign(l, {nodeType: StructuralNodeType.Jump}))); break; case SemanticNodeType.Property: const location = node.parent.parent.data.location; res = (location && location.id) ? this.codeService.getObjectProperties(objectID, location.id) .then((props: DescribedProperties) => TreeBuilder.getSubtreeForProperties(props)) : Promise.resolve([]); break; default: this.toastyService.error('TREE CHILDREN ERROR: Unimplemented subtree type'); res = Promise.resolve([]); } return res.then((r: any[]) => { if (r.length === 0) { node.data.children = []; node.data.hasChildren = false; this.toastyService.info(`The requested subtree is empty for ${objectID}`); this.tree.treeModel.update(); } return r; }); } jumpToAllocation(objectID: ObjectID, callingNode: TreeNode, valueNo: number): void { this.codeService.getAllocationLocations(objectID) .then((ls: ContextSensitiveDescribedLocation[]) => { if (ls.length === 1) { const loc = ls[0]; this.jumpTo(loc.fileID, loc.range.lineStart, loc.context); } else { TREE_ACTIONS.TOGGLE_EXPANDED(this.tree.treeModel, callingNode, {}); TREE_ACTIONS.TOGGLE_EXPANDED(this.tree.treeModel, callingNode.children[valueNo], {}); TREE_ACTIONS.TOGGLE_EXPANDED(this.tree.treeModel, callingNode.children[valueNo].children[1], {}); if (ls.length > 1) { this.toastyService.info(`More than one allocation location for ${objectID}`); } } }); } private refresh() { if (this.tree) { this.tree.viewportComponent.setViewport(); } } private getLineValuesAsTree(fileID: FileID, line: number): Promise<any[]> { return this.codeService.getLineValues(fileID, line) .then((values: LineValue[]) => Utility.sortLineValues(values)) .then((values: LineValue[]) => values.map((v: LineValue) => Object.assign(v, { nodeType: StructuralNodeType.Identifier, location: v.location, children: v.value.values.map(value => TreeBuilder.getSubtreeForValue(value)) }))); } }
/** * Registers all the available stored procedures, if a * resource can not be loaded from any reason(e.g. SQL syntax * failure) then the resource will be skipped. <br> * This method can be triggered with the : * <i>loadDefaultStoredprocedures</i> (seam event) like in * the next code snippet. * * <pre> * Events.instance().raiseAsynchronousEvent(&quot;loadDefaultStoredprocedures&quot;); * </pre> */ @Observer("loadDefaultStoredprocedures") public void processStoredProcedures() { final List<String> procedureNames = getProcedureNames(); final List<String> procedures = getProcedures(procedureNames); for (final String procedure : procedures) { try { final StoredProcedureWork work = new StoredProcedureWork(procedure); hibernateJDBCService.execute(work); } catch (final Exception e) { log.debug("Stored procedure #0 can not be processed.", procedure); log.warn(e.getMessage(), e); } } log.debug("Stored procedures #0 are succesfull processed.", procedures); }
Euclid NISP GWA and compensating mechanism This paper presents the GWA and the Compensating mechanism of the Near Infrared SpectroPhotometer (NISP) instrument of the ESA Euclid mission. The NIS instrument should perform an exposure sequence in the wave length range
/** * Base class for application settings. * * Provide theme, language and recent file limit settings. * Override createUserSettings() to add more. */ class Settings : public QSettings { Q_DECLARE_TR_FUNCTIONS(Settings) using user_settings_t = std::unique_ptr<SettingItem>; using user_settings_terator_pair_t = std::pair<std::list<Settings::user_settings_t>::const_iterator, std::list<Settings::user_settings_t>::const_iterator>; public: Settings(); ~Settings() override; QByteArray windowGeometry(); void putWindowGeometry(const QByteArray& geometry); bool hasRecentFiles(); QStringList recentFiles(); int recentFilesLimit(); void putRecentFile(const QString& path); void clearRecentFiles(); void setRecentFilesLimit(int value); user_settings_terator_pair_t items(); void initDefaults(); void saveUserSettings(); void readUserSettings(); QString style(); QByteArray windowState(); void putWindowState(const QByteArray& state); QString language(); void loadTranslation(const QString& language, QTranslator* translator); virtual void retranslateUi(); static QString key(const QString& sectionTag, const QString& key); protected: std::list<user_settings_t> _items = std::list<user_settings_t>(); void createBasicSettings(); virtual void createUserSettings(){}; virtual QString userSectionTag(); void addUserSetting(SettingItem* pItem); void addUserSettingFirst(SettingItem* pItem); virtual int recentFilesDefault(); private: static QString path(); inline static QString themeKey(); inline static QString languageKey(); inline static QString windowGeometryKey(); inline static QString windowStateKey(); inline static QString recentFilesKey(); inline static QString recentFilesLimitKey(); static inline QString fileKey(); virtual QLatin1String translationsDirectory(); static QString systemLanguage(); std::map<QString, QVariant> availableLanguages(); static const std::map<QString, QString> KNOWN_LANGUAGE; bool tryingToLoadTranslation(QTranslator* translator, const QLocale& locale, QLatin1String filename, const QString& successMessage, const QString& failMessage); }
/* Read data from socket or input file as appropriate. */ static svn_error_t *readbuf_input(svn_ra_svn_conn_t *conn, char *data, apr_size_t *len, apr_pool_t *pool) { svn_ra_svn__session_baton_t *session = conn->session; if (session && session->callbacks && session->callbacks->cancel_func) SVN_ERR((session->callbacks->cancel_func)(session->callbacks_baton)); SVN_ERR(check_io_limits(conn)); SVN_ERR(svn_ra_svn__stream_read(conn->stream, data, len)); if (*len == 0) return svn_error_create(SVN_ERR_RA_SVN_CONNECTION_CLOSED, NULL, NULL); conn->current_in += *len; if (session) { const svn_ra_callbacks2_t *cb = session->callbacks; session->bytes_read += *len; if (cb && cb->progress_func) (cb->progress_func)(session->bytes_read + session->bytes_written, -1, cb->progress_baton, pool); } return SVN_NO_ERROR; }
def group_reactons(d_user): group = d_user.create_group(d_user.u1, user_outpeers=[d_user.outpeer1, d_user.outpeer5], group_type=GROUPTYPE_GROUP, with_shortname=True) msg = d_user.send(d_user.u1, target_outpeer=OutPeer(id=group.group.id, access_hash=group.group.access_hash, type=2)) d_user.dialog_difference(d_user.u1) yield group, msg
package org.iglooproject.wicket.more.markup.html.form.observer.impl; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.util.Collection; import org.apache.wicket.Component; import org.apache.wicket.MetaDataKey; import org.apache.wicket.ajax.AjaxEventBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxAttributeName; import org.apache.wicket.ajax.attributes.AjaxCallListener; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes.Method; import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.html.form.CheckBoxMultipleChoice; import org.apache.wicket.markup.html.form.CheckGroup; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponent; import org.apache.wicket.markup.html.form.RadioChoice; import org.apache.wicket.markup.html.form.RadioGroup; import org.iglooproject.wicket.more.markup.html.form.observer.IFormComponentChangeObservable; import org.iglooproject.wicket.more.markup.html.form.observer.IFormComponentChangeObserver; import org.wicketstuff.wiquery.core.events.MouseEvent; import org.wicketstuff.wiquery.core.events.StateEvent; import org.wicketstuff.wiquery.core.javascript.JsStatement; import org.wicketstuff.wiquery.core.javascript.JsUtils; import com.github.openjson.JSONException; import com.github.openjson.JSONObject; import com.google.common.collect.Sets; /** * A behavior for notifying observers when changes occur on a given {@link FormComponent}. * * <p>This behavior differs from {@link AjaxFormComponentUpdatingBehavior} and * {@link AjaxFormChoiceComponentUpdatingBehavior} in that:<ul> * <li>It's more low-level: it does not presume of the actions to be executed on change. Only * {@link FormComponent#inputChanged()} is called on change, the calls to {@link FormComponent#validate()}, * {@link FormComponent#valid()}, {@link FormComponent#updateModel()}, and so on being the responsibility of the * observers (if they want to). * <li>It supports both choice and non-choice components * <li>It supports choice components whose markup ID was not rendered (it relies on the form's markup ID). This allows * using <code>radioGroup.setRenderBodyOnly(true)</code>, in particular. * <li>It supports binding multiple, independent observers to the same {@link FormComponent}, in which case only * one Ajax call will be made for all the observers. * </ul> */ public class FormComponentChangeAjaxEventBehavior extends AjaxEventBehavior implements IFormComponentChangeObservable { private static final long serialVersionUID = -2099510409333557398L; public static IFormComponentChangeObservable get(FormComponent<?> component) { FormComponentChangeAjaxEventBehavior ajaxEventBehavior = getExisting(component); if (ajaxEventBehavior == null) { ajaxEventBehavior = new FormComponentChangeAjaxEventBehavior((FormComponent<?>)component); component.add(ajaxEventBehavior); } return ajaxEventBehavior; } public static FormComponentChangeAjaxEventBehavior getExisting(Component component) { Collection<FormComponentChangeAjaxEventBehavior> ajaxEventBehaviors = component.getBehaviors(FormComponentChangeAjaxEventBehavior.class); if (ajaxEventBehaviors.isEmpty()) { return null; } else if (ajaxEventBehaviors.size() > 1) { throw new IllegalStateException("There should not be more than ONE FormComponentChangeAjaxEventBehavior attached to " + component); } else { return ajaxEventBehaviors.iterator().next(); } } private static final MetaDataKey<Boolean> IS_SUBMITTED_USING_THIS_BEHAVIOR = new MetaDataKey<Boolean>() { private static final long serialVersionUID = 1L; }; private final Collection<IFormComponentChangeObserver> observers = Sets.newHashSet(); private final FormComponent<?> prerequisiteField; private final boolean choice; private FormComponentChangeAjaxEventBehavior(FormComponent<?> prerequisiteField) { this(prerequisiteField, isChoice(prerequisiteField)); } private FormComponentChangeAjaxEventBehavior(FormComponent<?> prerequisiteField, boolean choice) { super(choice ? MouseEvent.CLICK.getEventLabel() /* Internet Explorer... */ : StateEvent.CHANGE.getEventLabel()); this.prerequisiteField = checkNotNull(prerequisiteField); this.choice = choice; } private static boolean isChoice(Component component) { return (component instanceof RadioChoice) || (component instanceof CheckBoxMultipleChoice) || (component instanceof RadioGroup) || (component instanceof CheckGroup); } @Override protected void onBind() { super.onBind(); Component component = getComponent(); checkState(prerequisiteField.equals(component), "This behavior can only be attached to the component passed to its constructor (%s)", prerequisiteField); if (choice) { component.setRenderBodyOnly(false); } } protected FormComponent<?> getFormComponent() { return (FormComponent<?>)getComponent(); } /* Due to the fact that, for choice components, events are attached to the form and not to the component itself, * we must remove the handlers on ajax refreshes. * Thus we need a unique event name, so that we can call $('#formId').off('click.my.unique.namespace') */ protected String getUniqueEventName() { return getEvent() + ".formComponentChange." + getComponent().getMarkupId(); } @Override protected CharSequence getCallbackScript(Component component) { if (choice) { /* Due to the fact that, for choice components, events are attached to the form and not to the component itself, * we must remove the handlers on ajax refreshes. * See also: getUniqueEventName(), updateAjaxAttributes(), postprocessConfiguration() */ return new StringBuilder() .append(new JsStatement().$(component.findParent(Form.class)).chain("off", JsUtils.quotes(getUniqueEventName(), true)).render(true)) .append(super.getCallbackScript(component)); } else { return super.getCallbackScript(component); } } @Override protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { super.updateAjaxAttributes(attributes); attributes.setMethod(Method.POST); /* Allows all sort of things to work properly: * * allows clicks on labels to work properly * * makes the radio/check buttons properly change their visual aspect on IE. */ attributes.setPreventDefault(false); if (choice) { // For explanations, see: getUniqueEventName(), getCallbackScript(), postprocessConfiguration() attributes.setEventNames(getUniqueEventName()); // Copied from AjaxFormChoiceComponentUpdatingBehavior attributes.setSerializeRecursively(true); attributes.getAjaxCallListeners().add(new AjaxCallListener() { private static final long serialVersionUID = 1L; @Override public CharSequence getPrecondition(Component component) { return String.format("return attrs.event.target.name === '%s'", getFormComponent().getInputName()); } }); } } @Override protected void postprocessConfiguration(JSONObject attributesJson, Component component) throws JSONException { super.postprocessConfiguration(attributesJson, component); if (choice) { /* RadioGroups *may* not have an ID in the resulting HTML, so we must attach the handler to each * input with the correct name in the same form. * See also: getUniqueEventName(), getCallbackScript(), updateAjaxAttributes() */ attributesJson.put(AjaxAttributeName.MARKUP_ID.jsonName(), component.findParent(Form.class).getMarkupId()); attributesJson.put(AjaxAttributeName.CHILD_SELECTOR.jsonName(), "input[name=\"" + ((FormComponent<?>)component).getInputName() + "\"]"); } } @Override public boolean isEnabled(Component component) { return super.isEnabled(component) && !observers.isEmpty(); } @Override protected void onEvent(AjaxRequestTarget target) { getComponent().setMetaData(IS_SUBMITTED_USING_THIS_BEHAVIOR, true); getFormComponent().inputChanged(); notify(target); } @Override public void detach(Component component) { super.detach(component); component.setMetaData(IS_SUBMITTED_USING_THIS_BEHAVIOR, null); } @Override public void subscribe(IFormComponentChangeObserver observer) { observers.add(observer); } @Override public void unsubscribe(IFormComponentChangeObserver observer) { observers.remove(observer); } @Override public boolean isBeingSubmitted() { Boolean submitted = getComponent().getMetaData(IS_SUBMITTED_USING_THIS_BEHAVIOR); return submitted != null && submitted; } @Override public void notify(AjaxRequestTarget target) { for (IFormComponentChangeObserver observer : observers) { observer.onChange(target); } } }
import { Component, OnInit, ViewChild, NgZone } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, last } from 'rxjs/operators'; import { NgxSpinnerService } from 'ngx-spinner'; import { notifyService } from 'src/app/services/snotify'; import { NgxSmartModalService } from 'ngx-smart-modal'; import * as RootReducer from "../../../app.reducers" import { NguiMapComponent } from '@ngui/map'; import { AgmCoreModule, MapsAPILoader } from "@agm/core"; import { Store } from '@ngrx/store'; import * as moment from 'moment'; declare let google: any; import {DomSanitizer} from '@angular/platform-browser'; import { ngxCsv } from 'ngx-csv/ngx-csv'; @Component({ selector: 'app-reports', templateUrl: './reports.component.html', styleUrls: ['./reports.component.css'] }) export class ReportsComponent implements OnInit { reports = [] hid from to dname_holder completed_drives = []; mapOptions_driveview = { gestureHandling: "greedy", streetViewControl: false, fullscreenControl: false, clickableIcons: false, mapTypeControl: false, zoom: 4, center: new google.maps.LatLng(26.5,50.3), tilt: 60 }; drivePoints = [] map_driveview trip_polyline bounds_drive log_holder = [] @ViewChild(NguiMapComponent, { static: true }) nguiMapComponent: NguiMapComponent; constructor(private sanitizer:DomSanitizer, public ngxSmartModalService: NgxSmartModalService, public http: HttpClient, public spinner: NgxSpinnerService,public notify: notifyService,public rootstore: Store<RootReducer.State>) { this.rootstore .select(state => state.common.user) .subscribe(userObj => { if(userObj){ this.hid = userObj['hid']; } }); this.to = moment().format('YYYY-MM-DD'); this.from = moment().subtract(7,'d').format('YYYY-MM-DD'); } sanitize(url:string){ return this.sanitizer.bypassSecurityTrustUrl('mailto:' + url); } ngOnInit(): void { this.getData(); } onMapReadyDriveView(map){ this.map_driveview = map; } downnloadcsv(){ let reps = JSON.parse(JSON.stringify(this.reports)); new ngxCsv(reps.map(e => { e['Driver Name'] = e['dname']; e['Driver Email'] = e['demail']; e['Total Distance Covered (Km)'] = e['total_distance']; e['Total Time Taken'] = e['total_time']; delete e['aadid']; delete e['dname']; delete e['demail']; delete e['total_distance']; delete e['total_time']; return e; }), 'Drivers Report'); } getData(){ this.spinner.show(); this.http.post('https://drivecraftlab.com/backend_gis/api/reports/get_reports.php',{hid: this.hid, from: moment.utc(this.from+' 00:00:00', 'YYYY-MM-DD HH:mm:ss').tz('Asia/Kuwait').format('YYYY-MM-DD'), to: moment.utc(this.to+' 00:00:00', 'YYYY-MM-DD HH:mm:ss').tz('Asia/Kuwait').format('YYYY-MM-DD')}).pipe(map(data => { if (data['status_code'] === 200) { this.spinner.hide(); this.reports = data['drivers']; }else{ this.spinner.hide(); this.notify.onError("Error", data['message']); } })).subscribe(result => { }); } getCompletedDrives(did){ this.spinner.show(); this.http.post('https://drivecraftlab.com/backend_gis/api/task/get_completed_tasks.php', {did: did}).pipe(map(data => { this.spinner.hide(); if (data['status_code'] === 200) { data['drives'] = data['drives'].map(e => { e.work_log = e.work_log ? JSON.parse(e.work_log) : {}; return e; }); this.completed_drives = data['drives'].reverse(); }else{ this.notify.onError("Error", data['message']); } })).subscribe(result => { }); } getFormatted1(time){ return moment.utc(time, 'YYYY-MM-DD HH:mm:ss').tz('Asia/Kuwait').format('hh:mm A'); } getFormatted2(time){ return moment.utc(time, 'YYYYMMDDHHmmss').tz('Asia/Kuwait').format('DD/MM/YYYY hh:mm A'); } clearDrive(){ this.drivePoints = []; if (this.trip_polyline) { this.trip_polyline.setMap(null); } } viewDrive(data, flag){ this.clearDrive(); this.bounds_drive = new google.maps.LatLngBounds(); Object.keys(data).forEach((key,i) => { this.bounds_drive.extend( new google.maps.LatLng(data[key]['lat'], data[key]['lng']) ); if(i == 0){ if(data[key]['vehicle']){ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'] }); }else{ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'], icon: 'dotstart.png' }); } var lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 }; this.trip_polyline = new google.maps.Polyline({ strokeColor: "#008E7C", strokeOpacity: 0, icons: [{ icon: lineSymbol, offset: '0', repeat: '15px' }], }); var path = this.trip_polyline.getPath(); path.push(new google.maps.LatLng(data[key]['lat'],data[key]['lng'])); }else if(Object.keys(data).length-1 == i){ if(data[key]['vehicle']){ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'] }); }else{ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'], icon: 'dotend.png' }); } var path = this.trip_polyline.getPath(); path.push(new google.maps.LatLng(data[key]['lat'],data[key]['lng'])); }else{ if(data[key]['vehicle']){ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'] }); }else{ this.drivePoints.push({ position: [ data[key]['lat'], data[key]['lng'] ], message: data[key]['message'], phone: data[key]['phone'], icon: 'dotmid.png' }); } var path = this.trip_polyline.getPath(); path.push(new google.maps.LatLng(data[key]['lat'],data[key]['lng'])); } }) this.trip_polyline.setMap(this.map_driveview); this.map_driveview.fitBounds(this.bounds_drive); } }
<reponame>cnSchwarzer/BUpload // // Created by cnsch on 2021/3/25. // #ifndef BILIBILIUP_BUP_H #define BILIBILIUP_BUP_H #include <string> #include <memory> #include <vector> #include <filesystem> #include <cpr/cpr.h> //No longer go through Fiddler, fork this repo, create your own vcpkg registry and comment the line below if you want. #undef USE_FIDDLER_PROXY #ifdef USE_FIDDLER_PROXY #define CPR_FIDDLER_PROXY\ ,\ cpr::Proxies{{"https", "http://127.0.0.1:8888"}, {"http", "http://127.0.0.1:8888"}},\ cpr::VerifySsl{false} #else #define CPR_FIDDLER_PROXY #endif namespace bup { struct Cover final { std::string url; }; struct Video final { std::string filename; std::string title; }; struct Upload final { //自制声明 bool copyright = false; //开启充电面板 open_elec bool openElectricity = false; // 关闭弹幕 bool closeDanmu = false; //关闭评论区 bool closeReply = false; //标题 std::string title; //转载来源 std::string source; //简介 std::string description; //动态 std::string dynamic; //标签,","分割 std::string tag; //类别 tid 17:单机游戏 int typeId = 17; //封面 std::shared_ptr<Cover> cover; //视频 std::vector<std::shared_ptr<Video>> videos; }; struct UploadResult final { bool succeed = false; std::string error; uint64_t av; std::string bv; }; class BUpload final { uint64_t mid; std::string access_key; public: BUpload() = delete; ~BUpload() = default; BUpload(const BUpload&) = delete; BUpload& operator=(const BUpload&) = delete; BUpload(BUpload&&) = delete; BUpload& operator=(BUpload&&) = delete; // 使用Fiddler与Proxifier抓投稿工具获得 BUpload(uint64_t mid, const std::string& access_token); std::shared_ptr<Video> uploadVideo(const std::filesystem::path& path); std::shared_ptr<Cover> uploadCover(const std::filesystem::path& path); UploadResult upload(const Upload& info); UploadResult edit(uint64_t av, const Upload& info); bool isPassedReview(uint64_t av); }; } #endif //BILIBILIUP_BUP_H
<filename>src/tests/gov/nasa/jpf/symbc/BooleanTest.java /* * Copyright (C) 2014, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * Symbolic Pathfinder (jpf-symbc) is 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 gov.nasa.jpf.symbc; public class BooleanTest extends InvokeTest { protected static String PC_x_1_y_0 = "x_1_SYMINT != CONST_0 && y_2_SYMINT == CONST_0"; protected static String PC_x_1_y_1 = "x_1_SYMINT != CONST_0 && y_2_SYMINT != CONST_0"; protected static String PC_x_0_y_0 = "x_1_SYMINT == CONST_0 && y_2_SYMINT == CONST_0"; protected static String PC_x_0_y_1 = "x_1_SYMINT == CONST_0 && y_2_SYMINT != CONST_0"; protected static void testBoolean(boolean x, boolean y) { // Note: "!y" compiles to IFEQ, so it creates a choice generator boolean z = !y; if (x) { assert pcMatches(PC_x_1_y_0) || pcMatches(PC_x_1_y_1) : makePCAssertString("TestBooleanSpecial1.testBoolean1 if (x == true)", "one of\n" + PC_x_1_y_0 + "\nor\n" + PC_x_1_y_1, TestUtils.getPathCondition()); z = y; } else { assert pcMatches(PC_x_0_y_0) || pcMatches(PC_x_0_y_1) : makePCAssertString("TestBooleanSpecial1.testBoolean1 (x == false)", "one of\n" + PC_x_0_y_0 + "\nor\n" + PC_x_0_y_1, TestUtils.getPathCondition()); } if (!z) { assert (pcMatches(PC_x_1_y_0) || pcMatches(PC_x_0_y_1)) : makePCAssertString("TestBooleanSpecial1.testBoolean1 (z == false)", "one of\n" + (PC_x_1_y_0 + " && " + PC_x_0_y_1) + "\n", TestUtils.getPathCondition()); z = true; } else { assert (pcMatches(PC_x_1_y_1) || pcMatches(PC_x_0_y_0)) : makePCAssertString("TestBooleanSpecial1.testBoolean1 (z == true)", "one of\n" + (PC_x_1_y_1 + " && " + PC_x_0_y_0) + "\n", TestUtils.getPathCondition()); } } }
FEATURES AND TRENDS IN THE DEVELOPMENT OF ARTIFICIAL INTELLIGENCE The scale of the tasks being solved has turned AI into a special area of modern science. AI is a branch of science that studies ways to train a computer, robotic technology, or analytical system to think intelligently. The article reveals the essence and concept of artificial intelligence. The main features, problems, trends and prospects of artificial intelligence development are analyzed.
The maniacs at East Coast Defender are no stranger to building lustworthy Land Rover Defenders. The Florida-based company has been restoring and restomodding old Landies for years now—in particular, carving out a nice niche for itself dropping LS3 smallblock V-8s usually found under the hood of Chevy Corvettes into the off-roader's boxy nose. The company's latest project, however, takes things a bit further: Not only did East Coast Defender drop a Corvette engine into a Land Rover, the team also outfitted it with a manual gearbox. The build is named 'Project Honey Badger,' presumably after the six-year-old Internet meme and not the compact suppressed firearm designed for American special forces. From the outside, only a true Land Rover buff would be able to distinguish this Honey Badger from any of the other Defender 90s roaming the world; apart from the LED lighting, the only thing that stands out is how new the vehicle looks in spite of its classic status.
MeerTRAP: A pulsar and fast transients survey with MeerKAT Abstract We present a brief overview of MeerTRAP, a real-time, fully commensal survey for pulsars and fast transients with the MeerKAT radio telescope in South Africa. MeerTRAP will combine the excellent sensitivity of MeerKAT with an unprecedented amount of on-sky time in order to significantly extend the parameter space covered by similar, previous or ongoing, surveys with other radio telescopes. Here, we will give a brief overview of the project.
/* * Remove an object from the object map at the end of an HTTP request */ @Override public Object remove(final @NonNull String name) { Map<String, Object> objectMap = this.getCurrentRequestObjects(); return objectMap.remove(name); }
/** * Test <code>DefaultSearchFileAlgorithm</code> * <p> * <table border="1" cellpadding="2" cellspacing="2" style="border-collapse: * collapse" bordercolor="#111111"> * <th width="20%">Method</th> * <th width="40%">Test Case</th> * <th width="40%">Expected</th> * * <tr> * <td>testFindFile</td> * <td>Get a <code>ReportDesign</code> instance, then find another file which * locates in the 'base' folder of the design.</td> * <td>If the file exists in the 'base' folder, returns the absolute path of * this file. If not, returns null.</td> * </tr> * * </table> * */ public class DefaultSearchFileAlgorithmTest extends BaseTestCase { public static Test suite(){ return new TestSuite(DefaultSearchFileAlgorithmTest.class); } public DefaultSearchFileAlgorithmTest(String name) { super(name); // TODO Auto-generated constructor stub } final static String INPUT = "DefaultSearchFileAlgorithm.xml"; //private final String fileName = "SimpleMasterPageHandleTest.xml"; //$NON-NLS-1$ private ResourceLocatorImpl algorithm; /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp( ) throws Exception { super.setUp( ); removeResource( ); // retrieve input file(s) from tests-model.jar file copyResource_INPUT( INPUT , INPUT ); openDesign( INPUT ); algorithm = new ResourceLocatorImpl( ); } /** * Tests the 'findFile' method of DefaultSearchFileAlgorithm. * * @throws Exception * if the test fails. */ public void testFindFile( ) throws Exception { URL url = algorithm.findResource( designHandle, "1.xml", IResourceLocator.IMAGE ); //$NON-NLS-1$ assertNull( url ); url = algorithm.findResource( designHandle, INPUT, IResourceLocator.IMAGE ); //$NON-NLS-1$ assertNotNull( url ); designHandle.setStringProperty( ReportDesign.BASE_PROP, PLUGIN_PATH+ this.getFullQualifiedClassName( ) + GOLDEN_FOLDER ); url = algorithm.findResource( designHandle, "1.xml", IResourceLocator.IMAGE ); //$NON-NLS-1$ assertNull( url ); } }
<gh_stars>0 // Chariot: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. use crate::media::Renderer; use nalgebra::Vector2; use std::cmp::{Ordering, PartialOrd}; use super::{ShapeKey, ShapeManager}; use crate::types::{Color, Rect}; #[derive(Copy, Clone, Debug)] pub enum RenderCommand { RenderShape(RenderOrder, RenderShapeParams), RenderRect(RenderOrder, RenderRectParams), RenderLine(RenderOrder, RenderLineParams), } impl RenderCommand { pub fn render_all(renderer: &mut Renderer, shape_manager: &mut ShapeManager, commands: &mut Vec<RenderCommand>) { use RenderCommand::*; commands.sort_by(|a, b| a.order().cmp(b.order())); for command in commands { match *command { RenderShape(_, params) => { shape_manager.get(&params.shape_key, renderer) .unwrap() .render_frame(renderer, params.frame_num as usize, &params.position, params.flip_horizontal, params.flip_vertical); } RenderRect(_, params) => { renderer.render_rect(params.rect); } RenderLine(_, params) => { renderer.set_render_color(params.color); renderer.render_line(params.points[0], params.points[1]); } } } } pub fn new_shape(layer: u16, depth: i32, shape_key: ShapeKey, frame_num: u16, position: Vector2<i32>, flip_horizontal: bool, flip_vertical: bool) -> RenderCommand { let order = RenderOrder::new(layer, depth, false); let params = RenderShapeParams::new(shape_key, frame_num, position, flip_horizontal, flip_vertical); RenderCommand::RenderShape(order, params) } pub fn new_line(layer: u16, depth: i32, color: Color, point1: Vector2<i32>, point2: Vector2<i32>) -> RenderCommand { let order = RenderOrder::new(layer, depth, false); let params = RenderLineParams::new(color, point1, point2); RenderCommand::RenderLine(order, params) } pub fn new_debug_rect(layer: u16, depth: i32, rect: Rect) -> RenderCommand { let order = RenderOrder::new(layer, depth, true); let params = RenderRectParams::new(rect); RenderCommand::RenderRect(order, params) } pub fn new_debug_line(layer: u16, depth: i32, color: Color, point1: Vector2<i32>, point2: Vector2<i32>) -> RenderCommand { let order = RenderOrder::new(layer, depth, true); let params = RenderLineParams::new(color, point1, point2); RenderCommand::RenderLine(order, params) } pub fn order(&self) -> &RenderOrder { use RenderCommand::*; match *self { RenderShape(ref order, _) => order, RenderRect(ref order, _) => order, RenderLine(ref order, _) => order, } } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct RenderOrder { pub layer: u16, pub depth: i32, pub debug: bool, } impl RenderOrder { pub fn new(layer: u16, depth: i32, debug: bool) -> RenderOrder { RenderOrder { layer: layer, depth: depth, debug: debug, } } } impl PartialOrd for RenderOrder { fn partial_cmp(&self, other: &RenderOrder) -> Option<Ordering> { match self.layer.cmp(&other.layer) { Ordering::Equal => self.depth.partial_cmp(&other.depth), v @ _ => Some(v), } } } impl Ord for RenderOrder { fn cmp(&self, other: &RenderOrder) -> Ordering { self.partial_cmp(other).unwrap() } } #[derive(Copy, Clone, Debug)] pub struct RenderShapeParams { pub shape_key: ShapeKey, pub frame_num: u16, pub position: Vector2<i32>, pub flip_horizontal: bool, pub flip_vertical: bool, } impl RenderShapeParams { pub fn new(shape_key: ShapeKey, frame_num: u16, position: Vector2<i32>, flip_horizontal: bool, flip_vertical: bool) -> RenderShapeParams { RenderShapeParams { shape_key: shape_key, frame_num: frame_num, position: position, flip_horizontal: flip_horizontal, flip_vertical: flip_vertical, } } } #[derive(Copy, Clone, Debug)] pub struct RenderRectParams { pub rect: Rect, } impl RenderRectParams { pub fn new(rect: Rect) -> RenderRectParams { RenderRectParams { rect: rect } } } #[derive(Copy, Clone, Debug)] pub struct RenderLineParams { pub color: Color, pub points: [Vector2<i32>; 2], } impl RenderLineParams { pub fn new(color: Color, point1: Vector2<i32>, point2: Vector2<i32>) -> RenderLineParams { RenderLineParams { color: color, points: [point1, point2], } } }
#pragma once #include <wge/core/asset.hpp> #include <wge/core/asset_manager.hpp> #include <wge/core/layer.hpp> #include <wge/graphics/tileset.hpp> #include <wge/graphics/texture.hpp> #include <wge/graphics/render_batch_2d.hpp> #include <wge/math/vector.hpp> namespace wge::core { struct tile { math::ivec2 position, uv; }; struct tilemap_info { core::resource_handle<graphics::tileset> tileset; }; struct tile_animation { float timer = 0; math::ivec2 start_frame; std::size_t frame_count; float interval; }; struct tilemap_manipulator { public: tilemap_manipulator(layer& pLayer) : mLayer(&pLayer), mInfo(pLayer.layer_components.get<tilemap_info>()) { if (!mInfo) mInfo = mLayer->layer_components.insert(tilemap_info{}); } object find_tile(math::ivec2 pPosition) { for (auto& [id, tile] : mLayer->each<core::tile>()) if (tile.position == pPosition) return mLayer->get_object(id); return object{}; } void update_animations(float pDelta) { for (auto& [id, animation, tile, quad] : mLayer->each<tile_animation, tile, graphics::quad_vertices>()) { animation.timer += pDelta; } } bool clear_tile(math::ivec2 pPosition) { if (object tile = find_tile(pPosition)) { tile.destroy(); return true; } return false; } bool clear_tile(queue_destruction_flag, math::ivec2 pPosition) { if (object tile = find_tile(pPosition)) { tile.destroy(queue_destruction); return true; } return false; } void set_tileset(core::resource_handle<graphics::tileset> pTileset) { mInfo->tileset = pTileset; } core::resource_handle<graphics::tileset> get_tileset() const { return mInfo->tileset; } math::ivec2 get_tilesize() const { assert(mInfo); assert(mInfo->tileset); return mInfo->tileset->tile_size; } object set_tile(const tile& pTile) { if (object existing = find_tile(pTile.position)) { // Update the uv of an existing tile. auto tile_comp = existing.get_component<tile>(); tile_comp->uv = pTile.uv; auto quad_comp = existing.get_component<graphics::quad_vertices>(); quad_comp->set_uv(get_uvrect(pTile.uv)); return existing; } else { // Create a new object for the tile. object new_tile = mLayer->add_object(); new_tile.add_component(pTile); graphics::quad_vertices quad_verts; quad_verts.set_rect(math::rect(math::vec2(pTile.position), math::vec2(1, 1))); quad_verts.set_uv(get_uvrect(pTile.uv)); new_tile.add_component(quad_verts); new_tile.add_component(graphics::quad_indicies{}); return new_tile; } } object set_tile(math::ivec2 pPosition, math::ivec2 pUV) { return set_tile(tile{ pPosition, pUV }); } void update_tile_uvs() { if (!mInfo->tileset) return; for (auto& [id, tile, quad_verts] : mLayer->each<tile, graphics::quad_vertices>()) quad_verts.set_uv(get_uvrect(tile.uv)); } private: math::rect get_uvrect(math::ivec2 pUV) const { if (mInfo->tileset) { auto tile_uv_size = math::vec2(mInfo->tileset->tile_size) / math::vec2(mInfo->tileset->get_texture().get_size()); return math::rect(math::vec2(pUV) * tile_uv_size, tile_uv_size); } else return math::rect{}; } private: tilemap_info* mInfo; layer* mLayer; }; inline bool is_tilemap_layer(const layer& pLayer) noexcept { return pLayer.layer_components.has<tilemap_info>(); } } // namespace wge::core
//////////////////////////////////////////////////////////////////////////// // Module : cpu.cpp // Created : 01.10.2004 // Modified : 01.10.2004 // Author : <NAME> // Description : CPU namespace //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "cpu.h" #include "ui.h" #include <float.h> CProcessorInfo CPU::processor_info; u64 CPU::cycles_per_second; u64 CPU::cycles_per_rdtsc; float CPU::cycles2seconds; float CPU::cycles2milisec; const u32 RDTSC_TRY_COUNT = 64; IC void detect () { // General CPU processor_infoentification if (!CPU::processor_info.detected()) { ui().log ("Warning : can't detect CPU/FPU."); return; } // Detecting timers and frequency u64 qwStart, qwEnd; u32 dwStart, dwTest; // setting realtime priority SetPriorityClass (GetCurrentProcess(),REALTIME_PRIORITY_CLASS); SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); Sleep(1); // Detecting frequency dwTest = timeGetTime(); do { dwStart = timeGetTime(); } while (dwTest == dwStart); qwStart = CPU::cycles(); for (; timeGetTime() - dwStart < 1000;); qwEnd = CPU::cycles(); CPU::cycles_per_second = qwEnd - qwStart; // Detect Overhead CPU::cycles_per_rdtsc = 0; u64 qwDummy = 0; for (s32 i=0; i<RDTSC_TRY_COUNT; i++) { qwStart = CPU::cycles(); CPU::cycles_per_rdtsc += CPU::cycles() - qwStart - qwDummy; } CPU::cycles_per_rdtsc /= RDTSC_TRY_COUNT; CPU::cycles_per_second -= CPU::cycles_per_rdtsc; // setting normal priority SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_NORMAL); SetPriorityClass (GetCurrentProcess(),NORMAL_PRIORITY_CLASS); _control87 (_PC_64,MCW_PC); _control87 (_RC_CHOP,MCW_RC); f64 a, b; a = 1.0; b = f64(s64(CPU::cycles_per_second)); CPU::cycles2seconds = f32(f64(a/b)); a = 1000.0; b = f64(s64(CPU::cycles_per_second)); CPU::cycles2milisec = f32(f64(a/b)); } void CPU::detect () { string128 features = "RDTSC"; ui().log ("Detecting hardware..."); ::detect (); ui().log ("completed\n Detected CPU: %s %s, F%d/M%d/S%d, %d mhz, %d-clk\n", CPU::processor_info.vendor_name(), CPU::processor_info.model_name(), CPU::processor_info.family(), CPU::processor_info.model(), CPU::processor_info.stepping(), u32(CPU::cycles_per_second/s64(1000000)), u32(CPU::cycles_per_rdtsc) ); if (CPU::processor_info.features() & CProcessorInfo::CPU_FEATURE_MMX) strcat (features,", MMX"); if (CPU::processor_info.features() & CProcessorInfo::CPU_FEATURE_3DNOW) strcat (features,", 3DNow!"); if (CPU::processor_info.features() & CProcessorInfo::CPU_FEATURE_SSE) strcat (features,", SSE"); if (CPU::processor_info.features() & CProcessorInfo::CPU_FEATURE_SSE2) strcat (features,", SSE2"); ui().log (" CPU Features: %s\n\n", features); }
salario_mensal = float(input('\033[1;97mDigite o seu salário mensal: ')) gasto_mensal = float(input('Digite em média o seu gasto mensal: \033[m')) salario_anual = salario_mensal * 12 gasto_anual = gasto_mensal * 12 economia_anual = salario_anual - gasto_anual print(f'\033[1;97mO valor economizado ao final do ano será de:R${economia_anual:.2f}\033[m')
package com.icthh.xm.uaa.lep; import com.icthh.xm.commons.config.client.service.TenantConfigService; import com.icthh.xm.commons.lep.commons.CommonsExecutor; import com.icthh.xm.commons.lep.commons.CommonsService; import com.icthh.xm.commons.lep.spring.SpringLepProcessingApplicationListener; import com.icthh.xm.lep.api.ScopedContext; import com.icthh.xm.uaa.repository.kafka.ProfileEventProducer; import com.icthh.xm.uaa.security.CustomizableLepTokenStorage; import com.icthh.xm.uaa.security.oauth2.athorization.code.CustomAuthorizationCodeServices; import com.icthh.xm.uaa.service.AccountService; import com.icthh.xm.uaa.service.LdapService; import com.icthh.xm.uaa.service.TenantPropertiesService; import com.icthh.xm.uaa.service.UserLoginService; import com.icthh.xm.uaa.service.UserService; import com.icthh.xm.uaa.service.mail.MailService; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; import static com.icthh.xm.uaa.lep.XmUaaLepConstants.*; /** * The {@link XmUaaLepProcessingApplicationListener} class. */ @RequiredArgsConstructor public class XmUaaLepProcessingApplicationListener extends SpringLepProcessingApplicationListener { private final MailService mailService; private final UserService userService; private final RestTemplate restTemplate; private final CommonsService commonsService; private final AccountService accountService; private final UserLoginService userLoginService; private final TenantConfigService tenantConfigService; private final ProfileEventProducer profileEventProducer; private final CustomizableLepTokenStorage customizableLepTokenStorage; private final CustomAuthorizationCodeServices customAuthorizationCodeServices; private final LdapService ldapService; private final UserDetailsService userDetailsService; private final TenantPropertiesService tenantPropertiesService; @Override protected void bindExecutionContext(final ScopedContext executionContext) { Map<String, Object> services = new HashMap<>(); services.put(BINDING_SUB_KEY_SERVICE_USER, userService); services.put(BINDING_SUB_KEY_SERVICE_MAIL, mailService); services.put(BINDING_SUB_KEY_SERVICE_ACCOUNT, accountService); services.put(BINDING_SUB_KEY_SERVICE_USER_LOGIN_SERVICE, userLoginService); services.put(BINDING_SUB_KEY_SERVICE_TENANT_CONFIG_SERVICE, tenantConfigService); services.put(BINDING_SUB_KEY_PROFILE_EVEBT_PRODUCER_SERVICE, profileEventProducer); services.put(BINDING_SUB_KEY_SERVICE_CUSTOMIZABLE_TOKE_STORAGE, customizableLepTokenStorage); services.put(BINDING_SUB_KEY_SERVICE_CUSTOM_AUTHORIZATION_CODE, customAuthorizationCodeServices); services.put(BINDING_SUB_KEY_SERVICE_LDAP_SERVICE, ldapService); services.put(BINDING_SUB_KEY_SERVICE_USER_DETAILS_SERVICE, userDetailsService); services.put(BINDING_SUB_KEY_SERVICE_TENANT_PROPERTIES_SERVICE, tenantPropertiesService); executionContext.setValue(BINDING_KEY_COMMONS, new CommonsExecutor(commonsService)); executionContext.setValue(BINDING_KEY_SERVICES, services); Map<String, Object> templates = new HashMap<>(); templates.put(BINDING_SUB_KEY_TEMPLATE_REST, restTemplate); executionContext.setValue(BINDING_KEY_TEMPLATES, templates); // other beans to be passed into LEP execution context? } }
It’s time for Gators coach Jim McElwain to turn on the charm. For Coach Mac and company — i.e., new defensive coordinator Geoff Collins and new offensive coordinator Doug Nussmeier — the time is now. There will never be a better time for this staff to show what kind of recruiting charisma it has than this weekend when the Gators host a slew of top-notch targets headlined by Seffner Armwood defensive end Byron Cowart. Cowart has been to Auburn. He’s heard what the enemy has to offer. The enemy, if you are a Florida Gators fan, is the two-headed former Swamp Monster known as Will Muschamp and Travaris Robinson. Those two coaches were hired by Auburn, and if it wasn’t difficult enough for McElwain and the new Gators staff to lure players to help resurrect the once proud UF program, it’s become even more difficult with Coach Champ and Coach TRob working against them. TRob, in particular, is one of the most well-liked and well-respected assistant coaches in all of the South. Talk to any top prospect from the state of Florida, and he knows all about Coach TRob. Most don’t even know his full name, but they know Coach Trob is now at Auburn and will recruit Florida with a vengeance. So that’s why this weekend is so huge for the new Gators’ coaches. They need to roll out the red carpet. They need to meet players at the airport. Pick up their bags from the luggage conveyor. Have limo drivers for every outing. They need to fawn over these players like they were on a first date. This impression is of the utmost importance. They better know every little thing about these players as is possible. If Cowart’s favorite food is a strawberry milkshake, they better have one at every stop. If he likes his steaks medium rare, Coach Mac might want to don an apron and make sure it’s done right. (Chris Hays) That goes for all of them, and there are a whole slew of prospects slated for Gainesville this weekend. Cowart will be joined by Fort Lauderdale St. Thomas Aquinas running back Jordan Scarlett, the Miami commit who is ripe for the picking, but UF coaches have to prove they can reach the fine fruit in the tip-top branches. A good harvest for McElwain’s bunch isn’t just going to fall off the trees. It will take effort. If Scarlett is allergic to goose-down pillows, that hotel room better not have any. Scarlett and Cowart will both visit FSU on Jan. 30. Another possible flip is Bradenton IMG quarterback Deondre Francois, who is committed to UF rival FSU. There are a lot of people of the opinion that if the Gators get Francois on campus, he’ll be wearing orange and blue next fall. He’ll be there Friday. The Gators need to shine. Francois to UF doesn’t really make a lot of sense because most figure him to be the QB of choice among the three 2015 commitments the Seminoles have, and there is talk that Maryland prospect Kai Locksley won’t even play QB in college. But the ’Noles also have future IMG quarterback Malik Henry, a top prospect out of California, committed to the 2016 class. Francois might want to be the focal point of an offense, not one of the floats in a quarterback parade. So the Gators do appear to have a chance if they can persuade Francois into thinking he can be the savior of the program. If Francois wants hot dogs instead of steak, they better get some buns. And if he wants them with mustard only, he better not see ketchup. Tampa Wharton wide receiver Auden Tate (6-4, 215) is another Seminole commit who is visiting. I don’t see Tate as a flip at this point, although Michigan could hold the spatula to that scenario. Tate, however, does have VH-1 in his corner. Gators’ cornerback Vernon Hargreaves also attended Wharton High, and the All-American could be the key to helping UF throw a change-up at Tate with a big recruiting pitch. Tate was a fixture at late-season Gators home games, and one never knows what might happen on National Signing Day. He’s big and he better have a king-sized bed at the hotel waiting for him. Others in town will be Texas commit and Miami Booker T. Washington CB Davante Davis (6-3, 200), Miami Westminster ATH Jordan Cronkrite (5-11, 198), Miami Norland LB Rayshad Jackson (6-2, 215) and Norcross (Ga.) WR Jared Pinkney. UF will have another big list of visitors for the Jan. 30 weekend, but this is the big event this weekend. It’s going to be all about the impressions. It’s all they have at this point. Make a bad impression or leave something undone that other coaches accomplished during player visits elsewhere, and it’s over. Most importantly, UF’s coaches must come across as honest and good people with the best of intentions for each and every player they are courting. Recruits aren’t stupid. They know a sales job. A lemon is a lemon, no matter what color you paint it. And right now, Gators’ orange has a sort of faded yellowish tint. New UF coaches have to prove to recruits they are reconstructing the image; restoring the colors to the brilliance that once shined on this football program. It won’t be easy, but getting these kids corralled in Gainesville for one weekend of wining, dining and shining plays right into the hands of these coaches. Now they just have to show they have what it takes to lure the talent. Chris Hays is the Sentinel's recruiting coverage coordinator and can be reached at [email protected]. Follow us on Twitter at @Os_Recruiting and Facebook at OS Recruiting, and on Instagram at os_recruiting.
<reponame>CharaD7/azure-sdk-for-python # coding=utf-8 # -------------------------------------------------------------------------- # 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. # -------------------------------------------------------------------------- from msrest.serialization import Model class TaskDependencies(Model): """Specifies any dependencies of a task. Any task that is explicitly specified or within a dependency range must complete before the dependant task will be scheduled. :param task_ids: The list of task ids that must complete before this task can be scheduled. :type task_ids: list of str :param task_id_ranges: The list of task ranges that must complete before this task can be scheduled. :type task_id_ranges: list of :class:`TaskIdRange <azure.batch.models.TaskIdRange>` """ _attribute_map = { 'task_ids': {'key': 'taskIds', 'type': '[str]'}, 'task_id_ranges': {'key': 'taskIdRanges', 'type': '[TaskIdRange]'}, } def __init__(self, task_ids=None, task_id_ranges=None): self.task_ids = task_ids self.task_id_ranges = task_id_ranges
<reponame>llavors-mutues/common-ui<filename>src/bundle.ts import { Lenses } from '@compository/lib'; import { AppWebsocket, CellId } from '@holochain/conductor-api'; import { TransactionList } from './elements/transaction-list'; import { CreateOffer } from './elements/create-offer'; import { Constructor } from 'lit-element'; //@ts-ignore import { createUniqueTag } from '@open-wc/scoped-elements/src/createUniqueTag'; import { TransactorStore } from './transactor.store'; import { PublicTransactorService } from './public-transactor.service'; import { MyOffers } from './elements/my-offers'; import { ProfilesService } from '@holochain-open-dev/profiles'; import { ProfilesStore } from '@holochain-open-dev/profiles/profiles.store'; import { connectStore } from '@holochain-open-dev/common'; import { MyBalance } from './elements/my-balance'; function renderUnique( tag: string, baseClass: Constructor<HTMLElement>, root: ShadowRoot ) { const registry = customElements; const uniqueTag = createUniqueTag(tag, registry); root.innerHTML = ` <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /> <${uniqueTag}></${uniqueTag}> `; registry.define( uniqueTag, (class extends baseClass {} as unknown) as Constructor<HTMLElement> ); } export default function lenses( appWebsocket: AppWebsocket, cellId: CellId ): Lenses { const profilesService = new ProfilesService(appWebsocket, cellId); const profilesStore = new ProfilesStore(profilesService); const service = new PublicTransactorService(appWebsocket, cellId); const store = new TransactorStore(service, profilesStore); const signalReceiver = AppWebsocket.connect( appWebsocket.client.socket.url, 12000, signal => { const payload = signal.data.payload; if (payload.OfferReceived) { store.storeOffer(payload.OfferReceived); } else if (payload.OfferAccepted) { store.storeTransaction(payload.OfferAccepted); } } ); return { standalone: [ { name: 'My Offers', render(root: ShadowRoot) { renderUnique('my-offers', connectStore(MyOffers, store), root); }, }, { name: 'My Balance', render(root: ShadowRoot) { renderUnique( 'my-balance', connectStore(MyBalance, store), root ); }, }, { name: 'Create Offer', render(root: ShadowRoot) { renderUnique( 'create-offer', connectStore(CreateOffer, store), root ); }, }, ], entryLenses: {}, attachmentsLenses: [], }; }
package com.delisar.relo.Setting; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Switch; import com.delisar.relo.Dashboard.DashboardMain; import com.delisar.relo.R; public class SettingsMain extends AppCompatActivity { Switch nightMode, bigSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); theme(); setContentView(R.layout.activity_settings_main); // setSupportActionBar(new Toolbar()); // getSupportActionBar().setTitle("Setting"); // for set actionbar title // getSupportActionBar().setDisplayHomeAsUpEnabled(true); init(); } private void theme() { SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE); if (prefs.getBoolean("nightMode", false)) { setTheme(R.style.dark); } else { setTheme(R.style.light); } } private void init() { SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE); nightMode = findViewById(R.id.sw_nightMode); bigSize = findViewById(R.id.sw_fontSize); nightMode.setChecked(prefs.getBoolean("nightMode", false)); bigSize.setChecked(prefs.getBoolean("bigSize", false)); } public void saveSettings(View view) { SharedPreferences.Editor editor = getSharedPreferences(getPackageName(), MODE_PRIVATE).edit(); editor.putBoolean("nightMode", nightMode.isChecked()); editor.putBoolean("bigSize", bigSize.isChecked()); editor.apply(); if (nightMode.isChecked()) { setTheme(R.style.dark); } else { setTheme( R.style.light); } if (bigSize.isChecked()){ bigSize.setTextSize(getResources().getDimension(R.dimen.bigText)); nightMode.setTextSize(getResources().getDimension(R.dimen.bigText)); }else{ bigSize.setTextSize(getResources().getDimension(R.dimen.normalText)); nightMode.setTextSize(getResources().getDimension(R.dimen.normalText)); } recreate(); gotoHome(); } private void gotoHome(){ startActivity(new Intent(SettingsMain.this, DashboardMain.class)); finish(); } @Override public void onBackPressed() { gotoHome(); } }
<filename>common/reflect/src/main/java/io/sunshower/reflect/incant/InvocationContext.java package io.sunshower.reflect.incant; import io.sunshower.lang.Refreshable; public interface InvocationContext extends Refreshable { <T> ServiceDescriptor<T> resolve(String name); <T> ServiceDescriptor<T> resolve(Class<T> type, String name); }
/** * A zone extending {@link ZoneType} used by Derby Track system.<br> * <br> * The zone shares peace, no summon and monster track behaviors. */ public class DerbyTrackZone extends ZoneType { public DerbyTrackZone(int id) { super(id); } @Override protected void onEnter(Creature character) { if (character instanceof Playable) { character.setInsideZone(ZoneId.MONSTER_TRACK, true); character.setInsideZone(ZoneId.PEACE, true); character.setInsideZone(ZoneId.NO_SUMMON_FRIEND, true); } } @Override protected void onExit(Creature character) { if (character instanceof Playable) { character.setInsideZone(ZoneId.MONSTER_TRACK, false); character.setInsideZone(ZoneId.PEACE, false); character.setInsideZone(ZoneId.NO_SUMMON_FRIEND, false); } } }
<reponame>gas3/Sia package host import ( "path/filepath" "gitlab.com/NebulousLabs/Sia/modules" "gitlab.com/NebulousLabs/errors" ) // upgradeFromV143ToV151 is an upgrade layer that fixes a bug in the host's // settings which got introduced when EphemeralAccountExpiry got moved from a // uint64 to a time.Duration. At that time, no compat was added, resulting in a // persist value in seconds, that is being interpreted as nanoseconds. func (h *Host) upgradeFromV143ToV151() error { h.log.Println("Attempting an upgrade for the host from v1.4.3 to v1.5.1") // Load the persistence object p := new(persistence) err := h.dependencies.LoadFile(modules.Hostv143PersistMetadata, p, filepath.Join(h.persistDir, settingsFile)) if err != nil { return errors.AddContext(err, "could not load persistence object") } // The persistence object for hosts that upgraded to v1.5.0 (so non-new // hosts) will have the EphemeralAccountExpiry persisted in seconds, and // wrongfully interpreted as a time.Duration, expressed in nanoseconds. // // We fix this by updating the field to the default value, but only if the // value in the persistence object wasn't manually altered to zero if shouldResetEphemeralAccountExpiry(p.Settings) { p.Settings.EphemeralAccountExpiry = modules.DefaultEphemeralAccountExpiry // reset to default } // Load it on the host h.loadPersistObject(p) // Save the updated persist so that the upgrade is not triggered again. err = h.saveSync() if err != nil { return errors.AddContext(err, "could not save persistence object") } return nil } // shouldResetEphemeralAccountExpiry is a helper function that returns true if // the given settings contain a value for the `EphemeralAccountExpiry` field // that needs to be reset. Extracted for unit testing purposes. func shouldResetEphemeralAccountExpiry(his modules.HostInternalSettings) bool { return his.EphemeralAccountExpiry != modules.CompatV1412DefaultEphemeralAccountExpiry && his.EphemeralAccountExpiry.Nanoseconds() != 0 }
import * as React from 'react'; import { useState } from 'react'; import { InternalFormFieldGroup } from './InternalFormFieldGroup'; export interface FormFieldGroupExpandableProps extends React.HTMLProps<HTMLDivElement> { /** Anything that can be rendered as form field group content. */ children?: React.ReactNode; /** Additional classes added to the form field group. */ className?: string; /** Form filed group header */ header?: React.ReactNode; /** Flag indicating if the form field group is initially expanded */ isExpanded?: boolean; /** Aria-label to use on the form filed group toggle button */ toggleAriaLabel?: string; } export const FormFieldGroupExpandable: React.FunctionComponent<FormFieldGroupExpandableProps> = ({ children, className, header, isExpanded = false, toggleAriaLabel, ...props }: FormFieldGroupExpandableProps) => { const [localIsExpanded, setIsExpanded] = useState(isExpanded); return ( <InternalFormFieldGroup className={className} header={header} isExpandable isExpanded={localIsExpanded} toggleAriaLabel={toggleAriaLabel} onToggle={() => setIsExpanded(!localIsExpanded)} {...props} > {children} </InternalFormFieldGroup> ); }; FormFieldGroupExpandable.displayName = 'FormFieldGroupExpandable';
#!/usr/bin/env python3 """It is a module that wraps cache and youtube.""" from youtube import search_youtube def search_song(song): """Search the song locally at first. If not found, search in youtube """ videos = search_youtube(song) video = videos[0] return video
def _parse_donor(self, row): receipt_option_f = { "notneeded": "REFUSED", "email": "EMAIL", "mail": "MAIL" }.get(re.sub("[^a-zA-Z]+", "", row["TRV"]).lower(), "EMAIL") documented_at_f = self._parse_date(row["Date"]) postal_f = re.sub("[^a-zA-Z0-9 ]+", "", row["Postal Code"]).upper()[:7] return { "donor_name": row["Donor Name"], "contact_name": row.get("Contact", row["Donor Name"]), "email": row["Email"], "want_receipt": receipt_option_f, "telephone_number": row["Telephone"], "mobile_number": row["Mobile"], "address_line_one": row["Address"], "address_line_two": row.get("Unit", ""), "city": row["City"], "province": row["Prov."], "postal_code": postal_f, "customer_ref": row["CustRef"], "documented_at": documented_at_f }
/* Copyright 2017 The Kubernetes 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 watch import ( "bytes" "fmt" "io" "strings" "sync" "time" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/watch" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/v1" ccapi "github.com/kubernetes-incubator/cluster-capacity/pkg/api" ) // Every watcher expects infinite byte stream // E.g. http.Body can provide continuous byte stream, // each chunk sent asynchronously (invocation of Read is blocked until new chunk) // Implementation of io.ReadCloser type WatchBuffer struct { buf *bytes.Buffer read chan []byte write chan []byte retc chan retc Resource ccapi.ResourceType closed bool closeMux sync.RWMutex } type retc struct { n int e error } var _ io.ReadCloser = &WatchBuffer{} // Read watch events as byte stream func (w *WatchBuffer) Read(p []byte) (n int, err error) { if w.closed { return 0, io.EOF } w.read <- p ret := <-w.retc return ret.n, ret.e } // Close all channels func (w *WatchBuffer) Close() error { w.closeMux.Lock() defer w.closeMux.Unlock() if !w.closed { w.closed = true close(w.read) close(w.write) close(w.retc) } return nil } // Write func (w *WatchBuffer) Write(data []byte) (nr int, err error) { if w.closed { return 0, io.EOF } w.write <- data return len(data), nil } func (c *WatchBuffer) EmitWatchEvent(eType watch.EventType, object runtime.Object) error { //event := watch.Event{ // Type: eType, // Object: object, //} info, ok := runtime.SerializerInfoForMediaType(api.Codecs.SupportedMediaTypes(), runtime.ContentTypeJSON) if !ok { return fmt.Errorf("serializer for %s not registered", runtime.ContentTypeJSON) } gv := v1.SchemeGroupVersion if c.Resource == ccapi.ReplicaSets { gv = schema.GroupVersion{Group: "extensions", Version: "v1beta1"} } encoder := api.Codecs.EncoderForVersion(info.Serializer, gv) obj_str := runtime.EncodeOrDie(encoder, object) obj_str = strings.Replace(obj_str, "\n", "", -1) var buffer bytes.Buffer buffer.WriteString("{\"type\":\"") buffer.WriteString(string(eType)) buffer.WriteString("\",\"object\":") buffer.WriteString(obj_str) buffer.WriteString("}") _, err := c.Write(buffer.Bytes()) return err } func (w *WatchBuffer) loop() { var dataIn, dataOut []byte var ok bool for { select { case dataIn = <-w.write: // channel closed if len(dataIn) == 0 { if w.closed { return } } _, err := w.buf.Write(dataIn) if err != nil { // TODO(jchaloup): add log message fmt.Println("Write error") break } case dataOut = <-w.read: if w.buf.Len() == 0 { dataIn, ok = <-w.write if !ok { break } _, err := w.buf.Write(dataIn) if err != nil { // TODO(jchaloup): add log message fmt.Println("Write error") break } } nr, err := w.buf.Read(dataOut) if w.closed { break } w.retc <- retc{nr, err} } } } func NewWatchBuffer(resource ccapi.ResourceType) *WatchBuffer { wb := &WatchBuffer{ buf: bytes.NewBuffer(nil), read: make(chan []byte), write: make(chan []byte), retc: make(chan retc), Resource: resource, closed: false, } go wb.loop() return wb } func main() { buffer := NewWatchBuffer("pods") go func() { buffer.Write([]byte("Ahoj")) time.Sleep(5 * time.Second) buffer.Write([]byte(" Svete")) //time.Sleep(time.Second) }() data := []byte{0, 0, 0, 0, 0, 0} buffer.Read(data) fmt.Printf("\tdata: %s\n", data) buffer.Read(data) fmt.Printf("\tdata: %s\n", data) time.Sleep(10 * time.Second) buffer.Close() fmt.Println("Ahoj") }