text
stringlengths
27
775k
package controller import ( "encoding/json" "errors" "github.com/code7unner/vk-scrapper/internal/api/service" "github.com/code7unner/vk-scrapper/internal/app" "io/ioutil" "net/http" "strconv" ) type PredictionController interface { GetInRealTime(w http.ResponseWriter, r *http.Request) Get(w http.ResponseWriter, r *http.Request) GetCached(w http.ResponseWriter, r *http.Request) UpdateStatus(w http.ResponseWriter, r *http.Request) } type PredictionCtrl struct { app *app.App } func NewPredictionController(app *app.App) PredictionController { return &PredictionCtrl{app} } func (p PredictionCtrl) Get(w http.ResponseWriter, r *http.Request) { data, err := ioutil.ReadAll(r.Body) if err != nil { p.error(w, r, http.StatusBadRequest, err) } r.Body.Close() predict, err := p.app.Vws.Predict(string(data)) if err != nil { p.error(w, r, http.StatusInternalServerError, err) } p.respond(w, r, http.StatusOK, predict) } func (p PredictionCtrl) GetInRealTime(w http.ResponseWriter, r *http.Request) { params := r.URL.Query() keys, ok := params["city"] if !ok { p.error(w, r, http.StatusBadRequest, errors.New("city query is required")) } city, _ := strconv.Atoi(keys[0]) users, err := service.GetVkUsers(city, &p.app.Conf) if err != nil { p.error(w, r, http.StatusInternalServerError, err) } subs, err := service.BulkGetVkUserSubs(users, &p.app.Conf) if err != nil { p.error(w, r, http.StatusInternalServerError, err) } p.respond(w, r, http.StatusOK, subs) } func (p PredictionCtrl) GetCached(w http.ResponseWriter, r *http.Request) { var city int params := r.URL.Query() cityKey, ok := params["city"] if ok { city, _ = strconv.Atoi(cityKey[0]) } else { city = 0 } schoolKey, ok := params["school"] if !ok { p.error(w, r, http.StatusBadRequest, errors.New("school query is required")) } school, _ := strconv.Atoi(schoolKey[0]) users, err := p.app.Repo.Users.Retrieve(p.app.Ctx, city, school) if err != nil { p.error(w, r, http.StatusInternalServerError, err) } p.respond(w, r, http.StatusOK, users) } func (p PredictionCtrl) UpdateStatus(w http.ResponseWriter, r *http.Request) { var req struct { Id int `json:"id"` Status string `json:"status"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { p.error(w, r, http.StatusInternalServerError, err) } defer r.Body.Close() rowsUpdated, err := p.app.Repo.Users.Update(p.app.Ctx, req.Id, req.Status) if err != nil { p.error(w, r, http.StatusInternalServerError, err) } p.respond(w, r, http.StatusOK, rowsUpdated) } // respond with error func (p PredictionCtrl) error(w http.ResponseWriter, r *http.Request, code int, err error) { p.respond(w, r, code, map[string]string{"error": err.Error()}) } // abstract respond func (p PredictionCtrl) respond(w http.ResponseWriter, r *http.Request, code int, data interface{}) { w.WriteHeader(code) if data != nil { json.NewEncoder(w).Encode(data) } }
import { AlarmArea, AreaDesc, VedoClient, VedoClientConfig, ZoneDesc, ZoneStatus, } from 'comelit-client'; import { intersection } from 'lodash'; import { Callback, CharacteristicEventTypes, Logger, PlatformAccessory, Service } from 'homebridge'; import { ComelitVedoPlatform } from '../comelit-vedo-platform'; const ALL = 32; export interface VedoAlarmConfig extends Partial<VedoClientConfig> { away_areas?: string[]; night_areas?: string[]; home_areas?: string[]; } const DEFAULT_LOGIN_TIMEOUT = 15000; export class VedoAlarm { readonly client: VedoClient; readonly log: Logger; readonly accessory: PlatformAccessory; readonly platform: ComelitVedoPlatform; readonly name: string; private readonly code: string; private securityService: Service; private lastUID: string; private lastLogin: number; private readonly away_areas: string[]; private readonly night_areas: string[]; private readonly home_areas: string[]; private zones: ZoneDesc; private areas: AreaDesc; constructor( platform: ComelitVedoPlatform, accessory: PlatformAccessory, address: string, port: number, code: string, config: VedoAlarmConfig ) { this.platform = platform; this.accessory = accessory; this.log = platform.log; this.code = code; this.name = 'VEDO Alarm @ ' + address; this.client = new VedoClient(address, port, config); this.client.setLogger(platform.log); this.away_areas = config.away_areas ? config.away_areas.map(a => a.toLowerCase().trim()) : []; this.night_areas = config.night_areas ? config.night_areas.map(a => a.toLowerCase().trim()) : []; this.home_areas = config.home_areas ? config.home_areas.map(a => a.toLowerCase().trim()) : []; this.lastLogin = 0; this.log.debug('Mapping areas set to ', this.night_areas, this.away_areas, this.home_areas); this.getAvailableServices(); } update(alarmAreas: AlarmArea[]) { const Characteristic = this.platform.homebridge.hap.Characteristic; const currentAlarmStatus = this.securityService.getCharacteristic( Characteristic.SecuritySystemCurrentState ).value; const armedAreas = alarmAreas .filter((area: AlarmArea) => area.armed) .map(a => a.description.toLowerCase()); const statusArmed = armedAreas.length !== 0; if (statusArmed) { this.log.debug(`Found ${armedAreas.length} armed areas: ${armedAreas.join(', ')}`); } else { this.log.debug('No armed areas'); } const triggered = alarmAreas.reduce( (triggered: boolean, area: AlarmArea) => triggered || area.triggered || area.sabotaged, false ); if (triggered) { const s = alarmAreas .filter(a => a.triggered || a.sabotaged) .map(a => a.description) .join(', '); this.log.warn(`Alarm triggered in area ${s}`); } else { this.log.debug('No triggering areas'); } if ( triggered && currentAlarmStatus !== Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED ) { this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED ); return; } if (statusArmed) { if ( this.away_areas.length && intersection(armedAreas, this.away_areas).length === armedAreas.length ) { this.log.debug('Setting new status to AWAY_ARM'); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.AWAY_ARM ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.AWAY_ARM ); } else if ( this.home_areas.length && intersection(armedAreas, this.home_areas).length === armedAreas.length ) { this.log.debug('Setting new status to STAY_ARM'); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.STAY_ARM ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.STAY_ARM ); } else if ( this.night_areas.length && intersection(armedAreas, this.night_areas).length === armedAreas.length ) { this.log.debug('Setting new status to NIGHT_ARM'); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.NIGHT_ARM ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.NIGHT_ARM ); } else { this.log.debug('Setting new status to AWAY_ARM (default)'); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.AWAY_ARM ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.AWAY_ARM ); } } else { this.log.debug('Setting new status to DISARMED'); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.DISARMED ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.DISARM ); } } async fetchZones(): Promise<ZoneStatus[]> { try { await this.refreshUID(); if (!this.zones) { this.zones = await this.client.zoneDesc(this.lastUID); } return await this.client.zoneStatus(this.lastUID, this.zones); } catch (e) { this.log.error(`Error fetching zones: ${e.message}`); } this.log.error('Unable to fetch token'); this.lastUID = null; return null; } async checkAlarm(): Promise<AlarmArea[]> { try { await this.refreshUID(); if (!this.areas) { this.areas = await this.client.areaDesc(this.lastUID); } return await this.client.findActiveAreas(this.lastUID, this.areas); } catch (e) { this.log.error(`Error checking alarm: ${e.message}`); } this.log.error('Unable to fetch token'); this.lastUID = null; return null; } async includeZone(index: number) { try { await this.refreshUID(); await this.client.includeZone(this.lastUID, index); } catch (e) { this.log.error(`Error including zone: ${e.message}`); } this.log.error('Unable to fetch token'); this.lastUID = null; return null; } async excludeZone(index: number) { try { await this.refreshUID(); await this.client.excludeZone(this.lastUID, index); } catch (e) { this.log.error(`Error excluding zone: ${e.message}`); } this.log.error('Unable to fetch token'); this.lastUID = null; return null; } private getAvailableServices(): Service[] { const Characteristic = this.platform.homebridge.hap.Characteristic; const Service = this.platform.homebridge.hap.Service; const accessoryInformation = this.accessory.getService(Service.AccessoryInformation) || this.accessory.addService(Service.AccessoryInformation); accessoryInformation .setCharacteristic(Characteristic.Name, 'Vedo Alarm') .setCharacteristic(Characteristic.Manufacturer, 'Comelit') .setCharacteristic(Characteristic.Model, 'None') .setCharacteristic(Characteristic.FirmwareRevision, 'None') .setCharacteristic(Characteristic.SerialNumber, 'None'); this.securityService = this.accessory.getService(Service.SecuritySystem) || this.accessory.addService(Service.SecuritySystem); this.securityService.setCharacteristic(Characteristic.Name, 'VEDO Alarm'); const validValues = [ Characteristic.SecuritySystemTargetState.DISARM, Characteristic.SecuritySystemTargetState.AWAY_ARM, ]; if (this.night_areas.length) { validValues.push(Characteristic.SecuritySystemTargetState.NIGHT_ARM); } if (this.home_areas.length) { validValues.push(Characteristic.SecuritySystemTargetState.STAY_ARM); } this.securityService.updateCharacteristic( Characteristic.SecuritySystemTargetState, Characteristic.SecuritySystemTargetState.DISARM ); this.securityService.updateCharacteristic( Characteristic.SecuritySystemCurrentState, Characteristic.SecuritySystemCurrentState.DISARMED ); this.securityService .getCharacteristic(Characteristic.SecuritySystemTargetState) .setProps({ validValues, }) .on(CharacteristicEventTypes.SET, async (value: number, callback: Callback) => this.setTargetState(value, callback) ); return [accessoryInformation, this.securityService]; } private async armAreas(areas: string[], uid: string): Promise<number[]> { this.log.info(`Arming system: ${areas.length ? areas.join(', ') : 'ALL SYSTEM'}`); const alarmAreas = await this.client.findActiveAreas(uid); if (areas && areas.length) { const indexes = areas .map(area => alarmAreas.findIndex(a => a.description.toLowerCase() === area)) .filter(index => index !== -1); if (indexes.length) { const promises = indexes.map(index => this.client.arm(uid, index)); await Promise.all(promises); return indexes; } } await this.client.arm(uid, ALL); return [ALL]; } private async refreshUID() { if (this.shouldLogin() || this.getTimeElapsedFromLastLogin() > DEFAULT_LOGIN_TIMEOUT) { if (this.lastUID) { await this.client.logout(this.lastUID); } this.lastUID = null; this.lastUID = await this.client.loginWithRetry(this.code); this.lastLogin = new Date().getTime(); } } private shouldLogin() { return !this.lastUID || this.getTimeElapsedFromLastLogin() > DEFAULT_LOGIN_TIMEOUT; } private getTimeElapsedFromLastLogin() { const now = new Date().getTime(); return now - this.lastLogin; } private async setTargetState(value: number, callback: Callback) { const Characteristic = this.platform.homebridge.hap.Characteristic; try { const uid = await this.client.loginWithRetry(this.code); if (uid) { switch (value) { case Characteristic.SecuritySystemTargetState.DISARM: this.log.info('Disarming system'); await this.client.disarm(uid, ALL); callback(); break; case Characteristic.SecuritySystemTargetState.AWAY_ARM: this.log.info('Arm system: AWAY'); await this.armAreas(this.away_areas, uid); callback(); break; case Characteristic.SecuritySystemTargetState.NIGHT_ARM: this.log.info('Arm system: NIGHT'); await this.armAreas(this.night_areas, uid); callback(); break; case Characteristic.SecuritySystemTargetState.STAY_ARM: this.log.info('Arm system: STAY'); await this.armAreas(this.home_areas, uid); callback(); break; default: callback(new Error(`Cannot execute requested action ${value}`)); } } else { callback(new Error('Cannot login into system')); } } catch (e) { callback(e); } } }
# Types of Races * [[Cobble]] * [[Flat]] * [[FlatHilly]] * [[Hilly]] * [[HillyMountain]] * [[Mountain]] * [[TT|Time Trial]]
package ilove.quark.us import io.quarkus.test.junit.QuarkusIntegrationTest @QuarkusIntegrationTest class GreetingControllerIT : GreetingControllerTest()
define([ 'dojo/_base/declare', 'dojo/_base/array', 'dojo/_base/lang', 'dojo/dom-construct', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'app/search/utilities' ], function ( declare, array, lang, domConstruct, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, utilities ) { return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { // description: // Shared code between radio and checkbox filters widgetsInTemplate: false, // items: Checkbox or Radio items: null, // Properties to be sent into constructor // filterTxt: String filterTxt: null, constructor: function () { // summary: // description console.log('app/search/_RadioCheckboxMixin:constructor', arguments); this.items = []; }, postCreate: function () { // summary: // Overrides method of same name in dijit._Widget. console.log('app.search._RadioCheckboxMixin::postCreate', arguments); var that = this; array.forEach(this.filterTxt.split(', '), function (txt) { var parts = utilities.getRadioFilterParts(txt); var item = new that.itemClass({ // eslint-disable-line new-cap value: parts.value, label: parts.label, name: that.id + '_radio' }, domConstruct.create('div', null, that.domNode)); that.own(item); that.own(item.on('change', lang.hitch(that, 'onChange'))); that.items.push(item); }); this.inherited(arguments); }, onChange: function () { // summary: // description console.log('app/search/_RadioCheckboxMixin:onChange', arguments); }, isValid: function () { // summary: // description // returns: Boolean console.log('app/search/_RadioCheckboxMixin:isValid', arguments); return true; }, getSelectedValues: function () { // summary: // returns the values of the selected items console.log('app/search/_RadioCheckboxMixin:getSelectedValues', arguments); var queries = []; array.forEach(this.items, function (c) { if (c.item.checked) { queries.push(c.value); } }); return queries; }, getQuery: function () { // summary: // assembles the queries // returns: String | Null (if no items are checked) console.log('app/search/_RadioCheckboxMixin:getQuery', arguments); var queries = this.getSelectedValues(); return (queries.length) ? queries.join(' OR ') : null; }, clear: function () { // summary: // clears all checkboxes console.log('app/search/_RadioCheckboxMixin:clear', arguments); array.forEach(this.items, function (c) { c.clear(); }); } }); });
import hljs from "highlight.js"; import marked from "marked"; marked.setOptions({ highlight: function(code: string, lang: string) { try { if (lang !== "") { return hljs.highlight(lang, code).value; } else { return hljs.highlightAuto(code).value; } } catch (e) { return hljs.highlightAuto(code).value; } } });
# Dart ```dart void main() { print('Hello, World!'); } ``` ## Environment Setup Download the Dart SDK for your platform from the official site, here: https://www.dartlang.org/tools/sdk#install For Windows, the most direct link is here: http://www.gekorm.com/dart-windows/ ## Building/Compiling Dart doesn't require a build/compile step. ## Running From a command line, `cd` into the directory containing your Dart code. Execute `dart <yourfile>.dart` to run.
package org.librazy.demo.dubbo.service; import java.util.Set; public interface UserSessionService { void newSession(String id, String sid, String ua, String key); String getKey(String id, String sid); String getUserAgent(String id, String sid); Set<String> getSessions(String id); void deleteSession(String id, String sid); void refreshSession(String id, String sid); void clearSession(String id); void renameId(String id, String sid, String now); boolean validNonce(String nonce); String sendCode(String email); boolean checkCode(String email, String req); }
#: requires require 'doodle' #: definitions class Event < Doodle has Date end #: use event = Event.new(:date => "Hello") #: output
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:eye_of_god/ui/Outdoor/outdoor.dart'; import 'package:eye_of_god/ui/Indoor/indoor.dart'; import 'package:eye_of_god/ui/selectorPage.dart'; import 'package:permission_handler/permission_handler.dart' as permission; // import 'package:eye_of_god/gg.dart'; import 'package:geolocator/geolocator.dart'; import 'package:fuzzy/fuzzy.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations( [DeviceOrientation.landscapeRight]); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Eye of God', theme: ThemeData( primarySwatch: Colors.blue, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: SelectorPage(), routes: { HomeView.id: (context) => HomeView(), Indoor.id: (context) => Indoor(), }, ); } }
sc.define("performKeyToDegree", { Array: function(degree, stepsPerOctave) { stepsPerOctave = stepsPerOctave === void 0 ? 12 : stepsPerOctave; var n = ((degree / stepsPerOctave)|0) * this.length; var key = degree % stepsPerOctave; return this.indexInBetween(key) + n; } });
package cli import ( "context" "fmt" "os" "github.com/ory/x/configx" "github.com/ory/x/errorsx" "github.com/ory/x/cmdx" "github.com/spf13/cobra" "github.com/driver005/oauth/config" "github.com/driver005/oauth/driver" "github.com/driver005/oauth/registry" "github.com/ory/x/flagx" ) type MigrateHandler struct{} func newMigrateHandler() *MigrateHandler { return &MigrateHandler{} } func (h *MigrateHandler) MigrateSQL(cmd *cobra.Command, args []string) { var d registry.Registry if flagx.MustGetBool(cmd, "read-from-env") { d = driver.New( cmd.Context(), driver.WithOptions( configx.SkipValidation(), configx.WithFlags(cmd.Flags())), driver.DisableValidation(), driver.DisablePreloading()) if len(d.Config().DSN()) == 0 { fmt.Println(cmd.UsageString()) fmt.Println("") fmt.Println("When using flag -e, environment variable DSN must be set") os.Exit(1) return } } else { if len(args) != 1 { fmt.Println(cmd.UsageString()) os.Exit(1) return } d = driver.New( cmd.Context(), driver.WithOptions( configx.WithFlags(cmd.Flags()), configx.SkipValidation(), configx.WithValue(config.KeyDSN, args[0]), ), driver.DisableValidation(), driver.DisablePreloading()) } p := d.Persister() conn := p.Connection(context.Background()) if conn == nil { fmt.Println(cmd.UsageString()) fmt.Println("") fmt.Printf("Migrations can only be executed against a SQL-compatible driver but DSN is not a SQL source.\n") os.Exit(1) return } if err := conn.Open(); err != nil { fmt.Printf("Could not open the database connection:\n%+v\n", err) os.Exit(1) return } // convert migration tables if err := p.PrepareMigration(context.Background()); err != nil { fmt.Printf("Could not convert the migration table:\n%+v\n", err) os.Exit(1) return } // print migration status fmt.Println("The following migration is planned:") fmt.Println("") status, err := p.MigrationStatus(context.Background()) if err != nil { fmt.Printf("Could not get the migration status:\n%+v\n", errorsx.WithStack(err)) os.Exit(1) return } _ = status.Write(os.Stdout) if !flagx.MustGetBool(cmd, "yes") { fmt.Println("") fmt.Println("To skip the next question use flag --yes (at your own risk).") if !cmdx.AskForConfirmation("Do you wish to execute this migration plan?", nil, nil) { fmt.Println("Migration aborted.") return } } // apply migrations if err := p.MigrateUp(context.Background()); err != nil { fmt.Printf("Could not apply migrations:\n%+v\n", errorsx.WithStack(err)) } fmt.Println("Successfully applied migrations!") }
* for CentOS 7 ``` sudo yum install -y dpkg cargo install cargo-deb ```
package org.motechproject.commons.api; import java.util.Map; /** * The <code>TasksEventParser</code> interface provides a way for modules to define * a custom way to handle trigger events. Before event parameters or subject are parsed, * the Tasks module will first check if received event contains parameter with key * {@literal custom_tasks_event_parser} and if so, it will look for custom parser that * matches the name exposed via <code>getName()</code> method. If any module wants * to use a custom event parser, they should simply implement this interface and * expose it as OSGi service. */ public interface TasksEventParser { String CUSTOM_PARSER_EVENT_KEY = "org.motechproject.tasks.custom_event_parser"; /** * Given a map of event parameters, parses them in a user-defined way to receive * a custom map of event parameters * * @param eventSubject The original event subject * @param eventParameters Initial event parameters * @return Custom, parsed event parameters, that will be used instead of initial params */ Map<String, Object> parseEventParameters(String eventSubject, Map<String, Object> eventParameters); /** * Adjusts event subject of the event. Thanks to this, we are able to map events of the same event subject * to different triggers. If there's no need to modify the subject of an event (eg. one event should map * only one trigger), simply return the original subject, that is passed as an argument. * * @param eventSubject The original event subject * @param eventParameters Initial event parameters * @return Custom event subject */ String parseEventSubject(String eventSubject, Map<String, Object> eventParameters); /** * Returns the name of the module that registers custom parser. Tasks module will look * for all registered event parsers and try to match the name passed in the event parameter * <code>org.motechproject.tasks.custom_event_parser</code> with the name returned by this method. If there's * a match, a custom parser with matched name will be used. * * @return Module name that registers custom event parser */ String getName(); }
import styled from 'styled-components'; export const StyledAutosuggestInput = styled.div` .react-autosuggest__container { position: relative; margin: 0 3px; } .react-autosuggest__input { width: 100%; padding: 10px; font-family: inherit; font-size: 1rem; line-height: 1.25; border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 0.25rem; transition: all 0.2s; outline: none; align-items: center; position: relative; display: flex; height: 2.5rem; background-color: #718096; color: #fff; padding-top: 0.5rem; padding-bottom: 0.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05); } .react-autosuggest__input::placeholder { color: #1a202c; } .react-autosuggest__input:focus { z-index: 1; border-color: #ed64a6; box-shadow: 0 0px 1px 0px #ed64a6; } .react-autosuggest__input--open { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } .react-autosuggest__suggestions-container { display: none; } .react-autosuggest__suggestions-container--open { display: block; color: #fff; position: absolute; top: 100%; width: 100%; margin-left: 0px; border: 0; background-color: #718096; font-family: inherit; font-size: 16px; border-bottom-left-radius: 3px; border-bottom-right-radius: 3px; max-height: 148px; overflow-y: auto; z-index: 2; } .react-autosuggest__suggestions-list { margin: 0; padding: 0px 0px 8px 0px; list-style-type: none; margin-top: 8px; } .react-autosuggest__suggestion { cursor: pointer; padding: 10px; } .react-autosuggest__suggestion--highlighted { color: #fff; background-color: #2d3748; } `;
-- | a.k.a. highliy composite numbers module AntiPrimes (Nui, Siz, Lst, size, dividers, proof, list) where import Data.List (foldr1, group, nub, sort, tails) import Data.Numbers.Primes (primeFactors) -- | Number under investigation type Nui = Int -- | number of divisors of Nui type Siz = Int -- | list of tuples: numbers and their divisor sizes type Lst = [(Nui, Siz)] -- calculate the frequencies of the list elements frequ :: [Int] -> [(Int, Int)] frequ list = map (\l -> (head l, length l)) (group (sort list)) -- good old combinatorics: combine n elements of a list without repetitions comb :: (Eq a, Num a) => a -> [a1] -> [[a1]] comb 0 lst = [[]] comb n lst = do (x:xs) <- tails lst rest <- comb (n-1) xs return $ x:rest -- all possible combinations of a list combAll :: (Eq a, Num a) => a -> [a1] -> [[a1]] combAll 0 lst = [] combAll n lst = (comb n lst) ++ (combAll (n-1) lst) -- error message msg :: String msg = "the number must be greater than 0" lst1 :: Lst lst1 = [(1,1)] -- multiplication all elements of a list mul :: (Num a, Foldable t) => t a -> a mul x = foldr1 (*) x -- generate a tuple with a number and ist size tup :: Nui -> (Nui, Siz) tup n = (n, size n) -- list of (n, size) for n = [2..n] lst :: Nui -> Lst lst n | n <= 0 = error msg | n == 1 = lst1 | otherwise = map tup rng where rng = [2..n] -- range of interest -- | calculate the "size" of all possible factors of a number -- -- >>> import qualified AntiPrimes as AP -- >>> AP.size 12 -- 6 -- as [1,2,3,4,6,12] are possible -- size :: Nui -> Siz size n | n <= 0 = error msg | n == 1 = 1 | otherwise = foldr1 (*) incrs where facts = primeFactors n frequs = frequ facts counts = map snd frequs incrs = map (1 +) counts -- | calculate all possible dividers of a number -- -- >>> import qualified AntiPrimes as AP -- >>> AP.dividers 12 -- [1,2,3,4,6,12] -- dividers :: Nui -> [Int] dividers n | n <= 0 = error msg | n == 1 = [1] | otherwise = sort add1 where facts = primeFactors n len = length facts combs = combAll len facts multi = map mul combs clean = nub multi add1 = clean ++ [1] -- | proof if a number is an antiprime -- -- >>> import qualified AntiPrimes as AP -- >>> AP.proof 4 -- True -- >>> AP.proof 5 -- False -- proof :: Nui -> Bool proof n | n <= 0 = error msg | n == 1 = True | n == 2 = True | otherwise = length flt == 1 where siz = size n flt = filter (\(a, b) -> b >= siz) $ lst n -- | show all (antiprimes, size) below a number -- -- >>> import qualified AntiPrimes as AP -- >>> AP.list 12 -- [(1,1),(2,2),(4,3),(6,4)] -- list :: Int -> Lst list 0 = error msg list 1 = lst1 list n | n <= 0 = error msg | n == 1 = lst1 | otherwise = list' lst1 (lst n) -- helper function to clean out excluded entries list' :: Lst -> Lst -> Lst list' aps [] = aps list' aps rest = list' nxt est where top = head rest rst = tail rest nxt = aps ++ [top] est = filter (\(a, b) -> b > (snd top)) $ rst
package leaks import ( "strings" "testing" ) func TestThreadDetectionLeak_Found(t *testing.T) { stop := make(chan bool) defer func() { stop <- true if x := recover(); x != nil { if strings.Contains(x.(string), "Potential Goroutines Leakage detected") { // Leaked goroutine found as expected. return } } panic("Leaking goroutine not detected") }() inspector := Inspector{} inspector.RunGoroutineLeakDetection("ThreadDetectionLeakFound", t, func(t *testing.T) { go func() { select { case <-stop: break } }() }) } func TestThreadDetectionLeak_NotFound(t *testing.T) { defer func() { if x := recover(); x != nil { panic("Detection of leaked goroutines failed, there is no leak") } }() inspector := Inspector{} inspector.RunGoroutineLeakDetection("ThreadDetectionLeakFound", t, func(t *testing.T) {}) }
'use strict'; const AsyncApiQueue = require('./lib/async-api-queue.js'); module.exports = AsyncApiQueue;
package kubelet import ( "context" "fmt" "net/http" "net/http/httptest" "net/url" "path" "regexp" "testing" ) func newServer(token string) *httptest.Server { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if token != "" && r.Header.Get("Authorization") != "Bearer "+token { w.WriteHeader(http.StatusUnauthorized) return } switch r.URL.RequestURI() { case podsPath: http.ServeFile(w, r, "testdata/pods.json") case statsPath: http.ServeFile(w, r, "testdata/summary.json") } }) return httptest.NewServer(handler) } func TestGetPod(t *testing.T) { ts := newServer("") defer ts.Close() tests := []struct { namespace, name string raiseError bool }{ { namespace: "default", name: "myapp", raiseError: false, }, { namespace: "default", name: "dummy", raiseError: true, }, { namespace: "dummy", name: "myapp", raiseError: true, }, { namespace: "dummy", name: "dummy", raiseError: true, }, { namespace: "default", name: "", raiseError: true, }, { namespace: "", name: "myapp", raiseError: true, }, { namespace: "", name: "", raiseError: true, }, } for _, tc := range tests { ctx := context.Background() c, err := NewClient(ts.Client(), "", ts.URL, tc.namespace, tc.name, nil) if err != nil { t.Errorf("should not raise error: %v", err) } _, err = c.GetPod(ctx) if (err != nil) != tc.raiseError { var cond string if !tc.raiseError { cond = "not " } t.Errorf("GetPod() should %sraise error, but got %q", cond, err) } } } func TestGetPodStats(t *testing.T) { ts := newServer("") defer ts.Close() tests := []struct { namespace, name string raiseError bool }{ { namespace: "default", name: "myapp", raiseError: false, }, { namespace: "default", name: "dummy", raiseError: true, }, { namespace: "dummy", name: "myapp", raiseError: true, }, { namespace: "dummy", name: "dummy", raiseError: true, }, { namespace: "default", name: "", raiseError: true, }, { namespace: "", name: "myapp", raiseError: true, }, { namespace: "", name: "", raiseError: true, }, } for _, tc := range tests { ctx := context.Background() c, err := NewClient(ts.Client(), "", ts.URL, tc.namespace, tc.name, nil) if err != nil { t.Errorf("should not raise error: %v", err) } _, err = c.GetPodStats(ctx) if (err != nil) != tc.raiseError { var cond string if !tc.raiseError { cond = "not " } t.Errorf("GetPodStats() should %sraise error, but got %q", cond, err) } } } func TestIgnoreContainer(t *testing.T) { ts := newServer("") defer ts.Close() tests := []struct { ignoreContainer *regexp.Regexp expected int }{ {nil, 2}, {regexp.MustCompile(`\Amackerel-container-agent\z`), 1}, {regexp.MustCompile(``), 0}, } for _, tc := range tests { ctx := context.Background() c, err := NewClient(ts.Client(), "", ts.URL, "default", "myapp", tc.ignoreContainer) if err != nil { t.Errorf("should not raise error: %v", err) } pod, err := c.GetPod(ctx) if err != nil { t.Errorf("GetPod() should not raise error: %v", err) } got := len(pod.Spec.Containers) if got != tc.expected { t.Errorf("meta.Containers expected %d containers, got %v containers", tc.expected, got) } stats, err := c.GetPodStats(ctx) if err != nil { t.Errorf("GetPodStats() should not raise error: %v", err) } got = len(stats.Containers) if got != tc.expected { t.Errorf("GetPodStats() expected %d containers, got %v containers", tc.expected, got) } } } func TestRequestToken(t *testing.T) { testToken := "testToken" ts := newServer(testToken) defer ts.Close() ctx := context.Background() c, err := NewClient(ts.Client(), testToken, ts.URL, "default", "myapp", nil) // c, err := NewClient(ts.Client(), "hoge", ts.URL, "default", "myapp", nil) if err != nil { t.Errorf("NewClient() should not raise error: %v", err) } _, err = c.GetPod(ctx) if err != nil { t.Errorf("newRequest() should not raise error: %v", err) } } func TestErrorMessage(t *testing.T) { var body string handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(body)) }) ts := httptest.NewServer(handler) c, err := NewClient(ts.Client(), "", ts.URL, "", "", nil) if err != nil { t.Errorf("should not raise error: %v", err) } tests := []struct { body string }{ {"Bad Request"}, {"Bad\nRequest"}, } for _, tc := range tests { body = tc.body ctx := context.Background() _, err = c.GetPod(ctx) if err == nil { t.Errorf("should raise error") } u, _ := url.Parse(ts.URL) u.Path = path.Join(u.Path, podsPath) expected := fmt.Sprintf("got status code %d (url: %s, body: %q)", http.StatusBadRequest, u, tc.body) got := err.Error() if got != expected { t.Errorf("error message expected %q, got %q", expected, got) } } }
#!/usr/bin/perl ######################################################################## # Tim M Strom February 2007 ######################################################################## use strict; use CGI; BEGIN {require './Solexa.pm';} use DBI; ######################################################################## # global variables ######################################################################## #my $showedit = 'F'; my $cgiquery = new CGI; my $ref = $cgiquery->Vars; my $solexa = new Solexa; my $personref = ""; my @fields =(); my @values =(); my $sql = ""; my $sth = ""; my $id=$ref->{idpool}; my $forward = qq#<meta http-equiv="refresh" content="0; URL=pool.pl?id=$id&mode=edit">#; ######################################################################## # main ######################################################################## $solexa->printHeader($forward); my ($dbh) = $solexa->loadSessionId(); # encoded name # delete beginning and trailing space $solexa->deleteSpace($ref); if ($ref->{mode} eq "edit") { delete($ref->{"mode"}); $solexa->editLibrary2pool($ref,$dbh,'library2pool'); } else { delete($ref->{"mode"}); $solexa->insertIntoLibrary2pool($ref,$dbh,'library2pool'); } # select and display new entry #my $pool = ""; #my $id=""; #if ($showedit eq 'F') { # $solexa->showMenu("library2pool"); # $solexa->showAllLibrary2pool($dbh,$ref->{idlibrary2pool}); #} #else { # $pool = ""; # $id=$ref->{idpool}; # $pool = $solexa->initPool(); # $solexa->showMenu(""); # print "<span class=\"big\">Edit Pool</span><br><br>" ; # $solexa->showPool2library($dbh,$id); # print qq(<form action="poolInsert.pl" method="post" name=\"myform\">); # $solexa->getShowPool($dbh,$id,$pool,'noprint'); # $solexa->drawMask($pool); # print $cgiquery->hidden(-name=>'mode',-default=>'edit'); # print "</form>"; #} $solexa->printFooter($dbh);
# Bazaarbite Break down your OpenBazaar selling experience into bite sized tasks or something idk idk idk * keeps separate database of all items created in OpenBazaaar * fires events when things happen in openbazaar * [ ] customer pays for digital item * [ ] customer * plugin support to manage your items * [x] lib/randomFollower.js - picks a random follower (used in ob://@saveabit weekly giveaways) ## Usage create an environment file, `.env` with the following contents-- ``` OB_PASSWORD=enter_your_openbazaar_login_password OB_USERNAME=enter_your_openbazaar_login_username OB_HOST=123.456.789.123 OB_PORT=18469 OB_PROTO=https OB_CA=/path/to/your/rootCA.crt ``` or if your store is super insecure (no SSL)-- ``` OB_PASSWORD=enter_your_openbazaar_login_password OB_USERNAME=enter_your_openbazaar_login_username OB_HOST=123.456.789.123 OB_PORT=18469 OB_PROTO=http ``` then run the program or something nf run index
#include "backend.h" #include <string.h> #include <wayland-client.h> #include <zigen-client-protocol.h> #include <zigen-opengl-client-protocol.h> #include <zigen-shell-client-protocol.h> #include <zmonitors-util.h> #include "ray.h" #include "zmonitors-backend.h" static void seat_capabilities(void* data, struct zgn_seat* seat, uint32_t capability) { Z_UNUSED(seat); struct zms_backend* backend = data; if (capability & ZGN_SEAT_CAPABILITY_RAY && backend->ray == NULL) { backend->ray = zms_ray_create(backend); backend->interface->gain_ray_capability(backend->user_data); } if (!(capability & ZGN_SEAT_CAPABILITY_RAY) && backend->ray) { zms_ray_destroy(backend->ray); backend->ray = NULL; backend->interface->lose_ray_capability(backend->user_data); } if (capability & ZGN_SEAT_CAPABILITY_KEYBOARD && backend->keyboard == NULL) { backend->keyboard = zms_backend_keyboard_create(backend); backend->interface->gain_keyboard_capability(backend->user_data); } if (!(capability & ZGN_SEAT_CAPABILITY_KEYBOARD) && backend->keyboard) { zms_backend_keyboard_destroy(backend->keyboard); backend->keyboard = NULL; backend->interface->lose_keyboard_capability(backend->user_data); } } static const struct zgn_seat_listener seat_listener = { .capabilities = seat_capabilities, }; static void shm_format(void* data, struct wl_shm* shm, uint32_t format) { // we use only the default formats (0 and 1). Z_UNUSED(data); Z_UNUSED(shm); Z_UNUSED(format); } static const struct wl_shm_listener shm_listener = { .format = shm_format, }; static void global_registry_handler(void* data, struct wl_registry* registry, uint32_t id, const char* interface, uint32_t version) { struct zms_backend* backend = data; if (strcmp(interface, "zgn_compositor") == 0) { backend->compositor = wl_registry_bind(registry, id, &zgn_compositor_interface, version); } else if (strcmp(interface, "zgn_seat") == 0) { backend->seat = wl_registry_bind(registry, id, &zgn_seat_interface, version); zgn_seat_add_listener(backend->seat, &seat_listener, backend); } else if (strcmp(interface, "zgn_shell") == 0) { backend->shell = wl_registry_bind(registry, id, &zgn_shell_interface, version); } else if (strcmp(interface, "wl_shm") == 0) { backend->shm = wl_registry_bind(registry, id, &wl_shm_interface, version); wl_shm_add_listener(backend->shm, &shm_listener, backend); } else if (strcmp(interface, "zgn_opengl") == 0) { backend->opengl = wl_registry_bind(registry, id, &zgn_opengl_interface, version); } } static void global_registry_remover(void* data, struct wl_registry* registry, uint32_t id) { // TODO: zms_log("event not implemented yet: wl_registry.global_remove\n"); Z_UNUSED(data); Z_UNUSED(registry); Z_UNUSED(id); } static const struct wl_registry_listener registry_listener = { .global = global_registry_handler, .global_remove = global_registry_remover, }; ZMS_EXPORT struct zms_backend* zms_backend_create( void* user_data, const struct zms_backend_interface* interface) { struct zms_backend* backend; backend = zalloc(sizeof *backend); if (backend == NULL) { zms_log("failed to allocate memory\n"); goto err; } backend->display = NULL; backend->user_data = user_data; backend->interface = interface; return backend; err: return NULL; } ZMS_EXPORT void zms_backend_destroy(struct zms_backend* backend) { if (backend->display) wl_display_disconnect(backend->display); free(backend); } ZMS_EXPORT bool zms_backend_connect(struct zms_backend* backend, const char* socket) { struct wl_display* display; struct wl_registry* registry; display = wl_display_connect(socket); if (display == NULL) goto err; registry = wl_display_get_registry(display); if (registry == NULL) goto err_registry; wl_registry_add_listener(registry, &registry_listener, backend); backend->display = display; wl_display_dispatch(display); wl_display_roundtrip(display); if (backend->compositor == NULL || backend->seat == NULL || backend->shell == NULL || backend->shm == NULL || backend->opengl == NULL) goto err_globals; return true; err_globals: wl_registry_destroy(registry); err_registry: wl_display_disconnect(display); backend->display = NULL; err: return false; } ZMS_EXPORT int zms_backend_get_fd(struct zms_backend* backend) { return wl_display_get_fd(backend->display); } ZMS_EXPORT int zms_backend_dispatch(struct zms_backend* backend) { return wl_display_dispatch(backend->display); } ZMS_EXPORT int zms_backend_flush(struct zms_backend* backend) { return wl_display_flush(backend->display); } ZMS_EXPORT int zms_backend_dispatch_pending(struct zms_backend* backend) { return wl_display_dispatch_pending(backend->display); }
import {Injectable} from "angular2/core"; import {Observer} from "rxjs/Observer"; import {Observable} from "rxjs/Observable"; import "rxjs/add/operator/share"; import {Product} from "./product"; import {Family} from "./family/family"; import {Category} from "./category/category"; export class ProductManagerService { /* * ///////// ATTRIBUTES ///////// * */ // //// PRODUCTS //// // Edit-product -> product that shall be edited private editProductObservable: Observable<Product>; private _editProductObserver: Observer<Product>; // Add-product -> product that shall be added private addProductObservable: Observable<Product>; private _addProductObserver: Observer<Product>; // Delete-product -> product that shall be deleted private deleteProductObservable: Observable<Product>; private _deleteProductObserver: Observer<Product>; // //// FAMILIES //// private editFamilyObservable: Observable<Family>; private _editFamilyObserver: Observer<Family>; private addFamilyObservable: Observable<Family>; private _addFamilyObserver: Observer<Family>; private deleteFamilyObservable: Observable<Family>; private _deleteFamilyObserver: Observer<Family>; // //// CATEGORIES //// private editCategoryObservable: Observable<Category>; private _editCategoryObserver: Observer<Category>; private addCategoryObservable: Observable<Category>; private _addCategoryObserver: Observer<Category>; private deleteCategoryObservable: Observable<Category>; private _deleteCategoryObserver: Observer<Category>; /* * ///////// INITIALIZATION ///////// * */ constructor() { // //// PRODUCTS //// this.editProductObservable = new Observable(observer => this._editProductObserver = observer).share(); this.addProductObservable = new Observable(observer => this._addProductObserver = observer).share(); this.deleteProductObservable = new Observable(observer => this._deleteProductObserver = observer).share(); // //// FAMILIES //// this.editFamilyObservable = new Observable(observer => this._editFamilyObserver = observer).share(); this.addFamilyObservable = new Observable(observer => this._addFamilyObserver = observer).share(); this.deleteFamilyObservable = new Observable(observer => this._deleteFamilyObserver = observer).share(); // //// CATEGORIES //// this.editCategoryObservable = new Observable(observer => this._editCategoryObserver = observer).share(); this.addCategoryObservable = new Observable(observer => this._addCategoryObserver = observer).share(); this.deleteCategoryObservable = new Observable(observer => this._deleteCategoryObserver = observer).share(); } /* * ///////// HELPERS ///////// * */ // //// PRODUCTS //// getEditProduct() { return this.editProductObservable; } setEditProduct(product: Product) { this._editProductObserver.next(product); } getAddProduct() { return this.addProductObservable; } setAddProduct(product: Product) { this._addProductObserver.next(product); } getDeleteProduct() { return this.deleteProductObservable; } setDeleteProduct(product: Product) { this._deleteProductObserver.next(product); } // //// FAMILIES //// getEditFamily() { return this.editFamilyObservable; } setEditFamily(family: Family) { this._editFamilyObserver.next(family); } getAddFamily() { return this.addFamilyObservable; } setAddFamily(family: Family) { this._addFamilyObserver.next(family); } getDeleteFamily() { return this.deleteFamilyObservable; } setDeleteFamily(family: Family) { this._deleteFamilyObserver.next(family); } // //// CATEGORIES //// getEditCategory() { return this.editCategoryObservable; } setEditCategory(category: Category) { this._editCategoryObserver.next(category); } getAddCategory() { return this.addCategoryObservable; } setAddCategory(category: Category) { this._addCategoryObserver.next(category); } getDeleteCategory() { return this.deleteCategoryObservable; } setDeleteCategory(category: Category) { this._deleteCategoryObserver.next(category); } }
import type { JSXNode } from '../render/jsx/types/jsx-node'; import { QError, qError } from '../error/error'; import { getProxyMap, readWriteProxy } from '../object/q-object'; import { resumeContainer } from '../object/store'; import type { RenderContext } from '../render/cursor'; import { getDocument } from '../util/dom'; import { newQObjectMap, QObjectMap } from './props-obj-map'; import { qPropWriteQRL } from './props-on'; import { QContainerAttr } from '../util/markers'; import type { QRL } from '../import/qrl.public'; import type { OnRenderFn } from '../component/component.public'; import { destroyWatch, isWatchDescriptor } from '../watch/watch.public'; import { pauseContainer } from '../object/store.public'; import { getRenderingState } from '../render/notify-render'; import { qDev } from '../util/qdev'; Error.stackTraceLimit = 9999; const Q_CTX = '__ctx__'; export function resumeIfNeeded(containerEl: Element): void { const isResumed = containerEl.getAttribute(QContainerAttr); if (isResumed === 'paused') { resumeContainer(containerEl); if (qDev) { appendQwikDevTools(containerEl); } } } export function appendQwikDevTools(containerEl: Element) { (containerEl as any)['qwik'] = { pause: () => pauseContainer(containerEl), renderState: getRenderingState(containerEl), }; } export interface QContextEvents { [eventName: string]: QRL | undefined; } /** * @alpha */ export interface ComponentCtx { hostElement: HTMLElement; styleId: string | undefined; styleClass: string | undefined; styleHostClass: string | undefined; slots: JSXNode[]; } export interface QContext { cache: Map<string, any>; refMap: QObjectMap; element: Element; dirty: boolean; props: Record<string, any> | undefined; renderQrl: QRL<OnRenderFn<any>> | undefined; seq: number[]; component: ComponentCtx | undefined; listeners?: Map<string, QRL<any>[]>; contexts?: Map<string, any>; } export function tryGetContext(element: Element): QContext | undefined { return (element as any)[Q_CTX]; } export function getContext(element: Element): QContext { let ctx = tryGetContext(element)!; if (!ctx) { const cache = new Map(); (element as any)[Q_CTX] = ctx = { element, cache, refMap: newQObjectMap(element), dirty: false, seq: [], props: undefined, renderQrl: undefined, component: undefined, }; } return ctx; } export function cleanupContext(ctx: QContext) { const el = ctx.element; ctx.refMap.array.forEach((obj) => { if (isWatchDescriptor(obj)) { if (obj.el === el) { destroyWatch(obj); } } ctx.component = undefined; ctx.renderQrl = undefined; ctx.seq = []; ctx.cache.clear(); ctx.dirty = false; ctx.refMap.array.length = 0; }); (el as any)[Q_CTX] = undefined; } const PREFIXES = ['document:on', 'window:on', 'on']; const SCOPED = ['on-document', 'on-window', 'on']; export function normalizeOnProp(prop: string) { let scope = 'on'; for (let i = 0; i < PREFIXES.length; i++) { const prefix = PREFIXES[i]; if (prop.startsWith(prefix)) { scope = SCOPED[i]; prop = prop.slice(prefix.length); } } if (prop.startsWith('-')) { prop = prop.slice(1); } else { prop = prop.toLowerCase(); } return `${scope}:${prop}`; } export function setEvent(rctx: RenderContext, ctx: QContext, prop: string, value: any) { qPropWriteQRL(rctx, ctx, normalizeOnProp(prop), value); } export function getProps(ctx: QContext) { if (!ctx.props) { ctx.props = readWriteProxy({}, getProxyMap(getDocument(ctx.element))); ctx.refMap.add(ctx.props); } return ctx.props!; } /** * Turn an `Array` or object literal into a `class` or `style` * * @param obj `string`, `Array` or object literal * @param isClass `true` if expecting `class` output * @returns `string` */ export function stringifyClassOrStyle(obj: any, isClass: boolean): string { if (obj == null) return ''; if (typeof obj == 'object') { let text = ''; let sep = ''; if (Array.isArray(obj)) { if (!isClass) { throw qError(QError.Render_unsupportedFormat_obj_attr, obj, 'style'); } for (let i = 0; i < obj.length; i++) { text += sep + obj[i]; sep = ' '; } } else { for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { const value = obj[key]; text += isClass ? (value ? sep + key : '') : sep + key + ':' + value; sep = isClass ? ' ' : ';'; } } } return text; } return String(obj); }
/// Smallest Multiple - https://projecteuler.net/problem=5 /// /// 2520 is the smallest number that can be divided by each of the numbers from /// 1 to 10 without any remainder. /// ///What is the smallest positive number that is evenly divisible by all of the ///numbers from 1 to 20? use std::collections::HashMap; //use std::collections::Vec; /// Return a dictionary with prime keys and exponent values /// /// The product of all the keys raised to their exponent is the number /// /// # Example: /// /// 20 = 2 ** 2 * 5 -> {2: 2, 5:1} /// fn get_prime_product(n: u64) -> HashMap<u64, u64> { let mut result: HashMap<u64, u64> = HashMap::new(); let primes_to_20 = [2, 3, 5, 7, 11, 13, 17, 19]; // Handle quickly case where the number is already prime let found = primes_to_20.iter().find(|&x| *x == n); match found { Some(_) => { result.insert(n, 1); return result; } None => { } } // Initialize all multiples to primes to 0 for p in primes_to_20.iter() { result.insert(*p, 0); } let mut number: u64 = n; for p in primes_to_20.iter() { while number % *p == 0 { let x = result[p].clone(); result.insert(*p, x + 1); number /= *p; } } result = result.iter().filter(|&(_, v)| *v != 0) .map(|(&k, &v)| (k, v)) .collect(); return result; } fn main() { let mut result: HashMap<u64, u64> = HashMap::new(); for n in 0..19 { let prime_product = get_prime_product(20 - n); for (&k, &v) in prime_product.iter() { if !result.contains_key(&k) || v > result[&k] { result.insert(k, v); } } } let mut final_number = 1; for (&k, &v) in result.iter() { final_number *= k.pow(v as u32); } println!("{}", final_number); assert_eq!(232792560, final_number) }
// This sample program demonstrates how to use the pool package to use a pool // of goroutines to get work done. package main import ( "log" "sync" "time" "github.com/george-kj/go-code/concurrency/patterns/pool" ) // names provides a set of names to display. var names = []string{ "steve", "bob", "mary", "therese", "jason", } // namePrinter provides special support for printing names. type namePrinter struct { name string } // Work implements the Worker interface. func (m namePrinter) Work() { log.Println(m.name) time.Sleep(3 * time.Second) } func main() { const routines = 10 // Create a task pool. t := pool.New(routines) var wg sync.WaitGroup wg.Add(routines * len(names)) for i := 0; i < routines; i++ { // Iterate over the slice of names. for _, name := range names { // Create a namePrinter and provide the specific name. np := namePrinter{ name: name, } go func(np namePrinter) { // Submit the task to be worked on. When Do returns, we know it is // being handled. t.Do(np) wg.Done() }(np) } } wg.Wait() // Shutdown the task pool and wait for all existing work to be completed. t.Shutdown() }
package de.fabmax.kool.util import de.fabmax.kool.KoolException /** * Super class for platform-dependent buffers. In the JVM these buffers directly map to the corresponding NIO buffers. * However, not all operations of NIO buffers are supported. * * Notice that Buffer is not generic, so that concrete types remain primitive. * * @author fabmax */ interface Buffer { var limit: Int var position: Int val remaining: Int val capacity: Int fun flip() fun clear() fun removeAt(index: Int) { if (position > index) { position-- } if (limit > index) { limit-- } } } /** * Represents a buffer for bytes. * * @author fabmax */ interface Uint8Buffer : Buffer { operator fun get(i: Int): Byte operator fun set(i: Int, value: Byte) operator fun plusAssign(value: Byte) { put(value) } fun put(value: Byte): Uint8Buffer fun put(data: ByteArray): Uint8Buffer = put(data, 0, data.size) fun put(data: ByteArray, offset: Int, len: Int): Uint8Buffer fun put(data: Uint8Buffer): Uint8Buffer fun toArray(): ByteArray { val array = ByteArray(capacity) for (i in 0 until capacity) { array[i] = get(i) } return array } override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for shorts. * * @author fabmax */ interface Uint16Buffer : Buffer { operator fun get(i: Int): Short operator fun set(i: Int, value: Short) operator fun plusAssign(value: Short) { put(value) } fun put(value: Short): Uint16Buffer fun put(data: ShortArray): Uint16Buffer = put(data, 0, data.size) fun put(data: ShortArray, offset: Int, len: Int): Uint16Buffer fun put(data: Uint16Buffer): Uint16Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for ints. * * @author fabmax */ interface Uint32Buffer : Buffer { operator fun get(i: Int): Int operator fun set(i: Int, value: Int) operator fun plusAssign(value: Int) { put(value) } fun put(value: Int): Uint32Buffer fun put(data: IntArray): Uint32Buffer = put(data, 0, data.size) fun put(data: IntArray, offset: Int, len: Int): Uint32Buffer fun put(data: Uint32Buffer): Uint32Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer for floats. * * @author fabmax */ interface Float32Buffer : Buffer { operator fun get(i: Int): Float operator fun set(i: Int, value: Float) operator fun plusAssign(value: Float) { put(value) } fun put(value: Float): Float32Buffer fun put(data: FloatArray): Float32Buffer = put(data, 0, data.size) fun put(data: FloatArray, offset: Int, len: Int): Float32Buffer fun put(data: Float32Buffer): Float32Buffer override fun removeAt(index: Int) { for (i in index until position) { this[i] = this[i+1] } super.removeAt(index) } } /** * Represents a buffer containing mixed type data. All buffer positions are in bytes. * * @author fabmax */ interface MixedBuffer : Buffer { fun putInt8(value: Byte) = putUint8(value) fun putInt8(data: ByteArray) = putUint8(data) fun putInt8(data: ByteArray, offset: Int, len: Int) = putUint8(data, offset, len) fun putInt8(data: Uint8Buffer) = putUint8(data) fun putInt16(value: Short) = putUint16(value) fun putInt16(data: ShortArray) = putUint16(data) fun putInt16(data: ShortArray, offset: Int, len: Int) = putUint16(data, offset, len) fun putInt16(data: Uint16Buffer) = putUint16(data) fun putInt32(value: Int) = putUint32(value) fun putInt32(data: IntArray) = putUint32(data) fun putInt32(data: IntArray, offset: Int, len: Int) = putUint32(data, offset, len) fun putInt32(data: Uint32Buffer) = putUint32(data) fun putUint8(value: Byte): MixedBuffer fun putUint8(data: ByteArray): MixedBuffer = putUint8(data, 0, data.size) fun putUint8(data: ByteArray, offset: Int, len: Int): MixedBuffer fun putUint8(data: Uint8Buffer): MixedBuffer fun putUint16(value: Short): MixedBuffer fun putUint16(data: ShortArray): MixedBuffer = putUint16(data, 0, data.size) fun putUint16(data: ShortArray, offset: Int, len: Int): MixedBuffer fun putUint16(data: Uint16Buffer): MixedBuffer fun putUint32(value: Int): MixedBuffer fun putUint32(data: IntArray): MixedBuffer = putUint32(data, 0, data.size) fun putUint32(data: IntArray, offset: Int, len: Int): MixedBuffer fun putUint32(data: Uint32Buffer): MixedBuffer fun putFloat32(value: Float): MixedBuffer fun putFloat32(data: FloatArray): MixedBuffer = putFloat32(data, 0, data.size) fun putFloat32(data: FloatArray, offset: Int, len: Int): MixedBuffer fun putFloat32(data: Float32Buffer): MixedBuffer override fun removeAt(index: Int) { throw KoolException("MixedBuffer does not support element removal") } } expect fun createUint8Buffer(capacity: Int): Uint8Buffer expect fun createUint16Buffer(capacity: Int): Uint16Buffer expect fun createUint32Buffer(capacity: Int): Uint32Buffer expect fun createFloat32Buffer(capacity: Int): Float32Buffer expect fun createMixedBuffer(capacity: Int): MixedBuffer
package com.nick_sib.popularlibraries.di.module import dagger.Module import dagger.Provides import ru.terrakok.cicerone.Cicerone import ru.terrakok.cicerone.NavigatorHolder import ru.terrakok.cicerone.Router import javax.inject.Singleton @Module class CiceroneModule { var cicerone: Cicerone<Router> = Cicerone.create() @Provides fun cicerone(): Cicerone<Router> = cicerone @Singleton @Provides fun navigatorHolder(): NavigatorHolder = cicerone.navigatorHolder @Singleton @Provides fun router(): Router = cicerone.router }
$LanManagerSettings = @{ Enable = $true Scope = 'DC' Source = @{ Name = "Lan Manager Settings" Data = { Get-WinADLMSettings -DomainController $DomainController } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( 'https://adsecurity.org/?p=3377' ) } Requirements = @{ CommandAvailable = 'Get-WinADLMSettings' } ExpectedOutput = $true } Tests = [ordered] @{ Level = @{ Enable = $true Name = 'LM Level' Parameters = @{ Property = 'Level' ExpectedValue = 5 OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } AuditBaseObjects = @{ Enable = $true Name = 'Audit Base Objects' Parameters = @{ Property = 'AuditBaseObjects' ExpectedValue = $false OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( 'https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-gpac/262a2bed-93d4-4c04-abec-cf06e9ec72fd' ) } } CrashOnAuditFail = @{ Enable = $true Name = 'Crash On Audit Fail' Parameters = @{ Property = 'CrashOnAuditFail' ExpectedValue = 0 OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( 'http://systemmanager.ru/win2k_regestry.en/46686.htm' ) } } EveryoneIncludesAnonymous = @{ Enable = $true Name = 'Everyone Includes Anonymous' Parameters = @{ Property = 'EveryoneIncludesAnonymous' ExpectedValue = $false OperationType = 'eq' } Details = [ordered] @{ Title = 'Disable and Enforce the Setting "Network access: Let Everyone permissions apply to anonymous users"' Area = '' Description = 'This setting helps to prevent an unauthorized user could from anonymously listing account names and shared resources and use using the information to attempt to guess passwords, perform social engineering attacks, or launch DoS attacks.' Resolution = '' Importance = 10 Resources = @( 'https://www.stigviewer.com/stig/windows_7/2014-04-02/finding/V-3377' ) } } SecureBoot = @{ Enable = $true Name = 'Secure Boot' Parameters = @{ Property = 'SecureBoot' ExpectedValue = $true OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } LSAProtectionCredentials = @{ Enable = $true Name = 'LSAProtectionCredentials' Parameters = @{ Property = 'LSAProtectionCredentials' ExpectedValue = $true OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } LimitBlankPasswordUse = @{ Enable = $true Name = 'LimitBlankPasswordUse' Parameters = @{ Property = 'LimitBlankPasswordUse' ExpectedValue = $true OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } NoLmHash = @{ Enable = $true Name = 'NoLmHash' Parameters = @{ Property = 'NoLmHash' ExpectedValue = $true OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } DisableDomainCreds = @{ Enable = $true Name = 'DisableDomainCreds' Parameters = @{ Property = 'DisableDomainCreds' ExpectedValue = $false OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( 'https://www.stigviewer.com/stig/windows_8/2014-01-07/finding/V-3376' ) } } ForceGuest = @{ Enable = $true Name = 'ForceGuest' Parameters = @{ Property = 'ForceGuest' ExpectedValue = $false OperationType = 'eq' } Details = [ordered] @{ Area = '' Description = '' Resolution = '' Importance = 10 Resources = @( ) } } } }
{-# LANGUAGE OverloadedStrings #-} module Bot.Quote where import Bot.Replies import Command import Control.Monad import qualified Data.Map as M import Data.Maybe import qualified Data.Text as T import Data.Time import Effect import Entity import Events import Property import Text.Printf import Text.Read data Quote = Quote { quoteContent :: T.Text , quoteQuoter :: T.Text , quoteTimestamp :: UTCTime } instance IsEntity Quote where toProperties quote = M.fromList [ ("content", PropertyText $ quoteContent quote) , ("quoter", PropertyText $ quoteQuoter quote) , ("timestamp", PropertyUTCTime $ quoteTimestamp quote) ] fromProperties properties = do content <- extractProperty "content" properties quoter <- extractProperty "quoter" properties timestamp <- extractProperty "timestamp" properties return Quote { quoteContent = content , quoteQuoter = quoter , quoteTimestamp = timestamp } deleteQuoteCommand :: CommandHandler T.Text deleteQuoteCommand sender quoteIdText = case readMaybe $ T.unpack quoteIdText of Just quoteId -> do deleteEntityById "quote" quoteId replyToSender sender "Quote has been deleted" Nothing -> replyToSender sender "Could not find quote with such id" addQuoteCommand :: CommandHandler T.Text addQuoteCommand sender content = do timestamp <- now quoter <- return $ senderName sender quote <- return Quote { quoteContent = content , quoteQuoter = quoter , quoteTimestamp = timestamp } entity <- createEntity "quote" quote quoteAddedReply quoter $ entityId entity quoteCommand :: CommandHandler T.Text quoteCommand sender "" = fmap listToMaybe (selectEntities "quote" (Take 1 $ Shuffle All)) >>= quoteFoundReply (senderName sender) quoteCommand sender quoteIdText = maybe (replyToUser (senderName sender) "Couldn't find any quotes") (getEntityById "quote" >=> quoteFoundReply (senderName sender)) (readMaybe $ T.unpack quoteIdText) quoteAddedReply :: T.Text -> Int -> Effect () quoteAddedReply user quoteId = replyToUser user $ T.pack $ printf "Added the quote under the number %d" quoteId quoteFoundReply :: T.Text -> Maybe (Entity Quote) -> Effect () quoteFoundReply user Nothing = replyToUser user "Couldn't find any quotes" quoteFoundReply user (Just entity) = replyToUser user $ T.pack $ printf "%s (%d)" (quoteContent $ entityPayload entity) (entityId entity)
use strict; use warnings; use lib 't/lib'; use Test::More; use Test::MockObject; use Test::MockModule; use Test::Trap; use App::DB::Migrate::SQLite::Constraint::Default; subtest 'new creates a Default constraint' => sub { my $def = App::DB::Migrate::SQLite::Constraint::Default->new(5, { type => 1 }); isa_ok($def, 'App::DB::Migrate::SQLite::Constraint::Default'); isa_ok($def, 'App::DB::Migrate::Constraint::Default'); isa_ok($def, 'App::DB::Migrate::Constraint'); }; subtest 'current_timestamp returns CURRENT_TIMESTAMP' => sub { is(App::DB::Migrate::SQLite::Constraint::Default->current_timestamp, 'CURRENT_TIMESTAMP'); }; done_testing();
/** * $File: JCS_SlideInput.cs $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ using UnityEngine; using System.Collections; namespace JCSUnity { /// <summary> /// Use this to receive the slide input from the device buffer. /// </summary> public class JCS_SlideInput : MonoBehaviour { /* Variables */ #if (UNITY_EDITOR || UNITY_STANDALONE) [Header("** Check Variables (JCS_SlideInput) **")] [Tooltip("Previous position.")] [SerializeField] private Vector3 mPrePos = Vector3.zero; [Tooltip("Is the application currently focused?")] [SerializeField] private bool mFocus = false; #endif [Header("** Runtime Variables (JCS_SlideInput) **")] [Tooltip("Is the screen touches?")] [SerializeField] private bool mTouched = false; [Tooltip("Delta value changes on the screen.")] [SerializeField] private Vector2 mDeltaPos = Vector2.zero; /* Setter & Getter */ public bool Touched { get { return this.mTouched; } } public Vector2 DeltaPos { get { return this.mDeltaPos; } } /* Functions */ #if (UNITY_EDITOR || UNITY_STANDALONE) private void OnApplicationFocus(bool focus) { if (focus) { mFocus = true; } else { // Do something when not focus? } } #endif private void Start() { // set to manager in order to get manage by "JCS_InputManager" JCS_InputManager.instance.SetJCSSlideInput(this); } private void Update() { #if (UNITY_EDITOR || UNITY_STANDALONE) mTouched = Input.GetMouseButton(0); Vector3 currPos = Input.mousePosition; // Don't update delta pos when window just focus. if (mTouched && !mFocus) { mDeltaPos = currPos - mPrePos; } else { mDeltaPos = Vector2.zero; // If focus, ignore one frame. mFocus = false; } mPrePos = currPos; #elif (UNITY_ANDROID || UNITY_IPHIONE || UNITY_IOS) // Detect Touch mTouched = (Input.touchCount == 1); if (mTouched) { mDeltaPos = Input.GetTouch(0).deltaPosition; } #endif } } }
import { HttpModule, Module } from '@nestjs/common'; import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core'; import { RequestLoggingInterceptor } from './http/interceptors/request.logging.interceptor'; import { JwtStrategy } from './http/strategies/jwt.strategy'; import { EvalySecretStrategy } from './http/strategies/evaly-secret.strategy'; import { PassportModule } from '@nestjs/passport'; import { JwtModule } from '@nestjs/jwt'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { ErrorsLoggerInterceptor } from './http/interceptors/errors.logger.interceptor'; import { ResponseTransformInterceptor } from './http/interceptors/response.transform.interceptor'; import { AuthServiceStrategy } from './http/strategies/auth-service.strategy'; import { HttpExceptionFilter } from './http/filters/exeptions.formatter.filter'; @Module({ imports: [ PassportModule, JwtModule.registerAsync({ imports: [ConfigModule], useFactory: async (configService: ConfigService) => ({ secret: configService.get<string>('JWT_SECRET_KEY'), }), inject: [ConfigService], }), ConfigModule, HttpModule, ], providers: [ { provide: APP_INTERCEPTOR, useClass: RequestLoggingInterceptor, }, { provide: APP_INTERCEPTOR, useClass: ErrorsLoggerInterceptor, }, { provide: APP_INTERCEPTOR, useClass: ResponseTransformInterceptor, }, { provide: APP_FILTER, useClass: HttpExceptionFilter, }, JwtStrategy, AuthServiceStrategy, EvalySecretStrategy, ], }) export class CoreModule {}
<?php declare(strict_types=1); namespace Podium\Tests\Stubs; use Podium\ActiveRecordApi\ActiveRecords\MemberActiveRecord; class MemberActiveRecordStub extends MemberActiveRecord { use ActiveRecordStubTrait; public function attributes(): array { return ['id', 'user_id', 'username', 'slug', 'status_id', 'created_at', 'updated_at']; } }
using Gibbit.Core.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Gibbit.Core.Managers { public class UrlManager { public string User = "https://api.github.com/user"; public string Starred(User user) { return $"{user.Url}/starred"; } public string Search(string query, int page) { var searchSettings = "&sort=stars&order=desc&per_page=10"; return $"https://api.github.com/search/repositories?q={query}{searchSettings}&page={page}"; } public string Readme(Repo repo) { return $"{repo.Url}/readme"; } public string Commits(Repo repo) { return $"{repo.Url}/commits"; } public string Star(Repo repo) { return $"https://api.github.com/user/starred/{repo.Owner.Name}/{repo.Name}"; } } }
# SUSE's openQA tests # # Copyright 2021 SUSE LLC # SPDX-License-Identifier: FSFAP # # Summary: Run 'audit-trail-protection' test case of 'audit-test' test suite # Maintainer: rfan1 <richard.fan@suse.com>, Liu Xiaojing <xiaojing.liu@suse.com> # Tags: poo#94447 use base 'consoletest'; use strict; use warnings; use testapi; use utils; use audit_test qw(run_testcase compare_run_log); sub run { my ($self) = shift; select_console 'root-console'; run_testcase('audit-trail-protection', (make => 1)); # Compare current test results with baseline my $result = compare_run_log('audit-trail-protection'); $self->result($result); } 1;
# Open the node api for your current version to the optional section. # TODO: Make the section part easier to use. function node-docs { # get the open command local open_cmd if [[ $(uname -s) == 'Darwin' ]]; then open_cmd='open' else open_cmd='xdg-open' fi $open_cmd "http://nodejs.org/docs/$(node --version)/api/all.html#all_$1" }
// Code generated by smithy-go-codegen DO NOT EDIT. package types type ApplicationInstanceHealthStatus string // Enum values for ApplicationInstanceHealthStatus const ( ApplicationInstanceHealthStatusRunning ApplicationInstanceHealthStatus = "RUNNING" ApplicationInstanceHealthStatusError ApplicationInstanceHealthStatus = "ERROR" ApplicationInstanceHealthStatusNotAvailable ApplicationInstanceHealthStatus = "NOT_AVAILABLE" ) // Values returns all known values for ApplicationInstanceHealthStatus. Note that // this can be expanded in the future, and so it is only as up to date as the // client. The ordering of this slice is not guaranteed to be stable across // updates. func (ApplicationInstanceHealthStatus) Values() []ApplicationInstanceHealthStatus { return []ApplicationInstanceHealthStatus{ "RUNNING", "ERROR", "NOT_AVAILABLE", } } type ApplicationInstanceStatus string // Enum values for ApplicationInstanceStatus const ( ApplicationInstanceStatusDeploymentPending ApplicationInstanceStatus = "DEPLOYMENT_PENDING" ApplicationInstanceStatusDeploymentRequested ApplicationInstanceStatus = "DEPLOYMENT_REQUESTED" ApplicationInstanceStatusDeploymentInProgress ApplicationInstanceStatus = "DEPLOYMENT_IN_PROGRESS" ApplicationInstanceStatusDeploymentError ApplicationInstanceStatus = "DEPLOYMENT_ERROR" ApplicationInstanceStatusDeploymentSucceeded ApplicationInstanceStatus = "DEPLOYMENT_SUCCEEDED" ApplicationInstanceStatusRemovalPending ApplicationInstanceStatus = "REMOVAL_PENDING" ApplicationInstanceStatusRemovalRequested ApplicationInstanceStatus = "REMOVAL_REQUESTED" ApplicationInstanceStatusRemovalInProgress ApplicationInstanceStatus = "REMOVAL_IN_PROGRESS" ApplicationInstanceStatusRemovalFailed ApplicationInstanceStatus = "REMOVAL_FAILED" ApplicationInstanceStatusRemovalSucceeded ApplicationInstanceStatus = "REMOVAL_SUCCEEDED" ) // Values returns all known values for ApplicationInstanceStatus. Note that this // can be expanded in the future, and so it is only as up to date as the client. // The ordering of this slice is not guaranteed to be stable across updates. func (ApplicationInstanceStatus) Values() []ApplicationInstanceStatus { return []ApplicationInstanceStatus{ "DEPLOYMENT_PENDING", "DEPLOYMENT_REQUESTED", "DEPLOYMENT_IN_PROGRESS", "DEPLOYMENT_ERROR", "DEPLOYMENT_SUCCEEDED", "REMOVAL_PENDING", "REMOVAL_REQUESTED", "REMOVAL_IN_PROGRESS", "REMOVAL_FAILED", "REMOVAL_SUCCEEDED", } } type ConnectionType string // Enum values for ConnectionType const ( ConnectionTypeStaticIp ConnectionType = "STATIC_IP" ConnectionTypeDhcp ConnectionType = "DHCP" ) // Values returns all known values for ConnectionType. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (ConnectionType) Values() []ConnectionType { return []ConnectionType{ "STATIC_IP", "DHCP", } } type DeviceConnectionStatus string // Enum values for DeviceConnectionStatus const ( DeviceConnectionStatusOnline DeviceConnectionStatus = "ONLINE" DeviceConnectionStatusOffline DeviceConnectionStatus = "OFFLINE" DeviceConnectionStatusAwaitingCredentials DeviceConnectionStatus = "AWAITING_CREDENTIALS" DeviceConnectionStatusNotAvailable DeviceConnectionStatus = "NOT_AVAILABLE" DeviceConnectionStatusError DeviceConnectionStatus = "ERROR" ) // Values returns all known values for DeviceConnectionStatus. Note that this can // be expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (DeviceConnectionStatus) Values() []DeviceConnectionStatus { return []DeviceConnectionStatus{ "ONLINE", "OFFLINE", "AWAITING_CREDENTIALS", "NOT_AVAILABLE", "ERROR", } } type DeviceStatus string // Enum values for DeviceStatus const ( DeviceStatusAwaitingProvisioning DeviceStatus = "AWAITING_PROVISIONING" DeviceStatusPending DeviceStatus = "PENDING" DeviceStatusSucceeded DeviceStatus = "SUCCEEDED" DeviceStatusFailed DeviceStatus = "FAILED" DeviceStatusError DeviceStatus = "ERROR" DeviceStatusDeleting DeviceStatus = "DELETING" ) // Values returns all known values for DeviceStatus. Note that this can be expanded // in the future, and so it is only as up to date as the client. The ordering of // this slice is not guaranteed to be stable across updates. func (DeviceStatus) Values() []DeviceStatus { return []DeviceStatus{ "AWAITING_PROVISIONING", "PENDING", "SUCCEEDED", "FAILED", "ERROR", "DELETING", } } type DeviceType string // Enum values for DeviceType const ( DeviceTypePanoramaApplianceDeveloperKit DeviceType = "PANORAMA_APPLIANCE_DEVELOPER_KIT" DeviceTypePanoramaAppliance DeviceType = "PANORAMA_APPLIANCE" ) // Values returns all known values for DeviceType. Note that this can be expanded // in the future, and so it is only as up to date as the client. The ordering of // this slice is not guaranteed to be stable across updates. func (DeviceType) Values() []DeviceType { return []DeviceType{ "PANORAMA_APPLIANCE_DEVELOPER_KIT", "PANORAMA_APPLIANCE", } } type JobResourceType string // Enum values for JobResourceType const ( JobResourceTypePackage JobResourceType = "PACKAGE" ) // Values returns all known values for JobResourceType. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (JobResourceType) Values() []JobResourceType { return []JobResourceType{ "PACKAGE", } } type JobType string // Enum values for JobType const ( JobTypeOta JobType = "OTA" ) // Values returns all known values for JobType. Note that this can be expanded in // the future, and so it is only as up to date as the client. The ordering of this // slice is not guaranteed to be stable across updates. func (JobType) Values() []JobType { return []JobType{ "OTA", } } type NetworkConnectionStatus string // Enum values for NetworkConnectionStatus const ( NetworkConnectionStatusConnected NetworkConnectionStatus = "CONNECTED" NetworkConnectionStatusNotConnected NetworkConnectionStatus = "NOT_CONNECTED" NetworkConnectionStatusConnecting NetworkConnectionStatus = "CONNECTING" ) // Values returns all known values for NetworkConnectionStatus. Note that this can // be expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (NetworkConnectionStatus) Values() []NetworkConnectionStatus { return []NetworkConnectionStatus{ "CONNECTED", "NOT_CONNECTED", "CONNECTING", } } type NodeCategory string // Enum values for NodeCategory const ( NodeCategoryBusinessLogic NodeCategory = "BUSINESS_LOGIC" NodeCategoryMlModel NodeCategory = "ML_MODEL" NodeCategoryMediaSource NodeCategory = "MEDIA_SOURCE" NodeCategoryMediaSink NodeCategory = "MEDIA_SINK" ) // Values returns all known values for NodeCategory. Note that this can be expanded // in the future, and so it is only as up to date as the client. The ordering of // this slice is not guaranteed to be stable across updates. func (NodeCategory) Values() []NodeCategory { return []NodeCategory{ "BUSINESS_LOGIC", "ML_MODEL", "MEDIA_SOURCE", "MEDIA_SINK", } } type NodeFromTemplateJobStatus string // Enum values for NodeFromTemplateJobStatus const ( NodeFromTemplateJobStatusPending NodeFromTemplateJobStatus = "PENDING" NodeFromTemplateJobStatusSucceeded NodeFromTemplateJobStatus = "SUCCEEDED" NodeFromTemplateJobStatusFailed NodeFromTemplateJobStatus = "FAILED" ) // Values returns all known values for NodeFromTemplateJobStatus. Note that this // can be expanded in the future, and so it is only as up to date as the client. // The ordering of this slice is not guaranteed to be stable across updates. func (NodeFromTemplateJobStatus) Values() []NodeFromTemplateJobStatus { return []NodeFromTemplateJobStatus{ "PENDING", "SUCCEEDED", "FAILED", } } type NodeInstanceStatus string // Enum values for NodeInstanceStatus const ( NodeInstanceStatusRunning NodeInstanceStatus = "RUNNING" NodeInstanceStatusError NodeInstanceStatus = "ERROR" NodeInstanceStatusNotAvailable NodeInstanceStatus = "NOT_AVAILABLE" ) // Values returns all known values for NodeInstanceStatus. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (NodeInstanceStatus) Values() []NodeInstanceStatus { return []NodeInstanceStatus{ "RUNNING", "ERROR", "NOT_AVAILABLE", } } type PackageImportJobStatus string // Enum values for PackageImportJobStatus const ( PackageImportJobStatusPending PackageImportJobStatus = "PENDING" PackageImportJobStatusSucceeded PackageImportJobStatus = "SUCCEEDED" PackageImportJobStatusFailed PackageImportJobStatus = "FAILED" ) // Values returns all known values for PackageImportJobStatus. Note that this can // be expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (PackageImportJobStatus) Values() []PackageImportJobStatus { return []PackageImportJobStatus{ "PENDING", "SUCCEEDED", "FAILED", } } type PackageImportJobType string // Enum values for PackageImportJobType const ( PackageImportJobTypeNodePackageVersion PackageImportJobType = "NODE_PACKAGE_VERSION" PackageImportJobTypeMarketplaceNodePackageVersion PackageImportJobType = "MARKETPLACE_NODE_PACKAGE_VERSION" ) // Values returns all known values for PackageImportJobType. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (PackageImportJobType) Values() []PackageImportJobType { return []PackageImportJobType{ "NODE_PACKAGE_VERSION", "MARKETPLACE_NODE_PACKAGE_VERSION", } } type PackageVersionStatus string // Enum values for PackageVersionStatus const ( PackageVersionStatusRegisterPending PackageVersionStatus = "REGISTER_PENDING" PackageVersionStatusRegisterCompleted PackageVersionStatus = "REGISTER_COMPLETED" PackageVersionStatusFailed PackageVersionStatus = "FAILED" PackageVersionStatusDeleting PackageVersionStatus = "DELETING" ) // Values returns all known values for PackageVersionStatus. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (PackageVersionStatus) Values() []PackageVersionStatus { return []PackageVersionStatus{ "REGISTER_PENDING", "REGISTER_COMPLETED", "FAILED", "DELETING", } } type PortType string // Enum values for PortType const ( PortTypeBoolean PortType = "BOOLEAN" PortTypeString PortType = "STRING" PortTypeInt32 PortType = "INT32" PortTypeFloat32 PortType = "FLOAT32" PortTypeMedia PortType = "MEDIA" ) // Values returns all known values for PortType. Note that this can be expanded in // the future, and so it is only as up to date as the client. The ordering of this // slice is not guaranteed to be stable across updates. func (PortType) Values() []PortType { return []PortType{ "BOOLEAN", "STRING", "INT32", "FLOAT32", "MEDIA", } } type StatusFilter string // Enum values for StatusFilter const ( StatusFilterDeploymentSucceeded StatusFilter = "DEPLOYMENT_SUCCEEDED" StatusFilterDeploymentError StatusFilter = "DEPLOYMENT_ERROR" StatusFilterRemovalSucceeded StatusFilter = "REMOVAL_SUCCEEDED" StatusFilterRemovalFailed StatusFilter = "REMOVAL_FAILED" StatusFilterProcessingDeployment StatusFilter = "PROCESSING_DEPLOYMENT" StatusFilterProcessingRemoval StatusFilter = "PROCESSING_REMOVAL" ) // Values returns all known values for StatusFilter. Note that this can be expanded // in the future, and so it is only as up to date as the client. The ordering of // this slice is not guaranteed to be stable across updates. func (StatusFilter) Values() []StatusFilter { return []StatusFilter{ "DEPLOYMENT_SUCCEEDED", "DEPLOYMENT_ERROR", "REMOVAL_SUCCEEDED", "REMOVAL_FAILED", "PROCESSING_DEPLOYMENT", "PROCESSING_REMOVAL", } } type TemplateType string // Enum values for TemplateType const ( TemplateTypeRtspCameraStream TemplateType = "RTSP_CAMERA_STREAM" ) // Values returns all known values for TemplateType. Note that this can be expanded // in the future, and so it is only as up to date as the client. The ordering of // this slice is not guaranteed to be stable across updates. func (TemplateType) Values() []TemplateType { return []TemplateType{ "RTSP_CAMERA_STREAM", } } type UpdateProgress string // Enum values for UpdateProgress const ( UpdateProgressPending UpdateProgress = "PENDING" UpdateProgressInProgress UpdateProgress = "IN_PROGRESS" UpdateProgressVerifying UpdateProgress = "VERIFYING" UpdateProgressRebooting UpdateProgress = "REBOOTING" UpdateProgressDownloading UpdateProgress = "DOWNLOADING" UpdateProgressCompleted UpdateProgress = "COMPLETED" UpdateProgressFailed UpdateProgress = "FAILED" ) // Values returns all known values for UpdateProgress. Note that this can be // expanded in the future, and so it is only as up to date as the client. The // ordering of this slice is not guaranteed to be stable across updates. func (UpdateProgress) Values() []UpdateProgress { return []UpdateProgress{ "PENDING", "IN_PROGRESS", "VERIFYING", "REBOOTING", "DOWNLOADING", "COMPLETED", "FAILED", } } type ValidationExceptionReason string // Enum values for ValidationExceptionReason const ( ValidationExceptionReasonUnknownOperation ValidationExceptionReason = "UNKNOWN_OPERATION" ValidationExceptionReasonCannotParse ValidationExceptionReason = "CANNOT_PARSE" ValidationExceptionReasonFieldValidationFailed ValidationExceptionReason = "FIELD_VALIDATION_FAILED" ValidationExceptionReasonOther ValidationExceptionReason = "OTHER" ) // Values returns all known values for ValidationExceptionReason. Note that this // can be expanded in the future, and so it is only as up to date as the client. // The ordering of this slice is not guaranteed to be stable across updates. func (ValidationExceptionReason) Values() []ValidationExceptionReason { return []ValidationExceptionReason{ "UNKNOWN_OPERATION", "CANNOT_PARSE", "FIELD_VALIDATION_FAILED", "OTHER", } }
; RUN: opt -O2 %s | llvm-dis > %t1 ; RUN: llc -filetype=obj -o - %t1 | llvm-readelf -s - | FileCheck -check-prefixes=CHECK %s ; RUN: llc -filetype=obj -addrsig -o - %t1 | llvm-readelf -s - | FileCheck -check-prefixes=CHECK %s ; ; Source Code: ; struct tt { int a; } __attribute__((preserve_access_index)); ; int test(struct tt *arg) { ; return arg->a; ; } ; Compilation flag: ; clang -target bpf -O2 -g -S -emit-llvm -Xclang -disable-llvm-passes t.c target triple = "bpf" %struct.tt = type { i32 } ; Function Attrs: nounwind readonly define dso_local i32 @test(%struct.tt* readonly %arg) local_unnamed_addr #0 !dbg !7 { entry: call void @llvm.dbg.value(metadata %struct.tt* %arg, metadata !16, metadata !DIExpression()), !dbg !17 %0 = tail call i32* @llvm.preserve.struct.access.index.p0i32.p0s_struct.tts(%struct.tt* %arg, i32 0, i32 0), !dbg !18, !llvm.preserve.access.index !12 %1 = load i32, i32* %0, align 4, !dbg !18, !tbaa !19 ret i32 %1, !dbg !24 } ; CHECK-NOT: llvm.tt:0:0$0:0 ; Function Attrs: nounwind readnone declare i32* @llvm.preserve.struct.access.index.p0i32.p0s_struct.tts(%struct.tt*, i32, i32) #1 ; Function Attrs: nounwind readnone speculatable declare void @llvm.dbg.value(metadata, metadata, metadata) #2 attributes #0 = { nounwind readonly "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" } attributes #1 = { nounwind readnone } attributes #2 = { nounwind readnone speculatable} !llvm.dbg.cu = !{!0} !llvm.module.flags = !{!3, !4, !5} !llvm.ident = !{!6} !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 10.0.0 (https://github.com/llvm/llvm-project.git 947f9692440836dcb8d88b74b69dd379d85974ce)", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None) !1 = !DIFile(filename: "test.c", directory: "/tmp/home/yhs/work/tests/bug") !2 = !{} !3 = !{i32 7, !"Dwarf Version", i32 4} !4 = !{i32 2, !"Debug Info Version", i32 3} !5 = !{i32 1, !"wchar_size", i32 4} !6 = !{!"clang version 10.0.0 (https://github.com/llvm/llvm-project.git 947f9692440836dcb8d88b74b69dd379d85974ce)"} !7 = distinct !DISubprogram(name: "test", scope: !1, file: !1, line: 2, type: !8, scopeLine: 2, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !15) !8 = !DISubroutineType(types: !9) !9 = !{!10, !11} !10 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) !11 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !12, size: 64) !12 = distinct !DICompositeType(tag: DW_TAG_structure_type, name: "tt", file: !1, line: 1, size: 32, elements: !13) !13 = !{!14} !14 = !DIDerivedType(tag: DW_TAG_member, name: "a", scope: !12, file: !1, line: 1, baseType: !10, size: 32) !15 = !{!16} !16 = !DILocalVariable(name: "arg", arg: 1, scope: !7, file: !1, line: 2, type: !11) !17 = !DILocation(line: 0, scope: !7) !18 = !DILocation(line: 3, column: 15, scope: !7) !19 = !{!20, !21, i64 0} !20 = !{!"tt", !21, i64 0} !21 = !{!"int", !22, i64 0} !22 = !{!"omnipotent char", !23, i64 0} !23 = !{!"Simple C/C++ TBAA"} !24 = !DILocation(line: 3, column: 3, scope: !7)
package org.abuhuraira.app.common.extensions import android.os.Bundle /** * Created by ahmedsaad on 2018-02-06. * Copyright © 2017. All rights reserved. */ fun Bundle.putOptionalInt(key: String, value: Int?) { this.putInt(key, value ?: -1) } fun Bundle.getOptionalInt(key: String, defaultValue: Int? = null): Int? { val value: Int = this.getInt(key, defaultValue ?: -1) return if (value == -1) null else value }
--- first_name: John last_name: Schnake image: https://avatars.githubusercontent.com/u/10273533 github_handle: johnSchnake --- Engineer
package String; public class rev { public static void main(String[] args) { // TODO Auto-generated method stub String str= "Yogesh Kumar",r="",r1=""; String[] str1; str1= str.split(" "); for(int i=str1[0].length()-1;i>=0;i--) { r=r+str1[0].charAt(i); } for(int i=str1[1].length()-1;i>=0;i--) { r1=r1+str1[1].charAt(i); } System.out.println(r+" "+r1); } }
package com.outsystems.plugins.healthfitness.store data class AdvancedQueryResponseBlock ( val block : Int, val startDate : Long, val endDate : Long, val values : MutableList<Float> )
# find-spirit 找到一种让精灵无处可躲的策略 [for-search-test](for-search-test.md) # 问题描述 你在森林里发现了**五**个神秘的罐子。 在罐子中藏着一个精灵,只要把他放出来就可以让他帮你实现一个愿望。 但是这个精灵很调皮,他并不想让你那么容易地抓住他。 在一开始,精灵会随机地藏在其中的一个罐子里。 每一个晚上,你都可以选择打开任何一个罐子来看看精灵是不是在里面。 如果你没有找到精灵,那么在第二天的白天,精灵必须移动到他原先躲藏的罐子旁边的另一个罐子里。 你一共可以尝试**六**个晚上。 请问,要怎么样利用这**六次机会**才能保证最后一定可以抓住精灵? # 分析 这个难点在于精灵可以移动 有一种暴力搜索的思路 将五个罐子进行编号,分别为0、1、2、3、4 这样6次打开罐子的顺序,可以用一串长为6位的数字来表示,例如 * `012344`表示第一次打开编号为0的罐子,第二次打开编号为1的罐子。。。最后一次打开编号为4的罐子 同理,精灵的6次移动,如果初始位置是3,可以表示成 ```mermaid graph LR 3 --> |第一次移动|4; ``` ```mermaid graph LR 4 --> |第二次移动|3; ``` ```mermaid graph LR 3 --> |第三次移动|2; ``` ```mermaid graph LR 2 --> |第四次移动|1; ``` ```mermaid graph LR 1 --> |第五次移动|2; ``` ```mermaid graph LR 2 --> |第六次移动|3; ``` 由于每次精灵都在罐子打开,并且关闭后,才移动,所以我们只关心精灵移动之前的位置即可,根据上面的例子,精灵的移动也可以用一串数字`343212`进行表示 现在来看几种**可以找到**精灵的场景 * 罐子打开的顺序为`001122`,精灵的移动为`012343`。第**一**次打开罐子就找到了精灵。 * 罐子打开的顺序为`001122`,精灵的移动为`101234`。第**二**次打开罐子就找到了精灵。 * 罐子打开的顺序为`001122`,精灵的移动为`321012`。第**三**次打开罐子就找到了精灵。 再来看几种**不可以找到**精灵的场景 * 罐子打开的顺序为`012343`,精灵的移动为`101010`。 * 罐子打开的顺序为`343434`,精灵的移动为`012101`。 * 罐子打开的顺序为`232323`,精灵的移动为`434343`。 所以问题可以进一步转为,是否存在一种罐子的打开顺序`abcdef`,使得精灵不论采用哪种初始位置和移动策略,都会被找到? # 暴力搜索 直接找很难,可以尝试暴力搜索 5个罐子,可以打开6次,总共有`5^6=15625`种罐子的打开策略,使用代码 ```java List<List<Integer>> strategies = GenerateUtil.combination(5, 6); ``` 生成 精灵移动策略也可以枚举出来(有点难算,但是给定一种移动策略,我们可以判断这个策略是否符合精灵每次只能移动到旁边罐子的规则) 所以在使用了代码生成`5^6=15625`种罐子的打开策略后,可以基于这些策略,来判断哪些可以被精灵使用(罐子的打开顺序和精灵的移动在本质上并没有区别,都是6位数字) ```java List<List<Integer>> spiritMoves = strategies.stream().filter(JudgeUtil::isSpiritMove) .collect(Collectors.toList()); ``` 总共找出来精灵的移动策略有**72**种。 接下来就是暴力搜索的时候了,对于`15625`种罐子的打开策略,进行遍历,对于每一个罐子的打开策略a, 查看**72**种精灵的移动策略是否存在能够不被找到的移动策略, 如果**存在**一种精灵的移动策略b,可以让精灵无法被罐子的打开策略a找到,说明这个罐子的打开策略**没法**保证100%找到精灵; 相反,如果**不存在**一种精灵的移动策略b,可以让精灵无法被罐子的打开策略a找到,说明这个罐子的打开策略**可以**保证100%找到精灵; # 运行代码 这是一个maven项目,确保你已经安装: * Git * Maven * Java 通过命令行 ```shell git clone https://github.com/Anilople/find-spirit.git cd find-spirit mvn clean compile cd target java -cp classes com.github.anilople.bottle.BottleApplication ``` 得到输出 ``` 罐子的编号分别为[0, 1, 2, 3, 4] 5^6=15625 策略总共有15625种 精灵移动的方式有72种 开始搜索让精灵无处可躲的罐子打开顺序 找到了4种策略,分别是 [1, 2, 3, 1, 2, 3] [1, 2, 3, 3, 2, 1] [3, 2, 1, 1, 2, 3] [3, 2, 1, 3, 2, 1] ``` 主类为`com.github.anilople.bottle.BottleApplication`
--- title: 'Where does this belong in the filesystem?' type: post tags: [ linux, filesystem ] comment: true date: 2020-09-03 07:00:00 +0200 mathjax: false published: true --- **TL;DR** > Know how to see which device a file belongs to. From time to time, I have to rediscover how to do this. *This* being a very simple thing: find out which underlying device is actually holding a file or a directory. As an example, I sometimes have to check whether there is enough space in the current directory, and in case go somewhere else. The bottom line is that [df][] is my friend, and I hope I will remember it when I will need this bit of information the next time: ```shell $ df "$HOME" Filesystem 1K-blocks Used Available Use% Mounted on /dev/mapper/foobarx--vg-root 36643428 15040292 19712016 44% / ``` This is it: just pass the path to the file/directory you want checked, and you will get back the only relevant line from [df][]. Brilliant! [df]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/df.html#tag_20_33
import {path} from 'ramda' /** * Selects user-events and maps it to values. * @param {Object} sources - Cycle driver sources. * @param {DOMSource} sources.DOM - Cycle DOMDriver. * @returns {Object} {value$ :: String} */ const intent = ({DOM}) => ({ input$: DOM.select('.cycle-input').events('input').map(path(['target', 'value'])) }) export default intent
package de.akquinet.jbosscc; import javax.enterprise.context.Conversation; import javax.inject.Inject; import javax.persistence.EntityManager; import junit.framework.Assert; import org.easymock.EasyMock; import org.junit.Rule; import org.junit.Test; import de.akquinet.jbosscc.dao.BlogEntryDao; import de.akquinet.jbosscc.dao.BlogEntryDaoBean; import de.akquinet.jbosscc.injectionprovider.CurrentUserInjectionProvider; import de.akquinet.jbosscc.testdata.BlogEntryTestdataBuilder; import de.akquinet.jbosscc.needle.annotation.InjectIntoMany; import de.akquinet.jbosscc.needle.annotation.ObjectUnderTest; import de.akquinet.jbosscc.needle.db.transaction.Runnable; import de.akquinet.jbosscc.needle.junit.DatabaseRule; import de.akquinet.jbosscc.needle.junit.NeedleRule; import de.akquinet.jbosscc.needle.mock.EasyMockProvider; public class BlogEntryServiceTest { @Rule public DatabaseRule databaseRule = new DatabaseRule(); @Rule public NeedleRule needleRule = new NeedleRule(databaseRule, new CurrentUserInjectionProvider()); @ObjectUnderTest private BlogEntryService blogEntryService; @SuppressWarnings("unused") @InjectIntoMany @ObjectUnderTest(implementation = BlogEntryDaoBean.class) private BlogEntryDao blogEntryDao; @Inject private EasyMockProvider mockProvider; @Inject private Conversation conversationMock; @Test public void testPersistNewInstance() throws Exception { final Long id = databaseRule.getTransactionHelper() .executeInTransaction(new Runnable<Long>() { @Override public Long run(EntityManager entityManager) throws Exception { blogEntryService.newInstance(); BlogEntry instance = blogEntryService.getInstance(); entityManager.persist(instance.getAuthor()); instance.setTitle("title"); instance.setContent("content"); blogEntryService.persistOrUpdate(); return instance.getId(); } }); BlogEntry blogEntry = databaseRule.getTransactionHelper().loadObject( BlogEntry.class, id); Assert.assertNotNull(blogEntry); } @Test public void testGetInstanceById() throws Exception { BlogEntry blogEntry = new BlogEntryTestdataBuilder( databaseRule.getEntityManager()).buildAndSave(); blogEntryService.setId(blogEntry.getId()); BlogEntry instance = blogEntryService.getInstance(); Assert.assertEquals(blogEntry.getId(), instance.getId()); } @Test public void testDelete() throws Exception { BlogEntry blogEntry = new BlogEntryTestdataBuilder( databaseRule.getEntityManager()).buildAndSave(); EasyMock.expect(conversationMock.isTransient()).andReturn(false) .anyTimes(); mockProvider.replayAll(); // init instance blogEntryService.setId(blogEntry.getId()); blogEntryService.getInstance(); blogEntryService.delete(); mockProvider.verifyAll(); BlogEntry loadObject = databaseRule.getTransactionHelper().loadObject( BlogEntry.class, blogEntry.getId()); Assert.assertNull(loadObject); } }
<?php declare(strict_types=1); namespace Psl\Async; use Psl\Dict; /** * Create a new fiber asynchronously for each one of the given callables, and wait for it to complete. * * If one or more callables fail, all callables will be completed before throwing. * * @template Tk of array-key * @template Tv * * @param iterable<Tk, (callable(): Tv)> $callables * * @return array<Tk, Tv> unwrapped values with the order preserved. */ function concurrent(iterable $callables): array { $awaitables = Dict\map( $callables, /** * @param callable(): Tv $callable * * @return Awaitable<Tv> */ static fn(callable $callable): Awaitable => run($callable), ); return namespace\all($awaitables); }
--- home: true heroImage: null heroText: Nushell tagline: Un nuevo tipo de shell. actionText: Empieza → actionLink: /es/book/ features: - title: Pipelines potentes para controlar tu sistema details: Pipelines permiten trabajar con tu sistema como nunca antes. Tienes el control del sistema, listo para tu siguiente comando. - title: Todo es data. details: En lugar de tener la necesidad de recordar todos los parámetros de todos los comandos, podemos usar los mismos, independientemente de su procedencia. - title: Plugins details: Nu no puede incluir todo lo que quieras hacer con él, por lo que puedes extenderlo usando su sistema fuerte de plugins. footer: Sugerencias o propuestas de cambios son bienvenidas. Escríbenos --- ### Instalación rápida #### Ultima versión Instala la última versión en la [pagina de releases](https://github.com/nushell/nushell/releases) Desde la fuente en [crates.io](https://crates.io): ```sh $ cargo install nu ``` #### Instalación a través de resolvedores de paquetes En [Homebrew](https://brew.sh/): ```sh $ brew install nushell ``` En [Scoop](https://scoop.sh): ```powershell $ scoop install nu ``` #### Inicia la shell ``` $ nu ```
--- title: '[foundation] neogen - multi-play BC stick' date: 2014-07-17T08:00:00.000+08:00 draft: false aliases: [ "/2014/07/foundation-neogen-multi-play-bc-stick.html" ] tags : [glamorous - 畫皮?] --- bb cream,cc cream連掃一枝過 簡直方便到極點! ![](/images/neogenbcstick.jpg) 一邊是bb+cc cream stick 果芯是cc cream,光澤度足 而且有強勁保濕因子不易乾燥 外層是bb cream,遮瑕度不錯 整個面色都好均勻 另一邊是掃 一拉勻bb+cc cream就超貼面 向毛孔位篤篤就輕易地遮起來 有光澤遮瑕度足又不厚重 而且用後不會很乾 SPF 45同PA++ 用來化妝補妝都非常順手 放在袋也不會很重 整個過程又是不用沾手 不用洗手這點我超buy就是 (洗得手多手乾燥嘛) 近期最愛的底妝品(大心)
package com.hootsuite.hermes.database.model import org.jetbrains.exposed.dao.IntIdTable /** * Users Table */ object Users : IntIdTable() { val githubName = varchar("githubName", 50).index() val slackName = varchar("slackName", 50) val teamName = varchar("teamName", 50) val avatarUrl = varchar("avatarUrl", 200).nullable() } /** * Teams Table */ object Teams : IntIdTable() { val teamName = varchar("teamName", 50).index() val slackUrl = varchar("slackUrl", 150) } /** * ReviewRequests Table */ object ReviewRequests : IntIdTable() { // TODO Key on something better than html url, issue id and pr id are different val htmlUrl = varchar("htmlUrl", 150).index() val githubName = varchar("githubName", 50) } /** * Reviews Table */ object Reviews : IntIdTable() { val githubName = varchar("githubName", 50).index() val htmlUrl = varchar("htmlUrl", 150) val reviewState = varchar("reviewState", 50) }
module.exports = { composeApp: require('./composeApp'), composeModel: require('./composeModel'), modules: require('./modules'), };
package com.victorrubia.tfg.data.repository.tag.datasourceImpl import com.victorrubia.tfg.data.model.tag.Tag import com.victorrubia.tfg.data.repository.tag.datasource.TagCacheDataSource /** * Implementation of [TagCacheDataSource] interface for retrieving and saving data from and to cache data source. */ class TagCacheDataSourceImpl : TagCacheDataSource { /** * Cache of tags. */ private var tags : MutableList<Tag> = ArrayList() override suspend fun getTagsFromCache(): List<Tag> { return tags } override suspend fun saveTagToCache(tag: Tag) { tags.add(tag) } override suspend fun clearAll() { tags.clear() } }
--- title: "Haoxin" github: "haoxinluo" avatar: "//www.gravatar.com/avatar/817f453076c40493bb488c138d58c19b?d=identicon" --- User description here!
YaH3C ===== 在原工程的基础上,增加了iNode版本动态加密上传的feature,弥补了协议的不足。原版本中,该version是写死的,不适用于我司的iNode产品。
const assert = require('assert/strict'); const assertRevert = require('@synthetixio/core-js/utils/assertions/assert-revert'); const { bootstrap } = require('@synthetixio/deployer/utils/tests'); const initializer = require('../../helpers/initializer'); const { ethers } = hre; describe('UpgradeModule', function () { describe('when upgrading to a new Proxy', function () { const { proxyAddress, routerAddress } = bootstrap(initializer); let UpgradeModule; before('identify module', async function () { UpgradeModule = await ethers.getContractAt( 'contracts/modules/UpgradeModule.sol:UpgradeModule', proxyAddress() ); }); describe('when attempting to set the implementation with a non owner signer', function () { it('reverts', async function () { const [, user] = await ethers.getSigners(); await assertRevert(UpgradeModule.connect(user).upgradeTo(user.address), 'Unauthorized'); }); }); describe('when upgrading the Router implementation', function () { let NewRouter; before('prepare modules', async function () { const factory = await ethers.getContractFactory('Router'); NewRouter = await factory.deploy(); }); it('sets the new address', async function () { assert.equal(await UpgradeModule.getImplementation(), routerAddress()); const tx = await UpgradeModule.upgradeTo(NewRouter.address); await tx.wait(); assert.equal(await UpgradeModule.getImplementation(), NewRouter.address); }); }); }); });
/**This package contains the object which will show tha ending scene.*/ package sample.View.EndPage;
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; typedef pair<double,string> pds; vector<pds> v; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin>>n; for(int i=0;i<n;i++) { string name; double s1,s2,s3,s4; cin>>name>>s1>>s2>>s3>>s4; v.emplace_back(s1+s2+s3+s4, name); } sort(v.begin(), v.end(), greater<pds>()); cout<<v.front().second<<" is the FMVP!"<<endl; return 0; }
program example use solver implicit none integer, dimension (1, 2) :: ele double precision, dimension (3, 2) :: X0, U double precision, dimension (6, 6) :: C logical, dimension (6, 2) :: DOF double precision, dimension (6, 2) :: dU, Q, res double precision, dimension (1, 6, 1) :: p, f double precision, dimension (1, 3, 1) :: om double precision, dimension (1, 1, 3, 3) :: rot integer, parameter :: MAXITER = 20 double precision, parameter :: TOLER = 1D-5 integer :: i, Niter, errck ele (1, :) = (/ 1, 2 /) X0 (:, 1) = (/ 0.0D1, 0.0D1, 0.0D1 /) X0 (:, 2) = (/ 1.0D1, 2.0D1, 3.0D1 /) U = 0.0D1 C = 0.0D1 do i = 1, 6 C (i, i) = 1.0D1 end do DOF (:, 1) = .FALSE. DOF (:, 2) = .TRUE. dU = 0.0D1 Q = 0.0D1 Q (2, 2) = 0.001 p = 0.0D1 f = 0.0D1 om = 0.0D1 rot = 0.0D1 do i = 1, 3 rot (1, 1, i, i) = 1 end do call newton_iter (ele, X0, U, C, DOF, dU, Q, p, rot, om, f, res, TOLER, MAXITER, 'RSD', Niter, errck, .TRUE.) print *, U (:, 2) print *, rot (1, 1, :, :) end program example
// CrlNumber using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Math; public class CrlNumber : DerInteger { public BigInteger Number => base.PositiveValue; public CrlNumber(BigInteger number) : base(number) { } public override string ToString() { return "CRLNumber: " + Number; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.brooklyn.entity.webapp.nodejs; import java.util.List; import com.google.common.collect.ImmutableList; import com.google.common.reflect.TypeToken; import org.apache.brooklyn.api.catalog.Catalog; import org.apache.brooklyn.api.entity.ImplementedBy; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.config.ConfigKeys; import org.apache.brooklyn.core.entity.Attributes; import org.apache.brooklyn.core.location.PortRanges; import org.apache.brooklyn.core.sensor.PortAttributeSensorAndConfigKey; import org.apache.brooklyn.entity.software.base.SoftwareProcess; import org.apache.brooklyn.entity.webapp.WebAppService; import org.apache.brooklyn.util.core.flags.SetFromFlag; @Catalog(name="Node.JS Application", description="Node.js is a cross-platform runtime environment for server-side and networking applications. Node.js applications are written in JavaScriptq", iconUrl="classpath:///nodejs-logo.png") @ImplementedBy(NodeJsWebAppServiceImpl.class) public interface NodeJsWebAppService extends SoftwareProcess, WebAppService { ConfigKey<String> SUGGESTED_VERSION = ConfigKeys.newConfigKeyWithDefault(SoftwareProcess.SUGGESTED_VERSION, "stable"); @SetFromFlag("httpPort") PortAttributeSensorAndConfigKey HTTP_PORT = ConfigKeys.newPortSensorAndConfigKeyWithDefault(Attributes.HTTP_PORT, PortRanges.fromInteger(3000)); @SetFromFlag("gitRepoUrl") ConfigKey<String> APP_GIT_REPOSITORY_URL = ConfigKeys.newStringConfigKey("nodejs.gitRepo.url", "The Git repository where the application is hosted"); @SetFromFlag("archiveUrl") ConfigKey<String> APP_ARCHIVE_URL = ConfigKeys.newStringConfigKey("nodejs.archive.url", "The URL where the application archive is hosted"); @SetFromFlag("appFileName") ConfigKey<String> APP_FILE = ConfigKeys.newStringConfigKey("nodejs.app.fileName", "The NodeJS application file to start", "app.js"); @SetFromFlag("appName") ConfigKey<String> APP_NAME = ConfigKeys.newStringConfigKey("nodejs.app.name", "The name of the NodeJS application"); @SetFromFlag("appCommand") ConfigKey<String> APP_COMMAND = ConfigKeys.newStringConfigKey("nodejs.app.command", "Command to start the NodeJS application (defaults to node)", "node"); @SetFromFlag("appCommandLine") ConfigKey<String> APP_COMMAND_LINE = ConfigKeys.newStringConfigKey("nodejs.app.commandLine", "Replacement command line to start the NodeJS application (ignores command and file if set)"); @SetFromFlag("nodePackages") ConfigKey<List<String>> NODE_PACKAGE_LIST = ConfigKeys.newConfigKey(new TypeToken<List<String>>() { }, "nodejs.packages", "The NPM packages to install", ImmutableList.<String>of()); ConfigKey<String> SERVICE_UP_PATH = ConfigKeys.newStringConfigKey("nodejs.serviceUp.path", "Path to use when checking the NodeJS application is running", "/"); @SetFromFlag("useHttpMonitoring") ConfigKey<Boolean> USE_HTTP_MONITORING = ConfigKeys.newConfigKey("httpMonitoring.enabled", "HTTP(S) monitoring enabled", Boolean.TRUE); Integer getHttpPort(); }
//! Hyperlinks. use constants::{HTML_START_OPEN, HTML_END_OPEN, HTML_CLOSE}; use content::Content; use section::Section; use symbol::Symbol; #[allow(dead_code)] pub struct LinkMetadata { href: String, title: Option<String>, } #[allow(dead_code)] impl LinkMetadata { fn new(href: &str, title: &str) -> LinkMetadata { let title = match title.len() > 0 { true => Some(title.to_string()), false => None, }; let href = href.to_string(); return LinkMetadata { href: href, title: title }; } fn from_inline(content: &Content, section: &Section) -> Option<LinkMetadata> { let mut link_start: usize = section.end; for i in section.start..section.end { match content.symbols[i] { Symbol::Newline | Symbol::Space => { if i == section.end { return None; } else { continue; } }, _ => { link_start = i; break; }, } } let mut link_end: usize = section.end; for i in link_start..section.end { match content.symbols[i] { Symbol::Newline | Symbol::Space => { link_end = i; break; }, _ => continue, } } if link_start == link_end { return None; } let href = &content.string[link_start..link_end]; let mut title: &str = ""; if link_end < section.end { for i in link_end..section.end { match content.symbols[i] { Symbol::Quote => { let subsection = Section::new(i + 1, section.end); title = match content.find_next("\"", &subsection) { None => "", Some(n) => &content.string[i + 1..n], }; break; }, Symbol::Apostrophe => { let subsection = Section::new(i + 1, section.end); title = match content.find_next("'", &subsection) { None => "", Some(n) => &content.string[i + 1..n], }; break; }, Symbol::LeftParenthsis => { let subsection = Section::new(i + 1, section.end); title = match content.find_next(")", &subsection) { None => "", Some(n) => &content.string[i + 1..n], }; break; }, _ => continue, } } } return Some(LinkMetadata::new(href, title)); } } #[allow(dead_code)] pub struct Link { id: String, metadata: LinkMetadata } #[allow(dead_code)] impl Link { fn new(id: &str, href: &str, title: &str) -> Link { let id = id.to_string(); let metadata = LinkMetadata::new(href, title); return Link { id: id, metadata: metadata }; } /* fn from_inline(content: &content, section: &Section) -> Option<Link> { let mut id_start = section.start; for i in section.start..section.end { if content.symbols[i] == Symbol::LeftBracket { break; } id_start += 1; } let id_end = match content.find_next("](", section) { None => return None, Some(i) => i, }; let id = &content.string[id_start..id_end]; } */ fn to_string(&self) -> String { let mut output = String::new(); output.push_str(HTML_START_OPEN); output.push_str("a href=\""); output.push_str(&self.metadata.href); output.push('"'); match self.metadata.title { None => output.push_str(HTML_CLOSE), Some(ref title) => { output.push_str(" title=\""); output.push_str(title); output.push('"'); output.push_str(HTML_CLOSE); } } output.push_str(&self.id); output.push_str(HTML_END_OPEN); output.push_str("a"); output.push_str(HTML_CLOSE); return output; } } #[cfg(test)] mod test { use super::Link; use super::LinkMetadata; use content::content; use section::Section; #[test] fn simple_link() { let link = Link::new("link", "http://carlcolglazier.com/", "Sample Link."); assert_eq!( "<a href=\"http://carlcolglazier.com/\" title=\"Sample Link.\">link</a>", link.to_string() ); } #[test] fn no_title() { let link = Link::new("link", "http://carlcolglazier.com/", ""); assert_eq!("<a href=\"http://carlcolglazier.com/\">link</a>", link.to_string()); } #[test] fn parse_link_metadata() { // Just the link. let content_str = "http://carlcolglazier.com"; let content = Content::from_str(content_str); let section = Section::new(0, content_str.len()); let link_metadata = match LinkMetadata::from_inline(&content, &section) { None => panic!("Parsing error."), Some(m) => m, }; assert_eq!(content_str, link_metadata.href); // Extra spaces. let extra_content_str = " http://carlcolglazier.com "; let content = Content::from_str(extra_content_str); let section = Section::new(0, extra_content_str.len()); let link_metadata = match LinkMetadata::from_inline(&content, &section) { None => panic!("Parsing error."), Some(m) => m, }; assert_eq!(content_str, link_metadata.href); // Include a title. let title_content_str = "http://carlcolglazier.com 'Title'"; let content = Content::from_str(title_content_str); let section = Section::new(0, title_content_str.len()); let link_metadata = match LinkMetadata::from_inline(&content, &section) { None => panic!("Parsing error."), Some(m) => m, }; assert_eq!(content_str, link_metadata.href); assert_eq!(Some("Title".to_string()), link_metadata.title); } }
# Minhas soluções do CodeWars. ## Tecnologias: Python; JavaScript; ## Autor: Renan Souza
import uvicorn from .server import app def run(*args, **kwargs): '''Run the uvicorn app. ''' uvicorn.run(app, *args, **kwargs)
rootProject.name = "fsynth" include("core", "cli", "web", ":web:worker", ":web:serviceworker", "android") enableFeaturePreview("GRADLE_METADATA")
package com.react.testapp.manifest import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Manifest( val name: String, val displayName: String, val components: List<Component> ) @JsonClass(generateAdapter = true) data class Component( val appKey: String, val displayName: String?, val initialProperties: Map<String, String?>? )
<?php namespace App\Entities\SectionImages; use App\Entities\FileExts\FileExtsStorage; use App\Libraries\ErrorMessages; use CodeIgniter\Entity; use Config\Services; use CodeIgniter\HTTP\Request; class SectionImageValid extends Entity { public static function save($data, Request $request = null) { $valid = Services::validation(); $valid->setRule('section_id', 'ID', 'required|is_natural_no_zero|is_not_unique[sections.id]'); if (!$valid->run($data)) throw new \Exception($valid->listErrors('modal_errors')); $file = $request->getFile('img'); if(empty($file)) throw new \Exception(ErrorMessages::get(75)); if ($file->isFile() === false) throw new \Exception(ErrorMessages::get(75)); $valid = Services::validation(); $valid->setRules([ 'img' => [ 'label' => 'Изображение', 'rules' => 'is_image[img]|max_size[img,102400]', ] ]); if (!$valid->withRequest($request)->run()) throw new \Exception($valid->listErrors('modal_errors')); if (!$file->isValid()) throw new \Exception(ErrorMessages::get(76)); if ($file->hasMoved()) throw new \Exception(ErrorMessages::get(77)); if (FileExtsStorage::getByExtension($file->getClientExtension()) === false) throw new \Exception(ErrorMessages::get(76)); } public static function delete(array $data) { $valid = Services::validation(); $valid->setRule('id', 'ID изображения', 'required|is_natural_no_zero'); if (!$valid->run($data)) throw new \Exception($valid->listErrors('modal_errors')); } public static function sort(array $data) { $valid = Services::validation(); $valid->setRule('section_id', 'Секция', 'required|is_natural_no_zero'); if (!$valid->run($data)) throw new \Exception($valid->listErrors('modal_errors')); foreach ($data['sort'] as $item) { $valid->reset(); $valid->setRule('id', 'ID изображения', 'required|is_natural_no_zero'); $valid->setRule('sort_num', 'Номер сортировки', 'required|is_natural_no_zero'); if (!$valid->run($item)) throw new \Exception($valid->listErrors('modal_errors')); } } }
package com.github.ageofwar.ktelegram import java.nio.file.Path import java.nio.file.Paths import kotlin.io.path.ExperimentalPathApi import kotlin.io.path.writeBytes suspend fun TelegramApi.downloadFile(fileId: String, file: java.io.File) { file.writeBytes(downloadFile(fileId)) } @OptIn(ExperimentalPathApi::class) suspend fun TelegramApi.downloadFile(fileId: String, path: Path) { path.writeBytes(downloadFile(fileId)) } suspend fun TelegramApi.downloadFile(fileId: String, path: String) { downloadFile(fileId, Paths.get(path)) }
# Guestlist Inviting people to your event has never been easier to keep track of.
using Newtonsoft.Json; namespace NewHorizons.External.Modules { [JsonObject] public class FocalPointModule { /// <summary> /// Name of the primary planet in this binary system /// </summary> public string primary; /// <summary> /// Name of the secondary planet in this binary system /// </summary> public string secondary; } }
extern crate bindgen; use bindgen::callbacks::{IntKind, ParseCallbacks}; extern crate cc; use std::env; use std::path::PathBuf; fn main() { println!("cargo:rerun-if-changed=build.rs"); println!("cargo:rerun-if-changed=sqlite_dependencies.h"); println!("cargo:rerun-if-changed=redis_dependencies.h"); cc::Build::new() .file("src/CDeps/Redis/redismodule.c") .include("src/CDeps/Redis/include") .compile("libredismodule.a"); cc::Build::new() .file("src/CDeps/SQLite/sqlite3.c") .include("src/CDeps/SQLite/include") .define("HAVE_USLEEP", Some("1")) .define("NDEBUG", Some("1")) .define("HAVE_FDATASYNC", Some("1")) .define("SQLITE_THREADSAFE", Some("2")) .define("SQLITE_ENABLE_JSON1", Some("1")) .define("SQLITE_ENABLE_FTS3", Some("1")) .define("SQLITE_ENABLE_FTS4", Some("1")) .define("SQLITE_ENABLE_FTS5", Some("1")) .define("SQLITE_ENABLE_RTREE", Some("1")) .flag_if_supported("-w") .compile("libsqlite3.a"); #[derive(Debug)] struct SqliteTypeChooser; impl ParseCallbacks for SqliteTypeChooser { fn int_macro( &self, _name: &str, value: i64, ) -> Option<IntKind> { if value >= i32::min_value() as i64 && value <= i32::max_value() as i64 { Some(IntKind::I32) } else { None } } } let bindings = bindgen::Builder::default() .parse_callbacks(Box::new(SqliteTypeChooser)) .header("sqlite_dependencies.h") .generate() .expect("Unable to generate bindings for SQLite"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings_sqlite.rs")) .expect("Couldn't write bindings for SQLite!"); let bindings = bindgen::Builder::default() .parse_callbacks(Box::new(SqliteTypeChooser)) // .rustfmt_bindings(false) // see https://github.com/rust-lang-nursery/rust-bindgen/issues/1306#event-1597477817 .header("redis_dependencies.h") .generate() .expect("Unable to generate bindings for Redis"); let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); bindings .write_to_file(out_path.join("bindings_redis.rs")) .expect("Couldn't write bindings for Redis!"); }
# -*- encoding: us-ascii -*- class Class def self.allocate Rubinius.primitive :class_s_allocate raise PrimitiveFailure, "Unable to create a new Class" end def set_superclass(sup) Rubinius.primitive :class_set_superclass raise TypeError, "superclass must be a Class (#{Rubinius::Type.object_class(sup)} given)" end private :set_superclass end
import SortBy from './SortBy'; export interface SortBys { sortBys?: SortBy[]; }
import sys import struct from functools import reduce def parse_seq_range (packet_bytes): seq_bytes = packet_bytes[10:18] cnt_bytes = packet_bytes[18:20] seq_num = struct.unpack(">Q", seq_bytes)[0] cnt_num = struct.unpack(">H", cnt_bytes)[0] return (seq_num, seq_num + cnt_num) def peek_ahead_packets_left (byte_source): expected_bytes = _get_packet_peek_bytes() read_attempt = _discard_session_ignored(byte_source) return len(read_attempt) == expected_bytes def extract_msgs_from_byte_source (byte_source): (session_num, _) = _consume_session_num_post_peek(byte_source) (seq_num, _) = _consume_seq_num(byte_source) (msgs, _) = _consume_packet_msgs(byte_source) return (session_num, seq_num, msgs) def read_next_packet_bytes (byte_source): discard_bytes = _discard_session_ignored(byte_source) return discard_bytes + _read_packet_post_discard(byte_source) \ if len(discard_bytes) else [] def _read_packet_post_discard(byte_source): (_, session_bytes) = _consume_session_num_post_peek(byte_source) (_, seq_num_bytes) = _consume_seq_num(byte_source) (_, msg_bytes) = _consume_packet_msgs(byte_source) return session_bytes + seq_num_bytes + msg_bytes def _discard_session_ignored (byte_source): return byte_source.read(_get_packet_peek_bytes()); def _consume_session_num_post_peek (byte_source): session_bytes = byte_source.read(_get_session_read_bytes()) session_parsable_bytes = _truncate_session_bytes_to_intable(session_bytes) return (struct.unpack(">Q", session_parsable_bytes)[0], session_bytes) # We can only use up to 8 bytes for sesssion num, so it's alright to discard # 2 to peek-ahead at any packets left. def _get_session_bytes(): return 10 def _get_session_read_bytes(): return _get_session_bytes() - _get_packet_peek_bytes() def _get_packet_peek_bytes(): return 2 def _truncate_session_bytes_to_intable (session_num_bytes): return session_num_bytes[-8:] def _consume_seq_num (byte_source): n_seq_num_bytes = 8 seq_bytes = byte_source.read(n_seq_num_bytes) return (struct.unpack(">Q", seq_bytes)[0], seq_bytes) def _consume_packet_msgs (byte_source): (msg_count, count_bytes) = _determine_message_count(byte_source) scan_rets = [_scan_message(byte_source) for i in range(msg_count)] return (_unpack_msgs_from_scans(scan_rets), count_bytes + _join_bytes_from_scans (scan_rets)) def _unpack_msgs_from_scans (scan_rets): return [i[0] for i in scan_rets] def _join_bytes_from_scans (scan_rets): unpacked_bytes = [i[1] for i in scan_rets] return reduce(lambda x,y: x+y, unpacked_bytes, bytearray()) def _scan_message (byte_source): (msg_size, size_bytes) = _pop_message_size(byte_source) msg_bytes = byte_source.read(msg_size) return (msg_bytes, size_bytes + msg_bytes) def _pop_message_size (byte_source): return _read_field_size(byte_source) def _determine_message_count (byte_source): (count_field_val, count_bytes) = _pop_message_count(byte_source) msg_count = _pivot_for_end_stream_count(count_field_val) return (msg_count, count_bytes) def _pivot_for_end_stream_count (count_val): end_of_stream_count = 65535 return count_val if \ count_val != end_of_stream_count else 0 def _pop_message_count (byte_source): return _read_field_size(byte_source) def _read_field_size (byte_source): n_size_bytes = 2 size_bytes = byte_source.read(n_size_bytes) return (struct.unpack(">H", size_bytes)[0], size_bytes)
package shell import ( "bytes" "context" "fmt" "testing" "github.com/evilmonkeyinc/golang-cli/errors" "github.com/evilmonkeyinc/golang-cli/flags" "github.com/stretchr/testify/assert" ) // Validate the StandardRouter struct matches the Router interface var _ Router = &StandardRouter{} func Test_Router(t *testing.T) { t.Run("newRouter", func(t *testing.T) { actual := newRouter() assert.NotNil(t, actual.children) assert.NotNil(t, actual.handlers) assert.NotNil(t, actual.middleware) assert.Nil(t, actual.parent) assert.Nil(t, actual.notFoundHandler) }) t.Run("childRouter", func(t *testing.T) { input := newRouter() input.notFoundHandler = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("not found") }) input.handlers["test"] = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("test") }) input.middleware = append(input.middleware, MiddlewareFunction(func(next Handler) Handler { return next })) input.children = append(input.children, newRouter()) actual := childRouter(input) assert.Equal(t, input, actual.parent) assert.NotNil(t, actual.notFoundHandler) assert.NotEqual(t, input.handlers, actual.handlers) assert.NotEqual(t, input.middleware, actual.middleware) assert.NotEqual(t, input.children, actual.children) }) t.Run("subRouter", func(t *testing.T) { input := newRouter() input.notFoundHandler = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("not found") }) input.handlers["test"] = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("test") }) input.middleware = append(input.middleware, MiddlewareFunction(func(next Handler) Handler { return next })) input.children = append(input.children, newRouter()) actual := subRouter(input) assert.Nil(t, actual.parent) assert.NotNil(t, actual.notFoundHandler) assert.NotEqual(t, input.handlers, actual.handlers) assert.NotEqual(t, input.middleware, actual.middleware) assert.NotEqual(t, input.children, actual.children) }) t.Run("Routes", func(t *testing.T) { input := newRouter() input.handlers["test"] = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("test") }) assert.Equal(t, input.handlers, input.Routes()) }) t.Run("Middlewares", func(t *testing.T) { input := newRouter() input.middleware = append(input.middleware, MiddlewareFunction(func(next Handler) Handler { return next })) assert.Equal(t, input.middleware, input.Middlewares()) }) t.Run("Use", func(t *testing.T) { router := &StandardRouter{} middleware := MiddlewareFunction(func(next Handler) Handler { return next }) assert.Len(t, router.middleware, 0) router.Use(middleware) assert.Len(t, router.middleware, 1) }) t.Run("NotFound", func(t *testing.T) { router := &StandardRouter{} router.NotFound(HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("not found") })) assert.NotNil(t, router.notFoundHandler) actual := router.notFoundHandler.Execute(nil, nil) assert.Equal(t, fmt.Errorf("not found"), actual) }) } func Test_Router_Execute(t *testing.T) { router := newRouter() t.Run("empty", func(t *testing.T) { request := NewRequest([]string{}, []string{"anything"}, &flags.DefaultFlagSet{}, nil) actual := router.Execute(nil, request) assert.Nil(t, actual) }) router.notFoundHandler = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("not found") }) router.handlers["test"] = HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) tests := []struct { name string input string expected error }{ { name: "found", input: "test", expected: fmt.Errorf("found"), }, { name: "not found", input: "other", expected: fmt.Errorf("not found"), }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { request := NewRequest([]string{}, []string{test.input}, &flags.DefaultFlagSet{}, nil) actual := router.Execute(nil, request) assert.Equal(t, test.expected, actual) }) } } func Test_Router_Match(t *testing.T) { router := &StandardRouter{} router.Use(MiddlewareFunction(func(next Handler) Handler { return HandlerFunction(func(rw ResponseWriter, r *Request) error { err := next.Execute(rw, r) return fmt.Errorf("%w with top middleware", err) }) })) router.HandleFunction("found", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) router.Route("child", func(r Router) { r.HandleFunction("func", func(ResponseWriter, *Request) error { return fmt.Errorf("found in child") }) r.NotFound(HandlerFunction(func(ResponseWriter, *Request) error { return fmt.Errorf("not found") })) }) router.Group(func(r Router) { r.Use(MiddlewareFunction(func(next Handler) Handler { return HandlerFunction(func(rw ResponseWriter, r *Request) error { err := next.Execute(rw, r) return fmt.Errorf("%w with group middleware", err) }) })) r.HandleFunction("group", func(ResponseWriter, *Request) error { return fmt.Errorf("found in group") }) }) type expected struct { err error found bool } tests := []struct { name string input []string expected expected }{ { name: "nil", input: nil, expected: expected{ err: nil, found: false, }, }, { name: "none", input: []string{}, expected: expected{ err: nil, found: false, }, }, { name: "found", input: []string{"found"}, expected: expected{ err: fmt.Errorf("found with top middleware"), found: true, }, }, { name: "child", input: []string{"child"}, expected: expected{ err: fmt.Errorf("not found with top middleware"), found: true, }, }, { name: "child func", input: []string{"child", "func"}, expected: expected{ err: fmt.Errorf("found in child with top middleware"), found: true, }, }, { name: "func", input: []string{"func"}, expected: expected{ err: nil, found: false, }, }, { name: "group", input: []string{"group"}, expected: expected{ err: fmt.Errorf("found in group with group middleware with top middleware"), found: true, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { handler, found := router.Match(test.input) assert.Equal(t, test.expected.found, found) if handler != nil { request := NewRequest([]string{}, test.input[1:], &flags.DefaultFlagSet{}, router) err := handler.Execute(nil, request) if test.expected.err != nil { assert.EqualValues(t, test.expected.err.Error(), err.Error()) } else { assert.Nil(t, err) } } else { assert.Nil(t, test.expected.err) assert.False(t, found) } }) } } func Test_Router_Group(t *testing.T) { router := &StandardRouter{} actual := router.Group(func(r Router) { r.HandleFunction("found", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) }) assert.Contains(t, router.children, actual) request := NewRequest([]string{}, []string{"found"}, &flags.DefaultFlagSet{}, nil) direct := actual.Execute(nil, request) parent := router.Execute(nil, request) assert.Equal(t, direct, parent) assert.Equal(t, direct, fmt.Errorf("found")) } func Test_Router_Route(t *testing.T) { t.Run("set route", func(t *testing.T) { router := &StandardRouter{} subRouter := router.Route("route", func(r Router) { r.HandleFunction("found", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) }) assert.Contains(t, router.handlers, "route") request := NewRequest([]string{}, []string{"route", "found"}, &flags.DefaultFlagSet{}, nil) parent := router.Execute(nil, request) request = NewRequest([]string{}, []string{"found"}, &flags.DefaultFlagSet{}, nil) direct := subRouter.Execute(nil, request) assert.Equal(t, fmt.Errorf("found"), parent) assert.Equal(t, fmt.Errorf("found"), direct) }) t.Run("duplicate panic", func(t *testing.T) { testPanic(t, func() { router := &StandardRouter{} router.Route("route", func(r Router) { r.HandleFunction("first", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) }) router.Route("route", func(r Router) { r.HandleFunction("second", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) }) }, errors.DuplicateCommand("route").Error()) }) } func Test_Router_Mount(t *testing.T) { t.Run("set route", func(t *testing.T) { subRouter := &StandardRouter{} subRouter.HandleFunction("found", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) router := &StandardRouter{} router.Mount("route", subRouter) assert.Contains(t, router.handlers, "route") request := NewRequest([]string{}, []string{"route", "found"}, &flags.DefaultFlagSet{}, nil) parent := router.Execute(nil, request) request = NewRequest([]string{}, []string{"found"}, &flags.DefaultFlagSet{}, nil) direct := subRouter.Execute(nil, request) assert.Equal(t, fmt.Errorf("found"), parent) assert.Equal(t, fmt.Errorf("found"), direct) }) t.Run("duplicate panic", func(t *testing.T) { testPanic(t, func() { subRouter := &StandardRouter{} subRouter.HandleFunction("first", func(ResponseWriter, *Request) error { return fmt.Errorf("found") }) router := &StandardRouter{} router.Mount("route", subRouter) router.Mount("route", subRouter) }, errors.DuplicateCommand("route").Error()) }) } func Test_Router_Handle(t *testing.T) { t.Run("first", func(t *testing.T) { router := &StandardRouter{} router.Handle("found", &testHandler{}) assert.Contains(t, router.handlers, "found") }) t.Run("duplicate", func(t *testing.T) { testPanic(t, func() { router := &StandardRouter{} router.Handle("found", &testHandler{}) router.Handle("found", &testHandler{}) }, errors.DuplicateCommand("found").Error()) }) } func Test_Router_HandleFunction(t *testing.T) { t.Run("first", func(t *testing.T) { router := &StandardRouter{} router.HandleFunction("found", HandlerFunction(func(ResponseWriter, *Request) error { return nil })) assert.Contains(t, router.handlers, "found") }) t.Run("duplicate", func(t *testing.T) { testPanic(t, func() { router := &StandardRouter{} router.HandleFunction("found", HandlerFunction(func(ResponseWriter, *Request) error { return nil })) router.HandleFunction("found", HandlerFunction(func(ResponseWriter, *Request) error { return nil })) }, errors.DuplicateCommand("found").Error()) }) } type testHandlerWithFlags struct { t *testing.T response string expectedFlags map[string]interface{} } func (handler *testHandlerWithFlags) Define(fd flags.FlagDefiner) { fd.String("test", "", "") } func (handler *testHandlerWithFlags) Execute(rw ResponseWriter, r *Request) error { flagValues := r.FlagValues() for key, expected := range handler.expectedFlags { actual := flagValues.Get(key) assert.Equal(handler.t, expected, actual) } return fmt.Errorf(handler.response) } func Test_Router_Flags(t *testing.T) { type input struct { args []string } type expected struct { err error parsed map[string]interface{} parseError string } tests := []struct { name string input input expected expected }{ { name: "go", input: input{ args: []string{"go"}, }, expected: expected{ err: fmt.Errorf("top"), parsed: map[string]interface{}{}, }, }, { name: "go -test this", input: input{ args: []string{"go", "-test", "this"}, }, expected: expected{ err: fmt.Errorf("top"), parsed: map[string]interface{}{ "test": "this", }, }, }, { name: "go -test=this", input: input{ args: []string{"go", "-test=this"}, }, expected: expected{ err: fmt.Errorf("top"), parsed: map[string]interface{}{ "test": "this", }, }, }, { name: "one -two", input: input{ args: []string{"one", "-two"}, }, expected: expected{ err: nil, parsed: map[string]interface{}{}, parseError: "flagset parse failed flag provided but not defined: -two\n", }, }, { name: "one go", input: input{ args: []string{"one", "go"}, }, expected: expected{ err: fmt.Errorf("after one"), parsed: map[string]interface{}{ "one": false, }, }, }, { name: "one -one go -test this", input: input{ args: []string{"one", "-one", "go", "-test", "this"}, }, expected: expected{ err: fmt.Errorf("after one"), parsed: map[string]interface{}{ "test": "this", "one": true, }, }, }, { name: "one go -test=this -one", input: input{ args: []string{"one", "go", "-test=this", "-one"}, }, expected: expected{ err: fmt.Errorf("after one"), parsed: map[string]interface{}{ "test": "this", "one": true, }, }, }, { name: "one two go", input: input{ args: []string{"one", "two", "go"}, }, expected: expected{ err: fmt.Errorf("after two"), parsed: map[string]interface{}{ "one": false, }, }, }, { name: "one -one two -two go -test this", input: input{ args: []string{"one", "-one", "two", "-two", "go", "-test", "this"}, }, expected: expected{ err: fmt.Errorf("after two"), parsed: map[string]interface{}{ "test": "this", "one": true, "two": true, }, }, }, { name: "one two go -test=this -one", input: input{ args: []string{"one", "two", "go", "-test=this", "-two", "-one"}, }, expected: expected{ err: fmt.Errorf("after two"), parsed: map[string]interface{}{ "test": "this", "one": true, "two": true, }, }, }, { name: "one two three go", input: input{ args: []string{"one", "two", "three", "go"}, }, expected: expected{ err: fmt.Errorf("after three"), parsed: map[string]interface{}{ "one": false, "two": false, "three": false, }, }, }, { name: "one -one two -two three -three=true go -test this", input: input{ args: []string{"one", "-one", "two", "-two", "three", "-three=true", "go", "-test", "this"}, }, expected: expected{ err: fmt.Errorf("after three"), parsed: map[string]interface{}{ "test": "this", "one": true, "two": true, "three": true, }, }, }, { name: "one two three go -test=this -two -three -one", input: input{ args: []string{"one", "two", "three", "go", "-test=this", "-two", "-three", "-one"}, }, expected: expected{ err: fmt.Errorf("after three"), parsed: map[string]interface{}{ "test": "this", "one": true, "two": true, "three": true, }, }, }, { name: "-help", input: input{ args: []string{"one", "-h"}, }, expected: expected{ err: errors.HelpRequested("flags"), }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { testRouter := &StandardRouter{} testRouter.Handle("go", &testHandlerWithFlags{ t: t, expectedFlags: test.expected.parsed, response: "top", }) testRouter.Route("one", func(r Router) { r.Flags(flags.FlagHandlerFunction(func(fd flags.FlagDefiner) { fd.Bool("one", false, "") })) r.Handle("go", &testHandlerWithFlags{ t: t, expectedFlags: test.expected.parsed, response: "after one", }) r.Route("two", func(r Router) { r.Flags(flags.FlagHandlerFunction(func(fd flags.FlagDefiner) { fd.Bool("two", false, "") })) r.Handle("go", &testHandlerWithFlags{ t: t, expectedFlags: test.expected.parsed, response: "after two", }) r.Route("three", func(r Router) { r.Flags(flags.FlagHandlerFunction(func(fd flags.FlagDefiner) { fd.Bool("three", false, "") })) r.Handle("go", &testHandlerWithFlags{ t: t, expectedFlags: test.expected.parsed, response: "after three", }) }) }) }) flagSet := flags.NewDefaultFlagSet() errWriter := &bytes.Buffer{} writer := NewWrapperWriter(context.Background(), &bytes.Buffer{}, errWriter) request := NewRequest([]string{}, test.input.args, flagSet, testRouter) actual := testRouter.Execute(writer, request) assert.Equal(t, test.expected.err, actual) assert.Equal(t, test.expected.parseError, errWriter.String()) }) } }
/* * Copyright (C) 2015-2021 Lightbend Inc. <https://www.lightbend.com> */ package akka.cluster.sharding import java.io.File import scala.concurrent.Await import scala.concurrent.duration._ import scala.util.Success import org.apache.commons.io.FileUtils import akka.actor.ActorRef import akka.actor.Props import akka.cluster.Cluster import akka.cluster.sharding.RemoveInternalClusterShardingData.RemoveOnePersistenceId.Removals import akka.cluster.sharding.RemoveInternalClusterShardingData.RemoveOnePersistenceId.Result import akka.persistence.PersistentActor import akka.persistence.Recovery import akka.persistence.RecoveryCompleted import akka.persistence.SnapshotOffer import akka.persistence.SnapshotSelectionCriteria import akka.testkit.AkkaSpec import akka.testkit.ImplicitSender import akka.testkit.TestActors.EchoActor import akka.testkit.WithLogCapturing object RemoveInternalClusterShardingDataSpec { val config = """ akka.loglevel = DEBUG akka.loggers = ["akka.testkit.SilenceAllTestEventListener"] akka.actor.provider = "cluster" akka.remote.classic.netty.tcp.port = 0 akka.remote.artery.canonical.port = 0 akka.persistence.journal.plugin = "akka.persistence.journal.leveldb" akka.persistence.journal.leveldb { native = off dir = "target/journal-RemoveInternalClusterShardingDataSpec" } akka.persistence.snapshot-store.plugin = "akka.persistence.snapshot-store.local" akka.persistence.snapshot-store.local.dir = "target/snapshots-RemoveInternalClusterShardingDataSpec" akka.cluster.sharding.snapshot-after = 5 akka.cluster.sharding.state-store-mode = persistence akka.cluster.sharding.keep-nr-of-batches = 0 akka.cluster.sharding.verbose-debug-logging = on """ val extractEntityId: ShardRegion.ExtractEntityId = { case msg: Int => (msg.toString, msg) } val extractShardId: ShardRegion.ExtractShardId = { case msg: Int => (msg % 10).toString } class HasSnapshots(override val persistenceId: String, replyTo: ActorRef) extends PersistentActor { var hasSnapshots = false override def receiveRecover: Receive = { case SnapshotOffer(_, _) => hasSnapshots = true case RecoveryCompleted => replyTo ! hasSnapshots context.stop(self) case _ => } override def receiveCommand: Receive = { case _ => } } class HasEvents(override val persistenceId: String, replyTo: ActorRef) extends PersistentActor { var hasEvents = false override def recovery: Recovery = Recovery(fromSnapshot = SnapshotSelectionCriteria.None) override def receiveRecover: Receive = { case _: ShardCoordinator.Internal.DomainEvent => hasEvents = true case RecoveryCompleted => replyTo ! hasEvents context.stop(self) } override def receiveCommand: Receive = { case _ => } } } class RemoveInternalClusterShardingDataSpec extends AkkaSpec(RemoveInternalClusterShardingDataSpec.config) with ImplicitSender with WithLogCapturing { import RemoveInternalClusterShardingDataSpec._ val storageLocations = List("akka.persistence.journal.leveldb.dir", "akka.persistence.snapshot-store.local.dir").map(s => new File(system.settings.config.getString(s))) override protected def atStartup(): Unit = { storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) } override protected def afterTermination(): Unit = { storageLocations.foreach(dir => if (dir.exists) FileUtils.deleteDirectory(dir)) } // same persistenceId as is used by ShardCoordinator def persistenceId(typeName: String): String = s"/sharding/${typeName}Coordinator" def hasSnapshots(typeName: String): Boolean = { system.actorOf(Props(classOf[HasSnapshots], persistenceId(typeName), testActor)) expectMsgType[Boolean] } def hasEvents(typeName: String): Boolean = { system.actorOf(Props(classOf[HasEvents], persistenceId(typeName), testActor)) expectMsgType[Boolean] } "RemoveOnePersistenceId" must { "setup sharding" in { Cluster(system).join(Cluster(system).selfAddress) val settings = ClusterShardingSettings(system) ClusterSharding(system).start("type1", Props[EchoActor](), settings, extractEntityId, extractShardId) ClusterSharding(system).start("type2", Props[EchoActor](), settings, extractEntityId, extractShardId) } "work when no data" in within(10.seconds) { hasSnapshots("type1") should ===(false) hasEvents("type1") should ===(false) val rm = system.actorOf( RemoveInternalClusterShardingData.RemoveOnePersistenceId .props(journalPluginId = "", persistenceId("type1"), testActor)) watch(rm) expectMsg(Result(Success(Removals(events = false, snapshots = false)))) expectTerminated(rm) } "remove all events when no snapshot" in within(10.seconds) { val region = ClusterSharding(system).shardRegion("type1") (1 to 3).foreach(region ! _) receiveN(3).toSet should be((1 to 3).toSet) hasSnapshots("type1") should ===(false) hasEvents("type1") should ===(true) val rm = system.actorOf( RemoveInternalClusterShardingData.RemoveOnePersistenceId .props(journalPluginId = "", persistenceId("type1"), testActor)) watch(rm) expectMsg(Result(Success(Removals(events = true, snapshots = false)))) expectTerminated(rm) hasSnapshots("type1") should ===(false) hasEvents("type1") should ===(false) } "remove all events and snapshots" in within(10.seconds) { val region = ClusterSharding(system).shardRegion("type2") (1 to 10).foreach(region ! _) receiveN(10).toSet should be((1 to 10).toSet) awaitAssert { // theoretically it might take a while until snapshot is visible hasSnapshots("type2") should ===(true) } hasEvents("type2") should ===(true) val rm = system.actorOf( RemoveInternalClusterShardingData.RemoveOnePersistenceId .props(journalPluginId = "", persistenceId("type2"), testActor)) watch(rm) expectMsg(Result(Success(Removals(events = true, snapshots = true)))) expectTerminated(rm) hasSnapshots("type2") should ===(false) hasEvents("type2") should ===(false) } } "RemoveInternalClusterShardingData" must { val typeNames = List("type10", "type20", "type30") "setup sharding" in { Cluster(system).join(Cluster(system).selfAddress) val settings = ClusterShardingSettings(system) typeNames.foreach { typeName => ClusterSharding(system).start(typeName, Props[EchoActor](), settings, extractEntityId, extractShardId) } } "remove all events and snapshots" in within(10.seconds) { typeNames.foreach { typeName => val region = ClusterSharding(system).shardRegion(typeName) (1 to 10).foreach(region ! _) receiveN(10).toSet should be((1 to 10).toSet) awaitAssert { // theoretically it might take a while until snapshot is visible hasSnapshots(typeName) should ===(true) } hasEvents(typeName) should ===(true) } val result = RemoveInternalClusterShardingData.remove(system, journalPluginId = "", typeNames.toSet, remove2dot3Data = true) Await.ready(result, remaining) typeNames.foreach { typeName => hasSnapshots(typeName) should ===(false) hasEvents(typeName) should ===(false) } } } }
// Copyright 2016 The LUCI 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 iam import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "time" "golang.org/x/oauth2" "google.golang.org/api/googleapi" "go.chromium.org/luci/common/logging" ) // IAM credentials service URL used in non-test code. const iamCredentialsBackend = "https://iamcredentials.googleapis.com" // ClaimSet contains information about the JWT signature including the // permissions being requested (scopes), the target of the token, the issuer, // the time the token was issued, and the lifetime of the token. // // See RFC 7515. type ClaimSet struct { Iss string `json:"iss"` // email address of the client_id of the application making the access token request Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional). Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch) Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch) Typ string `json:"typ,omitempty"` // token type (Optional). // Email for which the application is requesting delegated access (Optional). Sub string `json:"sub,omitempty"` } // CredentialsClient knows how to perform IAM Credentials API v1 calls. // // DEPRECATED: Prefer to use cloud.google.com/go/iam/credentials/apiv1 instead // if possible. type CredentialsClient struct { Client *http.Client // the HTTP client to use to make calls backendURL string // replaceable in tests, defaults to iamCredentialsBackend } // SignBlob signs a blob using a service account's system-managed key. // // The caller must have "roles/iam.serviceAccountTokenCreator" role in the // service account's IAM policy and caller's OAuth token must have one of the // scopes: // * https://www.googleapis.com/auth/iam // * https://www.googleapis.com/auth/cloud-platform // // Returns ID of the signing key and the signature on success. // // On API-level errors (e.g. insufficient permissions) returns *googleapi.Error. func (cl *CredentialsClient) SignBlob(ctx context.Context, serviceAccount string, blob []byte) (keyName string, signature []byte, err error) { var request struct { Payload []byte `json:"payload"` } request.Payload = blob var response struct { KeyID string `json:"keyId"` SignedBlob []byte `json:"signedBlob"` } if err = cl.request(ctx, serviceAccount, "signBlob", &request, &response); err != nil { return "", nil, err } return response.KeyID, response.SignedBlob, nil } // SignJWT signs a claim set using a service account's system-managed key. // // It injects the key ID into the JWT header before singing. As a result, JWTs // produced by SignJWT are slightly faster to verify, because we know what // public key to use exactly and don't need to enumerate all active keys. // // It also checks the expiration time and refuses to sign claim sets with // 'exp' set to more than 12h from now. Otherwise it is similar to SignBlob. // // The caller must have "roles/iam.serviceAccountTokenCreator" role in the // service account's IAM policy and caller's OAuth token must have one of the // scopes: // * https://www.googleapis.com/auth/iam // * https://www.googleapis.com/auth/cloud-platform // // Returns ID of the signing key and the signed JWT on success. // // On API-level errors (e.g. insufficient permissions) returns *googleapi.Error. func (cl *CredentialsClient) SignJWT(ctx context.Context, serviceAccount string, cs *ClaimSet) (keyName, signedJwt string, err error) { blob, err := json.Marshal(cs) if err != nil { return "", "", err } var request struct { Payload string `json:"payload"` } request.Payload = string(blob) // yep, this is JSON inside JSON var response struct { KeyID string `json:"keyId"` SignedJwt string `json:"signedJwt"` } if err = cl.request(ctx, serviceAccount, "signJwt", &request, &response); err != nil { return "", "", err } return response.KeyID, response.SignedJwt, nil } // GenerateAccessToken creates a service account OAuth token using IAM's // :generateAccessToken API. // // On non-success HTTP status codes returns googleapi.Error. func (cl *CredentialsClient) GenerateAccessToken(ctx context.Context, serviceAccount string, scopes []string, delegates []string, lifetime time.Duration) (*oauth2.Token, error) { var body struct { Delegates []string `json:"delegates,omitempty"` Scope []string `json:"scope"` Lifetime string `json:"lifetime,omitempty"` } body.Delegates = delegates body.Scope = scopes // Default lifetime is 3600 seconds according to API documentation. // Requesting longer lifetime will cause an API error which is // forwarded to the caller. if lifetime > 0 { body.Lifetime = lifetime.String() } var resp struct { AccessToken string `json:"accessToken"` ExpireTime string `json:"expireTime"` } if err := cl.request(ctx, serviceAccount, "generateAccessToken", &body, &resp); err != nil { return nil, err } expires, err := time.Parse(time.RFC3339, resp.ExpireTime) if err != nil { return nil, fmt.Errorf("unable to parse 'expireTime': %s", resp.ExpireTime) } return &oauth2.Token{ AccessToken: resp.AccessToken, TokenType: "Bearer", Expiry: expires.UTC(), }, nil } // GenerateIDToken creates a service account OpenID Connect ID token using IAM's // :generateIdToken API. // // On non-success HTTP status codes returns googleapi.Error. func (cl *CredentialsClient) GenerateIDToken(ctx context.Context, serviceAccount string, audience string, includeEmail bool, delegates []string) (string, error) { var body struct { Delegates []string `json:"delegates,omitempty"` Audience string `json:"audience"` IncludeEmail bool `json:"includeEmail,omitempty"` } body.Delegates = delegates body.Audience = audience body.IncludeEmail = includeEmail var resp struct { Token string `json:"token"` } if err := cl.request(ctx, serviceAccount, "generateIdToken", &body, &resp); err != nil { return "", err } return resp.Token, nil } // request performs HTTP POST to the IAM credentials API endpoint. func (cl *CredentialsClient) request(ctx context.Context, serviceAccount, action string, body, resp interface{}) error { // Construct the target POST URL. backendURL := cl.backendURL if backendURL == "" { backendURL = iamCredentialsBackend } url := fmt.Sprintf("%s/v1/projects/-/serviceAccounts/%s:%s?alt=json", backendURL, url.QueryEscape(serviceAccount), action, ) // Serialize the body. var reader io.Reader if body != nil { blob, err := json.Marshal(body) if err != nil { return err } reader = bytes.NewReader(blob) } // Issue the request. req, err := http.NewRequest("POST", url, reader) if err != nil { return err } if reader != nil { req.Header.Set("Content-Type", "application/json") } // Send and handle errors. This is roughly how google-api-go-client calls // methods. CheckResponse returns *googleapi.Error. logging.Debugf(ctx, "POST %s", url) res, err := cl.Client.Do(req.WithContext(ctx)) if err != nil { return err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { logging.WithError(err).Errorf(ctx, "POST %s failed", url) return err } return json.NewDecoder(res.Body).Decode(resp) }
from typing import List from msp.data_structures.data_structure import DataStructure class Misc(DataStructure): def __init__(self): self.int_power_trigger1 = 0 self.conf_mini_throttle = 0 self.max_throttle = 0 self.min_command = 0 self.conf_failsafe_throttle = 0 self.plog_arm = 0 self.plog_lifetime = 0 self.conf_mag_declination = 0 self.vbat_scale = 0 self.vbat_level_warn1 = 0 self.vbat_level_warn2 = 0 self.vbat_level_crit = 0 @staticmethod def parse(data: List[int]) -> DataStructure: misc = Misc() misc.int_power_trigger1 = 0 misc.conf_mini_throttle = 0 misc.max_throttle = 0 misc.min_command = 0 misc.conf_failsafe_throttle = 0 misc.plog_arm = 0 misc.plog_lifetime = 0 misc.conf_mag_declination = 0 misc.vbat_scale = 0 misc.vbat_level_warn1 = 0 misc.vbat_level_warn2 = 0 misc.vbat_level_crit = 0 return misc
package com.tinmegali.myweather.web import android.arch.lifecycle.LiveData import com.tinmegali.myweather.models.ApiResponse import com.tinmegali.myweather.models.WeatherResponse import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query import retrofit2.http.Url interface OpenWeatherApi { // Get Today's Weather by City @GET("weather") fun cityWeatherLive( @Query("APPID") appId: String, @Query("q") city: String, @Query("units") unit: String ) : LiveData<ApiResponse<WeatherResponse>> // Get Today's Weather by Location @GET("weather") fun cityWeatherByLocationLive( @Query("APPID") appId: String, @Query("lat") lat: String, @Query("lon") lon: String, @Query("units") unit: String ) : LiveData<ApiResponse<WeatherResponse>> }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Repositories\CartInterfaceRepository; use App\Models\Article; use App\Models\User; use App\Models\Adresse; use App\Models\Gamme; use Illuminate\Support\Facades\Gate; class CartController extends Controller { protected $cartRepository; // L'instance cartSessionRepository public function __construct(CartInterfaceRepository $cartRepository) { $this->cartRepository = $cartRepository; } # Affichage du panier public function show() { return view("cart.show"); // resources\views\cart\show.blade.php } # Ajout d'un produit au panier public function add($articleId, Request $request) { // Validation de la requête $this->validate($request, [ "quantite" => "numeric|min:1" ]); $article = Article::findOrFail($articleId); $quantite = $request->quantite; if ($article->stock >= $quantite) { // Ajout/Mise à jour du produit au panier avec sa quantité $this->cartRepository->add($article, $quantite); } else { return redirect()->back()->withErrors("Quantité en stock insuffisante !"); } // Redirection vers le panier avec un message return redirect()->route("cart.show")->withMessage("Produit ajouté au panier"); } // Suppression d'un produit du panier public function remove($key) { // Suppression du produit du panier par son identifiant $this->cartRepository->remove($key); // Redirection vers le panier return back()->withMessage("Produit retiré du panier"); } // Vider le panier public function empty() { // Suppression des informations du panier en session $this->cartRepository->empty(); // Redirection return back()->withMessage("Panier vidé"); } // Vider le panier après validation commande public function emptyAfterOrder() { // Suppression des informations du panier en session $this->cartRepository->empty(); // Redirection return redirect('home')->withMessage("Votre commande a été validée. Merci de votre confiance."); } // valider le panier public function validation(Request $request) { if (!Gate::allows('access_order_validation')){ abort(403); } $user = User::find(auth()->user()->id); $adresseLivraisonId = null; $adresseFacturationId = null; if (($request->input('adresseLivraisonId') != null)) { $adresseLivraisonId = $request->input('adresseLivraisonId'); $adresseLivraison = Adresse::findOrFail($adresseLivraisonId); session(['adresseLivraison' => $adresseLivraison]); } if (($request->input('adresseFacturationId') != null)) { $adresseFacturationId = $request->input('adresseFacturationId'); $adresseFacturation = Adresse::findOrFail($adresseFacturationId); session(['adresseFacturation' => $adresseFacturation]); } return view('cart/validation', [ 'user' => $user, 'adresseLivraisonId' => $adresseLivraisonId, 'adresseFacturationId' => $adresseFacturationId, ]); } // valider le mode de livraison choisi et modifier le prix en conséquence public function chooseDelivery(Request $request) { $user = User::find(auth()->user()->id); $total = $request->input('total'); $delivery = $request->input('delivery'); switch ($delivery) { case ('classique'): $total += 5; break; case ('express'): $total += 9.90; break; case ('pointrelais'): $total += 4; break; } return view('cart/validation', ['user' => $user, 'lastTotal' => $total, 'delivery' => $delivery]); } }
# Analyzer for RADIUS # - radius-protocol.pac: describes the RADIUS protocol messages # - radius-analyzer.pac: describes the RADIUS analyzer code %include binpac.pac %include bro.pac %extern{ #include "events.bif.h" %} analyzer RADIUS withcontext { connection: RADIUS_Conn; flow: RADIUS_Flow; }; # Our connection consists of two flows, one in each direction. connection RADIUS_Conn(bro_analyzer: BroAnalyzer) { upflow = RADIUS_Flow(true); downflow = RADIUS_Flow(false); }; %include radius-protocol.pac # Now we define the flow: flow RADIUS_Flow(is_orig: bool) { datagram = RADIUS_PDU(is_orig) withcontext(connection, this); }; %include radius-analyzer.pac
# estimation_experiment.sh runs all Markov chains for the estimation experiment # which generated figure 2B module load anaconda/2020a source activate crp # Model parameters sd0=0.5 sd=1.3 alpha=1.0 # Long chains for ground truth echo "starting long chain for ground truth" python ../modules/estimation_experiment.py --est_type truth --max_iter 10000 --k 5000 \ --pool_size 10 --sd0 $sd0 --sd $sd --alpha $alpha > ../logs/estimation_experiment_truth.log # parallel estimates max_time=90 pool_size=70 n_replicates=200 k=1 m=120 echo "starting coupled chain ests" python ../modules/estimation_experiment.py --est_type coupled --k $k --m $m \ --pool_size $pool_size --n_replicates $n_replicates --max_time $max_time \ --sd0 $sd0 --sd $sd --alpha $alpha > ../logs/estimation_experiment_coupled.log # echo "starting single chain ests" python ../modules/estimation_experiment.py --est_type single --k $k --m $m \ --pool_size $pool_size --n_replicates $n_replicates --max_time $max_time \ --sd0 $sd0 --sd $sd --alpha $alpha > ../logs/estimation_experiment_single.log
import { UILogic } from 'ui-logic-core' import { TestLogicContainer } from 'ui-logic-core/lib/testing' import { BackgroundModules } from 'src/background-script/setup' import { setupBackgroundIntegrationTest } from './background-integration-tests' export type UILogicTest<Context> = (context: Context) => Promise<void> export type UILogicTestFactory<Context> = ( description: string, test: UILogicTest<Context>, ) => void export interface UILogicTestDevice { backgroundModules: BackgroundModules createElement: <State, Event>( logic: UILogic<State, Event>, ) => TestLogicContainer<State, Event> } export interface SingleDeviceUILogicTestContext { device: UILogicTestDevice } export interface MultiDeviceUILogicTestContext { createDevice: () => Promise<UILogicTestDevice> } export function makeSingleDeviceUILogicTestFactory(): UILogicTestFactory< SingleDeviceUILogicTestContext > { return (description, test) => { it(description, async () => { const { backgroundModules } = await setupBackgroundIntegrationTest() await test({ device: { backgroundModules, createElement: logic => new TestLogicContainer(logic), }, }) }) } } export function makeMultiDeviceUILogicTestFactory(): UILogicTestFactory< MultiDeviceUILogicTestContext > { return (description, test) => { it(description, async () => { await test({ createDevice: async () => { const { backgroundModules, } = await setupBackgroundIntegrationTest() return { backgroundModules, createElement: logic => new TestLogicContainer(logic), } }, }) }) } }
import { RefreshTokenController } from './refresh-token-controller' import { Validator, AuthenticatedRequest } from '@controllers/protocols' import { badRequest, ok, serverError, unauthorized } from '@controllers/helpers/http-helper' import { ValidationError } from '@controllers/errors/validation-error' import { RefreshToken } from '@domain/usecases' import { TokenSet } from '@domain/models' import { AuthenticationError } from '@controllers/errors/authentication-error' interface SutTypes { sut: RefreshTokenController validatorStub: Validator refreshTokenStub: RefreshToken } const givenRefreshToken = 'refreshToken' const generatedAccessToken = 'access-token' const generatedRefreshToken = 'refresh-token' const givenAccount = { id: '123', name: 'any name', email: 'valid@email.com', } const makeRequest = (): AuthenticatedRequest => ({ body: { refreshToken: givenRefreshToken, }, account: givenAccount, }) const makeTokenSet = () => ({ accessToken: generatedAccessToken, refreshToken: generatedRefreshToken, }) const makeValidatorStub = () => { class ValidatorStub implements Validator { validate(): void { /* do nothing */ } } return new ValidatorStub() } const makeRefreshTokenStub = () => { class RefreshTokenStub implements RefreshToken { async refresh(): Promise<TokenSet> { return makeTokenSet() } } return new RefreshTokenStub() } const makeSut = (): SutTypes => { const validatorStub = makeValidatorStub() const refreshTokenStub = makeRefreshTokenStub() const sut = new RefreshTokenController(validatorStub, refreshTokenStub) return { sut, validatorStub, refreshTokenStub } } describe('Refresh Token Controller', () => { it('should call validator with correct value', async () => { const { sut, validatorStub } = makeSut() const validateSpy = jest.spyOn(validatorStub, 'validate') const givenBody = { refreshToken: givenRefreshToken } await sut.handle({ body: givenBody, account: givenAccount }) expect(validateSpy).toBeCalledWith(givenBody) }) it('should return badRequest if validator throws', async () => { const { sut, validatorStub } = makeSut() const givenError = new ValidationError('any error') jest.spyOn(validatorStub, 'validate').mockImplementationOnce(() => { throw givenError }) const response = await sut.handle({ body: {}, account: givenAccount }) expect(response).toEqual(badRequest(givenError)) }) it('should return error 500 if validator throws an internal error', async () => { const { sut, validatorStub } = makeSut() const givenError = new Error('any error') jest.spyOn(validatorStub, 'validate').mockImplementationOnce(() => { throw givenError }) const response = await sut.handle(makeRequest()) expect(response).toEqual(serverError(givenError)) }) it('should call RefreshToken with correct values', async () => { const { sut, refreshTokenStub } = makeSut() const refreshSpy = jest.spyOn(refreshTokenStub, 'refresh') sut.handle(makeRequest()) expect(refreshSpy).toBeCalledWith(givenAccount, givenRefreshToken) }) it('should return 401 if RefreshToken returns null', async () => { const { sut, refreshTokenStub } = makeSut() jest.spyOn(refreshTokenStub, 'refresh').mockResolvedValueOnce(null) const response = await sut.handle(makeRequest()) expect(response).toEqual(unauthorized(new AuthenticationError('Refresh Token is expired or invalid'))) }) it('should not handle RefreshToken errors', async () => { const { sut, refreshTokenStub } = makeSut() const givenError = new Error('any error') jest.spyOn(refreshTokenStub, 'refresh').mockRejectedValueOnce(givenError) const response = await sut.handle(makeRequest()) expect(response).toEqual(serverError(givenError)) }) it('should return the new generated token set', async () => { const { sut } = makeSut() const response = await sut.handle(makeRequest()) expect(response).toEqual(ok(makeTokenSet())) }) })
c==================================================================================== c c Synthetic Seismogram code for complete synthetics using spectral technique c for Moment Tensor and Point Force sources in flat layered media c c Funded by Treaty Verification Program, Lawrence Livermore National Lab c c George Randall, Dept. of Geological Sciences, University of South Carolina c ger@tigger.seis.scarolina.edu c Steve Taylor, Los Alamos National Lab c taylor@beta.lanl.gov c c based on c "Seismic Wave Propagation in Stratified Media" B.L.N. Kennett, c Cambridge University Press, 1983 c c Many useful discussions with and testing by c Chuck Ammon, Harley Benz, and Bill Walter c are gratefully acknowledged. c c c==================================================================================== c c Version 1.0 February 1 1993 c subroutine srcvec( m, p, isrc ) integer m, isrc complex p c c compute the upward and downward p and s waves from a c symmetric moment tensor source, for integer angular order m c and slowness p, for source isrc, (4.64) kennett c c fix sign of +1 and -1 terms give results consistent with crfl and others c include 'kennet.inc' c c su,sv,sw,sp,ss,st are the components of the jump in c the displacement - stress vector c from kennett (1983) (4.59 - 4.60) c complex su,sv,sw,sp,ss,st,i,zero data i,zero/(0.,1.),(0.,0.)/ c c calculate up and downgoing P,SV,SH at source (4.64) kennett c if ( m .eq. 0 ) then su = mzz(isrc)/(rhos*alfas*alfas) ss = p*( .5*(mxx(isrc)+myy(isrc)) * - mzz(isrc)*(1. - 2.*betas*betas/(alfas*alfas))) pup0(isrc) = i*(mds21*ss - nds11*su) svup0(isrc) = i*(mds22*ss - nds12*su) pdn0(isrc) = i*(mus21*ss - nus11*su) svdn0(isrc) = i*(mus22*ss - nus12*su) shup0(isrc) = zero shdn0(isrc) = zero endif if ( m .eq. 1 ) then sv = -( mxz(isrc) - i*myz(isrc) )/(2.*rhos*betas*betas) sw = -(-myz(isrc) - i*mxz(isrc) )/(2.*rhos*betas*betas) pupp1(isrc) =-i*nds21*sv svupp1(isrc) =-i*nds22*sv pdnp1(isrc) =-i*nus21*sv svdnp1(isrc) =-i*nus22*sv shupp1(isrc) =-i*ndssh*sw shdnp1(isrc) =-i*nussh*sw endif if ( m .eq. -1 ) then sv = -(-mxz(isrc) - i*myz(isrc) )/(2.*rhos*betas*betas) sw = -( myz(isrc) - i*mxz(isrc) )/(2.*rhos*betas*betas) pupm1(isrc) = -i*nds21*sv svupm1(isrc) = -i*nds22*sv pdnm1(isrc) = -i*nus21*sv svdnm1(isrc) = -i*nus22*sv shupm1(isrc) = -i*ndssh*sw shdnm1(isrc) = -i*nussh*sw endif if ( m .eq. 2 ) then ss = .25*p*( myy(isrc) - mxx(isrc) + 2.*i*mxy(isrc) ) st = .25*p*( i*(mxx(isrc) - myy(isrc)) + 2.*mxy(isrc) ) pupp2(isrc) = i*mds21*ss svupp2(isrc) = i*mds22*ss pdnp2(isrc) = i*mus21*ss svdnp2(isrc) = i*mus22*ss shupp2(isrc) = i*mdssh*st shdnp2(isrc) = i*mussh*st endif if ( m .eq. -2 ) then ss = .25*p*( myy(isrc) - mxx(isrc) - 2.*i*mxy(isrc) ) st = .25*p*( -i*(mxx(isrc) - myy(isrc)) + 2.*mxy(isrc) ) pupm2(isrc) = i*mds21*ss svupm2(isrc) = i*mds22*ss pdnm2(isrc) = i*mus21*ss svdnm2(isrc) = i*mus22*ss shupm2(isrc) = i*mdssh*st shdnm2(isrc) = i*mussh*st endif return end
declare type AuthSessionResult = RedirectResult | BrowserResult; declare type BrowserResult = { type: 'cancel' | 'dismiss'; }; declare type RedirectResult = { type: 'success'; url: string; }; export declare function openBrowserAsync(url: string): Promise<BrowserResult>; export declare function dismissBrowser(): void; export declare function openAuthSessionAsync(url: string, redirectUrl: string): Promise<AuthSessionResult>; export declare function dismissAuthSession(): void; export {};
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ImageController extends Controller { // public function upload(Request $request) { $this->validate($request, [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($request->hasFile('image')) { $image = $request->file('image'); $name = $image->getClientOriginalName();//time().'.'.$image->getClientOriginalExtension(); $liter = substr($name,0,1); $destinationPath = public_path('/images/' . $liter); $flag = !file_exists($destinationPath . '/' . $name); if (!$flag) { $flag = $image->getSize() != filesize($destinationPath . '/' . $name); if ($flag) { $name = time() . $name; } } if ($flag) { $image->move($destinationPath, $destinationPath . '/' . $name); } return response()->json(['url' => '/images/' . $liter . '/' . $name ]); //return back()->with('success','Image Upload successfully'); } } }
#!/usr/bin/python ############################################################################### # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License Version 2.0 (the "License"). You may not # # use this file except in compliance with the License. A copy of the License # # is located at # # # # http://www.apache.org/licenses/LICENSE-2.0/ # # # # or in the "license" file accompanying this file. This file is distributed # # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express # # or implied. See the License for the specific language governing permis- # # sions and limitations under the License. # ############################################################################### import pytest from afsbp_parse_input import parse_event def event(): return { 'expected_control_id': 'AutoScaling.1', 'parse_id_pattern': '^arn:(?:aws|aws-cn|aws-us-gov):autoscaling:(?:[a-z]{2}(?:-gov)?-[a-z]+-\\d):\\d{12}:autoScalingGroup:(?i:[0-9a-f]{11}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}):autoScalingGroupName/(.*)$', 'Finding': { "SchemaVersion": "2018-10-08", "Id": "arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0/AutoScaling.1/finding/635ceb5d-3dfd-4458-804e-48a42cd723e4", "ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub", "GeneratorId": "aws-foundational-security-best-practices/v/1.0.0/AutoScaling.1", "AwsAccountId": "111111111111", "Types": [ "Software and Configuration Checks/Industry and Regulatory Standards/AWS-Foundational-Security-Best-Practices" ], "FirstObservedAt": "2020-07-24T01:34:19.369Z", "LastObservedAt": "2021-02-18T13:45:30.638Z", "CreatedAt": "2020-07-24T01:34:19.369Z", "UpdatedAt": "2021-02-18T13:45:28.802Z", "Severity": { "Product": 0, "Label": "INFORMATIONAL", "Normalized": 0, "Original": "INFORMATIONAL" }, "Title": "AutoScaling.1 Auto scaling groups associated with a load balancer should use load balancer health checks", "Description": "This control checks whether your Auto Scaling groups that are associated with a load balancer are using Elastic Load Balancing health checks.", "Remediation": { "Recommendation": { "Text": "For directions on how to fix this issue, please consult the AWS Security Hub Foundational Security Best Practices documentation.", "Url": "https://docs.aws.amazon.com/console/securityhub/AutoScaling.1/remediation" } }, "ProductFields": { "StandardsArn": "arn:aws:securityhub:::standards/aws-foundational-security-best-practices/v/1.0.0", "StandardsSubscriptionArn": "arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0", "ControlId": "AutoScaling.1", "RecommendationUrl": "https://docs.aws.amazon.com/console/securityhub/AutoScaling.1/remediation", "RelatedAWSResources:0/name": "securityhub-autoscaling-group-elb-healthcheck-required-f986ecc9", "RelatedAWSResources:0/type": "AWS::Config::ConfigRule", "StandardsControlArn": "arn:aws:securityhub:us-east-1:111111111111:control/aws-foundational-security-best-practices/v/1.0.0/AutoScaling.1", "aws/securityhub/ProductName": "Security Hub", "aws/securityhub/CompanyName": "AWS", "aws/securityhub/annotation": "AWS Config evaluated your resources against the rule. The rule did not apply to the AWS resources in its scope, the specified resources were deleted, or the evaluation results were deleted.", "aws/securityhub/FindingId": "arn:aws:securityhub:us-east-1::product/aws/securityhub/arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0/AutoScaling.1/finding/635ceb5d-3dfd-4458-804e-48a42cd723e4" }, "Resources": [ { "Type": "AwsAccount", "Id": "arn:aws:autoscaling:us-east-1:111111111111:autoScalingGroup:785df3481e1-cd66-435d-96de-d6ed5416defd:autoScalingGroupName/sharr-test-autoscaling-1", "Partition": "aws", "Region": "us-east-1" } ], "Compliance": { "Status": "FAILED", "StatusReasons": [ { "ReasonCode": "CONFIG_EVALUATIONS_EMPTY", "Description": "AWS Config evaluated your resources against the rule. The rule did not apply to the AWS resources in its scope, the specified resources were deleted, or the evaluation results were deleted." } ] }, "WorkflowState": "NEW", "Workflow": { "Status": "NEW" }, "RecordState": "ACTIVE" } } def expected(): return { "account_id": '111111111111', "resource_id": 'sharr-test-autoscaling-1', 'control_id': 'AutoScaling.1', 'testmode': False, "finding_id": 'arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0/AutoScaling.1/finding/635ceb5d-3dfd-4458-804e-48a42cd723e4', "product_arn": 'arn:aws:securityhub:us-east-1::product/aws/securityhub', "object": { "Type": 'AwsAccount', "Id": 'sharr-test-autoscaling-1', "OutputKey": 'Remediation.Output' }, "matches": [ "sharr-test-autoscaling-1" ], 'details': {}, 'resource': event().get('Finding').get('Resources')[0] } def test_parse_event(): parsed_event = parse_event(event(), {}) assert parsed_event == expected() def test_parse_event_multimatch(): expected_result = expected() expected_result['matches'] = [ "us-east-1", "sharr-test-autoscaling-1" ] test_event = event() test_event['resource_index'] = 2 test_event['parse_id_pattern'] = '^arn:(?:aws|aws-cn|aws-us-gov):autoscaling:((?:[a-z]{2}(?:-gov)?-[a-z]+-\\d)):\\d{12}:autoScalingGroup:(?i:[0-9a-f]{11}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}):autoScalingGroupName/(.*)$' parsed_event = parse_event(test_event, {}) assert parsed_event == expected_result def test_bad_finding_id(): test_event = event() test_event['Finding']['Id'] = "badvalue" with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: Finding Id is invalid: badvalue' def test_bad_control_id(): test_event = event() test_event['Finding']['Id'] = "arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0//finding/635ceb5d-3dfd-4458-804e-48a42cd723e4" with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: Finding Id is invalid: arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0//finding/635ceb5d-3dfd-4458-804e-48a42cd723e4 - missing Control Id' def test_control_id_nomatch(): test_event = event() test_event['Finding']['Id'] = "arn:aws:securityhub:us-east-1:111111111111:subscription/aws-foundational-security-best-practices/v/1.0.0/EC2.1/finding/635ceb5d-3dfd-4458-804e-48a42cd723e4" with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: Control Id from input (EC2.1) does not match AutoScaling.1' def test_bad_account_id(): test_event = event() test_event['Finding']['AwsAccountId'] = "1234123412345" with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: AwsAccountId is invalid: 1234123412345' def test_bad_productarn(): test_event = event() test_event['Finding']['ProductArn'] = "badvalue" with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: ProductArn is invalid: badvalue' def test_bad_resource_match(): test_event = event() test_event['parse_id_pattern'] = '^arn:(?:aws|aws-cn|aws-us-gov):logs:::([A-Za-z0-9.-]{3,63})$' with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: Invalid resource Id arn:aws:autoscaling:us-east-1:111111111111:autoScalingGroup:785df3481e1-cd66-435d-96de-d6ed5416defd:autoScalingGroupName/sharr-test-autoscaling-1' def test_no_resource_pattern(): test_event = event() expected_result = expected() test_event['parse_id_pattern'] = '' expected_result['resource_id'] = 'arn:aws:autoscaling:us-east-1:111111111111:autoScalingGroup:785df3481e1-cd66-435d-96de-d6ed5416defd:autoScalingGroupName/sharr-test-autoscaling-1' expected_result['matches'] = [] expected_result['object']['Id'] = expected_result['resource_id'] parsed_event = parse_event(test_event, {}) assert parsed_event == expected_result def test_no_resource_pattern_no_resource_id(): test_event = event() test_event['parse_id_pattern'] = '' test_event['Finding']['Resources'][0]['Id'] = '' with pytest.raises(SystemExit) as pytest_wrapped_e: parsed_event = parse_event(test_event, {}) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 'ERROR: Resource Id is missing from the finding json Resources (Id)'
<?php /** * YYF - A simple, secure, and efficient PHP RESTful Framework. * * @link https://github.com/YunYinORG/YYF/ * * @license Apache2.0 * @copyright 2015-2017 NewFuture@yunyin.org */ /** * Model 数据Model基类 * 基本的Facde接口,对model封装 * * @author NewFuture * * @example * class UserModel extends Model{} * * UserModel::find(1);//返回id为1的数据 * UserModel::slecet('id,number,name AS username');//列出用户 * * UserModel::set('pwd','1234')->save(1);//将id为1的用户密码设置为1234 * UserModel::where('id','=','1')->update(['pwd'=>'1234']);//同上,也可以使用save * * UserModel::set(['pwd'=>'mypwd','name'=>'test'])->add();//添加新用户 * UserModel::add(['pwd'=>'mypwd','name'=>'test']);//同上,也可以使用insert() * * UserModel::where('id','>','10')->where('id','<','100')->select();//查找所有id在10到100之间的用户 * UserModel::where('id','=','1')->get('name');//获取id为一的用户的name * UserModel::where('id','>','1')->limit(10)->select('id,name');//查询id>1的10个用户的id和name * UserModel::where('id','>','1')->field('id','uid')->field('name','uname')->select();//查询id>1的用户的uid和uname(表示id和name) * UserModel::where('name','LIKE','%future%')->count();//统计name中包含future的字数 * * 也可以实例化操作 $user=new UserModel; * $user->find(1); */ abstract class Model { protected $name = null; //数据库表 protected $pk = 'id'; //主键 protected $prefix = true; //前缀 protected $fields = null; //字段过滤 protected $dbname = null; //使用指定数据库 private $_orm = null; //底层orm /** * 构造函数 * * @param array $data 传入数据 */ final public function __construct(array $data = null) { if (!$name = &$this->name) { $name = strtolower(preg_replace('/.(?=[A-Z])/', '$1_', substr(get_called_class(), 0, -5))); } $this->_orm = new Orm($name, $this->pk, $this->prefix); if ($this->fields) { //字段设置 $this->_orm->field($this->fields); } if ($data) { //预填充数据 $this->_orm->set($data); } if ($this->dbname) { //指定数据库 $this->_orm->setDb($this->dbname); } } /** * 直接修改字段 * * @param string $name 字段名 * @param mixed $value 对应值 */ public function __set($name, $value) { return $this->_orm->set($name, $value); } /** * 直接读取字段 * * @param string $name 字段名 * * @return mixed 对应的值 */ public function __get($name) { return $this->_orm->get($name, false); } /** * 直接调用model的操作 * * @param string $method * @param array $params */ public function __call($method, $params) { return call_user_func_array(array($this->getOrm(), $method), $params); } /** * 静态调用model的操作 * * @param string $method * @param array $params */ public static function __callStatic($method, $params) { $model = new static(); return call_user_func_array(array($model->getOrm(), $method), $params); } /** * 获取模型实例 * * @return Orm 返回对应ORM对象 */ public function getOrm() { return $this->_orm; } public function toArray() { return $this->_orm->get(); } /** * 数据转成json * * @param int $type JSON_ENCODE type 【256 是JSON_UNESCAPED_UNICODE值】 */ public function toJson($type = 256) { return json_encode($this->_orm->get(), $type); } }
use wasm_encoder::{EntityType, Instruction}; use crate::{codegen::*, core::ast::*}; impl<'a> Walker<FunctionDeclaration> for Context<'a> { fn walk(&mut self, function_declaration: FunctionDeclaration) -> Result<(), Error> { let parameters_type: Vec<_> = function_declaration .parameters .iter() .cloned() .flat_map(|(_, ty)| self.convert_type(ty)) .collect(); let return_type = self.convert_type(function_declaration.return_type.clone()); let id = self.declare_function_type(parameters_type, return_type); if function_declaration.is_extern { self.declare_extern_type( "extern", function_declaration.name.clone(), EntityType::Function(id), )?; } else { self.set_local(function_declaration.name.content.clone(), id); let mut param_id = 0; for (pat, _ty) in &function_declaration.parameters { match pat { Pattern::Slot(name) => match name { Name::Ident(token) => { self.set_local(token.content.clone(), param_id); } Name::Placeholder => {} }, } param_id += 1; } let mut body = Vec::new(); std::mem::swap(&mut self.instructions, &mut body); if let Some(body) = function_declaration.body.clone() { self.walk(body)?; } std::mem::swap(&mut self.instructions, &mut body); if function_declaration .body .and_then(|block| block.last_expression) .is_none() { if matches!(&function_declaration.return_type, Type::Tuple(v) if v.is_empty()) { body.push(Instruction::I32Const(0)); } else { return Err(Error::mismatched_type( function_declaration.return_type, Type::Tuple(Vec::new()), function_declaration.name.span, )); } } body.push(Instruction::End); dbg!(&body); for (pat, _ty) in &function_declaration.parameters { match pat { Pattern::Slot(name) => match name { Name::Ident(token) => { self.remove_local(&token.content); } Name::Placeholder => {} }, } } self.implement_function(id, body); } if function_declaration.is_pub { self.export_function(function_declaration.name.content, id) } Ok(()) } }
package Bat::Interpreter::Delegate::Executor::System; use utf8; use Moo; use namespace::autoclean; with 'Bat::Interpreter::Role::Executor'; # VERSION =encoding utf-8 =head1 NAME Bat::Interpreter::Delegate::Executor::PartialDryRunner - Executor for executing commands via perl system =head1 SYNOPSIS use Bat::Interpreter; use Bat::Interpreter::Delegate::Executor::System; my $system_executor = Bat::Interpreter::Delegate::Executor::System->new; my $interpreter = Bat::Interpreter->new(executor => $system_executor); $interpreter->run('my.cmd'); =head1 DESCRIPTION Every command gets through system. So if you are in Linux using bash, bash will try to execute the command. This executor is as dumb and simple as it can, be cautious. =head1 METHODS =cut =head2 execute_command Execute general commands. This executor use perl system =cut sub execute_command { my $self = shift(); my $command = shift(); return system($command); } =head2 execute_for_command Execute commands for use in FOR expressions. This is usually used to capture output and implement some logic inside the bat/cmd file. This executor executes this commands via perl subshell: `` =cut sub execute_for_command { my $self = shift(); my $command = shift(); my $output = `$command`; chomp $output; return $output; } 1;
using System; using System.Collections.Generic; using Swarmops.Basic.Types; using Swarmops.Common; using Swarmops.Basic.Types.Structure; using Swarmops.Database; using Swarmops.Logic.Structure; namespace Swarmops.Logic.Cache { public class GeographyCache { private static DateTime lastRefresh; private static object loadCacheLock = new object(); public static bool loadCache = true; private static Dictionary<int, List<BasicGeography>> __geographyCache = null; private static readonly int cacheLifeSpanMinutes = 2; static GeographyCache() { lastRefresh = Constants.DateTimeLow; } private static Dictionary<int, List<BasicGeography>> GetHashedGeographies() { lock (loadCacheLock) { if (loadCache || lastRefresh.AddMinutes (cacheLifeSpanMinutes) < DateTime.Now) { __geographyCache = SwarmDb.GetDatabaseForReading().GetHashedGeographies(); lastRefresh = DateTime.Now; loadCache = false; } return __geographyCache; } } public static Geography FromCache (int geographyId) { lock (loadCacheLock) { return Geography.FromBasic (GetGeography (geographyId)); } } public static BasicGeography[] GetAllGeographies() { lock (loadCacheLock) { List<BasicGeography> result = new List<BasicGeography>(); Dictionary<int, List<BasicGeography>> hashedGeographies = GetHashedGeographies(); foreach (int entry in hashedGeographies.Keys) { result.Add (hashedGeographies[entry][0]); } return result.ToArray(); } } public static BasicGeography[] GetGeographies (int[] ids) { List<BasicGeography> result = new List<BasicGeography>(); lock (loadCacheLock) { foreach (int i in ids) { result.Add (GetGeography (i)); } return result.ToArray(); } } public static BasicGeography[] GetGeographyChildren (int parentGeographyId) { List<BasicGeography> result = new List<BasicGeography>(); lock (loadCacheLock) { // Prime the cache GetGeography (parentGeographyId); //TODO: Possible to miss a child geography here if it was added since last cache reload. Dictionary<int, List<BasicGeography>> hashedGeographies = GetHashedGeographies(); foreach (BasicGeography b in hashedGeographies[parentGeographyId]) { if (b.Identity != parentGeographyId) result.Add (b); } return result.ToArray(); } } public static int CountGeographyChildren (int parentGeographyId) { lock (loadCacheLock) { // Prime the cache GetGeography (parentGeographyId); return GetHashedGeographies()[parentGeographyId].Count - 1; } } public static BasicGeography[] GetGeographyLine (int leafGeographyId) { List<BasicGeography> result = new List<BasicGeography>(); BasicGeography currentNode = GetGeography (leafGeographyId); // This iterates until the zero-parentid root node is found while (currentNode.GeographyId != 0) { result.Add (currentNode); if (currentNode.ParentGeographyId != 0) { currentNode = GetGeography (currentNode.ParentGeographyId); } else { currentNode = new BasicGeography (0, 0, string.Empty); } } result.Reverse(); return result.ToArray(); } public static BasicGeography[] GetGeographyTree() { return GetGeographyTree (1); } public static Dictionary<int, BasicGeography> GetGeographyHashtable (int startGeographyId) { BasicGeography[] nodes = GetGeographyTree (startGeographyId); Dictionary<int, BasicGeography> result = new Dictionary<int, BasicGeography>(); foreach (BasicGeography node in nodes) { result[node.GeographyId] = node; } return result; } public static BasicGeography[] GetGeographyTree (int startGeographyId) { Dictionary<int, List<BasicGeography>> nodes = GetHashedGeographies(); return GetGeographyTree (nodes, startGeographyId, 0); } private static BasicGeography[] GetGeographyTree (Dictionary<int, List<BasicGeography>> geographies, int startNodeId, int generation) { List<BasicGeography> result = new List<BasicGeography>(); List<BasicGeography> thisList = geographies[startNodeId]; foreach (BasicGeography node in thisList) { if (node.GeographyId != startNodeId) { result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation + 1)); // Add recursively BasicGeography[] children = GetGeographyTree (geographies, node.GeographyId, generation + 1); if (children.Length > 0) { foreach (BasicGeography child in children) { result.Add (child); } } } else if (generation == 0) { // The top parent is special and should be added; the others shouldn't result.Add (new BasicGeography (node.GeographyId, node.ParentGeographyId, node.Name, generation)); } } return result.ToArray(); } public static BasicGeography GetGeography (int geographyId) { lock (loadCacheLock) { Dictionary<int, List<BasicGeography>> hashedGeographies = GetHashedGeographies(); if (hashedGeographies.ContainsKey (geographyId)) return hashedGeographies[geographyId][0]; else { loadCache = true; hashedGeographies = GetHashedGeographies(); if (hashedGeographies.ContainsKey (geographyId)) return hashedGeographies[geographyId][0]; else { throw new ArgumentException ("No such GeographyId: " + geographyId.ToString()); } } } } public static BasicGeography GetGeographyByName (string geographyName) { string cmpName = geographyName.ToLower().Trim(); Dictionary<int, List<BasicGeography>> hashedGeographies = GetHashedGeographies(); foreach (int entry in hashedGeographies.Keys) { if (hashedGeographies[entry][0].Name.ToLower().Trim() == cmpName) return hashedGeographies[entry][0]; } //TODO: This can miss due to that the geography was added after last cache reload throw new ArgumentException ("No such GeographyName: " + geographyName); } public static void SetGeographyName (int geographyId, string name) { SwarmDb.GetDatabaseForWriting().SetGeographyName (geographyId, name); BasicGeography geo = SwarmDb.GetDatabaseForReading().GetGeography (geographyId); Dictionary<int, List<BasicGeography>> hashedGeographies = GetHashedGeographies(); hashedGeographies[geographyId][0] = geo; } /********************** * Might be handled.... public GeographyLevel[] GetGeographyLevelsAtGeographyId (int geographyId) { return SwarmDb.GetDatabaseForReading().GetGeographyLevelsAtGeographyId(geographyId); } public int[] GetGeographyIdsFromLevel (int countryId, GeographyLevel level) { return SwarmDb.GetDatabaseForReading().GetGeographyIdsFromLevel(countryId, level); } ************************/ } }
db DEX_VENONAT ; pokedex id db 60 ; base hp db 55 ; base attack db 50 ; base defense db 45 ; base speed db 40 ; base special db BUG ; species type 1 db POISON ; species type 2 db 190 ; catch rate db 75 ; base exp yield INCBIN "pic/bmon/venonat.pic",0,1 ; 55, sprite dimensions dw VenonatPicFront dw VenonatPicBack ; attacks known at lvl 0 db TACKLE db DISABLE db 0 db 0 db 0 ; growth rate ; learnset tmlearn 6 tmlearn 9,10 tmlearn 20,21,22 tmlearn 29,31,32 tmlearn 33,34 tmlearn 44,46 tmlearn 50 db 0 ; padding
use scholars::v1::definition::FullPaper; use scholars::v1::endpoint::GetPaper; use scholars::v1::query_params::PaperParams; use scholars::v1::utils::all_full_paper_fields; #[tokio::main] async fn main() -> anyhow::Result<()> { env_logger::init(); let client = reqwest::Client::new(); let endpoint = GetPaper::new(query_params(), paper_id()); // A blocking query execution through the default reqwest client implementation. let paper: FullPaper = endpoint.query_async(&client).await?; println!("{}", serde_json::to_string_pretty(&paper).unwrap()); Ok(()) } fn query_params() -> PaperParams { PaperParams::new(Some(all_full_paper_fields())) } fn paper_id() -> String { "649def34f8be52c8b66281af98ae884c09aef38b".to_owned() }
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of Query_sekunder_m * * @author Mardella */ class Query_sekunder_m extends CI_Model { public function __construct() { parent::__construct(); } public function getAll($table) { return $this->db->get($table)->result_array(); } public function getWhere($id, $table) { $this->db ->select("*") ->from($table) ->where("id", $id); return $this->db->get()->row(); } public function getId($caption, $table) { $no = $this->countAll($table) + 1; $id = uniqid($caption . "_" . $no . "_"); return $id; } public function countAll($table) { return $this->db->get($table)->num_rows(); } public function insert($data, $table) { return $this->db->insert($table, $data); } public function update($data, $id, $table) { return $this->db->update($table, $data, array("id" => $id)); } public function delete($id, $table) { return $this->db->delete($table, array("id" => $id)); } }
import axios from "axios"; import { BASEURL } from "../constants/baseUrl"; const instance = axios.create({ baseURL: BASEURL, }); /* 만료되었다면 로그인 페이지로 리다이렉트, 그게 아니라면 요청 수행 1. jwt verify를 통해 만료여부 확인 장: 매번 요청이 없어 속도와 서버 트래픽을 고려함에 있어 훌륭한 방식 단: jwt 암호키를 알아야 함 2. verifyToken api를 통해 만료여부 확인 장: api 서버에 verifyToken api를 둠으로써 로직의 분리가 확실함. 단: 매 요청마다 서버와 통신을 해야함 */ instance.interceptors.request.use( (config) => config, (error) => Promise.reject(error) ); instance.interceptors.response.use( (response) => response, (error) => Promise.reject(error) ); export default instance;
# The Social App This project was done before I started a project that will be avaible in the future on the app store and play store. # About the Author Name: Samira Mc Queen [LinkedIn](https://www.linkedin.com/in/samira-mc-queen-1882431a7/) Free Spririted Caribbean Woman. Software Developer and aspiring Game Developer # Project ![Video](src/assets/social-app.gif) ## Experience with Project - I enjoy using Ionc/Angular and Capacitor - This is the beginning of something greater - This project taught me more about the framework # Application Features - User can create an account - User can login - User can update feed - User can view feed and what is being updated # Frontend Built With - Ionic Angular - Ionic Components # Backend Built With - Json server # Project setup Once the project is downloaded locally on your device do the following: ` npm install ` If there are dependencies that need updating or you want to check: ` npm outdated ` If there are outdated dependencies: ` npm update ` To check and update packages in package.json: ` npx npm-check-updates -u ` ### Start Project ` ng serve ` ` ionic buld capacitor ios ` ` ionic build capacitor android ` ` npx cap open ios ` ` npx cap open android `
- Installs the [elasticsearch-head](https://mobz.github.io/elasticsearch-head/) plugin - plugin would be installed by default for any other clusters defined as well - 5 total nodes - 2 Master Nodes - 3 Data nodes - Cluster named *2m3d* To load this configuration, run `esvm 2m3d` ``` { "clusters": { "2m3d": { "plugins": ["mobz/elasticsearch-head"], "nodes": [ { "cluster": { "name": "2m3d" }, "node": { "name": "master-1", "data": false, "master": true } }, { "cluster": { "name": "2m3d" }, "node": { "name": "master-2", "data": false, "master": true } }, { "cluster": { "name": "2m3d" }, "node": { "name": "data-1", "data": true, "master": false } }, { "cluster": { "name": "2m3d" }, "node": { "name": "data-2", "data": true, "master": false } }, { "cluster": { "name": "2m3d" }, "node": { "name": "data-3", "data": true, "master": false } } ] } } } ```
# GAME2012 3D Graphics - OpenGL ### Synopsis Repository of all my projects for GAME2012 - 3D Graphics Using OpenGL ### Purpose Keeping track of all my projects ### Installation * Fork/Download repository
import React, { useState } from "react"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; import ProfilePic from "components/Picture/ProfilePic"; import { WhiteSpace } from "antd-mobile"; import { getInitials } from "utils/userInfo"; import fakePosts from "assets/data/fakePosts"; // feed import Posts from "components/Feed/Posts"; // feed import FeedWrapper from "components/Feed/FeedWrapper"; //feed import CreatePost from "components/CreatePost/CreatePost"; // ICONS import SvgIcon from "components/Icon/SvgIcon"; import createPost from "assets/icons/create-post.svg"; // feed import menu from "assets/icons/menu.svg"; import edit from "assets/icons/edit.svg"; import editEmpty from "assets/icons/edit-empty.svg"; import linkedinBlue from "assets/icons/social-linkedin-blue.svg"; import twitterBlue from "assets/icons/social-twitter-blue.svg"; import locationIcon from "assets/icons/location.svg"; import { ProfileLayout, BackgroundHeader, MenuIcon, UserInfoContainer, EditIcon, UserInfoDesktop, NameDiv, PlaceholderIcon, EditEmptyIcon, DescriptionDesktop, LocationDesktopDiv, LocationMobileDiv, IconsContainer, HelpContainer, HelpImage, LocationIcon, LinkedinBlueIcon, TwitterBlueIcon, DescriptionMobile, SectionHeader, CreatePostDiv, CreatePostIcon, DrawerHeader, CustomDrawer, } from "../components/Profile/ProfileComponents"; const offerHelpInactive = require("assets/help-gesture-unselected.svg"); const needHelpInactive = require("assets/thermometer-unselected.svg"); const Profile = (props) => { const { firstName, lastName, about, address, country } = props.user; const needHelp = true; const [modal, setModal] = useState(false); const [drawer, setDrawer] = useState(false); //requires responsive implementation const renderMyActivities = () => { return ( <> <FeedWrapper> <Posts filteredPosts={fakePosts} /> <SvgIcon src={createPost} className="create-post" onClick={() => setModal(!modal)} /> <CreatePost onCancel={() => setModal(false)} visible={modal} /> </FeedWrapper> </> ); }; return ( <ProfileLayout> <BackgroundHeader> <MenuIcon src={menu} /> </BackgroundHeader> <UserInfoContainer> <EditIcon src={edit} onClick={() => setDrawer(true)} /> <ProfilePic noPic={true} initials={getInitials(firstName, lastName)} /> <UserInfoDesktop> <NameDiv> {firstName} {lastName} <PlaceholderIcon /> <EditEmptyIcon src={editEmpty} onClick={() => setDrawer(true)} /> </NameDiv> <DescriptionDesktop> {about} </DescriptionDesktop> <LocationMobileDiv> {address}, {country} </LocationMobileDiv> <IconsContainer> <HelpContainer> <HelpImage src={needHelp ? needHelpInactive : offerHelpInactive} alt="help-type-icon" /> {needHelp ? "I need help" : "I want to help"} </HelpContainer> <LocationDesktopDiv> <LocationIcon src={locationIcon} /> {needHelp ? "I need help" : "I want to help"} • {address},{" "} {country} </LocationDesktopDiv> <PlaceholderIcon /> <LinkedinBlueIcon src={linkedinBlue} /> <TwitterBlueIcon src={twitterBlue} /> </IconsContainer> </UserInfoDesktop> </UserInfoContainer> <WhiteSpace /> <div style={{ margin: "0 2.5rem" }}> <WhiteSpace /> <DescriptionMobile> <SectionHeader> About</SectionHeader> {about} </DescriptionMobile> <WhiteSpace /> <SectionHeader> My Activity <PlaceholderIcon /> <CreatePostDiv>Create post</CreatePostDiv> <CreatePostIcon src={createPost} onClick={() => setModal(!modal)} /> </SectionHeader> {renderMyActivities()} </div> <CustomDrawer placement="bottom" closable={false} onClose={() => setDrawer(false)} visible={drawer} height="150px" key="bottom" > <DrawerHeader> <Link to="/edit-profile">Edit Account Information</Link> </DrawerHeader> <DrawerHeader> <Link to="/edit-profile">Edit Profile </Link> </DrawerHeader> </CustomDrawer> <WhiteSpace /> </ProfileLayout> ); }; const mapStateToProps = (state) => { return { user: state.user, }; }; export default connect(mapStateToProps)(Profile);