max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
1,443
<reponame>cssence/mit-license { "copyright": "<NAME>", "url": "http://endel.me", "email": "<EMAIL>", "theme": "flesch", "gravatar": true }
67
480
// Copyright 2019 Espressif Systems (Shanghai) PTE LTD // // 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. #include <string.h> #include <stdlib.h> #include <sys/cdefs.h> #include "esp_log.h" #include "esp_eth.h" #include "eth_phy_regs_struct.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" static const char *TAG = "enc28j60"; #define PHY_CHECK(a, str, goto_tag, ...) \ do \ { \ if (!(a)) \ { \ ESP_LOGE(TAG, "%s(%d): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ goto goto_tag; \ } \ } while (0) /***************Vendor Specific Register***************/ /** * @brief PHCON2(PHY Control Register 2) * */ typedef union { struct { uint32_t reserved_7_0 : 8; // Reserved uint32_t hdldis : 1; // Half-Duplex Loopback Disable uint32_t reserved_9: 1; // Reserved uint32_t jabber: 1; // Disable Jabber Correction uint32_t reserved_12_11: 2; // Reserved uint32_t txdis: 1; // Disable Twist-Pair Transmitter uint32_t frclnk: 1; // Force Linkup uint32_t reserved_15: 1; //Reserved }; uint32_t val; } phcon2_reg_t; #define ETH_PHY_PHCON2_REG_ADDR (0x10) /** * @brief PHSTAT2(PHY Status Register 2) * */ typedef union { struct { uint32_t reserved_4_0 : 5; // Reserved uint32_t plrity : 1; // Polarity Status uint32_t reserved_8_6 : 3; // Reserved uint32_t dpxstat : 1; // PHY Duplex Status uint32_t lstat : 1; // PHY Link Status (non-latching) uint32_t colstat : 1; // PHY Collision Status uint32_t rxstat : 1; // PHY Receive Status uint32_t txstat : 1; // PHY Transmit Status uint32_t reserved_15_14 : 2; // Reserved }; uint32_t val; } phstat2_reg_t; #define ETH_PHY_PHSTAT2_REG_ADDR (0x11) typedef struct { esp_eth_phy_t parent; esp_eth_mediator_t *eth; uint32_t addr; uint32_t reset_timeout_ms; eth_link_t link_status; int reset_gpio_num; } phy_enc28j60_t; static esp_err_t enc28j60_update_link_duplex_speed(phy_enc28j60_t *enc28j60) { esp_eth_mediator_t *eth = enc28j60->eth; eth_speed_t speed = ETH_SPEED_10M; // enc28j60 speed is fixed to 10Mbps eth_duplex_t duplex = ETH_DUPLEX_HALF; phstat2_reg_t phstat; PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_PHSTAT2_REG_ADDR, &(phstat.val)) == ESP_OK, "read PHSTAT2 failed", err); eth_link_t link = phstat.lstat ? ETH_LINK_UP : ETH_LINK_DOWN; /* check if link status changed */ if (enc28j60->link_status != link) { /* when link up, read result */ if (link == ETH_LINK_UP) { if (phstat.dpxstat) { duplex = ETH_DUPLEX_FULL; } else { duplex = ETH_DUPLEX_HALF; } PHY_CHECK(eth->on_state_changed(eth, ETH_STATE_SPEED, (void *)speed) == ESP_OK, "change speed failed", err); PHY_CHECK(eth->on_state_changed(eth, ETH_STATE_DUPLEX, (void *)duplex) == ESP_OK, "change duplex failed", err); } PHY_CHECK(eth->on_state_changed(eth, ETH_STATE_LINK, (void *)link) == ESP_OK, "change link failed", err); enc28j60->link_status = link; } return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_set_mediator(esp_eth_phy_t *phy, esp_eth_mediator_t *eth) { PHY_CHECK(eth, "can't set mediator for enc28j60 to null", err); phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); enc28j60->eth = eth; return ESP_OK; err: return ESP_ERR_INVALID_ARG; } static esp_err_t enc28j60_get_link(esp_eth_phy_t *phy) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); /* Updata information about link, speed, duplex */ PHY_CHECK(enc28j60_update_link_duplex_speed(enc28j60) == ESP_OK, "update link duplex speed failed", err); return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_reset(esp_eth_phy_t *phy) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); enc28j60->link_status = ETH_LINK_DOWN; esp_eth_mediator_t *eth = enc28j60->eth; bmcr_reg_t bmcr = {.reset = 1}; PHY_CHECK(eth->phy_reg_write(eth, enc28j60->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val) == ESP_OK, "write BMCR failed", err); /* Wait for reset complete */ uint32_t to = 0; for (to = 0; to < enc28j60->reset_timeout_ms / 10; to++) { vTaskDelay(pdMS_TO_TICKS(10)); PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)) == ESP_OK, "read BMCR failed", err); if (!bmcr.reset) { break; } } PHY_CHECK(to < enc28j60->reset_timeout_ms / 10, "PHY reset timeout", err); return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_reset_hw(esp_eth_phy_t *phy) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); // set reset_gpio_num minus zero can skip hardware reset phy chip if (enc28j60->reset_gpio_num >= 0) { gpio_pad_select_gpio(enc28j60->reset_gpio_num); gpio_set_direction(enc28j60->reset_gpio_num, GPIO_MODE_OUTPUT); gpio_set_level(enc28j60->reset_gpio_num, 0); gpio_set_level(enc28j60->reset_gpio_num, 1); } return ESP_OK; } static esp_err_t enc28j60_negotiate(esp_eth_phy_t *phy) { /** * ENC28J60 does not support automatic duplex negotiation. * If it is connected to an automatic duplex negotiation enabled network switch, * ENC28J60 will be detected as a half-duplex device. * To communicate in Full-Duplex mode, ENC28J60 and the remote node * must be manually configured for full-duplex operation. */ phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); /* Updata information about link, speed, duplex */ PHY_CHECK(enc28j60_update_link_duplex_speed(enc28j60) == ESP_OK, "update link duplex speed failed", err); return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_pwrctl(esp_eth_phy_t *phy, bool enable) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); esp_eth_mediator_t *eth = enc28j60->eth; bmcr_reg_t bmcr; PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)) == ESP_OK, "read BMCR failed", err); if (!enable) { /* Enable IEEE Power Down Mode */ bmcr.power_down = 1; } else { /* Disable IEEE Power Down Mode */ bmcr.power_down = 0; } PHY_CHECK(eth->phy_reg_write(eth, enc28j60->addr, ETH_PHY_BMCR_REG_ADDR, bmcr.val) == ESP_OK, "write BMCR failed", err); PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_BMCR_REG_ADDR, &(bmcr.val)) == ESP_OK, "read BMCR failed", err); if (!enable) { PHY_CHECK(bmcr.power_down == 1, "power down failed", err); } else { PHY_CHECK(bmcr.power_down == 0, "power up failed", err); } return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_set_addr(esp_eth_phy_t *phy, uint32_t addr) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); enc28j60->addr = addr; return ESP_OK; } static esp_err_t enc28j60_get_addr(esp_eth_phy_t *phy, uint32_t *addr) { PHY_CHECK(addr, "addr can't be null", err); phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); *addr = enc28j60->addr; return ESP_OK; err: return ESP_ERR_INVALID_ARG; } static esp_err_t enc28j60_del(esp_eth_phy_t *phy) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); free(enc28j60); return ESP_OK; } static esp_err_t enc28j60_init(esp_eth_phy_t *phy) { phy_enc28j60_t *enc28j60 = __containerof(phy, phy_enc28j60_t, parent); esp_eth_mediator_t *eth = enc28j60->eth; /* Power on Ethernet PHY */ PHY_CHECK(enc28j60_pwrctl(phy, true) == ESP_OK, "power control failed", err); /* Reset Ethernet PHY */ PHY_CHECK(enc28j60_reset(phy) == ESP_OK, "reset failed", err); /* Check PHY ID */ phyidr1_reg_t id1; phyidr2_reg_t id2; PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_IDR1_REG_ADDR, &(id1.val)) == ESP_OK, "read ID1 failed", err); PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_IDR2_REG_ADDR, &(id2.val)) == ESP_OK, "read ID2 failed", err); PHY_CHECK(id1.oui_msb == 0x0083 && id2.oui_lsb == 0x05 && id2.vendor_model == 0x00, "wrong chip ID", err); /* Disable half duplex loopback */ phcon2_reg_t phcon2; PHY_CHECK(eth->phy_reg_read(eth, enc28j60->addr, ETH_PHY_PHCON2_REG_ADDR, &(phcon2.val)) == ESP_OK, "read PHCON2 failed", err); phcon2.hdldis = 1; PHY_CHECK(eth->phy_reg_write(eth, enc28j60->addr, ETH_PHY_PHCON2_REG_ADDR, phcon2.val) == ESP_OK, "write PHCON2 failed", err); return ESP_OK; err: return ESP_FAIL; } static esp_err_t enc28j60_deinit(esp_eth_phy_t *phy) { /* Power off Ethernet PHY */ PHY_CHECK(enc28j60_pwrctl(phy, false) == ESP_OK, "power off Ethernet PHY failed", err); return ESP_OK; err: return ESP_FAIL; } esp_eth_phy_t *esp_eth_phy_new_enc28j60(const eth_phy_config_t *config) { PHY_CHECK(config, "can't set phy config to null", err); phy_enc28j60_t *enc28j60 = calloc(1, sizeof(phy_enc28j60_t)); PHY_CHECK(enc28j60, "calloc enc28j60 failed", err); enc28j60->addr = config->phy_addr; // although PHY addr is meaningless to ENC28J60 enc28j60->reset_timeout_ms = config->reset_timeout_ms; enc28j60->reset_gpio_num = config->reset_gpio_num; enc28j60->link_status = ETH_LINK_DOWN; enc28j60->parent.reset = enc28j60_reset; enc28j60->parent.reset_hw = enc28j60_reset_hw; enc28j60->parent.init = enc28j60_init; enc28j60->parent.deinit = enc28j60_deinit; enc28j60->parent.set_mediator = enc28j60_set_mediator; enc28j60->parent.negotiate = enc28j60_negotiate; enc28j60->parent.get_link = enc28j60_get_link; enc28j60->parent.pwrctl = enc28j60_pwrctl; enc28j60->parent.get_addr = enc28j60_get_addr; enc28j60->parent.set_addr = enc28j60_set_addr; enc28j60->parent.del = enc28j60_del; return &(enc28j60->parent); err: return NULL; }
5,633
830
<reponame>LaudateCorpus1/deepmath<filename>deepmath/zz/CodeBreeder/HeapSynth.cc /* Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include ZZ_Prelude_hh #include "HeapSynth.hh" namespace ZZ { using namespace std; //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm HeapSynth::HeapSynth(Expr const& prog, Params_HeapSynth const& P) : P(P), Q(cost), reportC(P.report_freq) { try{ rt.run(prog, P.P_rt); }catch (Excp_ParseError err){ wrLn("PARSE ERROR! %_", err.msg); exit(1); } } void HeapSynth::enqueue(State const& S, Pool p, uind from) { state_id id = state.size(); state.push(S); #if 1 cost.push(S.cost()); #else // randomize a little /**/static uint64 seed = 42; double prio0 = (from == NO_PARENT) ? 0 : cost[from]; double cost0 = (from == NO_PARENT) ? 0 : state[from].cost(); double delta = S.cost() - cost0; cost.push(prio0 + delta * drand(seed)); #endif pool.push(p); parent.push(from); Q.add(id); } void HeapSynth::getParents(state_id s, Vec<state_id>& out_parents) { out_parents.clear(); while (s != NO_PARENT){ out_parents.push(s); s = parent[s]; } reverse(out_parents); } void HeapSynth::run() { start(); for(;;){ if (Q.size() == 0) flush(); if (Q.size() == 0) break; if (reportC != 0){ reportC--; if (reportC == 0){ reportProgress(false); reportC = P.report_freq; } } state_id s = Q.pop(); uint dummy; if (state[s].getLast(ENUM::g_Obl, dummy)) expand(s); else eval(s); } if (reportC != 0) reportProgress(true); } //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm // Default implementation: // Returns 0 if successful, 1 on Evo runtime error, 2 on Evo compile time error. static uint evalExpr(Expr const& expr, RunTime& rt, Spec const& spec, ResLims const& rlim, /*outputs:*/Vec<uint>& run_results, double& eval_time) { // Type: fun run_all_<IN,OUT>(io_pairs :[(IN, OUT)], f_ :IN->OUT, rlim :RLim, checker_ :(IN, OUT, OUT)->Bool) -> [Int] Expr e_rlim = mxTuple({mxLit_Int(rlim.cpu), mxLit_Int(rlim.mem), mxLit_Int(rlim.rec)}); Expr e_fun = mxAppl(spec.wrapper[0], expr); Expr e_arg = mxTuple({spec.io_pairs[0], e_fun, e_rlim, spec.checker[0]}); Expr e_run = mxAppl(spec.runner[0], e_arg); run_results.reset(res_SIZE+1, 0); uint ret_code = 0; rt.push(); double T0_eval = cpuTime(); try{ Params_RunTime P_rt; P_rt.verbose = false; addr_t ret = rt.run(e_run, P_rt); if (ret == 0){ ret_code = 1; //**/wrLn("RUNTIME ERROR:\n%_", ppFmt(expr)); /**/wrLn("RUNTIME ERROR:\n%_", ppFmt(e_run)); }else{ // Extract result vector and summarize it: addr_t vec_head = rt.data(ret).val; addr_t vec_data = rt.data(vec_head).val; addr_t vec_size = rt.data(vec_head+1).val; Array<VM::Word const> results = slice(rt.data(vec_data), rt.data(vec_data + vec_size)); for (VM::Word w : results){ assert((uint64)w.val < res_SIZE); run_results[w.val]++; run_results[LAST]++; } } }catch (Excp_ParseError err){ /**/wrLn("COMPILE ERROR:\n%_", ppFmt(expr)); /**/wrLn(" - %_", err.msg); ret_code = 2; } double T1 = cpuTime(); eval_time += T1 - T0_eval; rt.pop(); return ret_code; } void SimpleSynth::expand(state_id s) { /**/wrLn("expand %_ %_", s, state[s].expr(spec.pool)); uint tgt_i; bool ok = state[s].getLast(ENUM::g_Obl, tgt_i); assert(ok); expandOne(spec.pool, state[s], tgt_i, [&](State S){ enqueue(S, s); }, P.P_enum, nullptr); } void SimpleSynth::eval(state_id s) { Expr expr = state[s].expr(spec.pool); Vec<uint> result_counts; double cpu_time = 0; uint ret ___unused = evalExpr(expr, rt, spec, P.rlim, result_counts, cpu_time); /**/wrLn("eval %_: %_ %_", s, result_counts[res_RIGHT], expr); if (result_counts[res_RIGHT] == spec.n_io_pairs){ wrLn("Found solution!"); wrLn("PRETTY-PRINTED: [%_]\t+\t+\n%_\t-\t-\n", spec.name, ppFmt(expr)); Q.clear(); // -- aborts search } } //mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm }
2,377
648
<reponame>swrobel/fhir {"resourceType":"DataElement","id":"QuestionnaireResponse.status","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00"},"url":"http://hl7.org/fhir/DataElement/QuestionnaireResponse.status","status":"draft","experimental":true,"stringency":"fully-specified","element":[{"path":"QuestionnaireResponse.status","short":"in-progress | completed | amended","definition":"The lifecycle status of the questionnaire response as a whole.","requirements":"The information on Questionnaire resources may possibly be gathered during multiple sessions and altered after considered being finished. Questionnaire resources with just questions may serve as template forms, with the applicable publication statuses.","min":1,"max":"1","type":[{"code":"code"}],"isModifier":true,"isSummary":true,"binding":{"strength":"required","description":"Lifecycle status of the questionnaire response.","valueSetReference":{"reference":"http://hl7.org/fhir/ValueSet/questionnaire-answers-status"}},"mapping":[{"identity":"rim","map":".statusCode (also whether there's a revisionControlAct - and possibly mood to distinguish \"in-progress\" from \"published)"},{"identity":"w5","map":"status"}]}]}
288
862
<filename>atlasdb-ete-tests/src/main/java/com/palantir/atlasdb/coordination/CoordinationResource.java /* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.coordination; import com.palantir.atlasdb.internalschema.InternalSchemaMetadata; import com.palantir.processors.AutoDelegate; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @AutoDelegate @Path("/coordination") public interface CoordinationResource { @POST @Path("/get-transactions-schema-version") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) int getTransactionsSchemaVersion(long timestamp); @POST @Path("/try-install-transactions-schema-version") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) boolean tryInstallNewTransactionsSchemaVersion(int newVersion); /** * Force install a new version of the transactions schema. After this method returns, the provided * transactions schema version should be installed, and timestamps brought forward to the point where the * provided version will actively be used in transactions. * * @param newVersion new schema verison to install */ @POST @Path("/force-install-transactions-schema-version") @Consumes(MediaType.APPLICATION_JSON) void forceInstallNewTransactionsSchemaVersion(int newVersion); @POST @Path("/transaction") @Produces(MediaType.APPLICATION_JSON) boolean doTransactionAndReportOutcome(); /** * After this method returns, the state of the {@link CoordinationService} that is backing this * {@link CoordinationResource} should be reset. The latest value of the * {@link InternalSchemaMetadata#timestampToTransactionsTableSchemaVersion()} should be * {@link com.palantir.atlasdb.transaction.impl.TransactionConstants#TRANSACTIONS_TABLE_SCHEMA_VERSION}, * and that version of the transaction schema should already be in effect, with no pending installs. * * @return a fresh timestamp after the reset has been executed */ @POST @Path("/reset-state") @Produces(MediaType.APPLICATION_JSON) long resetStateAndGetFreshTimestamp(); @Path("/fresh-timestamp") @POST // POST because we can't allow caching @Produces(MediaType.APPLICATION_JSON) long getFreshTimestamp(); }
973
2,177
<reponame>yagosys/AlfredWorkflow.com<filename>Sources/Workflows/Todo/itemview.py # -*- coding: utf-8 -*- from uuid import uuid4 import alfred import parser import itemlist import helpers import config def generate_add_feedbackitem(query, info): q = info['task'] tag = info['tag'] title = "New item '" + ('...' if len(q)==0 else q) + "'" subtitle = "Type something to create a new todo" if tag is None: tag = 'default' if tag != 'default': subtitle = "Item will be tagged #{0}".format(tag) # quick create only works best in default list mode quick_create = False if len(q) > 0 and tag == 'default': config.update_state(command='quick_create', tag='#'+tag, query=query) quick_create = True else: config.update_state(command='', tag='', query='') if quick_create: return alfred.Item( attributes = { 'uid' : uuid4(), 'arg' : '#' + tag + ' ' + q, 'valid' : 'no', 'autocomplete' : '' }, title = title, subtitle = subtitle, icon = "todo_add.png" ) else: return alfred.Item( attributes = { 'uid' : uuid4(), 'arg' : '#' + tag + ' ' + q, 'valid' : 'no' if len(q) == 0 else 'yes', 'autocomplete' : '' if len(q) > 0 else '#' + tag + ' ' }, title = title, subtitle = subtitle, icon = "todo_add.png" ) def generate_todo_feedbackitem(t): return alfred.Item( attributes = { 'uid' : uuid4(), 'arg' : helpers.encode_todo_id(str(t['id'])) }, title = t['title'], subtitle = helpers.create_subtitle(t), icon = helpers.create_icon(t) ) def generate_pinned_feedbackitem(t): return alfred.Item( attributes = { 'uid' : uuid4(), 'arg' : helpers.encode_todo_id(str(t['id'])) }, title = t['title'], subtitle = helpers.create_subtitle(t), icon = "todo_pin.png" ) def generate_view(query): if len(query) == 0 and config.get('todo.command.last') == 'quick_create': add_query = config.get('todo.user.query') add_tag = config.get('todo.tag.recent') itemlist.save_todo(add_query,silent=True) config.update_state(command='', query='') info = parser.parse(query) tag = info['tag'] q = info['task'] todos = itemlist.get_todo_list() # view for pinned items # pinned items should have unique uuid and different logo pinned = [t for t in todos if itemlist.feature(t,'pinned') == True] pinned = [t for t in pinned if (tag is None or t['group'] == tag)] pinned = [t for t in pinned if (q is None or t['title'].lower().find(q.lower()) >= 0)] pinned = pinned[::-1] # view for non-pinned items normal = [t for t in todos if itemlist.feature(t,'pinned') == False] normal = [t for t in normal if (tag is None or t['group'] == tag)] normal = [t for t in normal if (q is None or t['title'].lower().find(q.lower()) >= 0)] normal = normal[::-1] feedback_items = [] if len(normal) == 0 and len(pinned) == 0: feedback_items.append( generate_add_feedbackitem(query, info) ) else: pinned = map(lambda x: generate_pinned_feedbackitem(x), pinned) normal = map(lambda x: generate_todo_feedbackitem(x), normal) feedback_items = pinned + normal alfred.write(alfred.xml(feedback_items))
1,258
429
<filename>Boot/Windows/IntFilter.cpp /* Copyright (c) 2008 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #include "Platform.h" #include "BootMemory.h" #include "BootConfig.h" #include "BootConsoleIo.h" #include "BootDebug.h" #include "BootDefs.h" #include "BootDiskIo.h" #include "BootEncryptedIo.h" #include "BootStrings.h" #include "IntFilter.h" static uint32 OriginalInt13Handler; static uint32 OriginalInt15Handler; static Registers IntRegisters; bool Int13Filter () { CheckStack(); Registers regs; memcpy (&regs, &IntRegisters, sizeof (regs)); __asm sti static int ReEntryCount = -1; ++ReEntryCount; byte function = (byte) (regs.AX >> 8); #ifdef TC_TRACE_INT13 DisableScreenOutput(); PrintHex (function); Print (" EN:"); Print (ReEntryCount); Print (" SS:"); PrintHex (regs.SS); uint16 spdbg; __asm mov spdbg, sp PrintChar (' '); PrintHex (spdbg); PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); #endif bool passOriginalRequest = true; switch (function) { case 0x2: // Read sectors case 0x3: // Write sectors { byte drive = (byte) regs.DX; ChsAddress chs; chs.Cylinder = ((regs.CX << 2) & 0x300) | (regs.CX >> 8); chs.Head = regs.DX >> 8; chs.Sector = regs.CX & 0x3f; byte sectorCount = (byte) regs.AX; #ifdef TC_TRACE_INT13 PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); Print (" Chs: "); Print (chs); #endif uint64 sector; if (drive == BootDrive) { if (!BootDriveGeometryValid) TC_THROW_FATAL_EXCEPTION; ChsToLba (BootDriveGeometry, chs, sector); #ifdef TC_TRACE_INT13 PrintVal (" Sec", sector.LowPart, false); #endif } #ifdef TC_TRACE_INT13 PrintVal (" Count", sectorCount, false); Print (" Buf: "); PrintHex (regs.ES); PrintChar (':'); PrintHex (regs.BX); PrintEndl(); #endif if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) { BiosResult result; if (function == 0x3) result = WriteEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); else result = ReadEncryptedSectors (regs.ES, regs.BX, drive, sector, sectorCount); __asm cli memcpy (&IntRegisters, &regs, sizeof (regs)); IntRegisters.AX = (uint16) result << 8; if (result == BiosResultSuccess) { IntRegisters.AX |= sectorCount; IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; } else IntRegisters.Flags |= TC_X86_CARRY_FLAG; passOriginalRequest = false; } } break; case 0x42: // Read sectors LBA case 0x43: // Write sectors LBA { byte drive = (byte) regs.DX; BiosLbaPacket lba; CopyMemory (regs.DS, regs.SI, (byte *) &lba, sizeof (lba)); #ifdef TC_TRACE_INT13 PrintVal (": Drive", drive - TC_FIRST_BIOS_DRIVE, false); PrintVal (" Sec", lba.Sector.LowPart, false); PrintVal (" Count", lba.SectorCount, false); PrintVal (" Buf", lba.Buffer, false, true); PrintEndl(); #endif if (ReEntryCount == 0 && drive == EncryptedVirtualPartition.Drive) { BiosResult result; uint16 segment = (uint16) (lba.Buffer >> 16); uint16 offset = (uint16) lba.Buffer; if (function == 0x43) result = WriteEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); else result = ReadEncryptedSectors (segment, offset, drive, lba.Sector, lba.SectorCount); __asm cli memcpy (&IntRegisters, &regs, sizeof (regs)); IntRegisters.AX = (IntRegisters.AX & 0xff) | ((uint16) result << 8); if (result == BiosResultSuccess) IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; else IntRegisters.Flags |= TC_X86_CARRY_FLAG; passOriginalRequest = false; } } break; default: #ifdef TC_TRACE_INT13 PrintEndl(); #endif break; } #ifdef TC_TRACE_INT13 EnableScreenOutput(); #endif --ReEntryCount; return passOriginalRequest; } #define TC_MAX_MEMORY_MAP_SIZE 80 BiosMemoryMapEntry BiosMemoryMap[TC_MAX_MEMORY_MAP_SIZE]; static size_t BiosMemoryMapSize; static void CreateBootLoaderMemoryMapEntry (BiosMemoryMapEntry *newMapEntry, uint32 bootLoaderStart) { newMapEntry->Type = 0x2; newMapEntry->BaseAddress.HighPart = 0; newMapEntry->BaseAddress.LowPart = bootLoaderStart; newMapEntry->Length.HighPart = 0; newMapEntry->Length.LowPart = TC_BOOT_MEMORY_REQUIRED * 1024UL; } static bool CreateNewBiosMemoryMap () { // Create a new BIOS memory map presenting the memory area of the loader as reserved BiosMemoryMapSize = 0; BiosMemoryMapEntry entry; BiosMemoryMapEntry *newMapEntry = BiosMemoryMap; const BiosMemoryMapEntry *mapEnd = BiosMemoryMap + TC_MAX_MEMORY_MAP_SIZE; uint64 bootLoaderStart; bootLoaderStart.HighPart = 0; uint16 codeSeg; __asm mov codeSeg, cs bootLoaderStart.LowPart = GetLinearAddress (codeSeg, 0); uint64 bootLoaderEnd; bootLoaderEnd.HighPart = 0; bootLoaderEnd.LowPart = bootLoaderStart.LowPart + TC_BOOT_MEMORY_REQUIRED * 1024UL; bool loaderEntryInserted = false; if (GetFirstBiosMemoryMapEntry (entry)) { do { uint64 entryEnd = entry.BaseAddress + entry.Length; if (entry.Type == 0x1 && RegionsIntersect (bootLoaderStart, TC_BOOT_MEMORY_REQUIRED * 1024UL, entry.BaseAddress, entryEnd - 1)) { // Free map entry covers the boot loader area if (entry.BaseAddress < bootLoaderStart) { // Create free entry below the boot loader area if (newMapEntry >= mapEnd) goto mapOverflow; *newMapEntry = entry; newMapEntry->Length = bootLoaderStart - entry.BaseAddress; ++newMapEntry; } if (!loaderEntryInserted) { // Create reserved entry for the boot loader if it has not been done yet if (newMapEntry >= mapEnd) goto mapOverflow; CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); ++newMapEntry; loaderEntryInserted = true; } if (bootLoaderEnd < entryEnd) { // Create free entry above the boot loader area if (newMapEntry >= mapEnd) goto mapOverflow; newMapEntry->Type = 0x1; newMapEntry->BaseAddress = bootLoaderEnd; newMapEntry->Length = entryEnd - bootLoaderEnd; ++newMapEntry; } } else { if (newMapEntry >= mapEnd) goto mapOverflow; if (!loaderEntryInserted && entry.BaseAddress > bootLoaderStart) { // Create reserved entry for the boot loader if it has not been done yet CreateBootLoaderMemoryMapEntry (newMapEntry, bootLoaderStart.LowPart); ++newMapEntry; loaderEntryInserted = true; } // Copy map entry *newMapEntry++ = entry; } } while (GetNextBiosMemoryMapEntry (entry)); } BiosMemoryMapSize = newMapEntry - BiosMemoryMap; return true; mapOverflow: size_t overSize = 0; while (GetNextBiosMemoryMapEntry (entry)) { ++overSize; } PrintErrorNoEndl ("MMP:"); Print (overSize); PrintEndl(); return false; } bool Int15Filter () { CheckStack(); #ifdef TC_TRACE_INT15 DisableScreenOutput(); Print ("15-"); PrintHex (IntRegisters.AX); Print (" SS:"); PrintHex (IntRegisters.SS); uint16 spdbg; __asm mov spdbg, sp PrintChar (' '); PrintHex (spdbg); PrintChar ('<'); PrintHex (TC_BOOT_LOADER_STACK_TOP); Print (" EAX:"); PrintHex (IntRegisters.EAX); Print (" EBX:"); PrintHex (IntRegisters.EBX); Print (" ECX:"); PrintHex (IntRegisters.ECX); Print (" EDX:"); PrintHex (IntRegisters.EDX); Print (" DI:"); PrintHex (IntRegisters.DI); PrintEndl(); #endif if (IntRegisters.EBX >= BiosMemoryMapSize) { IntRegisters.Flags |= TC_X86_CARRY_FLAG; IntRegisters.EBX = 0; IntRegisters.AX = -1; } else { CopyMemory ((byte *) &BiosMemoryMap[IntRegisters.EBX], IntRegisters.ES, IntRegisters.DI, sizeof (BiosMemoryMap[0])); IntRegisters.Flags &= ~TC_X86_CARRY_FLAG; IntRegisters.EAX = 0x534D4150UL; ++IntRegisters.EBX; if (IntRegisters.EBX >= BiosMemoryMapSize) IntRegisters.EBX = 0; IntRegisters.ECX = sizeof (BiosMemoryMap[0]); } if (IntRegisters.EBX == 0 && !(BootSectorFlags & TC_BOOT_CFG_FLAG_WINDOWS_VISTA_OR_LATER)) { // Uninstall filter when the modified map has been issued three times to prevent // problems with hardware drivers on some notebooks running Windows XP. static int CompleteMapIssueCount = 0; if (++CompleteMapIssueCount >= 3) { __asm { cli push es lea si, OriginalInt15Handler xor ax, ax mov es, ax mov di, 0x15 * 4 mov ax, [si] mov es:[di], ax mov ax, [si + 2] mov es:[di + 2], ax pop es sti } } } #ifdef TC_TRACE_INT15 BiosMemoryMapEntry entry; CopyMemory (IntRegisters.ES, IntRegisters.DI, (byte *) &entry, sizeof (entry)); PrintHex (entry.Type); PrintChar (' '); PrintHex (entry.BaseAddress); PrintChar (' '); PrintHex (entry.Length); PrintChar (' '); PrintHex (entry.BaseAddress + entry.Length); PrintEndl(); Print ("EAX:"); PrintHex (IntRegisters.EAX); Print (" EBX:"); PrintHex (IntRegisters.EBX); Print (" ECX:"); PrintHex (IntRegisters.ECX); Print (" EDX:"); PrintHex (IntRegisters.EDX); Print (" DI:"); PrintHex (IntRegisters.DI); Print (" FL:"); PrintHex (IntRegisters.Flags); PrintEndl (2); #endif #ifdef TC_TRACE_INT15 EnableScreenOutput(); #endif return false; } void IntFilterEntry () { // No automatic variables should be used in this scope as SS may change static uint16 OrigStackPointer; static uint16 OrigStackSegment; __asm { pushf pushad cli mov cs:IntRegisters.DI, di lea di, cs:IntRegisters.EAX TC_ASM_EMIT4 (66,2E,89,05) // mov [cs:di], eax lea di, cs:IntRegisters.EBX TC_ASM_EMIT4 (66,2E,89,1D) // mov [cs:di], ebx lea di, cs:IntRegisters.ECX TC_ASM_EMIT4 (66,2E,89,0D) // mov [cs:di], ecx lea di, cs:IntRegisters.EDX TC_ASM_EMIT4 (66,2E,89,15) // mov [cs:di], edx mov ax, [bp + 8] mov cs:IntRegisters.Flags, ax mov cs:IntRegisters.SI, si mov si, [bp + 2] // Int number mov cs:IntRegisters.DS, ds mov cs:IntRegisters.ES, es mov cs:IntRegisters.SS, ss // Compiler assumes SS == DS - use our stack if this condition is not met mov ax, ss mov bx, cs cmp ax, bx jz stack_ok mov cs:OrigStackPointer, sp mov cs:OrigStackSegment, ss mov ax, cs mov ss, ax mov sp, TC_BOOT_LOADER_STACK_TOP stack_ok: // DS = CS push ds push es mov ax, cs mov ds, ax mov es, ax push si // Int number // Filter request cmp si, 0x15 je filter15 cmp si, 0x13 jne $ call Int13Filter jmp s0 filter15: call Int15Filter s0: pop si // Int number pop es pop ds // Restore original SS:SP if our stack is empty cli mov bx, TC_BOOT_LOADER_STACK_TOP cmp bx, sp jnz stack_in_use mov ss, cs:OrigStackSegment mov sp, cs:OrigStackPointer stack_in_use: test ax, ax // passOriginalRequest jnz pass_request // Return results of filtered request popad popf mov ax, cs:IntRegisters.Flags mov [bp + 8], ax leave lea di, cs:IntRegisters.EAX TC_ASM_EMIT4 (66,2E,8B,05) // mov eax, [cs:di] lea di, cs:IntRegisters.EBX TC_ASM_EMIT4 (66,2E,8B,1D) // mov ebx, [cs:di] lea di, cs:IntRegisters.ECX TC_ASM_EMIT4 (66,2E,8B,0D) // mov ecx, [cs:di] lea di, cs:IntRegisters.EDX TC_ASM_EMIT4 (66,2E,8B,15) // mov edx, [cs:di] mov di, cs:IntRegisters.DI mov si, cs:IntRegisters.SI mov es, cs:IntRegisters.ES mov ds, cs:IntRegisters.DS sti add sp, 2 iret // Pass original request pass_request: sti cmp si, 0x15 je pass15 cmp si, 0x13 jne $ popad popf leave add sp, 2 jmp cs:OriginalInt13Handler pass15: popad popf leave add sp, 2 jmp cs:OriginalInt15Handler } } void Int13FilterEntry () { __asm { leave push 0x13 jmp IntFilterEntry } } static void Int15FilterEntry () { __asm { pushf cmp ax, 0xe820 // Get system memory map je filter popf leave jmp cs:OriginalInt15Handler filter: leave push 0x15 jmp IntFilterEntry } } bool InstallInterruptFilters () { #ifndef TC_WINDOWS_BOOT_RESCUE_DISK_MODE // If the filters have already been installed, it usually indicates stack corruption // and a consequent reentry of this routine without a system reset. uint32 currentInt13Handler; CopyMemory (0, 0x13 * 4, &currentInt13Handler, sizeof (currentInt13Handler)); if (currentInt13Handler == (uint32) Int13FilterEntry) { PrintError ("Memory corrupted"); Print (TC_BOOT_STR_UPGRADE_BIOS); GetKeyboardChar(); return true; } #endif if (!CreateNewBiosMemoryMap()) return false; __asm { cli push es // Save original INT 13 handler xor ax, ax mov es, ax mov si, 0x13 * 4 lea di, OriginalInt13Handler mov ax, es:[si] mov [di], ax mov ax, es:[si + 2] mov [di + 2], ax // Install INT 13 filter lea ax, Int13FilterEntry mov es:[si], ax mov es:[si + 2], cs // Save original INT 15 handler mov si, 0x15 * 4 lea di, OriginalInt15Handler mov ax, es:[si] mov [di], ax mov ax, es:[si + 2] mov [di + 2], ax // Install INT 15 filter lea ax, Int15FilterEntry mov es:[si], ax mov es:[si + 2], cs // If the BIOS does not support system memory map (INT15 0xe820), // set amount of available memory to CS:0000 - 0:0000 cmp BiosMemoryMapSize, 1 jg mem_map_ok mov ax, cs shr ax, 10 - 4 // CS * 16 / 1024 mov es:[0x413], ax // = KBytes available mem_map_ok: pop es sti } return true; }
5,665
2,209
from datetime import datetime, timedelta from tabulate import tabulate import click from kungfu.command.journal import journal, pass_ctx_from_parent import kungfu.yijinjing.time as kft import kungfu.yijinjing.journal as kfj SESSION_DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DURATION_FORMAT = '%H:%M:%S.%N' DURATION_TZ_ADJUST = int(timedelta(hours=datetime.fromtimestamp(0).hour).total_seconds() * 1e9) @journal.command() @click.option('-i', '--session_id', type=int, required=True, help='session id') @click.option('-t', '--io_type', type=click.Choice(['all', 'in', 'out']), default='all', help='input or output during this session') @click.option('-f', '--tablefmt', default='simple', type=click.Choice(['plain', 'simple', 'orgtbl', 'grid', 'fancy_grid', 'rst', 'textile']), help='output format') @click.option('-p', '--pager', is_flag=True, help='show in a pager') @click.pass_context def trace(ctx, session_id, io_type, tablefmt, pager): pass_ctx_from_parent(ctx) trace_df = kfj.trace_journal(ctx, session_id, io_type) trace_df['gen_time'] = trace_df['gen_time'].apply(lambda t: kft.strftime(t)) trace_df['trigger_time'] = trace_df['trigger_time'].apply(lambda t: kft.strftime(t)) table = tabulate(trace_df.values, headers=trace_df.columns, tablefmt=tablefmt) if pager: click.echo_via_pager(table) else: click.echo(table)
574
2,504
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "MediaReader.h" using namespace winrt::Windows::ApplicationModel; MediaReader::MediaReader() { ZeroMemory(&m_waveFormat, sizeof(m_waveFormat)); m_installedLocation = Package::Current().InstalledLocation(); m_installedLocationPath = m_installedLocation.Path() + L"\\"; } WAVEFORMATEX* MediaReader::GetOutputWaveFormatEx() { return &m_waveFormat; } std::vector<byte> MediaReader::LoadMedia(_In_ winrt::hstring const& filename) { winrt::check_hresult( MFStartup(MF_VERSION) ); winrt::com_ptr<IMFSourceReader> reader; winrt::check_hresult( MFCreateSourceReaderFromURL( (m_installedLocationPath + filename).c_str(), nullptr, reader.put() ) ); // Set the decoded output format as PCM. // XAudio2 on Windows can process PCM and ADPCM-encoded buffers. // When using MediaFoundation, this sample always decodes into PCM. winrt::com_ptr<IMFMediaType> mediaType; winrt::check_hresult( MFCreateMediaType(mediaType.put()) ); winrt::check_hresult( mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio) ); winrt::check_hresult( mediaType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM) ); winrt::check_hresult( reader->SetCurrentMediaType(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, mediaType.get()) ); // Get the complete WAVEFORMAT from the Media Type. winrt::com_ptr<IMFMediaType> outputMediaType; winrt::check_hresult( reader->GetCurrentMediaType(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), outputMediaType.put()) ); UINT32 size = 0; WAVEFORMATEX* waveFormat; winrt::check_hresult( MFCreateWaveFormatExFromMFMediaType(outputMediaType.get(), &waveFormat, &size) ); CopyMemory(&m_waveFormat, waveFormat, sizeof(m_waveFormat)); CoTaskMemFree(waveFormat); PROPVARIANT propVariant; winrt::check_hresult( reader->GetPresentationAttribute(static_cast<uint32_t>(MF_SOURCE_READER_MEDIASOURCE), MF_PD_DURATION, &propVariant) ); // 'duration' is in 100ns units; convert to seconds, and round up // to the nearest whole byte. LONGLONG duration = propVariant.uhVal.QuadPart; unsigned int maxStreamLengthInBytes = static_cast<unsigned int>( ((duration * static_cast<ULONGLONG>(m_waveFormat.nAvgBytesPerSec)) + 10000000) / 10000000 ); std::vector<byte> fileData(maxStreamLengthInBytes); winrt::com_ptr<IMFSample> sample; winrt::com_ptr<IMFMediaBuffer> mediaBuffer; DWORD flags = 0; int positionInData = 0; bool done = false; while (!done) { sample = nullptr; mediaBuffer = nullptr; winrt::check_hresult( reader->ReadSample(static_cast<uint32_t>(MF_SOURCE_READER_FIRST_AUDIO_STREAM), 0, nullptr, &flags, nullptr, sample.put()) ); if (sample != nullptr) { winrt::check_hresult( sample->ConvertToContiguousBuffer(mediaBuffer.put()) ); BYTE* audioData = nullptr; DWORD sampleBufferLength = 0; winrt::check_hresult( mediaBuffer->Lock(&audioData, nullptr, &sampleBufferLength) ); for (DWORD i = 0; i < sampleBufferLength; i++) { fileData[positionInData++] = audioData[i]; } } if (flags & MF_SOURCE_READERF_ENDOFSTREAM) { done = true; } } return fileData; }
1,896
764
{"symbol": "YFMS","address": "0xfef3bEf71A5EB97E097039038776fD967ae5B106","overview":{"en": "YF Moonshot is a DeFi protocol which allows users to stake their cryptocurrency assets in various different pools (USDT, DAI, TUSD) and earn governance token YFMS as reward."},"email": "","website": "https://www.yfmoonshot.com","state": "NORMAL","links": {"blog": "https://medium.com/@moonshotfinance/yf-moonshot-about-us-2d09d3da3235","twitter": "https://twitter.com/YFMoonshot","telegram": "https://t.me/YFMOONSHOTCHAT","github": "https://github.com/yfmoonshot/YFMOONSHOT"}}
207
692
<reponame>learnforpractice/micropython-cpp print('foo')
20
1,275
<reponame>fredsterorg/incubator-pinot /** * 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.pinot.core.operator.transform.function; import com.google.common.base.Preconditions; import java.util.List; import java.util.Map; import org.apache.pinot.core.operator.blocks.ProjectionBlock; import org.apache.pinot.core.operator.transform.TransformResultMetadata; import org.apache.pinot.core.plan.DocIdSetPlanNode; import org.apache.pinot.segment.spi.datasource.DataSource; /** * A group of commonly used math transformation which has only one single parameter, * including abs, exp, ceil, floor, sqrt. */ public abstract class SingleParamMathTransformFunction extends BaseTransformFunction { private TransformFunction _transformFunction; protected double[] _results; @Override public void init(List<TransformFunction> arguments, Map<String, DataSource> dataSourceMap) { Preconditions .checkArgument(arguments.size() == 1, "Exactly 1 argument is required for transform function: %s", getName()); TransformFunction transformFunction = arguments.get(0); Preconditions.checkArgument(!(transformFunction instanceof LiteralTransformFunction), "Argument cannot be literal for transform function: %s", getName()); Preconditions.checkArgument(transformFunction.getResultMetadata().isSingleValue(), "Argument must be single-valued for transform function: %s", getName()); _transformFunction = transformFunction; } @Override public TransformResultMetadata getResultMetadata() { return DOUBLE_SV_NO_DICTIONARY_METADATA; } @Override public double[] transformToDoubleValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new double[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } double[] values = _transformFunction.transformToDoubleValuesSV(projectionBlock); applyMathOperator(values, projectionBlock.getNumDocs()); return _results; } abstract protected void applyMathOperator(double[] values, int length); public static class AbsTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "abs"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.abs(values[i]); } } } public static class CeilTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "ceil"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.ceil(values[i]); } } } public static class ExpTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "exp"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.exp(values[i]); } } } public static class FloorTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "floor"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.floor(values[i]); } } } public static class LnTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "ln"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.log(values[i]); } } } public static class SqrtTransformFunction extends SingleParamMathTransformFunction { public static final String FUNCTION_NAME = "sqrt"; @Override public String getName() { return FUNCTION_NAME; } @Override protected void applyMathOperator(double[] values, int length) { for (int i = 0; i < length; i++) { _results[i] = Math.sqrt(values[i]); } } } }
1,683
8,027
<filename>test/com/facebook/buck/apple/testdata/swift_header_dep_caching/producer.h static int kFoo = 42;
39
940
/* * spcflags.hpp - CPU special flags * * Kheperix (C) 2003-2005 <NAME> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef SPCFLAGS_H #define SPCFLAGS_H /** * Basic special flags **/ enum { SPCFLAG_CPU_EXEC_RETURN = 1 << 0, // Return from emulation loop SPCFLAG_CPU_TRIGGER_INTERRUPT = 1 << 1, // Trigger user interrupt SPCFLAG_CPU_HANDLE_INTERRUPT = 1 << 2, // Call user interrupt handler SPCFLAG_CPU_ENTER_MON = 1 << 3, // Enter cxmon SPCFLAG_JIT_EXEC_RETURN = 1 << 4, // Return from compiled code }; class basic_spcflags { uint32 mask; spinlock_t lock; public: basic_spcflags() : mask(0), lock(SPIN_LOCK_UNLOCKED) { } bool empty() const { return (mask == 0); } bool test(uint32 v) const { return (mask & v); } void init(uint32 v) { spin_lock(&lock); mask = v; spin_unlock(&lock); } uint32 get() const { return mask; } void set(uint32 v) { spin_lock(&lock); mask |= v; spin_unlock(&lock); } void clear(uint32 v) { spin_lock(&lock); mask &= ~v; spin_unlock(&lock); } }; #endif /* SPCFLAGS_H */
620
3,428
{"id":"00290","group":"easy-ham-1","checksum":{"type":"MD5","value":"98400fc8bb102f11e201c037a613cf85"},"text":"From <EMAIL> Wed Oct 9 10:53:11 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby spamassassin.taint.org (Postfix) with ESMTP id AC66A16F7C\n\tfor <zzzz@localhost>; Wed, 9 Oct 2002 10:52:11 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor zzzz@localhost (single-drop); Wed, 09 Oct 2002 10:52:11 +0100 (IST)\nReceived: from egwn.net (ns2.egwn.net [172.16.31.10]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g998YdK26404 for\n <<EMAIL>>; Wed, 9 Oct 2002 09:34:39 +0100\nReceived: from auth02.nl.egwn.net (localhost [127.0.0.1]) by egwn.net\n (8.11.6/8.11.6/EGWN) with ESMTP id g998V3f31189; Wed, 9 Oct 2002 10:31:03\n +0200\nReceived: from mail.addix.net (kahless.addix.net [195.179.139.19]) by\n egwn.net (8.11.6/8.11.6/EGWN) with ESMTP id g998UHf30709 for\n <<EMAIL>>; Wed, 9 Oct 2002 10:30:17 +0200\nReceived: from wolf359.ision-cic.de (soran.int.addix.net [172.16.31.10]\n (may be forged)) by mail.addix.net (8.9.3/8.9.3) with SMTP id KAA26671 for\n <<EMAIL>>; Wed, 9 Oct 2002 10:29:47 +0200\nFrom: <NAME> <<EMAIL>>\nTo: <EMAIL>\nSubject: Re: Apt repository authentication: it's time\nMessage-Id: <<EMAIL>>\nIn-Reply-To: <<EMAIL>.<EMAIL>>\nReferences: <<EMAIL>08175452.<EMAIL>>\nOrganization: [NDC] ;-)\nX-Mailer: Sylpheed version 0.8.3claws (GTK+ 1.2.10; i386-redhat-linux)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=US-ASCII\nContent-Transfer-Encoding: 7bit\nX-Mailscanner: Found to be clean, Found to be clean\nSender: [email protected]\nErrors-To: [email protected]\nX-Beenthere: [email protected]\nX-Mailman-Version: 2.0.11\nPrecedence: bulk\nReply-To: rpm-zzzlist<EMAIL>rpms.net\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Freshrpms RPM discussion list <rpm-zzzlist.freshrpms.net>\nList-Unsubscribe: <http://lists.freshrpms.net/mailman/listinfo/rpm-zzzlist>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://lists.freshrpms.net/pipermail/rpm-zzzlist/>\nX-Original-Date: Wed, 9 Oct 2002 10:28:23 +0200\nDate: Wed, 9 Oct 2002 10:28:23 +0200\n\nHi.\n\<NAME> <<EMAIL>> wrote:\n\n> What's it take to ensure we're covered against this kind of\n> childish/moronic/Microsoft-era problems?\n\nWell, I am checking the packet signatures while building the apt-tree.\nNot very pretty, not very fast, but it works.\n\nNonetheless:\ndid anyone ever play with this:\nhttp://distro.conectiva.com.br/pipermail/apt-rpm/2002-August/000653.html\n\n-- \nR!\n\n_______________________________________________\nRPM-List mailing list <<EMAIL>>\nhttp://lists.freshrpms.net/mailman/listinfo/rpm-list\n\n\n"}
1,278
1,228
<gh_stars>1000+ package com.fly.blog.client.hystrix; import com.fly.blog.client.UserServiceClient; import com.fly.blog.entity.User; import com.fly.common.dto.RespDTO; import org.springframework.stereotype.Component; /** * Description: <UserServiceHystrix><br> * Author:    mxdl<br> * Date:     2019/2/19<br> * Version:   V1.0.0<br> * Update:     <br> */ @Component public class UserServiceHystrix implements UserServiceClient { @Override public RespDTO<User> getUser(String token, String username) { System.out.println(token); System.out.println(username); return null; } }
238
1,014
<reponame>MobileAir/FinanceDatabase [ "Agricultural Inputs", "Airlines", "Apparel Retail", "Asset Management", "Banks - Diversified", "Banks - Regional", "Beverages - Brewers", "Beverages - Non-Alcoholic", "Beverages - Wineries & Distilleries", "Building Materials", "Capital Markets", "Chemicals", "Confectioners", "Conglomerates", "Consumer Electronics", "Copper", "Department Stores", "Engineering & Construction", "Farm Products", "Financial Conglomerates", "Financial Data & Stock Exchanges", "Furnishings, Fixtures & Appliances", "Gambling", "Information Technology Services", "Insurance - Diversified", "Insurance Brokers", "Integrated Freight & Logistics", "Leisure", "Lumber & Wood Production", "Marine Shipping", "Medical Care Facilities", "Oil & Gas Refining & Marketing", "Other Industrial Metals & Mining", "Packaged Foods", "Packaging & Containers", "Paper & Paper Products", "Real Estate - Development", "Real Estate Services", "Residential Construction", "Resorts & Casinos", "Specialty Chemicals", "Steel", "Telecom Services", "Utilities - Diversified", "Utilities - Independent Power Producers", "Utilities - Regulated Electric", "Utilities - Regulated Gas", "Utilities - Regulated Water", "Utilities - Renewable" ]
572
2,151
<reponame>AOSiP/platform_external_libcxx<gh_stars>1000+ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <assert.h> #include <ext/hash_map> #include <string> int main() { assert(__gnu_cxx::hash<std::string>()(std::string()) == 0); // error }
168
669
<gh_stars>100-1000 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import collections import copy import logging import os import onnx import tvm from tvm import auto_scheduler, autotvm, relay from tvm.contrib import graph_executor from tvm.relay import vm log = logging.getLogger("tvm_ep") ANSOR_TYPE = "Ansor" AUTO_TVM_TYPE = "AutoTVM" @tvm.register_func("tvm_onnx_import_and_compile") def onnx_compile( model_string, model_path, executor, target, target_host, opt_level, opset, freeze_params, input_shapes, nhwc=False, tuning_logfile="", tuning_type=AUTO_TVM_TYPE, ): def get_tvm_executor(irmod, executor, target, params): if executor == "vm": log.info("Build TVM virtual machine") lib = vm.compile( copy.deepcopy(irmod), target, params=params, ) elif executor == "graph": log.info("Build TVM graph executor") lib = relay.build(irmod, target=target, params=params) else: log.error( "Executor type {} is unsupported. ".format(executor) + 'Only "vm" and "graph" types are supported' ) return None return lib model = onnx.load_model_from_string(bytes(model_string)) if model_path: base_dir = os.path.dirname(os.path.abspath(model_path)) onnx.load_external_data_for_model(model, base_dir) # Collect only feed input names from all input names all_input_names = [node.name for node in model.graph.input] all_initializer = [node.name for node in model.graph.initializer] net_feed_input_names = list(set(all_input_names) - set(all_initializer)) # Match names and input shapes all_input_mapping = [(name, shape) for (name, shape) in zip(all_input_names, input_shapes)] # Using an ordereddict maintains input ordering. shape_dict = collections.OrderedDict(all_input_mapping) # Get only feed input pairs feed_shape_dict = {} for name in net_feed_input_names: feed_shape_dict[name] = shape_dict[name] irmod, params = relay.frontend.from_onnx(model, feed_shape_dict, opset=opset, freeze_params=freeze_params) irmod = relay.transform.DynamicToStatic()(irmod) # Tuning file can be set by client through ep options if tuning_logfile == "": tuning_logfile = os.getenv("AUTOTVM_TUNING_LOG") lib = None tvm_target = tvm.target.Target(target, host=target_host) if tuning_logfile: if tuning_type == ANSOR_TYPE: desired_layouts = { "nn.conv2d": ["NHWC", "default"], "nn.conv2d_transpose": ["NHWC", "default"], "nn.upsampling": ["NHWC", "default"], "vision.roi_align": ["NHWC", "default"], } log.info("Use tuning file from ", ANSOR_TYPE, ": ", tuning_logfile) with auto_scheduler.ApplyHistoryBest(tuning_logfile): with tvm.transform.PassContext( opt_level=opt_level, config={ "relay.backend.use_auto_scheduler": True, "relay.FuseOps.max_depth": 30, }, ): if nhwc: seq = tvm.transform.Sequential( [ relay.transform.InferType(), relay.transform.ConvertLayout(desired_layouts), relay.transform.EliminateCommonSubexpr(), relay.transform.FoldConstant(), ] ) irmod = seq(irmod) lib = get_tvm_executor(irmod, executor, tvm_target, params) elif tuning_type == AUTO_TVM_TYPE: with relay.build_config(opt_level=opt_level): log.info("Use tuning file from ", AUTO_TVM_TYPE, ": ", tuning_logfile) with autotvm.apply_history_best(tuning_logfile): lib = get_tvm_executor(irmod, executor, tvm_target, params) else: log.error( "Tuning log type {} is unsupported. ".format(tuning_type) + "Only {} and {} types are supported".format(ANSOR_TYPE, AUTO_TVM_TYPE) ) return None else: with tvm.transform.PassContext(opt_level=opt_level): lib = get_tvm_executor(irmod, executor, tvm_target, params) if lib is None: return None ctx = tvm.device(target, 0) if executor == "vm": m = tvm.runtime.vm.VirtualMachine(lib, ctx) elif executor == "graph": m = graph_executor.GraphModule(lib["default"](ctx)) else: print( "ERROR: Executor type {} is unsupported. ".format(executor), 'Only "vm" and "graph" types are supported', ) return None return m.module
2,488
1,738
<reponame>jeikabu/lumberyard /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "stdafx.h" #include "EditorCommon.h" #include "PropertyHandlerEntityIdComboBox.h" #include <AzToolsFramework/UI/PropertyEditor/PropertyQTConstants.h> #include <AzToolsFramework/UI/PropertyEditor/DHQComboBox.hxx> void PropertyHandlerEntityIdComboBox::WriteGUIValuesIntoProperty(size_t index, PropertyEntityIdComboBoxCtrl* GUI, property_t& instance, AzToolsFramework::InstanceDataNode* node) { Q_UNUSED(index); Q_UNUSED(node); instance = GUI->value(); } bool PropertyHandlerEntityIdComboBox::ReadValuesIntoGUI(size_t index, PropertyEntityIdComboBoxCtrl* GUI, const property_t& instance, AzToolsFramework::InstanceDataNode* node) { Q_UNUSED(index); Q_UNUSED(node); GUI->setValue(instance); return false; } QWidget* PropertyHandlerEntityIdComboBox::CreateGUI(QWidget* pParent) { PropertyEntityIdComboBoxCtrl* newCtrl = aznew PropertyEntityIdComboBoxCtrl(pParent); QObject::connect(newCtrl, &PropertyEntityIdComboBoxCtrl::valueChanged, this, [newCtrl]() { EBUS_EVENT(AzToolsFramework::PropertyEditorGUIMessages::Bus, RequestWrite, newCtrl); }); return newCtrl; } void PropertyHandlerEntityIdComboBox::ConsumeAttribute(PropertyEntityIdComboBoxCtrl* GUI, AZ::u32 attrib, AzToolsFramework::PropertyAttributeReader* attrValue, const char* debugName) { (void)debugName; if (attrib == AZ_CRC("EnumValue", 0xe4f32eed)) { AZStd::pair<AZ::EntityId, AZStd::string> guiEnumValue; AZStd::pair<AZ::EntityId, AZStd::string> enumValue; AZ::Edit::EnumConstant<AZ::EntityId> enumConstant; if (attrValue->Read<AZ::Edit::EnumConstant<AZ::EntityId>>(enumConstant)) { guiEnumValue.first = enumConstant.m_value; guiEnumValue.second = enumConstant.m_description; GUI->addEnumValue(guiEnumValue); } else { // Legacy path. Support temporarily for compatibility. if (attrValue->Read< AZStd::pair<AZ::EntityId, AZStd::string> >(enumValue)) { guiEnumValue = static_cast<AZStd::pair<AZ::EntityId, AZStd::string>>(enumValue); GUI->addEnumValue(guiEnumValue); } else { AZStd::pair<AZ::EntityId, const char*> enumValueConst; if (attrValue->Read< AZStd::pair<AZ::EntityId, const char*> >(enumValueConst)) { AZStd::string consted = enumValueConst.second; guiEnumValue = AZStd::make_pair(enumValueConst.first, consted); GUI->addEnumValue(guiEnumValue); } else { AZ_WarningOnce("AzToolsFramework", false, "Failed to read 'EnumValue' attribute from property '%s' into enum combo box. Expected pair<IntegerType, char*> or pair<IntegerType, AZStd::string>, where IntegerType is int or u32 ", debugName); } } } } else if (attrib == AZ::Edit::Attributes::EnumValues) { AZStd::vector<AZStd::pair<AZ::EntityId, AZStd::string>> guiEnumValues; AZStd::vector<AZStd::pair<AZ::EntityId, AZStd::string> > enumValues; AZStd::vector<AZ::Edit::EnumConstant<AZ::EntityId>> enumConstantValues; if (attrValue->Read<AZStd::vector<AZ::Edit::EnumConstant<AZ::EntityId>>>(enumConstantValues)) { for (const AZ::Edit::EnumConstant<AZ::EntityId>& constantValue : enumConstantValues) { guiEnumValues.push_back(); auto& enumValue = guiEnumValues.back(); enumValue.first = constantValue.m_value; enumValue.second = constantValue.m_description; } GUI->addEnumValues(guiEnumValues); } else { // Legacy path. Support temporarily for compatibility. if (attrValue->Read< AZStd::vector<AZStd::pair<AZ::EntityId, AZStd::string> > >(enumValues)) { for (auto it = enumValues.begin(); it != enumValues.end(); ++it) guiEnumValues.push_back(static_cast<AZStd::pair<AZ::EntityId, AZStd::string>>(*it)); GUI->addEnumValues(guiEnumValues); } else { AZStd::vector<AZStd::pair<AZ::EntityId, const char*> > attempt2; if (attrValue->Read<AZStd::vector<AZStd::pair<AZ::EntityId, const char*> > >(attempt2)) { for (auto it = attempt2.begin(); it != attempt2.end(); ++it) guiEnumValues.push_back(AZStd::make_pair<AZ::EntityId, AZStd::string>(it->first, it->second)); GUI->addEnumValues(guiEnumValues); } else { // emit a warning! AZ_WarningOnce("AzToolsFramework", false, "Failed to read 'EnumValue' attribute from property '%s' into enum combo box", debugName); } } } } } void PropertyHandlerEntityIdComboBox::Register() { EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew PropertyHandlerEntityIdComboBox()); } PropertyEntityIdComboBoxCtrl::PropertyEntityIdComboBoxCtrl(QWidget* pParent) : QWidget(pParent) { // create the gui, it consists of a layout, and in that layout, a text field for the value // and then a slider for the value. QHBoxLayout* pLayout = new QHBoxLayout(this); m_pComboBox = aznew AzToolsFramework::DHQComboBox(this); // many UI elements hide 1 pixel of their size in a border area that only shows up when they are selected. // The combo box used in this layout does not do this, so adding 1 to the left and right margins will make // sure that it has the same dimensions as the other UI elements when they are unselected. pLayout->setSpacing(4); pLayout->setContentsMargins(1, 0, 1, 0); pLayout->addWidget(m_pComboBox); m_pComboBox->setMinimumWidth(AzToolsFramework::PropertyQTConstant_MinimumWidth); m_pComboBox->setFixedHeight(AzToolsFramework::PropertyQTConstant_DefaultHeight); m_pComboBox->setFocusPolicy(Qt::StrongFocus); setLayout(pLayout); setFocusProxy(m_pComboBox); setFocusPolicy(m_pComboBox->focusPolicy()); connect(m_pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onChildComboBoxValueChange(int))); }; void PropertyEntityIdComboBoxCtrl::setValue(AZ::EntityId value) { m_pComboBox->blockSignals(true); bool indexWasFound = false; for (size_t enumValIndex = 0; enumValIndex < m_enumValues.size(); enumValIndex++) { if (m_enumValues[enumValIndex].first == value) { m_pComboBox->setCurrentIndex(static_cast<int>(enumValIndex)); indexWasFound = true; break; } } AZ_Warning("AzToolsFramework", indexWasFound == true, "No index in property enum for value %d", value); m_pComboBox->blockSignals(false); } void PropertyEntityIdComboBoxCtrl::addEnumValue(AZStd::pair<AZ::EntityId, AZStd::string>& val) { m_pComboBox->blockSignals(true); m_enumValues.push_back(val); m_pComboBox->addItem(val.second.c_str()); m_pComboBox->blockSignals(false); } void PropertyEntityIdComboBoxCtrl::addEnumValues(AZStd::vector< AZStd::pair<AZ::EntityId, AZStd::string> >& vals) { m_pComboBox->blockSignals(true); for (size_t valIndex = 0; valIndex < vals.size(); valIndex++) { m_enumValues.push_back(vals[valIndex]); m_pComboBox->addItem(vals[valIndex].second.c_str()); } m_pComboBox->blockSignals(false); } AZ::EntityId PropertyEntityIdComboBoxCtrl::value() const { AZ_Assert(m_pComboBox->currentIndex() >= 0 && m_pComboBox->currentIndex() < static_cast<int>(m_enumValues.size()), "Out of range combo box index %d", m_pComboBox->currentIndex()); return m_enumValues[m_pComboBox->currentIndex()].first; } void PropertyEntityIdComboBoxCtrl::onChildComboBoxValueChange(int comboBoxIndex) { AZ_Assert(comboBoxIndex >= 0 && comboBoxIndex < static_cast<int>(m_enumValues.size()), "Out of range combo box index %d", comboBoxIndex); emit valueChanged(m_enumValues[comboBoxIndex].first); } QWidget* PropertyEntityIdComboBoxCtrl::GetFirstInTabOrder() { return m_pComboBox; } QWidget* PropertyEntityIdComboBoxCtrl::GetLastInTabOrder() { return m_pComboBox; } void PropertyEntityIdComboBoxCtrl::UpdateTabOrder() { // There's only one QT widget on this property. } #include <PropertyHandlerEntityIdComboBox.moc>
3,862
348
{"nom":"Chalonnes-sur-Loire","circ":"2ème circonscription","dpt":"Maine-et-Loire","inscrits":4852,"abs":2021,"votants":2831,"blancs":68,"nuls":29,"exp":2734,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":1465},{"nuance":"LR","nom":"<NAME>","voix":378},{"nuance":"FI","nom":"Mme <NAME>","voix":259},{"nuance":"FN","nom":"M. <NAME>","voix":171},{"nuance":"ECO","nom":"M. <NAME>","voix":103},{"nuance":"UDI","nom":"<NAME>","voix":94},{"nuance":"DLF","nom":"<NAME>","voix":61},{"nuance":"DIV","nom":"M. <NAME>","voix":46},{"nuance":"COM","nom":"M. <NAME>","voix":46},{"nuance":"SOC","nom":"Mme <NAME>","voix":35},{"nuance":"DIV","nom":"M. <NAME>","voix":24},{"nuance":"DIV","nom":"M. <NAME>","voix":20},{"nuance":"EXG","nom":"<NAME>","voix":17},{"nuance":"DIV","nom":"Mme <NAME>","voix":15}]}
320
347
#include "AnimGraphNode_MotionField.h" #include "MotionMatchingEditor.h" #define LOCTEXT_NAMESPACE "A3Nodes" UAnimGraphNode_MotionField::UAnimGraphNode_MotionField(const FObjectInitializer& ObjectInitializer) :Super(ObjectInitializer) { } FLinearColor UAnimGraphNode_MotionField::GetNodeTitleColor() const { return FLinearColor::Red; } FText UAnimGraphNode_MotionField::GetTooltipText() const { return LOCTEXT("Generates_A_Pose_By_Matching_Against_The_Motion_Keys_Of_A_Motion_Field", "Generates a pose by Matching against the Motion Keys of a Motion Field"); } FText UAnimGraphNode_MotionField::GetNodeTitle(ENodeTitleType::Type TitleType) const { return LOCTEXT("Motion_Field", "Motion Field"); } FString UAnimGraphNode_MotionField::GetNodeCategory() const { return TEXT("Tools"); } #undef LOCTEXT_NAMESPACE
280
373
<reponame>ADLINK/edk2-platforms /** @file This protocol indicates that the platform SPI interface is ready for use. Copyright (c) 2013-2015 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef _PLATFORM_SPI_READY_H_ #define _PLATFORM_SPI_READY_H_ // {7A5DBC75-5B2B-4e67-BDE1-D48EEE761562} #define EFI_SMM_SPI_READY_PROTOCOL_GUID \ { 0x7a5dbc75, 0x5b2b, 0x4e67, 0xbd, 0xe1, 0xd4, 0x8e, 0xee, 0x76, 0x15, 0x62 } // // Extern the GUID for protocol users. // extern EFI_GUID gEfiSmmSpiReadyProtocolGuid; #endif
303
1,633
from arbitrage import arbitrage arbitrage.main()
15
14,668
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_WIN_CONFLICTS_ENUMERATE_INPUT_METHOD_EDITORS_H_ #define CHROME_BROWSER_WIN_CONFLICTS_ENUMERATE_INPUT_METHOD_EDITORS_H_ #include <stdint.h> #include "base/callback_forward.h" namespace base { class FilePath; } // The path to the registry key where IMEs are registered. extern const wchar_t kImeRegistryKey[]; // Finds third-party IMEs (Input Method Editor) installed on the computer by // enumerating the registry. In addition to the file path, the SizeOfImage and // TimeDateStamp of the module is returned via the |on_ime_enumerated| callback. using OnImeEnumeratedCallback = base::RepeatingCallback<void(const base::FilePath&, uint32_t, uint32_t)>; void EnumerateInputMethodEditors(OnImeEnumeratedCallback on_ime_enumerated, base::OnceClosure on_enumeration_finished); #endif // CHROME_BROWSER_WIN_CONFLICTS_ENUMERATE_INPUT_METHOD_EDITORS_H_
384
3,579
package com.querydsl.spatial.hibernate; import static org.junit.Assert.assertTrue; import java.util.Map; import org.junit.Test; import com.querydsl.core.types.Operator; import com.querydsl.spatial.SpatialOps; public class HibernateSpatialSupportTest { @Test public void allMapped() { Map<Operator, String> mapping = HibernateSpatialSupport.getSpatialOps(); for (Operator operator : SpatialOps.values()) { assertTrue(operator + " missing", mapping.containsKey(operator)); } } }
206
1,570
from tastypie.api import Api my_api = Api()
19
1,205
<reponame>DT021/findatapy __author__ = 'saeedamen' # <NAME> # # Copyright 2016-2021 Cuemacro # # 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. # if __name__ == '__main__': ###### below line CRUCIAL when running Windows, otherwise multiprocessing doesn't work! (not necessary on Linux) from findatapy.util import SwimPool; SwimPool() from findatapy.market import Market, MarketDataRequest, MarketDataGenerator market = Market(market_data_generator=MarketDataGenerator()) # We can grab market data, by using MarketDataRequest objects # However, sometimes we might wish to create more freeform requests # eg. if we have tickers stored in a spreadsheet) # eg. from a single string (either for predefined tickers or any tickers/vendor_tickers combinations we want) # Here, we show how to this, and also how to call tickers which are already predefined in the CSV config files # Now we will try various examples with Bloomberg # only works if you have Bloomberg terminal installed and the Python API! # In this case, we are using the special 'fx' category md_request = MarketDataRequest(start_date='week', category='fx', data_source='bloomberg') # Let's try creating a MarketDataRequest overwrites in the tickers field md_request.freeform_md_request = [{'tickers' : ['AUDJPY']}, {'tickers' : ['AUDJPY', 'AUDUSD']}] md_request_list = market.create_md_request_from_freeform(md_request) print(md_request_list) # Now, we can do the same thing with a more complicated overwrite md_request.freeform_md_request = [{'tickers' : ['AUDJPY'], 'fields' : 'close'}, {'tickers' : ['AUDJPY', 'AUDUSD'], 'fields' : 'close'}] md_request_list = market.create_md_request_from_freeform(md_request) print(md_request_list) # We can also create MarketDataRequest by passing a str that relates to predefined tickers md_request = market.create_md_request_from_str('backtest.fx.bloomberg.daily.NYC.EURUSD.close') print(md_request) # We can do an approximate match for predefined tickers, and findatapy will "guess" the closest match md_request = market.create_md_request_from_str('_.bloomberg.EURUSD.NYC') print(md_request) # We get *all* the predefined tickers which match in any column with quandl and fx, and these be smart grouped # into the smallest number of requests md_request = market.create_md_request_from_str('_.quandl.fx', best_match_only=False, smart_group=True) print(md_request) # We can also create MarketDataRequest by passing a str for an arbitrary Parquet, note, if we have dots in the path # we need to use {} to denote them (we can use either 'raw' to denote this or just 'r') md_request = market.create_md_request_from_str('raw.data_source.{c:\parquet_files\dump.parquet}.tickers.EURUSD') print(md_request) # We can also create a MarketDataRequest using a JSON string (we must be careful to adhere to correct format) # where the keys match those available of a MarketDataRequest md_request = market.create_md_request_from_str('''{"data_source" : "bloomberg", "category" : "fx", "freq" : "daily", "tickers" : ["EURUSD", "GBPUSD"], "cut" : "NYC", "fields" : "close"}''') print(md_request) # Or directly from a dict where the keys match those available of a MarketDataRequest (again we need to be careful # with the keys, so they match those of a MarketDataRequest md_request = market.create_md_request_from_dict({ "data_source" : "bloomberg", "category" : "fx", "freq" : "daily", "tickers" : ["EURUSD", "GBPUSD"], "cut" : "NYC", "fields" : "close"}) print(md_request) # Or we can do a raw request using any properties we want. At a minimum, we need to have the data_source, tickers, # and vendor_tickers field, any ones we don't include, will just be taken from the defaults md_request = market.create_md_request_from_str('raw.data_source.bloomberg.tickers.EURUSD.vendor_tickers.EURUSD Curncy') print(md_request) # Or we can directly call fetch_market with it # Format of the call is environment.category.freq.cut.ticker.field which is for predefined tickers # Note, we can choose to omit the environment if we want and findatapy will choose the default environment # which is backtest (in this case, we have included it) print(market.fetch_market('backtest.fx.bloomberg.daily.NYC.EURUSD.close')) print(market.fetch_market('backtest.fx.quandl.daily.NYC.EURUSD.close')) # We can also pass in a MarketDataRequest which can contain many more parameters, which we can't specify # with a string of the above form. Given we've ignored adding the environment here, findatapy will automatically # add the default environment which is backtest print(market.fetch_market(md_request_str='fx.bloomberg.intraday.NYC.EURUSD', md_request=MarketDataRequest(fields=['open', 'high', 'low', 'close']))) # Let's do that for whole vol surface for EURUSD (note, we have omitted backtest here, which findatapy assumes as default) print(market.fetch_market('fx-implied-vol.bloomberg.daily.BGN.EURUSD.close', start_date='30 Apr 2021', finish_date='30 Apr 2021')) # We can also download any arbitary properties such as tickers/vendor tickers which aren't predefined print(market.fetch_market('raw.data_source.bloomberg.tickers.VIX.vendor_tickers.VIX Index', start_date='01 Apr 2021', finish_date='30 Apr 2021')) # Or let's give it a Python dict like above, which is likely to be easier to structure, when we have many properties print(market.fetch_market({ "start_date" : "01 Apr 2021", "finish_date" : "30 Apr 2021", "category": "fx", "data_source" : "bloomberg", "freq" : "daily", "tickers" : ["EURUSD", "GBPUSD"], "cut" : "NYC", "fields" : "close"}))
2,287
631
<reponame>767248371/octo-rpc /** * Autogenerated by Thrift Compiler (0.8.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #ifndef Echo_H #define Echo_H #include <transport/TBufferTransports.h> #include <tr1/functional> namespace apache { namespace thrift { namespace async { class TAsyncChannel; }}} #include <TProcessor.h> #include <async/TAsyncProcessor.h> #include "echo_types.h" namespace echo { class EchoIf { public: virtual ~EchoIf() {} virtual void echo(std::string& _return, const std::string& arg, const test& arg2) = 0; }; class EchoIfFactory { public: typedef EchoIf Handler; virtual ~EchoIfFactory() {} virtual EchoIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) = 0; virtual void releaseHandler(EchoIf* /* handler */) = 0; }; class EchoIfSingletonFactory : virtual public EchoIfFactory { public: EchoIfSingletonFactory(const boost::shared_ptr<EchoIf>& iface) : iface_(iface) {} virtual ~EchoIfSingletonFactory() {} virtual EchoIf* getHandler(const ::apache::thrift::TConnectionInfo&) { return iface_.get(); } virtual void releaseHandler(EchoIf* /* handler */) {} protected: boost::shared_ptr<EchoIf> iface_; }; class EchoNull : virtual public EchoIf { public: virtual ~EchoNull() {} void echo(std::string& /* _return */, const std::string& /* arg */, const test& /* arg2 */) { return; } }; typedef struct _Echo_echo_args__isset { _Echo_echo_args__isset() : arg(false), arg2(false) {} bool arg; bool arg2; } _Echo_echo_args__isset; class Echo_echo_args { public: Echo_echo_args() : arg("") { } virtual ~Echo_echo_args() throw() {} std::string arg; test arg2; _Echo_echo_args__isset __isset; void __set_arg(const std::string& val) { arg = val; } void __set_arg2(const test& val) { arg2 = val; } bool operator == (const Echo_echo_args & rhs) const { if (!(arg == rhs.arg)) return false; if (!(arg2 == rhs.arg2)) return false; return true; } bool operator != (const Echo_echo_args &rhs) const { return !(*this == rhs); } bool operator < (const Echo_echo_args & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; class Echo_echo_pargs { public: virtual ~Echo_echo_pargs() throw() {} const std::string* arg; const test* arg2; uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; typedef struct _Echo_echo_result__isset { _Echo_echo_result__isset() : success(false) {} bool success; } _Echo_echo_result__isset; class Echo_echo_result { public: Echo_echo_result() : success("") { } virtual ~Echo_echo_result() throw() {} std::string success; _Echo_echo_result__isset __isset; void __set_success(const std::string& val) { success = val; } bool operator == (const Echo_echo_result & rhs) const { if (!(success == rhs.success)) return false; return true; } bool operator != (const Echo_echo_result &rhs) const { return !(*this == rhs); } bool operator < (const Echo_echo_result & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; typedef struct _Echo_echo_presult__isset { _Echo_echo_presult__isset() : success(false) {} bool success; } _Echo_echo_presult__isset; class Echo_echo_presult { public: virtual ~Echo_echo_presult() throw() {} std::string* success; _Echo_echo_presult__isset __isset; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; }; class EchoClient : virtual public EchoIf { public: EchoClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) : piprot_(prot), poprot_(prot) { iprot_ = prot.get(); oprot_ = prot.get(); } EchoClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, boost::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) : piprot_(iprot), poprot_(oprot) { iprot_ = iprot.get(); oprot_ = oprot.get(); } boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() { return piprot_; } boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() { return poprot_; } void echo(std::string& _return, const std::string& arg, const test& arg2); void send_echo(const std::string& arg, const test& arg2); void recv_echo(std::string& _return); protected: boost::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_; boost::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_; ::apache::thrift::protocol::TProtocol* iprot_; ::apache::thrift::protocol::TProtocol* oprot_; }; class EchoProcessor : public ::apache::thrift::TProcessor { protected: boost::shared_ptr<EchoIf> iface_; virtual bool process_fn(apache::thrift::protocol::TProtocol* iprot, apache::thrift::protocol::TProtocol* oprot, std::string& fname, int32_t seqid, void* callContext); private: std::map<std::string, void (EchoProcessor::*)(int32_t, apache::thrift::protocol::TProtocol*, apache::thrift::protocol::TProtocol*, void*)> processMap_; void process_echo(int32_t seqid, apache::thrift::protocol::TProtocol* iprot, apache::thrift::protocol::TProtocol* oprot, void* callContext); public: EchoProcessor(boost::shared_ptr<EchoIf> iface) : iface_(iface) { processMap_["echo"] = &EchoProcessor::process_echo; } virtual bool process(boost::shared_ptr<apache::thrift::protocol::TProtocol> piprot, boost::shared_ptr<apache::thrift::protocol::TProtocol> poprot, void* callContext); virtual ~EchoProcessor() {} }; class EchoProcessorFactory : public ::apache::thrift::TProcessorFactory { public: EchoProcessorFactory(const ::boost::shared_ptr< EchoIfFactory >& handlerFactory) : handlerFactory_(handlerFactory) {} ::boost::shared_ptr< ::apache::thrift::TProcessor > getProcessor(const ::apache::thrift::TConnectionInfo& connInfo); protected: ::boost::shared_ptr< EchoIfFactory > handlerFactory_; }; class EchoMultiface : virtual public EchoIf { public: EchoMultiface(std::vector<boost::shared_ptr<EchoIf> >& ifaces) : ifaces_(ifaces) { } virtual ~EchoMultiface() {} protected: std::vector<boost::shared_ptr<EchoIf> > ifaces_; EchoMultiface() {} void add(boost::shared_ptr<EchoIf> iface) { ifaces_.push_back(iface); } public: void echo(std::string& _return, const std::string& arg, const test& arg2) { size_t sz = ifaces_.size(); for (size_t i = 0; i < sz; ++i) { if (i == sz - 1) { ifaces_[i]->echo(_return, arg, arg2); return; } else { ifaces_[i]->echo(_return, arg, arg2); } } } }; class EchoCobClient; class EchoCobClIf { public: virtual ~EchoCobClIf() {} virtual void echo(std::tr1::function<void(EchoCobClient* client)> cob, const std::string& arg, const test& arg2) = 0; }; class EchoCobSvIf { public: virtual ~EchoCobSvIf() {} virtual void echo(std::tr1::function<void(std::string const& _return)> cob, const std::string& arg, const test& arg2) = 0; }; class EchoCobSvIfFactory { public: typedef EchoCobSvIf Handler; virtual ~EchoCobSvIfFactory() {} virtual EchoCobSvIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) = 0; virtual void releaseHandler(EchoCobSvIf* /* handler */) = 0; }; class EchoCobSvIfSingletonFactory : virtual public EchoCobSvIfFactory { public: EchoCobSvIfSingletonFactory(const boost::shared_ptr<EchoCobSvIf>& iface) : iface_(iface) {} virtual ~EchoCobSvIfSingletonFactory() {} virtual EchoCobSvIf* getHandler(const ::apache::thrift::TConnectionInfo&) { return iface_.get(); } virtual void releaseHandler(EchoCobSvIf* /* handler */) {} protected: boost::shared_ptr<EchoCobSvIf> iface_; }; class EchoCobSvNull : virtual public EchoCobSvIf { public: virtual ~EchoCobSvNull() {} void echo(std::tr1::function<void(std::string const& _return)> cob, const std::string& /* arg */, const test& /* arg2 */) { std::string _return = ""; return cob(_return); } }; class EchoCobClient : virtual public EchoCobClIf { public: EchoCobClient(boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel, ::apache::thrift::protocol::TProtocolFactory* protocolFactory) : channel_(channel), itrans_(new ::apache::thrift::transport::TMemoryBuffer()), otrans_(new ::apache::thrift::transport::TMemoryBuffer()), piprot_(protocolFactory->getProtocol(itrans_)), poprot_(protocolFactory->getProtocol(otrans_)) { iprot_ = piprot_.get(); oprot_ = poprot_.get(); } boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> getChannel() { return channel_; } virtual void completed__(bool /* success */) {} void echo(std::tr1::function<void(EchoCobClient* client)> cob, const std::string& arg, const test& arg2); void send_echo(const std::string& arg, const test& arg2); void recv_echo(std::string& _return); protected: boost::shared_ptr< ::apache::thrift::async::TAsyncChannel> channel_; boost::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> itrans_; boost::shared_ptr< ::apache::thrift::transport::TMemoryBuffer> otrans_; boost::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_; boost::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_; ::apache::thrift::protocol::TProtocol* iprot_; ::apache::thrift::protocol::TProtocol* oprot_; }; class EchoAsyncProcessor : public ::apache::thrift::TAsyncProcessor { protected: boost::shared_ptr<EchoCobSvIf> iface_; virtual void process_fn(std::tr1::function<void(bool ok)> cob, apache::thrift::protocol::TProtocol* iprot, apache::thrift::protocol::TProtocol* oprot, std::string& fname, int32_t seqid); private: std::map<std::string, void (EchoAsyncProcessor::*)(std::tr1::function<void(bool ok)>, int32_t, apache::thrift::protocol::TProtocol*, apache::thrift::protocol::TProtocol*)> processMap_; void process_echo(std::tr1::function<void(bool ok)> cob, int32_t seqid, apache::thrift::protocol::TProtocol* iprot, apache::thrift::protocol::TProtocol* oprot); void return_echo(std::tr1::function<void(bool ok)> cob, int32_t seqid, ::apache::thrift::protocol::TProtocol* oprot, void* ctx, const std::string& _return); void throw_echo(std::tr1::function<void(bool ok)> cob, int32_t seqid, apache::thrift::protocol::TProtocol* oprot, void* ctx, apache::thrift::TDelayedException* _throw); public: EchoAsyncProcessor(boost::shared_ptr<EchoCobSvIf> iface) : iface_(iface) { processMap_["echo"] = &EchoAsyncProcessor::process_echo; } virtual void process(std::tr1::function<void(bool ok)> cob, boost::shared_ptr<apache::thrift::protocol::TProtocol> piprot, boost::shared_ptr<apache::thrift::protocol::TProtocol> poprot); virtual ~EchoAsyncProcessor() {} }; class EchoAsyncProcessorFactory : public ::apache::thrift::async::TAsyncProcessorFactory { public: EchoAsyncProcessorFactory(const ::boost::shared_ptr< EchoCobSvIfFactory >& handlerFactory) : handlerFactory_(handlerFactory) {} ::boost::shared_ptr< ::apache::thrift::async::TAsyncProcessor > getProcessor(const ::apache::thrift::TConnectionInfo& connInfo); protected: ::boost::shared_ptr< EchoCobSvIfFactory > handlerFactory_; }; } // namespace #endif
4,195
1,147
<reponame>akirallL/TurboTransformers # Copyright (C) 2020 THL A29 Limited, a Tencent company. # All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); you may # not use this file except in compliance with the License. You may # obtain a copy of the License at # https://opensource.org/licenses/BSD-3-Clause # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" basis, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. See the License for the specific language governing # permissions and limitations under the License. # See the AUTHORS file for names of contributors. import sys import turbo_transformers import unittest import torch import os from onmt.encoders.transformer import TransformerEncoderLayer sys.path.append(os.path.dirname(__file__)) import test_helper fname = "tt_transformer_encoder_layer.txt" def create_test(batch_size, src_length, T, with_quantize_dynamic=False): class TestEncoder(unittest.TestCase): def init_data(self, use_cuda): self.test_device = torch.device('cuda:0') if use_cuda else \ torch.device('cpu:0') if not use_cuda: torch.set_num_threads(4) turbo_transformers.set_num_threads(4) torch.set_grad_enabled(False) self.model_dim = 1024 self.onmt_encoder = TransformerEncoderLayer(d_model=self.model_dim, heads=8, d_ff=1024, dropout=0., attention_dropout=0.) self.onmt_encoder.eval() if use_cuda: self.onmt_encoder.to(self.test_device) self.turbo_encoder = turbo_transformers.TransformerEncoderLayer.from_onmt( self.onmt_encoder) # https://pytorch.org/docs/stable/quantization.html if with_quantize_dynamic and not use_cuda: self.quantized_onmt_encoder = torch.quantization.quantize_dynamic( self.onmt_encoder) def check_torch_and_turbo(self, use_cuda, num_iter=1): deivce_type = "GPU" if use_cuda else "CPU" info = f"\"({deivce_type}, {batch_size}, {src_length}, {T})\"" self.init_data(use_cuda=use_cuda) self.inputs = torch.rand( batch_size, src_length, self.model_dim, dtype=torch.float32, device=self.test_device) self.mask = torch.randint(-100, 0, (batch_size, 1, src_length), dtype=torch.int64, device=self.test_device) onmt_mask = self.mask > 0 onmt_model = lambda: self.onmt_encoder(self.inputs, onmt_mask) onmt_result, torch_qps, torch_time_consume = \ test_helper.run_model(onmt_model, use_cuda, num_iter) print( f"ONMT Encoder {info} ", f"{deivce_type} QPS, {torch_qps}, time, {torch_time_consume}") if with_quantize_dynamic and not use_cuda: quantized_onmt_model = lambda: self.quantized_onmt_encoder( self.inputs,onmt_mask) quantized_onmt_result, quantized_torch_qps, quantized_torch_time_consume = \ test_helper.run_model(quantized_onmt_model, use_cuda, num_iter) print( f"ONMT Quantized Encoder {info} ", f"{deivce_type} QPS, {quantized_torch_qps}, time, {quantized_torch_time_consume}" ) turbo_model = lambda: self.turbo_encoder(self.inputs, onmt_mask) with turbo_transformers.pref_guard(info) as perf: turbo_result, turbo_qps, turbo_time_consume = \ test_helper.run_model(turbo_model, use_cuda, num_iter) print( f"Turbo Encoder {info} ", f"{deivce_type} QPS, {turbo_qps}, time, {turbo_time_consume}") print(f"diff max {torch.max(torch.abs(onmt_result - turbo_result))}") self.assertTrue( torch.max(torch.abs(onmt_result - turbo_result)) < (1e-3 if use_cuda else 1e-4)) if with_quantize_dynamic and not use_cuda: with open(fname, "a") as fh: fh.write( f"{info} {torch_qps}, {quantized_torch_qps}, {turbo_qps}\n" ) else: with open(fname, "a") as fh: fh.write(f"{info} {torch_qps}, {turbo_qps}\n") def test_encoder(self): self.check_torch_and_turbo(use_cuda=False) if torch.cuda.is_available() and \ turbo_transformers.config.is_compiled_with_cuda(): self.check_torch_and_turbo(use_cuda=True) globals( )[f"TestEncoder{batch_size}_{src_length}_{T}_{with_quantize_dynamic}"] = TestEncoder with open(fname, "w") as fh: fh.write(", torch, *q_torch, turbo_transformers\n") for quantize in [True]: for batch_size in [4]: for src_length in [10, 20, 40, 60, 80, 100]: for T in range(10, src_length, 10): create_test(batch_size, src_length, T, quantize) if __name__ == '__main__': unittest.main()
2,908
7,706
<filename>plugin/src/main/java/com/google/tsunami/plugin/PluginManager.java /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.tsunami.plugin; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.tsunami.common.data.NetworkServiceUtils.isWebService; import com.google.auto.value.AutoValue; import com.google.common.base.Ascii; import com.google.common.collect.ImmutableList; import com.google.common.collect.Streams; import com.google.tsunami.proto.NetworkService; import com.google.tsunami.proto.ReconnaissanceReport; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import javax.inject.Inject; import javax.inject.Provider; /** * Plugin manager manages all the registered plugins and provides map like interfaces for retrieving * plugins from the registry. */ public class PluginManager { private final Map<PluginDefinition, Provider<TsunamiPlugin>> tsunamiPlugins; @Inject PluginManager(Map<PluginDefinition, Provider<TsunamiPlugin>> tsunamiPlugins) { this.tsunamiPlugins = tsunamiPlugins; } /** * Retrieves all {@link PortScanner} plugins. * * @return a list of all the installed {@link PortScanner} plugins. */ public ImmutableList<PluginMatchingResult<PortScanner>> getPortScanners() { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.PORT_SCAN)) .map( entry -> PluginMatchingResult.<PortScanner>builder() .setPluginDefinition(entry.getKey()) .setTsunamiPlugin((PortScanner) entry.getValue().get()) .build()) .collect(toImmutableList()); } /** * Retrieves the first {@link PortScanner} plugin if present. * * @return the first installed {@link PortScanner} plugin. */ public Optional<PluginMatchingResult<PortScanner>> getPortScanner() { ImmutableList<PluginMatchingResult<PortScanner>> allPortScanners = getPortScanners(); return allPortScanners.isEmpty() ? Optional.empty() : Optional.of(allPortScanners.get(0)); } /** * Retrieves a {@link ServiceFingerprinter} plugin for the given {@link NetworkService}. * * @param networkService the target {@link NetworkService} to be fingerprinted. * @return the matched {@link ServiceFingerprinter} plugin for the given network service. */ public Optional<PluginMatchingResult<ServiceFingerprinter>> getServiceFingerprinter( NetworkService networkService) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.SERVICE_FINGERPRINT)) .filter(entry -> hasMatchingServiceName(networkService, entry.getKey())) .map( entry -> PluginMatchingResult.<ServiceFingerprinter>builder() .setPluginDefinition(entry.getKey()) .setTsunamiPlugin((ServiceFingerprinter) entry.getValue().get()) .addMatchedService(networkService) .build()) .findFirst(); } public ImmutableList<PluginMatchingResult<VulnDetector>> getVulnDetectors( ReconnaissanceReport reconnaissanceReport) { return tsunamiPlugins.entrySet().stream() .filter(entry -> entry.getKey().type().equals(PluginType.VULN_DETECTION)) .map(entry -> matchVulnDetectors(entry.getKey(), entry.getValue(), reconnaissanceReport)) .flatMap(Streams::stream) .collect(toImmutableList()); } private static Optional<PluginMatchingResult<VulnDetector>> matchVulnDetectors( PluginDefinition pluginDefinition, Provider<TsunamiPlugin> vulnDetectorProvider, ReconnaissanceReport reconnaissanceReport) { List<NetworkService> matchedNetworkServices; if (!pluginDefinition.targetServiceName().isPresent() && !pluginDefinition.targetSoftware().isPresent() && !pluginDefinition.isForWebService()) { // No filtering annotation applied, just match all network services from reconnaissance. matchedNetworkServices = reconnaissanceReport.getNetworkServicesList(); } else { // At least one filtering annotation applied, check services to see if any one matches. matchedNetworkServices = reconnaissanceReport.getNetworkServicesList().stream() .filter( networkService -> hasMatchingServiceName(networkService, pluginDefinition) || hasMatchingSoftware(networkService, pluginDefinition)) .collect(toImmutableList()); } return matchedNetworkServices.isEmpty() ? Optional.empty() : Optional.of( PluginMatchingResult.<VulnDetector>builder() .setPluginDefinition(pluginDefinition) .setTsunamiPlugin((VulnDetector) vulnDetectorProvider.get()) .addAllMatchedServices(matchedNetworkServices) .build()); } private static boolean hasMatchingServiceName( NetworkService networkService, PluginDefinition pluginDefinition) { String serviceName = networkService.getServiceName(); boolean hasServiceNameMatch = pluginDefinition.targetServiceName().isPresent() && (serviceName.isEmpty() || Arrays.stream(pluginDefinition.targetServiceName().get().value()) .anyMatch( targetServiceName -> Ascii.equalsIgnoreCase(targetServiceName, serviceName))); boolean hasWebServiceMatch = pluginDefinition.isForWebService() && isWebService(networkService); return hasServiceNameMatch || hasWebServiceMatch; } private static boolean hasMatchingSoftware( NetworkService networkService, PluginDefinition pluginDefinition) { String softwareName = networkService.getSoftware().getName(); return pluginDefinition.targetSoftware().isPresent() && (softwareName.isEmpty() || Ascii.equalsIgnoreCase( pluginDefinition.targetSoftware().get().name(), softwareName)); } /** Matched {@link TsunamiPlugin}s based on certain criteria. */ @AutoValue public abstract static class PluginMatchingResult<T extends TsunamiPlugin> { public abstract PluginDefinition pluginDefinition(); public abstract T tsunamiPlugin(); public abstract ImmutableList<NetworkService> matchedServices(); public String pluginId() { return pluginDefinition().id(); } public static <T extends TsunamiPlugin> Builder<T> builder() { return new AutoValue_PluginManager_PluginMatchingResult.Builder<T>(); } /** Builder for {@link PluginMatchingResult}. */ @AutoValue.Builder public abstract static class Builder<T extends TsunamiPlugin> { public abstract Builder<T> setPluginDefinition(PluginDefinition value); public abstract Builder<T> setTsunamiPlugin(T value); abstract ImmutableList.Builder<NetworkService> matchedServicesBuilder(); public Builder<T> addMatchedService(NetworkService networkService) { matchedServicesBuilder().add(networkService); return this; } public Builder<T> addAllMatchedServices(Iterable<NetworkService> networkServices) { matchedServicesBuilder().addAll(networkServices); return this; } public abstract PluginMatchingResult<T> build(); } } }
2,771
1,191
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.android; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollRuntime; import org.appcelerator.kroll.common.Log; import org.appcelerator.kroll.util.KrollAssetHelper; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.proxy.IntentProxy; import org.appcelerator.titanium.proxy.ServiceProxy; import android.app.Service; import android.content.Intent; import android.os.Bundle; @SuppressWarnings("deprecation") public class TiJSIntervalService extends TiJSService { private static final String TAG = "TiJSIntervalService"; private List<IntervalServiceRunner> runners = null; public TiJSIntervalService(String url) { super(url); } @Override protected void executeServiceCode(ServiceProxy proxy) { final String EXTRA_NAME = "interval"; IntentProxy intentProxy = proxy.getIntent(); if (intentProxy == null || !intentProxy.hasExtra(EXTRA_NAME)) { Log.w(TAG, "The intent is missing the extra value '" + EXTRA_NAME + "', therefore the code will be executed only once."); super.executeServiceCode(proxy); return; } Intent intent = intentProxy.getIntent(); Bundle extras = intent.getExtras(); Object intervalObj = extras.get(EXTRA_NAME); long interval = -1; if (intervalObj instanceof Number) { interval = ((Number) intervalObj).longValue(); } if (interval < 0) { Log.w(TAG, "The intent's extra '" + EXTRA_NAME + "' value is negative or non-numeric, therefore the code will be executed only once."); super.executeServiceCode(proxy); return; } if (runners == null) { runners = Collections.synchronizedList(new ArrayList<>()); } String fullUrl = url; if (!fullUrl.contains("://") && !fullUrl.startsWith("/") && proxy.getCreationUrl().baseUrl != null) { fullUrl = proxy.getCreationUrl().baseUrl + fullUrl; } if (fullUrl.startsWith(TiC.URL_APP_PREFIX)) { fullUrl = fullUrl.replaceAll("app:/", "Resources"); } else if (fullUrl.startsWith(TiC.URL_ANDROID_ASSET_RESOURCES)) { fullUrl = fullUrl.replaceAll("file:///android_asset/", ""); } IntervalServiceRunner runner = new IntervalServiceRunner(this, proxy, interval, fullUrl); runners.add(runner); runner.start(); } private IntervalServiceRunner findRunnerOfProxy(ServiceProxy proxy) { if (proxy == null || runners == null) { return null; } synchronized (runners) { for (IntervalServiceRunner runner : runners) { if (proxy.equals(runner.proxy)) { return runner; } } } return null; } private void destroyRunners() { try { if (runners != null) { synchronized (runners) { for (IntervalServiceRunner runner : runners) { runner.stop(); } } runners.clear(); } } catch (Throwable t) { Log.w(TAG, "Thrown while clearing interval service runners: " + t.getMessage(), t); } } @Override public void onDestroy() { Log.d(TAG, "onDestroy", Log.DEBUG_MODE); destroyRunners(); super.onDestroy(); } @Override public void unbindProxy(ServiceProxy proxy) { IntervalServiceRunner runner = findRunnerOfProxy(proxy); if (runner != null) { Log.d(TAG, "Stopping IntervalServiceRunner because of unbind", Log.DEBUG_MODE); runner.stop(); } runners.remove(runner); } private static class IntervalServiceRunner { protected ServiceProxy proxy; private long interval; private Timer timer = null; private TimerTask task = null; private String serviceSimpleName; private String url; private byte[] source; private final AtomicInteger counter = new AtomicInteger(); IntervalServiceRunner(Service service, ServiceProxy proxy, long interval, String url) { this.proxy = proxy; this.interval = interval; this.url = url; this.source = KrollAssetHelper.readAssetBytes(url); this.serviceSimpleName = service.getClass().getSimpleName(); } private void destroyTimer() { try { if (task != null) { Log.d(TAG, "Canceling TimerTask", Log.DEBUG_MODE); task.cancel(); task = null; } if (timer != null) { Log.d(TAG, "Canceling Timer", Log.DEBUG_MODE); timer.cancel(); timer.purge(); timer = null; } } catch (Throwable t) { Log.w(TAG, "Thrown while destroying timer: " + t.getMessage(), t); } } void stop() { Log.d(TAG, "stop runner", Log.DEBUG_MODE); if (proxy != null) { proxy.fireEvent(TiC.EVENT_STOP, new KrollDict()); } destroyTimer(); } void start() { Log.d(TAG, "start runner", Log.DEBUG_MODE); task = new TimerTask() { @Override public void run() { int iteration = counter.incrementAndGet(); try { KrollDict event = new KrollDict(); event.put("iteration", iteration); proxy.fireEvent(TiC.EVENT_RESUME, event); KrollRuntime.getInstance().runModuleBytes(source, url, proxy); proxy.fireEvent(TiC.EVENT_PAUSE, event); } catch (Throwable e) { Log.e(TAG, "Failure evaluating service JS " + url + ": " + e.getMessage(), e); } } }; timer = new Timer(serviceSimpleName + "_Timer_" + proxy.getServiceInstanceId()); timer.schedule(task, 0, interval); } } }
2,107
669
<filename>fbrp/src/fbrp/life_cycle.py import threading from fbrp import util import a0 import dataclasses import enum import json import typing import types _TOPIC = "fbrp/state" _CFG = a0.Cfg(_TOPIC) class Ask(enum.Enum): NONE = "NONE" UP = "UP" DOWN = "DOWN" class State(enum.Enum): UNKNOWN = "UNKNOWN" STARTING = "STARTING" STARTED = "STARTED" STOPPING = "STOPPING" STOPPED = "STOPPED" @dataclasses.dataclass(frozen=True) class ProcInfo: ask: Ask state: State return_code: int launcher_running: bool def asdict(self): return dict( ask=self.ask.value, state=self.state.value, return_code=self.return_code, launcher_running=self.launcher_running, ) @classmethod def fromdict(cls, dict_): return cls( ask=Ask(dict_.get("ask", Ask.NONE)), state=State(dict_.get("state", State.UNKNOWN)), return_code=dict_.get("return_code", 0), launcher_running=dict_.get("launcher_running", False), ) @dataclasses.dataclass class SystemState: procs: typing.Mapping[str, ProcInfo] def asdict(self): return {"procs": {k: v.asdict() for k, v in self.procs.items()}} @classmethod def fromdict(cls, dict_): return SystemState( procs={k: ProcInfo.fromdict(v) for k, v in dict_.get("procs", {}).items()} ) def _ensure_setup() -> None: _CFG.write_if_empty(json.dumps(SystemState(procs={}).asdict())) def system_state() -> SystemState: _ensure_setup() return SystemState.fromdict(json.loads(_CFG.read().payload)) def proc_info(proc_name) -> ProcInfo: return system_state().procs[proc_name] def system_state_watcher(callback) -> a0.CfgWatcher: _ensure_setup() def callback_wrapper(pkt): callback(SystemState.fromdict(json.loads(pkt.payload))) return a0.CfgWatcher(_TOPIC, callback_wrapper) async def aio_system_state_watcher(): _ensure_setup() async for pkt in a0.aio_cfg(_TOPIC): yield SystemState.fromdict(json.loads(pkt.payload)) def proc_info_watcher(proc_name, callback) -> a0.CfgWatcher: ns = types.SimpleNamespace() ns.last_proc_info = None def callback_wrapper(system_state): if ns.last_proc_info != system_state.procs.get(proc_name): ns.last_proc_info = system_state.procs[proc_name] callback(system_state.procs[proc_name]) return system_state_watcher(callback_wrapper) async def aio_proc_info_watcher(proc_name): ns = types.SimpleNamespace() ns.last_proc_info = None async for system_state in aio_system_state_watcher(): if ns.last_proc_info != system_state.procs.get(proc_name): ns.last_proc_info = system_state.procs[proc_name] yield system_state.procs[proc_name] def set_ask(proc_name, ask): _CFG.mergepatch({"procs": {proc_name: {"ask": ask.value}}}) def set_state(proc_name, state, return_code=0): _CFG.mergepatch( {"procs": {proc_name: {"state": state.value, "return_code": return_code}}} ) def set_launcher_running(proc_name, launcher_running): _CFG.mergepatch({"procs": {proc_name: {"launcher_running": launcher_running}}})
1,419
917
/******************************************************************************* * * (C) COPYRIGHT AUTHORS, 2018 - 2021 * * TITLE: VICTIM.H * * VERSION: 1.10 * * DATE: 02 Apr 2021 * * Victim support prototypes and definitions. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF * ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. * *******************************************************************************/ #pragma once BOOL VictimCreate( _In_ HINSTANCE ModuleBase, _In_ LPWSTR Name, //same as device name _In_ ULONG ResourceId, _Out_opt_ PHANDLE VictimHandle); BOOL VictimRelease( _In_ LPWSTR Name);
254
2,268
<reponame>TotallyMehis/source-sdk-2013<filename>sp/src/utils/lzma/C/Common/Alloc.h<gh_stars>1000+ // Common/Alloc.h #ifndef __COMMON_ALLOC_H #define __COMMON_ALLOC_H #include <stddef.h> void *MyAlloc(size_t size) throw(); void MyFree(void *address) throw(); #ifdef _WIN32 bool SetLargePageSize(); void *MidAlloc(size_t size) throw(); void MidFree(void *address) throw(); void *BigAlloc(size_t size) throw(); void BigFree(void *address) throw(); #else #define MidAlloc(size) MyAlloc(size) #define MidFree(address) MyFree(address) #define BigAlloc(size) MyAlloc(size) #define BigFree(address) MyFree(address) #endif #endif
251
848
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ #pragma once #include <vitis/ai/carplaterecog.hpp> namespace vitis { namespace ai { class CarPlateRecogImp : public CarPlateRecog { public: explicit CarPlateRecogImp( const std::string &cardetect_model, const std::string &platedetect_model, const std::string &carplaterecog_model, bool need_preprocess); explicit CarPlateRecogImp( const std::string &cardetect_model, const std::string &platedetect_model, const std::string &carplaterecog_model, xir::Attrs *attrs, bool need_preprocess); virtual ~CarPlateRecogImp(); private: virtual CarPlateRecogResult run(const cv::Mat &image) override; virtual std::vector<CarPlateRecogResult> run(const std::vector<cv::Mat> &image) override; /// Input width(image cols) virtual int getInputWidth() const override; /// Input height(image rows) virtual int getInputHeight() const override; virtual size_t get_input_batch() const override; std::unique_ptr<vitis::ai::SSD> ssd_; std::unique_ptr<vitis::ai::PlateRecog> plate_recog_; }; } // namespace ai } // namespace vitis
727
335
<filename>I/Innocuous_adjective.json { "word": "Innocuous", "definitions": [ "Not harmful or offensive." ], "parts-of-speech": "Adjective" }
76
1,350
<filename>sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/CosmosTriggerTest.java<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.cosmos; import com.azure.cosmos.models.CosmosTriggerResponse; import com.azure.cosmos.models.CosmosTriggerProperties; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.models.SqlQuerySpec; import com.azure.cosmos.models.TriggerOperation; import com.azure.cosmos.models.TriggerType; import com.azure.cosmos.rx.TestSuiteBase; import com.azure.cosmos.util.CosmosPagedIterable; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Factory; import org.testng.annotations.Test; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; public class CosmosTriggerTest extends TestSuiteBase { private CosmosClient client; private CosmosContainer container; @Factory(dataProvider = "clientBuilders") public CosmosTriggerTest(CosmosClientBuilder clientBuilder) { super(clientBuilder); } @BeforeClass(groups = {"simple"}, timeOut = SETUP_TIMEOUT) public void before_CosmosTriggerTest() { assertThat(this.client).isNull(); this.client = getClientBuilder().buildClient(); CosmosAsyncContainer asyncContainer = getSharedMultiPartitionCosmosContainer(this.client.asyncClient()); container = client.getDatabase(asyncContainer.getDatabase().getId()).getContainer(asyncContainer.getId()); } @AfterClass(groups = {"simple"}, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true) public void afterClass() { assertThat(this.client).isNotNull(); this.client.close(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void createTrigger() throws Exception { CosmosTriggerProperties trigger = getCosmosTriggerProperties(); CosmosTriggerResponse triggerResponse = container.getScripts().createTrigger(trigger); validateResponse(trigger, triggerResponse); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readTrigger() throws Exception { CosmosTriggerProperties trigger = getCosmosTriggerProperties(); container.getScripts().createTrigger(trigger); CosmosTriggerResponse readResponse = container.getScripts().getTrigger(trigger.getId()).read(); validateResponse(trigger, readResponse); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void replaceTrigger() throws Exception { CosmosTriggerProperties trigger = getCosmosTriggerProperties(); container.getScripts().createTrigger(trigger); CosmosTriggerProperties readTrigger = container.getScripts().getTrigger(trigger.getId()).read().getProperties(); readTrigger.setBody("function() {var x = 11;}"); CosmosTriggerResponse replace = container.getScripts().getTrigger(trigger.getId()).replace(readTrigger); validateResponse(trigger, replace); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void deleteTrigger() throws Exception { CosmosTriggerProperties trigger = getCosmosTriggerProperties(); container.getScripts().createTrigger(trigger); container.getScripts().getTrigger(trigger.getId()).delete(); } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void readAllTriggers() throws Exception { CosmosTriggerProperties trigger = getCosmosTriggerProperties(); container.getScripts().createTrigger(trigger); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<CosmosTriggerProperties> feedResponseIterator3 = container.getScripts().readAllTriggers(cosmosQueryRequestOptions); assertThat(feedResponseIterator3.iterator().hasNext()).isTrue(); } private CosmosTriggerProperties getCosmosTriggerProperties() { CosmosTriggerProperties trigger = new CosmosTriggerProperties( UUID.randomUUID().toString(), "function() {var x = 10;}" ); trigger.setTriggerOperation(TriggerOperation.CREATE); trigger.setTriggerType(TriggerType.PRE); return trigger; } @Test(groups = {"simple"}, timeOut = TIMEOUT) public void queryTriggers() throws Exception { CosmosTriggerProperties properties = getCosmosTriggerProperties(); container.getScripts().createTrigger(properties); String query = String.format("SELECT * from c where c.id = '%s'", properties.getId()); CosmosQueryRequestOptions cosmosQueryRequestOptions = new CosmosQueryRequestOptions(); CosmosPagedIterable<CosmosTriggerProperties> feedResponseIterator1 = container.getScripts().queryTriggers(query, cosmosQueryRequestOptions); assertThat(feedResponseIterator1.iterator().hasNext()).isTrue(); SqlQuerySpec querySpec = new SqlQuerySpec(query); CosmosPagedIterable<CosmosTriggerProperties> feedResponseIterator2 = container.getScripts().queryTriggers(query, cosmosQueryRequestOptions); assertThat(feedResponseIterator2.iterator().hasNext()).isTrue(); } private void validateResponse(CosmosTriggerProperties properties, CosmosTriggerResponse createResponse) { // Basic validation assertThat(createResponse.getProperties().getId()).isNotNull(); assertThat(createResponse.getProperties().getId()) .as("check Resource Id") .isEqualTo(properties.getId()); } }
1,925
1,093
from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QDialog, QLabel, QGridLayout, QDialogButtonBox, QLineEdit from lanzou.gui.qss import dialog_qss_style from lanzou.gui.models import FileInfos from lanzou.debug import SRC_DIR class SetPwdDialog(QDialog): new_infos = pyqtSignal(object) def __init__(self, parent=None): super(SetPwdDialog, self).__init__(parent) self.infos = [] self.initUI() self.update_text() self.setStyleSheet(dialog_qss_style) def set_values(self, infos): self.infos = infos self.update_text() # 更新界面 def set_tip(self): # 用于提示状态 self.setWindowTitle("请稍等……") def initUI(self): self.setWindowTitle("请稍等……") self.setWindowIcon(QIcon(SRC_DIR + "password.ico")) self.lb_oldpwd = QLabel() self.lb_oldpwd.setText("当前提取码:") self.lb_oldpwd.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_oldpwd = QLineEdit() # 当前提取码 只读 self.tx_oldpwd.setFocusPolicy(Qt.NoFocus) self.tx_oldpwd.setReadOnly(True) self.lb_newpwd = QLabel() self.lb_newpwd.setText("新的提取码:") self.lb_newpwd.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.tx_newpwd = QLineEdit() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.button(QDialogButtonBox.Ok).setText("确定") self.buttonBox.button(QDialogButtonBox.Cancel).setText("取消") self.grid = QGridLayout() self.grid.setSpacing(10) self.grid.addWidget(self.lb_oldpwd, 1, 0) self.grid.addWidget(self.tx_oldpwd, 1, 1) self.grid.addWidget(self.lb_newpwd, 2, 0) self.grid.addWidget(self.tx_newpwd, 2, 1) self.grid.addWidget(self.buttonBox, 3, 0, 1, 2) self.setLayout(self.grid) self.buttonBox.accepted.connect(self.btn_ok) self.buttonBox.accepted.connect(self.accept) self.buttonBox.accepted.connect(self.set_tip) self.buttonBox.rejected.connect(self.reject) self.buttonBox.rejected.connect(self.set_tip) self.setMinimumWidth(280) def update_text(self): num = len(self.infos) if num == 1: self.tx_oldpwd.setVisible(True) self.lb_oldpwd.setVisible(True) infos = self.infos[0] if infos.has_pwd: self.tx_oldpwd.setText(str(infos.pwd)) self.tx_oldpwd.setPlaceholderText("") else: self.tx_oldpwd.setText("") self.tx_oldpwd.setPlaceholderText("无") if isinstance(infos, FileInfos): # 文件 通过size列判断是否为文件 self.setWindowTitle("修改文件提取码") self.tx_newpwd.setPlaceholderText("2-6位字符,关闭请留空") self.tx_newpwd.setMaxLength(6) # 最长6个字符 else: # 文件夹 self.setWindowTitle("修改文件夹名提取码") self.tx_newpwd.setPlaceholderText("2-12位字符,关闭请留空") self.tx_newpwd.setMaxLength(12) # 最长12个字符 elif num > 1: self.tx_oldpwd.setVisible(False) self.lb_oldpwd.setVisible(False) self.setWindowTitle(f"批量修改{num}个文件(夹)的提取码") self.tx_newpwd.setPlaceholderText("2-12位字符,关闭请留空") self.tx_newpwd.setMaxLength(12) # 最长12个字符 self.tx_newpwd.setText('') for infos in self.infos: if isinstance(infos, FileInfos): # 文件 self.tx_newpwd.setPlaceholderText("2-6位字符,文件无法关闭") self.tx_newpwd.setMaxLength(6) # 最长6个字符 break def btn_ok(self): new_pwd = self.tx_newpwd.text() for infos in self.infos: infos.new_pwd = <PASSWORD> self.new_infos.emit(self.infos) # 最后一位用于标示文件还是文件夹
2,337
2,151
<reponame>zipated/src // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/arc/auth/arc_auth_service.h" #include <utility> #include "base/command_line.h" #include "base/memory/singleton.h" #include "base/time/time.h" #include "chrome/browser/chromeos/arc/arc_optin_uma.h" #include "chrome/browser/chromeos/arc/arc_session_manager.h" #include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/arc/auth/arc_background_auth_code_fetcher.h" #include "chrome/browser/chromeos/arc/auth/arc_robot_auth_code_fetcher.h" #include "chrome/browser/chromeos/arc/policy/arc_policy_util.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/profiles/profile.h" #include "chromeos/chromeos_switches.h" #include "components/arc/arc_bridge_service.h" #include "components/arc/arc_browser_context_keyed_service_factory_base.h" #include "components/arc/arc_features.h" #include "components/arc/arc_prefs.h" #include "components/arc/arc_service_manager.h" #include "components/arc/arc_supervision_transition.h" #include "components/arc/arc_util.h" #include "components/prefs/pref_service.h" #include "components/user_manager/user_manager.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace arc { namespace { // Singleton factory for ArcAuthService. class ArcAuthServiceFactory : public internal::ArcBrowserContextKeyedServiceFactoryBase< ArcAuthService, ArcAuthServiceFactory> { public: // Factory name used by ArcBrowserContextKeyedServiceFactoryBase. static constexpr const char* kName = "ArcAuthServiceFactory"; static ArcAuthServiceFactory* GetInstance() { return base::Singleton<ArcAuthServiceFactory>::get(); } private: friend struct base::DefaultSingletonTraits<ArcAuthServiceFactory>; ArcAuthServiceFactory() = default; ~ArcAuthServiceFactory() override = default; }; // Convers mojom::ArcSignInStatus into ProvisiningResult. ProvisioningResult ConvertArcSignInStatusToProvisioningResult( mojom::ArcSignInStatus reason) { using ArcSignInStatus = mojom::ArcSignInStatus; #define MAP_PROVISIONING_RESULT(name) \ case ArcSignInStatus::name: \ return ProvisioningResult::name switch (reason) { MAP_PROVISIONING_RESULT(UNKNOWN_ERROR); MAP_PROVISIONING_RESULT(MOJO_VERSION_MISMATCH); MAP_PROVISIONING_RESULT(MOJO_CALL_TIMEOUT); MAP_PROVISIONING_RESULT(DEVICE_CHECK_IN_FAILED); MAP_PROVISIONING_RESULT(DEVICE_CHECK_IN_TIMEOUT); MAP_PROVISIONING_RESULT(DEVICE_CHECK_IN_INTERNAL_ERROR); MAP_PROVISIONING_RESULT(GMS_NETWORK_ERROR); MAP_PROVISIONING_RESULT(GMS_SERVICE_UNAVAILABLE); MAP_PROVISIONING_RESULT(GMS_BAD_AUTHENTICATION); MAP_PROVISIONING_RESULT(GMS_SIGN_IN_FAILED); MAP_PROVISIONING_RESULT(GMS_SIGN_IN_TIMEOUT); MAP_PROVISIONING_RESULT(GMS_SIGN_IN_INTERNAL_ERROR); MAP_PROVISIONING_RESULT(CLOUD_PROVISION_FLOW_FAILED); MAP_PROVISIONING_RESULT(CLOUD_PROVISION_FLOW_TIMEOUT); MAP_PROVISIONING_RESULT(CLOUD_PROVISION_FLOW_INTERNAL_ERROR); MAP_PROVISIONING_RESULT(NO_NETWORK_CONNECTION); MAP_PROVISIONING_RESULT(CHROME_SERVER_COMMUNICATION_ERROR); MAP_PROVISIONING_RESULT(ARC_DISABLED); MAP_PROVISIONING_RESULT(SUCCESS); MAP_PROVISIONING_RESULT(SUCCESS_ALREADY_PROVISIONED); } #undef MAP_PROVISIONING_RESULT NOTREACHED() << "unknown reason: " << static_cast<int>(reason); return ProvisioningResult::UNKNOWN_ERROR; } mojom::ChromeAccountType GetAccountType(const Profile* profile) { if (profile->IsChild()) return mojom::ChromeAccountType::CHILD_ACCOUNT; return IsRobotAccountMode() ? mojom::ChromeAccountType::ROBOT_ACCOUNT : mojom::ChromeAccountType::USER_ACCOUNT; } mojom::AccountInfoPtr CreateAccountInfo(bool is_enforced, const std::string& auth_info, const std::string& account_name, mojom::ChromeAccountType account_type, bool is_managed) { mojom::AccountInfoPtr account_info = mojom::AccountInfo::New(); account_info->account_name = account_name; if (account_type == mojom::ChromeAccountType::ACTIVE_DIRECTORY_ACCOUNT) { account_info->enrollment_token = auth_info; } else { if (!is_enforced) account_info->auth_code = base::nullopt; else account_info->auth_code = auth_info; } account_info->account_type = account_type; account_info->is_managed = is_managed; return account_info; } } // namespace // static const char ArcAuthService::kArcServiceName[] = "arc::ArcAuthService"; // static ArcAuthService* ArcAuthService::GetForBrowserContext( content::BrowserContext* context) { return ArcAuthServiceFactory::GetForBrowserContext(context); } ArcAuthService::ArcAuthService(content::BrowserContext* browser_context, ArcBridgeService* arc_bridge_service) : profile_(Profile::FromBrowserContext(browser_context)), arc_bridge_service_(arc_bridge_service), url_loader_factory_( content::BrowserContext::GetDefaultStoragePartition(profile_) ->GetURLLoaderFactoryForBrowserProcess()), weak_ptr_factory_(this) { arc_bridge_service_->auth()->SetHost(this); arc_bridge_service_->auth()->AddObserver(this); } ArcAuthService::~ArcAuthService() { arc_bridge_service_->auth()->RemoveObserver(this); arc_bridge_service_->auth()->SetHost(nullptr); } void ArcAuthService::OnConnectionClosed() { fetcher_.reset(); } void ArcAuthService::OnAuthorizationComplete(mojom::ArcSignInStatus status, bool initial_signin) { if (!initial_signin) { // Note, UMA for initial signin is updated from ArcSessionManager. DCHECK_NE(mojom::ArcSignInStatus::SUCCESS_ALREADY_PROVISIONED, status); UpdateReauthorizationResultUMA( ConvertArcSignInStatusToProvisioningResult(status), profile_); return; } ArcSessionManager::Get()->OnProvisioningFinished( ConvertArcSignInStatusToProvisioningResult(status)); } void ArcAuthService::OnSignInCompleteDeprecated() { OnAuthorizationComplete(mojom::ArcSignInStatus::SUCCESS, true /* initial_signin */); } void ArcAuthService::OnSignInFailedDeprecated(mojom::ArcSignInStatus reason) { DCHECK_NE(mojom::ArcSignInStatus::SUCCESS, reason); OnAuthorizationComplete(reason, true /* initial_signin */); } void ArcAuthService::ReportMetrics(mojom::MetricsType metrics_type, int32_t value) { switch (metrics_type) { case mojom::MetricsType::NETWORK_WAITING_TIME_MILLISECONDS: UpdateAuthTiming("ArcAuth.NetworkWaitTime", base::TimeDelta::FromMilliseconds(value)); break; case mojom::MetricsType::CHECKIN_ATTEMPTS: UpdateAuthCheckinAttempts(value); break; case mojom::MetricsType::CHECKIN_TIME_MILLISECONDS: UpdateAuthTiming("ArcAuth.CheckinTime", base::TimeDelta::FromMilliseconds(value)); break; case mojom::MetricsType::SIGNIN_TIME_MILLISECONDS: UpdateAuthTiming("ArcAuth.SignInTime", base::TimeDelta::FromMilliseconds(value)); break; case mojom::MetricsType::ACCOUNT_CHECK_MILLISECONDS: UpdateAuthTiming("ArcAuth.AccountCheckTime", base::TimeDelta::FromMilliseconds(value)); break; } } void ArcAuthService::ReportAccountCheckStatus( mojom::AccountCheckStatus status) { UpdateAuthAccountCheckStatus(status); } void ArcAuthService::ReportSupervisionChangeStatus( mojom::SupervisionChangeStatus status) { switch (status) { case mojom::SupervisionChangeStatus::CLOUD_DPC_DISABLED: case mojom::SupervisionChangeStatus::CLOUD_DPC_ALREADY_DISABLED: case mojom::SupervisionChangeStatus::CLOUD_DPC_ENABLED: case mojom::SupervisionChangeStatus::CLOUD_DPC_ALREADY_ENABLED: profile_->GetPrefs()->SetInteger( prefs::kArcSupervisionTransition, static_cast<int>(ArcSupervisionTransition::NO_TRANSITION)); // TODO(brunokim): notify potential observers. break; case mojom::SupervisionChangeStatus::INVALID_SUPERVISION_STATE: case mojom::SupervisionChangeStatus::CLOUD_DPC_DISABLING_FAILED: case mojom::SupervisionChangeStatus::CLOUD_DPC_ENABLING_FAILED: default: LOG(WARNING) << "Failed to changed supervision: " << status; // TODO(crbug/841939): Block ARC++ in case of Unicorn graduation failure. } } void ArcAuthService::OnAccountInfoReady(mojom::AccountInfoPtr account_info, mojom::ArcSignInStatus status) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* instance = ARC_GET_INSTANCE_FOR_METHOD(arc_bridge_service_->auth(), OnAccountInfoReady); DCHECK(instance); instance->OnAccountInfoReady(std::move(account_info), status); } void ArcAuthService::RequestAccountInfo(bool initial_signin) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // No other auth code-related operation may be in progress. DCHECK(!fetcher_); if (IsArcOptInVerificationDisabled()) { OnAccountInfoReady( CreateAccountInfo( false /* is_enforced */, std::string() /* auth_info */, std::string() /* auth_name */, GetAccountType(profile_), policy_util::IsAccountManaged(profile_)), mojom::ArcSignInStatus::SUCCESS); return; } if (IsActiveDirectoryUserForProfile(profile_)) { // For Active Directory enrolled devices, we get an enrollment token for a // managed Google Play account from DMServer. auto enrollment_token_fetcher = std::make_unique<ArcActiveDirectoryEnrollmentTokenFetcher>( ArcSessionManager::Get()->support_host()); enrollment_token_fetcher->Fetch( base::BindOnce(&ArcAuthService::OnEnrollmentTokenFetched, weak_ptr_factory_.GetWeakPtr())); fetcher_ = std::move(enrollment_token_fetcher); return; } // For non-AD enrolled devices an auth code is fetched. std::unique_ptr<ArcAuthCodeFetcher> auth_code_fetcher; if (IsRobotAccountMode()) { // In Kiosk and public session mode, use Robot auth code fetching. auth_code_fetcher = std::make_unique<ArcRobotAuthCodeFetcher>(); } else { // Optionally retrieve auth code in silent mode. auth_code_fetcher = std::make_unique<ArcBackgroundAuthCodeFetcher>( url_loader_factory_, profile_, ArcSessionManager::Get()->auth_context(), initial_signin); } auth_code_fetcher->Fetch(base::Bind(&ArcAuthService::OnAuthCodeFetched, weak_ptr_factory_.GetWeakPtr())); fetcher_ = std::move(auth_code_fetcher); } void ArcAuthService::OnEnrollmentTokenFetched( ArcActiveDirectoryEnrollmentTokenFetcher::Status status, const std::string& enrollment_token, const std::string& user_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); fetcher_.reset(); switch (status) { case ArcActiveDirectoryEnrollmentTokenFetcher::Status::SUCCESS: { // Save user_id to the user profile. profile_->GetPrefs()->SetString(prefs::kArcActiveDirectoryPlayUserId, user_id); // Send enrollment token to ARC. OnAccountInfoReady( CreateAccountInfo(true /* is_enforced */, enrollment_token, std::string() /* account_name */, mojom::ChromeAccountType::ACTIVE_DIRECTORY_ACCOUNT, true), mojom::ArcSignInStatus::SUCCESS); break; } case ArcActiveDirectoryEnrollmentTokenFetcher::Status::FAILURE: { // Send error to ARC. OnAccountInfoReady( nullptr, mojom::ArcSignInStatus::CHROME_SERVER_COMMUNICATION_ERROR); break; } case ArcActiveDirectoryEnrollmentTokenFetcher::Status::ARC_DISABLED: { // Send error to ARC. OnAccountInfoReady(nullptr, mojom::ArcSignInStatus::ARC_DISABLED); break; } } } void ArcAuthService::OnAuthCodeFetched(bool success, const std::string& auth_code) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); fetcher_.reset(); if (success) { OnAccountInfoReady( CreateAccountInfo( !IsArcOptInVerificationDisabled(), auth_code, ArcSessionManager::Get()->auth_context()->full_account_id(), GetAccountType(profile_), policy_util::IsAccountManaged(profile_)), mojom::ArcSignInStatus::SUCCESS); } else { // Send error to ARC. OnAccountInfoReady( nullptr, mojom::ArcSignInStatus::CHROME_SERVER_COMMUNICATION_ERROR); } } void ArcAuthService::SetURLLoaderFactoryForTesting( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) { url_loader_factory_ = std::move(url_loader_factory); } } // namespace arc
5,330
4,200
/* * Copyright 2018 Rundeck, Inc. (http://rundeck.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtolabs.rundeck.core.properties; import java.util.Properties; /** * CoreConfigurationPropertiesLoader * This interface defines a service that can be used to customize the loading of the rundeck-config.properties file * when Rundeck bootstraps. * Implementing classes can be installed using the facilities provided by the java {@link java.util.ServiceLoader} class. * * @author <NAME> * @version $Revision$ */ public interface CoreConfigurationPropertiesLoader { Properties loadProperties(); }
307
2,164
../../../SDWebImage/SDWebImage/SDWebImageImageIOCoder.h
20
23,901
# coding=utf-8 # Copyright 2021 The Google Research 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. """Various constants needed in the solution.""" import utils class DistributeModeChoices(utils.FlagChoices): mirroredstrategy = "MirroredStrategy" none = "None" onedevicestrategy = "OneDeviceStrategy" split_vertically = "split_vertically" split_and_data_parallel = "split_vertically_data_parallel" tpustrategy = "TPUStrategy" STRATEGIES = frozenset([ DistributeModeChoices.onedevicestrategy, DistributeModeChoices.tpustrategy, DistributeModeChoices.mirroredstrategy ]) DATA_PARALLEL_DMC = frozenset([ DistributeModeChoices.tpustrategy, DistributeModeChoices.mirroredstrategy, DistributeModeChoices.split_and_data_parallel ]) # Pure Data Parallel Strategies means that they don't do Model Parallelism. # This is (was) for when we also used tf.distribute.TPUMPStrategy PURE_DATA_PARALLEL_STRATEGIES = frozenset([ DistributeModeChoices.tpustrategy, DistributeModeChoices.mirroredstrategy, ]) DATA_PARALLEL_STRATEGIES = frozenset([ DistributeModeChoices.tpustrategy, DistributeModeChoices.mirroredstrategy, ]) # Taken from internal documentation COMPUTATION_SHAPE_FROM_NUM_CORES = { 1: [1, 1, 1, 1], 2: [1, 1, 1, 2], 4: [1, 2, 1, 2], 8: [2, 2, 1, 2], 16: [4, 2, 1, 2], } class ApproachTypeChoices(utils.FlagChoices): naked_lm = "naked_lm" lm_and_realm = "lm_and_realm" cached_realm = "cached_realm" cached_pretok = "cached_pretok" class ModelTypeChoices(utils.FlagChoices): distilgpt2 = "distilgpt2" gpt2_xl = "gpt2-xl" gpt2_large = "gpt2-large" gpt2_medium = "gpt2-medium" gpt2 = "gpt2" RETRIEVAL_APPROACH_TYPES = frozenset([ ApproachTypeChoices.lm_and_realm, ApproachTypeChoices.cached_realm, ApproachTypeChoices.cached_pretok, ]) # There will eventually be more, like generate. class TaskChoices(utils.FlagChoices): train = "train" class DatasetNameChoices(utils.FlagChoices): kilt_eli5 = "kilt_eli5" PPL_MASK_ID = -100 RAGGED_PADDING_ID = -1 class CTH5Fields(utils.FlagChoices): distances = "distances" gpt2_question_ids_inputs = "gpt2_question_ids" gpt2_answer_ids_inputs = "gpt2_answer_ids" gpt2_retrieved_ids = "gpt2_retrieved_ids" # Deprecated: gpt2_question_ids_labels = "gpt2_question_labels" gpt2_answer_ids_labels = "gpt2_answer_labels" class SplitChoices(utils.FlagChoices): train = "train" eval = "eval" test = "test" class DatasetTypeChoices(utils.FlagChoices): tfr = "tfr" hdf5 = "hdf5"
1,166
353
<reponame>codeproject/DeepStack<filename>windows_packages_gpu/torch/include/torch/csrc/utils/throughput_benchmark.h #pragma once #include <ATen/core/ivalue.h> #include <torch/csrc/jit/api/module.h> #include <pybind11/pybind11.h> #include <torch/csrc/jit/python/pybind_utils.h> #include <iostream> #include <memory> #include <string> #include <vector> namespace py = pybind11; namespace torch { namespace throughput_benchmark { /** * The struct is used to provide results of a benchmark to the caller * In the future all additional statics should be added here. */ struct BenchmarkExecutionStats { float latency_avg_ms{-1}; int64_t num_iters{-1}; }; std::ostream& operator<<(std::ostream& os, const BenchmarkExecutionStats& value); /** * Use this struct in order to configure a throughput benchmark run. * This struct should include parameters related to threading, batching, number * of iterations, warm-up, etc. More configs can be added as needed. * General rule here is that only things that c++ must(!) to be aware of should * be here. If we can keep other parts in python, we should keep them there. * This is typical for things that are not perf critical and don't affect * execution statistics benchmark returns. */ struct BenchmarkConfig { public: // Calling threads are those threads that are calling into a module in // parallel. int num_calling_threads{1}; // Worker threads are not supported yet. This is just an example that we plan // to support some sort of multi-threaded forward calls. We may change this // setting in the future to support different intra and inter op parallelizm // which is not available in PyTorch yet int num_worker_threads{1}; // Warmup iters are used to make sure we run a module a few times before // actually measuring things. This way we avoid cold caches and any other // similar problems int num_warmup_iters{1}; // Number of iterations the benchmark should run with. This number is separate // from the warmup iterations int64_t num_iters{100}; // If set autograd profiler will be enabled. I.e. this variable would be created // before the main benchmark loop (but after the warmup): // RecordProfile guard(profiler_output_path); std::string profiler_output_path{""}; }; namespace detail { /** * A helper class to abstract out different models we test throughput of */ template <class Input, class Output, class Model> class BenchmarkHelper { public: BenchmarkHelper(); explicit BenchmarkHelper(Model model): model_(model), initialized_(true) {} // This method to be used in benchmark() method // Note that there is no result. This way we don't have to call this under GIL // even when running in the nn.Module mode. Otherwise destructor of the result // would race with Python void runOnce(Input&&) const; // This method is to be used when calling from Python dirrectly Output runOnce(py::args&&, py::kwargs&&) const; // Aggregate input in the format Model expects in order to avoid further // conversions at the benchmark time void addInput(py::args&&, py::kwargs&&); void addInput(Input&&); BenchmarkExecutionStats benchmark(const BenchmarkConfig& config) const; bool initialized() const { return initialized_; } // Destructor doesn't require the GIL because it is going to be executed on // the PyThon thread std::vector<Input> inputs_; Model model_; bool initialized_{false}; }; struct C10_HIDDEN ModuleInput { ModuleInput(ModuleInput&& other) = default; ModuleInput(const ModuleInput&) = delete; ModuleInput& operator=(ModuleInput& other) = delete; ModuleInput& operator=(ModuleInput&& other) = delete; ModuleInput(py::args&& args, py::kwargs&& kwargs) : args(std::move(args)), kwargs(std::move(kwargs)) {} py::args args; py::kwargs kwargs; }; typedef py::object ModuleOutput; typedef std::vector<at::IValue> ScriptModuleInput; typedef at::IValue ScriptModuleOutput; template<class Input> Input cloneInput(const Input& input); typedef BenchmarkHelper< ScriptModuleInput, at::IValue, jit::Module> ScriptModuleBenchmark; template <> inline BenchmarkHelper<ScriptModuleInput, at::IValue, jit::Module>::BenchmarkHelper() : model_("Module", std::make_shared<jit::CompilationUnit>()), initialized_(false) {} typedef BenchmarkHelper<ModuleInput, py::object, py::object> ModuleBenchmark; template <> inline BenchmarkHelper<ModuleInput, py::object, py::object>::BenchmarkHelper() : initialized_(false) {} template <> void ScriptModuleBenchmark::runOnce( ScriptModuleInput&& input) const; template <> ScriptModuleOutput ScriptModuleBenchmark::runOnce( py::args&& args, py::kwargs&& kwargs) const; template <> void ModuleBenchmark::runOnce(ModuleInput&& input) const; template <> ModuleOutput ModuleBenchmark::runOnce(py::args&& args, py::kwargs&& kwargs) const; template <> void ScriptModuleBenchmark::addInput(py::args&& args, py::kwargs&& kwargs); template <> void ScriptModuleBenchmark::addInput(ScriptModuleInput&& input); template <> void ModuleBenchmark::addInput(py::args&& args, py::kwargs&& kwargs); } // namespace detail /** * This class is a small c++ component responsible for executing a PyTorch * module under an inference server like load. It can emulate multiple calling * threads to a single module provided. In the future we plan to enhance this * component to support inter and intra-op parallelism as well as multiple * models running in a single process. * * For current available configurations refer to the BenchmkarConfig * documentation * * The class supports working with either nn.Module or ScriptModule. * Under the hood it just dispatches to corresponding specialization of * class BenchmarkHelper<Input, Output, Model> */ class C10_HIDDEN ThroughputBenchmark { public: explicit ThroughputBenchmark(jit::Module module); explicit ThroughputBenchmark(py::object module); // Add one more input example. This input example should be in the exact // format the module under test expects. It is responsibility of the module to // perform any such format checks, the benchmark doesn't perform any // validation of its own void addInput(py::args args, py::kwargs kwargs); // Equivalent to just running the model dirrectly on the given input py::object runOnce(py::args&& args, py::kwargs&& kwargs); // The main method of the class allows to perform a multi-threaded benchmark // It returns BenchmarkExecutionStats object with a lot of useful statistics // about runtime execution. We can enhance this class in the future to provide // more information to the user BenchmarkExecutionStats benchmark(const BenchmarkConfig& config) const; private: detail::ScriptModuleBenchmark script_module_; detail::ModuleBenchmark module_; }; } // namespace throughput benchmark } // namepsace torch #include <torch/csrc/utils/throughput_benchmark-inl.h>
2,188
777
<reponame>google-ar/chromium // Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MailboxTextureHolder_h #define MailboxTextureHolder_h #include "platform/PlatformExport.h" #include "platform/graphics/TextureHolder.h" #include "platform/graphics/WebGraphicsContext3DProviderWrapper.h" #include "third_party/khronos/GLES2/gl2.h" #include "wtf/WeakPtr.h" namespace blink { class PLATFORM_EXPORT MailboxTextureHolder final : public TextureHolder { public: ~MailboxTextureHolder() override; bool isSkiaTextureHolder() final { return false; } bool isMailboxTextureHolder() final { return true; } unsigned sharedContextId() final; IntSize size() const final { return m_size; } bool currentFrameKnownToBeOpaque(Image::MetadataMode) final { return false; } gpu::Mailbox mailbox() final { return m_mailbox; } gpu::SyncToken syncToken() final { return m_syncToken; } void updateSyncToken(gpu::SyncToken syncToken) final { m_syncToken = syncToken; } // In WebGL's commit or transferToImageBitmap calls, it will call the // DrawingBuffer::transferToStaticBitmapImage function, which produces the // input parameters for this method. MailboxTextureHolder(const gpu::Mailbox&, const gpu::SyncToken&, unsigned textureIdToDeleteAfterMailboxConsumed, WeakPtr<WebGraphicsContext3DProviderWrapper>, IntSize mailboxSize); // This function turns a texture-backed SkImage into a mailbox and a // syncToken. MailboxTextureHolder(std::unique_ptr<TextureHolder>); private: void releaseTextureThreadSafe(); gpu::Mailbox m_mailbox; gpu::SyncToken m_syncToken; unsigned m_textureId; WeakPtr<WebGraphicsContext3DProviderWrapper> m_contextProvider; IntSize m_size; bool m_isConvertedFromSkiaTexture; }; } // namespace blink #endif // MailboxTextureHolder_h
682
3,269
<filename>C++/pacific-atlantic-water-flow.cpp // Time: O(m * n) // Space: O(m * n) class Solution { public: vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) { if (matrix.empty()) { return {}; } vector<pair<int, int>> res; const auto m = matrix.size(), n = matrix[0].size(); vector<vector<int>> visited(m, vector<int>(n)); for (int i = 0; i < m; ++i) { pacificAtlanticHelper(matrix, i, 0, numeric_limits<int>::min(), PACIFIC, &visited, &res); pacificAtlanticHelper(matrix, i, n - 1, numeric_limits<int>::min(), ATLANTIC, &visited, &res); } for (int j = 0; j < n; ++j) { pacificAtlanticHelper(matrix, 0, j, numeric_limits<int>::min(), PACIFIC, &visited, &res); pacificAtlanticHelper(matrix, m - 1, j, numeric_limits<int>::min(), ATLANTIC, &visited, &res); } return res; } private: void pacificAtlanticHelper(const vector<vector<int>>& matrix, int x, int y, int prev_height, int prev_val, vector<vector<int>> *visited, vector<pair<int, int>> *res) { if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[x][y] < prev_height || ((*visited)[x][y] | prev_val) == (*visited)[x][y]) { return; } (*visited)[x][y] |= prev_val; if ((*visited)[x][y] == (PACIFIC | ATLANTIC)) { res->emplace_back(x, y); } for (const auto& dir : directions) { pacificAtlanticHelper(matrix, x + dir.first, y + dir.second, matrix[x][y], (*visited)[x][y], visited, res); } } enum ocean { PACIFIC = 1, ATLANTIC = 2 }; const vector<pair<int, int>> directions{ {0, -1}, {0, 1}, {-1, 0}, {1, 0} }; };
877
389
<gh_stars>100-1000 package editor.util; public class Pair<A, B> { A _a; B _b; public Pair( A a, B b ) { _a = a; _b = b; } public A getFirst() { return _a; } public B getSecond() { return _b; } }
119
7,482
<filename>bsp/rm48x50/HALCoGen/include/emac.h /** * \file emac.h * * \brief EMAC APIs and macros. * * This file contains the driver API prototypes and macro definitions. */ /* (c) Texas Instruments 2009-2013, All rights reserved. */ #ifndef __EMAC_H__ #define __EMAC_H__ #include "sys_common.h" #include "hw_emac.h" #ifdef __cplusplus extern "C" { #endif /*****************************************************************************/ /* ** Macros which can be used as speed parameter to the API EMACRMIISpeedSet */ #define EMAC_RMIISPEED_10MBPS (0x00000000U) #define EMAC_RMIISPEED_100MBPS (0x00008000U) /* ** Macros which can be used as duplexMode parameter to the API ** EMACDuplexSet */ #define EMAC_DUPLEX_FULL (0x00000001U) #define EMAC_DUPLEX_HALF (0x00000000U) /* ** Macros which can be used as matchFilt parameters to the API ** EMACMACAddrSet */ /* Address not used to match/filter incoming packets */ #define EMAC_MACADDR_NO_MATCH_NO_FILTER (0x00000000U) /* Address will be used to filter incoming packets */ #define EMAC_MACADDR_FILTER (0x00100000U) /* Address will be used to match incoming packets */ #define EMAC_MACADDR_MATCH (0x00180000U) /* ** Macros which can be passed as eoiFlag to EMACRxIntAckToClear API */ #define EMAC_INT_CORE0_RX (0x1U) #define EMAC_INT_CORE1_RX (0x5U) #define EMAC_INT_CORE2_RX (0x9U) /* ** Macros which can be passed as eoiFlag to EMACTxIntAckToClear API */ #define EMAC_INT_CORE0_TX (0x2U) #define EMAC_INT_CORE1_TX (0x6U) #define EMAC_INT_CORE2_TX (0xAU) /*****************************************************************************/ /** * @defgroup EMACMDIO EMAC/MDIO * @brief Ethernet Media Access Controller/Management Data Input/Output. * * The EMAC controls the flow of packet data from the system to the PHY. The MDIO module controls PHY * configuration and status monitoring. * * Both the EMAC and the MDIO modules interface to the system core through a custom interface that * allows efficient data transmission and reception. This custom interface is referred to as the EMAC control * module and is considered integral to the EMAC/MDIO peripheral * * Related Files * - emac.h * - emac.c * - hw_emac.h * - hw_emac_ctrl.h * - hw_mdio.h * - hw_reg_access.h * - mdio.h * - mdio.c * @addtogroup EMACMDIO * @{ */ /* ** Prototypes for the APIs */ extern void EMACTxIntPulseEnable(uint32 emacBase, uint32 emacCtrlBase, uint32 ctrlCore, uint32 channel); extern void EMACTxIntPulseDisable(uint32 emacBase, uint32 emacCtrlBase, uint32 ctrlCore, uint32 channel); extern void EMACRxIntPulseEnable(uint32 emacBase, uint32 emacCtrlBase, uint32 ctrlCore, uint32 channel); extern void EMACRxIntPulseDisable(uint32 emacBase, uint32 emacCtrlBase, uint32 ctrlCore, uint32 channel); extern void EMACRMIISpeedSet(uint32 emacBase, uint32 speed); extern void EMACDuplexSet(uint32 emacBase, uint32 duplexMode); extern void EMACTxEnable(uint32 emacBase); extern void EMACRxEnable(uint32 emacBase); extern void EMACTxHdrDescPtrWrite(uint32 emacBase, uint32 descHdr, uint32 channel); extern void EMACRxHdrDescPtrWrite(uint32 emacBase, uint32 descHdr, uint32 channel); extern void EMACInit(uint32 emacCtrlBase, uint32 emacBase); extern void EMACMACSrcAddrSet(uint32 emacBase, uint8 * macAddr); extern void EMACMACAddrSet(uint32 emacBase, uint32 channel, uint8 * macAddr, uint32 matchFilt); extern void EMACMIIEnable(uint32 emacBase); extern void EMACRxUnicastSet(uint32 emacBase, uint32 channel); extern void EMACCoreIntAck(uint32 emacBase, uint32 eoiFlag); extern void EMACTxCPWrite(uint32 emacBase, uint32 channel, uint32 comPtr); extern void EMACRxCPWrite(uint32 emacBase, uint32 channel, uint32 comPtr); extern void EMACRxBroadCastEnable(uint32 emacBase, uint32 channel); extern void EMACNumFreeBufSet(uint32 emacBase, uint32 channel, uint32 nBuf); extern uint32 EMACIntVectorGet(uint32 emacBase); #ifdef __cplusplus } #endif /**@}*/ #endif /* __EMAC_H__ */
1,979
757
import os import tqdm import torch import torch.nn as nn import torch.nn.functional as F import argparse import torchvision.transforms as transforms from torchvision import datasets from model.model import RandWire from utils.hparams import HParam from utils.graph_reader import read_graph from utils.evaluation import validate from dataset.dataloader import create_dataloader, MNIST_dataloader, CIFAR10_dataloader if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', type=str, required=True, help="yaml file for configuration") parser.add_argument('-p', '--checkpoint_path', type=str, default=None, required=False, help="path of checkpoint pt file") args = parser.parse_args() hp = HParam(args.config) graphs = [ read_graph(hp.model.graph0), read_graph(hp.model.graph1), read_graph(hp.model.graph2), ] print('Loading model from checkpoint...') model = RandWire(hp, graphs).cuda() checkpoint = torch.load(args.checkpoint_path) model.load_state_dict(checkpoint['model']) step = checkpoint['step'] dataset = hp.data.type switcher = { 'MNIST': MNIST_dataloader, 'CIFAR10':CIFAR10_dataloader, 'ImageNet':create_dataloader, } assert dataset in switcher.keys(), 'Dataset type currently not supported' dl_func = switcher[dataset] valset = dl_func(hp, args, False) print('Validating...') test_avg_loss, accuracy = validate(model, valset) print('Result on step %d:' % step) print('Average test loss: %.4f' % test_avg_loss) print('Accuracy: %.3f' % accuracy)
682
1,695
<reponame>SanjayTechGuru/TRINO /* * 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 io.trino.sql.planner.rowpattern; import com.google.common.collect.ImmutableMap; import io.trino.sql.planner.Symbol; import io.trino.sql.planner.rowpattern.LogicalIndexExtractor.ExpressionAndValuePointers; import io.trino.sql.tree.Node; import io.trino.sql.tree.SymbolReference; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; import static io.trino.sql.util.AstUtils.treeEqual; public class ExpressionAndValuePointersEquivalence { private ExpressionAndValuePointersEquivalence() {} public static boolean equivalent(ExpressionAndValuePointers left, ExpressionAndValuePointers right) { return equivalent(left, right, Symbol::equals); } public static boolean equivalent(ExpressionAndValuePointers left, ExpressionAndValuePointers right, BiFunction<Symbol, Symbol, Boolean> symbolEquivalence) { if (left.getLayout().size() != right.getLayout().size()) { return false; } for (int i = 0; i < left.getLayout().size(); i++) { ValuePointer leftPointer = left.getValuePointers().get(i); ValuePointer rightPointer = right.getValuePointers().get(i); if (leftPointer.getClass() != rightPointer.getClass()) { return false; } if (leftPointer instanceof ScalarValuePointer) { if (!equivalent( (ScalarValuePointer) leftPointer, (ScalarValuePointer) rightPointer, left.getClassifierSymbols(), left.getMatchNumberSymbols(), right.getClassifierSymbols(), right.getMatchNumberSymbols(), symbolEquivalence)) { return false; } } else if (leftPointer instanceof AggregationValuePointer) { if (!equivalent((AggregationValuePointer) leftPointer, (AggregationValuePointer) rightPointer, symbolEquivalence)) { return false; } } else { throw new UnsupportedOperationException("unexpected ValuePointer type: " + leftPointer.getClass().getSimpleName()); } } ImmutableMap.Builder<Symbol, Symbol> mapping = ImmutableMap.builder(); for (int i = 0; i < left.getLayout().size(); i++) { mapping.put(left.getLayout().get(i), right.getLayout().get(i)); } return treeEqual(left.getExpression(), right.getExpression(), mappingComparator(mapping.buildOrThrow())); } private static boolean equivalent( ScalarValuePointer left, ScalarValuePointer right, Set<Symbol> leftClassifierSymbols, Set<Symbol> leftMatchNumberSymbols, Set<Symbol> rightClassifierSymbols, Set<Symbol> rightMatchNumberSymbols, BiFunction<Symbol, Symbol, Boolean> symbolEquivalence) { if (!left.getLogicalIndexPointer().equals(right.getLogicalIndexPointer())) { return false; } Symbol leftInputSymbol = left.getInputSymbol(); Symbol rightInputSymbol = right.getInputSymbol(); boolean leftIsClassifier = leftClassifierSymbols.contains(leftInputSymbol); boolean leftIsMatchNumber = leftMatchNumberSymbols.contains(leftInputSymbol); boolean rightIsClassifier = rightClassifierSymbols.contains(rightInputSymbol); boolean rightIsMatchNumber = rightMatchNumberSymbols.contains(rightInputSymbol); if (leftIsClassifier != rightIsClassifier || leftIsMatchNumber != rightIsMatchNumber) { return false; } if (!leftIsClassifier && !leftIsMatchNumber) { return symbolEquivalence.apply(leftInputSymbol, rightInputSymbol); } return true; } private static boolean equivalent(AggregationValuePointer left, AggregationValuePointer right, BiFunction<Symbol, Symbol, Boolean> symbolEquivalence) { if (!left.getFunction().equals(right.getFunction()) || !left.getSetDescriptor().equals(right.getSetDescriptor()) || left.getArguments().size() != right.getArguments().size()) { return false; } BiFunction<Node, Node, Boolean> comparator = subsetComparator(left.getClassifierSymbol(), left.getMatchNumberSymbol(), right.getClassifierSymbol(), right.getMatchNumberSymbol(), symbolEquivalence); for (int i = 0; i < left.getArguments().size(); i++) { if (!treeEqual(left.getArguments().get(i), right.getArguments().get(i), comparator)) { return false; } } return true; } private static BiFunction<Node, Node, Boolean> subsetComparator( Symbol leftClassifierSymbol, Symbol leftMatchNumberSymbol, Symbol rightClassifierSymbol, Symbol rightMatchNumberSymbol, BiFunction<Symbol, Symbol, Boolean> symbolEquivalence) { return (left, right) -> { if (left instanceof SymbolReference && right instanceof SymbolReference) { Symbol leftSymbol = Symbol.from((SymbolReference) left); Symbol rightSymbol = Symbol.from((SymbolReference) right); boolean leftIsClassifier = leftSymbol.equals(leftClassifierSymbol); boolean leftIsMatchNumber = leftSymbol.equals(leftMatchNumberSymbol); boolean rightIsClassifier = rightSymbol.equals(rightClassifierSymbol); boolean rightIsMatchNumber = rightSymbol.equals(rightMatchNumberSymbol); if (leftIsClassifier != rightIsClassifier || leftIsMatchNumber != rightIsMatchNumber) { return false; } if (!leftIsClassifier && !leftIsMatchNumber) { return symbolEquivalence.apply(leftSymbol, rightSymbol); } return true; } if (!left.shallowEquals(right)) { return false; } return null; }; } private static BiFunction<Node, Node, Boolean> mappingComparator(Map<Symbol, Symbol> mapping) { return (left, right) -> { if (left instanceof SymbolReference && right instanceof SymbolReference) { Symbol leftSymbol = Symbol.from((SymbolReference) left); Symbol rightSymbol = Symbol.from((SymbolReference) right); return rightSymbol.equals(mapping.get(leftSymbol)); } if (!left.shallowEquals(right)) { return false; } return null; }; } }
3,108
575
<reponame>sarang-apps/darshan_browser<gh_stars>100-1000 // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DOWNLOAD_NOTIFICATION_DOWNLOAD_NOTIFICATION_MANAGER_H_ #define CHROME_BROWSER_DOWNLOAD_NOTIFICATION_DOWNLOAD_NOTIFICATION_MANAGER_H_ #include <map> #include <memory> #include "chrome/browser/download/download_ui_controller.h" #include "chrome/browser/download/download_ui_model.h" #include "chrome/browser/download/notification/download_item_notification.h" #include "components/offline_items_collection/core/offline_item.h" class Profile; using offline_items_collection::ContentId; class DownloadNotificationManager : public DownloadUIController::Delegate, public DownloadItemNotification::Observer { public: explicit DownloadNotificationManager(Profile* profile); ~DownloadNotificationManager() override; // DownloadUIController::Delegate overrides. void OnNewDownloadReady(download::DownloadItem* item) override; // DownloadItemNotification::Observer overrides. void OnDownloadDestroyed(const ContentId& contentId) override; private: friend class test::DownloadItemNotificationTest; Profile* profile_; std::map<ContentId, DownloadItemNotification::DownloadItemNotificationPtr> items_; DISALLOW_COPY_AND_ASSIGN(DownloadNotificationManager); }; #endif // CHROME_BROWSER_DOWNLOAD_NOTIFICATION_DOWNLOAD_NOTIFICATION_MANAGER_H_
496
854
<gh_stars>100-1000 __________________________________________________________________________________________________ 4ms int optimization = []() { ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> ans; int l = 0, r = numbers.size() - 1; while (l < r) { int sum = numbers[l] + numbers[r]; if (sum == target) { ans.push_back(l + 1); ans.push_back(r + 1); break; } else if (sum < target) { ++l; } else if (sum > target) { --r; } } return ans; } }; __________________________________________________________________________________________________ 9296 kb class Solution { public: vector<int> twoSum(vector<int>& numbers, int target) { int l = 0, r = numbers.size() - 1; while (l < r) { int sum = numbers[l] + numbers[r]; if(sum == target) { return {l + 1, r + 1}; }else if (sum < target) { ++l; }else { --r; } } return {}; } }; __________________________________________________________________________________________________
710
608
<filename>package.json<gh_stars>100-1000 { "name": "ts-optchain", "version": "0.1.8", "description": "Optional Chaining for TypeScript", "repository": { "type": "git", "url": "git+https://github.com/rimeto/ts-optchain.git" }, "main": "./dist/proxy/index.js", "types": "./index.d.ts", "files": [ "dist", "index.d.ts", "transform.js" ], "scripts": { "build": "npm run clean && tsc && find ./dist -type d -and -name '__tests__' | xargs rm -rf", "clean": "rm -rf build dist", "prepublishOnly": "npm run build", "test": "npm run test-proxy && npm run test-transform", "test-proxy": "tsc --noEmit && jest", "test-transform": "ttsc -p src/transform/__tests__ && jest src/transform/__tests__; ret=$?; rm -rf src/transform/__tests__/dist; exit $ret" }, "license": "MIT", "devDependencies": { "@types/jest": "^24.0.12", "conditional-type-checks": "^1.0.0", "jest": "^24.7.1", "ts-jest": "^24.0.2", "ttypescript": "^1.5.6", "typescript": "^3.5.3" }, "jest": { "moduleFileExtensions": [ "ts", "tsx", "js", "json" ], "rootDir": "./src", "testEnvironment": "node", "testMatch": [ "**/__tests__/**/*-test.[jt]s?(x)" ], "transform": { ".(ts|tsx)": "ts-jest" } }, "keywords": [ "existential operator", "null conditional operator", "null propagation operator", "optional chaining", "safe navigation operator", "typescript" ], "engines": { "node": ">=6" } }
709
2,103
#!/usr/bin/env python # Copyright (c) 2019 The Khronos Group Inc. # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE.txt file. """ Generator for uniformbuffers* tests. This file needs to be run in its folder. """ import sys _DO_NOT_EDIT_WARNING = """<!-- This file is auto-generated from uniformbuffers_test_generator.py DO NOT EDIT! --> """ _HTML_TEMPLATE = """<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>WebGL Uniform Block Conformance Tests</title> <link rel="stylesheet" href="../../../../resources/js-test-style.css"/> <script src="../../../../js/js-test-pre.js"></script> <script src="../../../../js/webgl-test-utils.js"></script> <script src="../../../../closure-library/closure/goog/base.js"></script> <script src="../../../deqp-deps.js"></script> <script>goog.require('functional.gles3.es3fUniformBlockTests');</script> </head> <body> <div id="description"></div> <div id="console"></div> <canvas id="canvas" width="200" height="100"> </canvas> <script> var wtu = WebGLTestUtils; var gl = wtu.create3DContext('canvas', null, 2); functional.gles3.es3fUniformBlockTests.run([%(start)s, %(end)s]); </script> </body> </html> """ _GROUPS = [ 'single_basic_type', 'single_basic_array', 'single_struct', 'single_struct_array', 'single_nested_struct', 'single_nested_struct_array', 'instance_array_basic_type', 'multi_basic_types', 'multi_nested_struct', 'random', ] def GenerateFilename(group): """Generate test filename.""" filename = group filename += ".html" return filename def WriteTest(filename, start, end): """Write one test.""" file = open(filename, "wb") file.write(_DO_NOT_EDIT_WARNING) file.write(_HTML_TEMPLATE % { 'start': start, 'end': end }) file.close def GenerateTests(): """Generate all tests.""" filelist = [] for ii in range(len(_GROUPS)): filename = GenerateFilename(_GROUPS[ii]) filelist.append(filename) WriteTest(filename, ii, ii + 1) return filelist def GenerateTestList(filelist): file = open("00_test_list.txt", "wb") file.write('\n'.join(filelist)) file.close def main(argv): """This is the main function.""" filelist = GenerateTests() GenerateTestList(filelist) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
889
648
{"resourceType":"CodeSystem","id":"adjudication","meta":{"lastUpdated":"2017-04-19T07:44:43.294+10:00","profile":["http://hl7.org/fhir/StructureDefinition/shareablecodesystem"]},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>Adjudication Value Codes</h2>\n <div>\n <p>This value set includes a smattering of Adjudication Value codes which includes codes to indicate the amounts eligible under the plan, the amount of benefit, copays etc.</p>\n\n </div>\n <p>\n <b>Copyright Statement:</b> This is an example set.\n </p>\n <p>This code system http://hl7.org/fhir/adjudication defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td>\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td>total\n <a name=\"adjudication-total\"> </a>\n </td>\n <td>Total</td>\n <td>Total submitted</td>\n </tr>\n <tr>\n <td>copay\n <a name=\"adjudication-copay\"> </a>\n </td>\n <td>CoPay</td>\n <td>Patient Co-Payment</td>\n </tr>\n <tr>\n <td>eligible\n <a name=\"adjudication-eligible\"> </a>\n </td>\n <td>Eligible Amount</td>\n <td>Amount of the change which is considered for adjudication</td>\n </tr>\n <tr>\n <td>deductible\n <a name=\"adjudication-deductible\"> </a>\n </td>\n <td>Deductable</td>\n <td>Amount deducted from the eligible amount prior to adjudication</td>\n </tr>\n <tr>\n <td>eligpercent\n <a name=\"adjudication-eligpercent\"> </a>\n </td>\n <td>Eligible %</td>\n <td>Eligible Percentage</td>\n </tr>\n <tr>\n <td>tax\n <a name=\"adjudication-tax\"> </a>\n </td>\n <td>Emergency Department</td>\n <td>Emergency Department</td>\n </tr>\n <tr>\n <td>benefit\n <a name=\"adjudication-benefit\"> </a>\n </td>\n <td>Benefit Amount</td>\n <td>Amount payable under the coverage</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-ballot-status","valueString":"Informative"},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-fmm","valueInteger":1},{"url":"http://hl7.org/fhir/StructureDefinition/structuredefinition-wg","valueCode":"fm"}],"url":"http://hl7.org/fhir/adjudication","identifier":{"system":"urn:ietf:rfc:3986","value":"urn:oid:2.16.840.1.113883.4.642.1.589"},"version":"3.0.1","name":"Adjudication Value Codes","status":"draft","experimental":true,"publisher":"FHIR Project team","contact":[{"telecom":[{"system":"url","value":"http://hl7.org/fhir"}]}],"description":"This value set includes a smattering of Adjudication Value codes which includes codes to indicate the amounts eligible under the plan, the amount of benefit, copays etc.","copyright":"This is an example set.","caseSensitive":true,"valueSet":"http://hl7.org/fhir/ValueSet/adjudication","content":"complete","concept":[{"code":"total","display":"Total","definition":"Total submitted"},{"code":"copay","display":"CoPay","definition":"Patient Co-Payment"},{"code":"eligible","display":"Eligible Amount","definition":"Amount of the change which is considered for adjudication"},{"code":"deductible","display":"Deductable","definition":"Amount deducted from the eligible amount prior to adjudication"},{"code":"eligpercent","display":"Eligible %","definition":"Eligible Percentage"},{"code":"tax","display":"Emergency Department","definition":"Emergency Department"},{"code":"benefit","display":"Benefit Amount","definition":"Amount payable under the coverage"}]}
2,167
1,002
<filename>winrt/test.internal/xaml/GameLoopThreadTests.cpp<gh_stars>1000+ // Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. #include "pch.h" #include <lib/xaml/GameLoopThread.h> #include "MockCoreIndependentInputSource.h" #ifdef CANVAS_ANIMATED_CONTROL_IS_ENABLED class Waiter { Event m_event; public: Waiter() : m_event(CreateEventEx(NULL, NULL, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS)) { } void Set() { SetEvent(m_event.Get()); } void Wait(int timeout = 5 * 1000) { Assert::AreEqual(WAIT_OBJECT_0, WaitForSingleObjectEx(m_event.Get(), timeout, false), L"timed out waiting"); } }; class FakeDispatcher : public MockDispatcher { std::mutex m_mutex; std::condition_variable m_conditionVariable; bool m_stopped; std::vector<ComPtr<AnimatedControlAsyncAction>> m_pendingActions; public: CALL_COUNTER_WITH_MOCK(RunAsyncValidation, void(CoreDispatcherPriority)); FakeDispatcher() : m_stopped(false) { RunAsyncValidation.AllowAnyCall(); } virtual IFACEMETHODIMP RunAsync( CoreDispatcherPriority priority, IDispatchedHandler* agileCallback, IAsyncAction** asyncAction) override { RunAsyncValidation.WasCalled(priority); Lock lock(m_mutex); auto action = Make<AnimatedControlAsyncAction>(agileCallback); m_pendingActions.push_back(action); m_conditionVariable.notify_all(); return action.CopyTo(asyncAction); } virtual IFACEMETHODIMP StopProcessEvents() override { Lock lock(m_mutex); m_stopped = true; m_conditionVariable.notify_all(); return S_OK; } virtual IFACEMETHODIMP ProcessEvents( CoreProcessEventsOption options) override { Assert::IsTrue(options == CoreProcessEventsOption_ProcessUntilQuit); Lock lock(m_mutex); m_stopped = false; while (!m_stopped) { std::vector<ComPtr<AnimatedControlAsyncAction>> actions; std::swap(actions, m_pendingActions); if (!actions.empty()) { lock.unlock(); for (auto& action : actions) { action->InvokeAndFireCompletion(); } lock.lock(); } if (actions.empty()) { m_conditionVariable.wait(lock); } } return S_OK; } }; struct MockGameLoopClient : public ICanvasGameLoopClient { CALL_COUNTER_WITH_MOCK(GameLoopStarting, void()); CALL_COUNTER_WITH_MOCK(GameLoopStopped, void()); virtual void OnGameLoopStarting() override { GameLoopStarting.WasCalled(); } virtual void OnGameLoopStopped() override { GameLoopStopped.WasCalled(); } virtual bool Tick(CanvasSwapChain* target, bool areResourcesCreated) override { return true; } virtual void OnTickLoopEnded() override { } }; TEST_CLASS(GameLoopThreadTests) { struct Fixture { ComPtr<FakeDispatcher> Dispatcher; ComPtr<StubSwapChainPanel> SwapChainPanel; MockGameLoopClient Client; std::unique_ptr<IGameLoopThread> Thread; Fixture() : Dispatcher(Make<FakeDispatcher>()) , SwapChainPanel(Make<StubSwapChainPanel>()) { SwapChainPanel->CreateCoreIndependentInputSourceMethod.AllowAnyCall( [=] (CoreInputDeviceTypes, ICoreInputSourceBase** value) { auto inputSource = Make<StubCoreIndependentInputSource>(Dispatcher); return inputSource.CopyTo(value); }); Client.GameLoopStarting.AllowAnyCall(); Client.GameLoopStopped.AllowAnyCall(); } void CreateThread() { Thread = CreateGameLoopThread(SwapChainPanel.Get(), &Client); } void RunAndWait(std::function<void()> fn = nullptr) { auto handler = Callback<IDispatchedHandler>( [=] { return ExceptionBoundary( [&] { if (fn) fn(); }); }); auto action = Thread->RunAsync(handler.Get()); Waiter w; auto completed = Callback<IAsyncActionCompletedHandler>( [&] (IAsyncAction*, AsyncStatus) { w.Set(); return S_OK; }); ThrowIfFailed(action->put_Completed(completed.Get())); w.Wait(); } void RunDirectlyOnDispatcherAndWait() { Waiter w; auto handler = Callback<IDispatchedHandler>( [&] { w.Set(); return S_OK; }); ComPtr<IAsyncAction> ignoredAction; ThrowIfFailed(Dispatcher->RunAsync(CoreDispatcherPriority_Normal, handler.Get(), &ignoredAction)); w.Wait(); } }; TEST_METHOD_EX(GameLoopThread_ConstructionDestruction) { Fixture f; f.CreateThread(); } TEST_METHOD_EX(GameLoopThread_HasThreadAccess_CallsThroughToDispatcher) { Fixture f; f.CreateThread(); f.RunAndWait(); // give the thread a chance to start f.Dispatcher->get_HasThreadAccessMethod.SetExpectedCalls(1, [] (boolean* value) { *value = TRUE; return S_OK; }); Assert::IsTrue(f.Thread->HasThreadAccess()); f.Dispatcher->get_HasThreadAccessMethod.SetExpectedCalls(1, [] (boolean* value) { *value = FALSE; return S_OK; }); Assert::IsFalse(f.Thread->HasThreadAccess()); f.Dispatcher->get_HasThreadAccessMethod.SetExpectedCalls(1, [] (boolean*) { return E_FAIL; }); ExpectHResultException(E_FAIL, [&] { f.Thread->HasThreadAccess(); }); } TEST_METHOD_EX(GameLoopThread_RunAsync_ExecutesHandler) { Fixture f; f.CreateThread(); f.RunAndWait(); } TEST_METHOD_EX(GameLoopThread_WhenStartDispatcherCalled_DispatcherStartsProcessingEvents) { Fixture f; f.CreateThread(); f.Thread->StartDispatcher(); f.RunDirectlyOnDispatcherAndWait(); } TEST_METHOD_EX(GameLoopThread_WhenStopDispatcherCalled_DispatcherStopsProcessingEvents) { Fixture f; f.CreateThread(); f.Thread->StartDispatcher(); f.Thread->StopDispatcher(); auto handler = Callback<IDispatchedHandler>( [&] { Assert::Fail(L"did not expect to see this"); return S_OK; }); ComPtr<IAsyncAction> ignoredAction; ThrowIfFailed(f.Dispatcher->RunAsync(CoreDispatcherPriority_Normal, handler.Get(), &ignoredAction)); f.RunAndWait(); } TEST_METHOD_EX(GameLoopThread_TicksAreScheduledOnDispatcherAtLowPriority) { // If the dispatcher is being shared by input then we want the input // events to take priority over the ticks. We ensure this by scheduling // the ticks at low priority. Fixture f; f.CreateThread(); f.Thread->StartDispatcher(); f.RunDirectlyOnDispatcherAndWait(); f.Dispatcher->RunAsyncValidation.SetExpectedCalls(1, [] (CoreDispatcherPriority priority) { Assert::AreEqual(CoreDispatcherPriority_Low, priority); }); f.RunAndWait(); } TEST_METHOD_EX(GameLoopThread_OnGameLoopStarting_IsCalledBeforeGameLoopStarts) { Fixture f; f.Client.GameLoopStarting.SetExpectedCalls(1); f.CreateThread(); f.Client.GameLoopStarting.SetExpectedCalls(0); f.RunAndWait(); } TEST_METHOD_EX(GameLoopThread_OnGameLoopStopped_IsCalledAfterGameLoopStops) { Fixture f; f.Client.GameLoopStopped.SetExpectedCalls(0); f.CreateThread(); f.Thread->StartDispatcher(); f.Thread->StopDispatcher(); f.Client.GameLoopStopped.SetExpectedCalls(1); f.Thread.reset(); } TEST_METHOD_EX(GameLoopThead_WhenCreateCoreIndependentInputSourceFails_ConstructorStillCompletes) { Fixture f; f.SwapChainPanel->CreateCoreIndependentInputSourceMethod.SetExpectedCalls(1, [=] (CoreInputDeviceTypes, ICoreInputSourceBase**) { // This is what happens when // CreateCoreIndependentInputSource is called from inside // the designer. return E_UNEXPECTED; }); f.CreateThread(); // If this test fails then CreateThread will never return. } }; TEST_CLASS(CanvasGameLoopTests) { // // This repros a specific issue that may be the root cause of // https://github.com/Microsoft/Win2D/issues/338 that happens when // ScheduleTick runs something on a dispatcher such that the IAsyncAction // completes before it gets a chance to call put_Completed. This can result // in a mutex being taken recursively. // TEST_METHOD_EX(CanvasGameLoop_When_TickCompletes_BeforeCompletionHandlerRegistered_NothingBadHappens) { MockGameLoopClient gameLoopClient; class MockGameLoopThread : public IGameLoopThread { bool m_first; public: MockGameLoopThread() : m_first(true) {} virtual ComPtr<IAsyncAction> RunAsync(IDispatchedHandler* handler) override { auto action = Make<AnimatedControlAsyncAction>(handler); if (m_first) { action->InvokeAndFireCompletion(); m_first = false; } return action; } virtual void StartDispatcher() override {} virtual void StopDispatcher() override {} virtual bool HasThreadAccess() override { return true; } }; CanvasGameLoop gameLoop(&gameLoopClient, std::make_unique<MockGameLoopThread>()); CanvasSwapChain* anySwapChain{}; bool anyAreResourcesCreated{}; gameLoop.StartTickLoop(anySwapChain, anyAreResourcesCreated); } }; #endif
5,200
892
<filename>advisories/unreviewed/2022/05/GHSA-7rvr-gh9x-q4mq/GHSA-7rvr-gh9x-q4mq.json { "schema_version": "1.2.0", "id": "GHSA-7rvr-gh9x-q4mq", "modified": "2022-05-01T07:38:08Z", "published": "2022-05-01T07:38:08Z", "aliases": [ "CVE-2006-6458" ], "details": "The Trend Micro scan engine before 8.320 for Windows and before 8.150 on HP-UX and AIX, as used in Trend Micro PC Cillin - Internet Security 2006, Office Scan 7.3, and Server Protect 5.58, allows remote attackers to cause a denial of service (CPU consumption and system hang) via a malformed RAR archive with an Archive Header section with the head_size and pack_size fields set to zero, which triggers an infinite loop.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-6458" }, { "type": "WEB", "url": "http://labs.idefense.com/intelligence/vulnerabilities/display.php?id=439" }, { "type": "WEB", "url": "http://secunia.com/advisories/23321" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/21509" }, { "type": "WEB", "url": "http://www.vupen.com/english/advisories/2006/4918" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
596
2,338
<reponame>mkinsner/llvm /* * Copyright 2019 Cerebras Systems * * Use of this software is governed by the MIT license * * Written by <NAME>, * Cerebras Systems, 175 S San Antonio Rd, Los Altos, CA, USA */ #define xFN(TYPE,NAME) TYPE ## _ ## NAME #define FN(TYPE,NAME) xFN(TYPE,NAME) /* Return a list of minima (maxima if "max" is set) * for each of the expressions in "f" over their (shared) domain. * * An element in the list is infinity or negative infinity if the optimal * value of the corresponding expression is unbounded and * NaN if the domain of the expression is empty. * * Iterate over all the expressions in "f" and collect the results. */ static __isl_give isl_multi_val *FN(TYPE,opt_multi_val)(__isl_take TYPE *f, int max) { int i; isl_size n; isl_space *space; isl_multi_val *mv; n = FN(TYPE,dim)(f, isl_dim_out); if (n < 0) f = FN(TYPE,free)(f); if (!f) return NULL; space = isl_space_range(FN(TYPE,get_space)(f)); space = isl_space_drop_all_params(space); mv = isl_multi_val_zero(space); for (i = 0; i < n; ++i) { isl_val *v; isl_pw_aff *pa; pa = FN(TYPE,get_pw_aff)(f, i); v = isl_pw_aff_opt_val(pa, max); mv = isl_multi_val_set_val(mv, i, v); } FN(TYPE,free)(f); return mv; } /* Return a list of minima * for each of the expressions in "f" over their (shared) domain. * * An element in the list is negative infinity if the optimal * value of the corresponding expression is unbounded and * NaN if the domain of the expression is empty. */ __isl_give isl_multi_val *FN(TYPE,min_multi_val)(__isl_take TYPE *f) { return FN(TYPE,opt_multi_val)(f, 0); } /* Return a list of maxima * for each of the expressions in "f" over their (shared) domain. * * An element in the list is infinity if the optimal * value of the corresponding expression is unbounded and * NaN if the domain of the expression is empty. */ __isl_give isl_multi_val *FN(TYPE,max_multi_val)(__isl_take TYPE *f) { return FN(TYPE,opt_multi_val)(f, 1); }
738
343
<gh_stars>100-1000 package org.cronhub.managesystem.commons.utils; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.apache.struts2.ServletActionContext; import org.cronhub.managesystem.commons.params.Params; /*** * 利用{"equal":{"state":"success","mode":"true"},"like":{"ip":"230.91"}}生成形如WHERE state = 'success' AND mode = 'true' AND ip LIKE '%230.91%'这样的SQL * @author mac * */ public class FilterSqlGenerater { public static final String EQUAL = "equal"; public static final String LIKE = "like"; public static final String CUSTOM = "custom"; public static final String genWhereSql(){ if(ServletActionContext.getRequest().getParameterMap().containsKey(Params.FILTER)){ String filterJson = ServletActionContext.getRequest().getParameter(Params.FILTER); return genWhereSql(filterJson); } return ""; } public static final String genWhereSql(String filter_json_string){ JSONObject filter_jsons = JSONObject.fromObject(filter_json_string); return genWhereSql(filter_jsons); } // public static final String genWhereSql(JSONArray filter_jsons){ // StringBuilder whereSql = new StringBuilder(" WHERE "); // List<String> eachStmt = new ArrayList<String>(); // for(Iterator iter= filter_jsons.iterator();iter.hasNext();){ // JSONArray perList = (JSONArray)iter.next(); // Object[] perArray = perList.toArray(); // if(perArray[0].toString().equals(FilterSqlGenerater.EQUAL)){ // JSONObject equalJson = perList.getJSONObject(1); // for(Object key : equalJson.keySet()){ // eachStmt.add(String.format("%s = '%s'", key.toString(),equalJson.get(key))); // } // }else if(perArray[0].toString().equals(FilterSqlGenerater.LIKE)){ // JSONObject likeJson = perList.getJSONObject(1); // for(Object key : likeJson.keySet()){ // eachStmt.add(key.toString()+" LIKE '%"+likeJson.get(key).toString()+"%'"); // } // } // } // whereSql.append(StringUtils.join(eachStmt," AND ")).append(" "); // return whereSql.toString(); // } public static final String genWhereSql(JSONObject filter_json){ StringBuilder whereSql = new StringBuilder(" WHERE "); List<String> eachStmt = new ArrayList<String>(); if(filter_json.containsKey(FilterSqlGenerater.CUSTOM)){ JSONObject customJson = JSONObject.fromObject(filter_json.get(FilterSqlGenerater.CUSTOM)); for (Object customKey : customJson.keySet()) { String key = customKey.toString(); eachStmt.add(String.format("%s %s",key.toString(),customJson.get(customKey))); } } if (filter_json.containsKey(FilterSqlGenerater.EQUAL)) { JSONObject equalJson = JSONObject.fromObject(filter_json.get(FilterSqlGenerater.EQUAL)); for (Object equalKey : equalJson.keySet()) { String key = equalKey.toString(); eachStmt.add(String.format("%s = '%s'", key.toString(), equalJson.get(equalKey))); } } if(filter_json.containsKey(FilterSqlGenerater.LIKE)){ JSONObject likeJson = JSONObject.fromObject(filter_json.get(FilterSqlGenerater.LIKE)); for (Object likeKey : likeJson.keySet()) { String key = likeKey.toString(); eachStmt.add(key.toString()+" LIKE '%"+likeJson.get(likeKey).toString()+"%'"); } } whereSql.append(StringUtils.join(eachStmt," AND ")).append(" "); return whereSql.toString(); } public static void main(String[] args) { System.out.println(FilterSqlGenerater.genWhereSql("{\"equal\":{\"type\":1,\"live\":false},\"like\":{\"ip\":\"192\"},\"custom\":{\"end_times\":\">'3'\"}}")); } }
1,373
679
/************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "java/lang/String.hxx" #include "java/lang/Boolean.hxx" #include "java/sql/ResultSet.hxx" #include "java/math/BigDecimal.hxx" #include "java/sql/JStatement.hxx" #include "java/sql/SQLWarning.hxx" #include "java/sql/Timestamp.hxx" #include "java/sql/Array.hxx" #include "java/sql/Ref.hxx" #include "java/sql/Clob.hxx" #include "java/sql/Timestamp.hxx" #include "java/sql/Blob.hxx" #include "java/sql/ResultSetMetaData.hxx" #include "java/io/InputStream.hxx" #include "java/io/Reader.hxx" #include "java/tools.hxx" #include <comphelper/property.hxx> #include "connectivity/CommonTools.hxx" #include <cppuhelper/typeprovider.hxx> #include <comphelper/sequence.hxx> #include <com/sun/star/beans/PropertyAttribute.hpp> #include "TConnection.hxx" #include <comphelper/types.hxx> #include "connectivity/dbtools.hxx" #include "connectivity/dbexception.hxx" #include "resource/common_res.hrc" #include "resource/sharedresources.hxx" #include "java/LocalRef.hxx" #include <rtl/logfile.hxx> #include <string.h> using namespace ::comphelper; using namespace connectivity; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; IMPLEMENT_SERVICE_INFO(java_sql_ResultSet,"com.sun.star.sdbcx.JResultSet","com.sun.star.sdbc.ResultSet"); //************************************************************** //************ Class: java.sql.ResultSet //************************************************************** jclass java_sql_ResultSet::theClass = 0; java_sql_ResultSet::java_sql_ResultSet( JNIEnv * pEnv, jobject myObj, const java::sql::ConnectionLog& _rParentLogger,java_sql_Connection& _rConnection, java_sql_Statement_Base* pStmt) :java_sql_ResultSet_BASE(m_aMutex) ,java_lang_Object( pEnv, myObj ) ,OPropertySetHelper(java_sql_ResultSet_BASE::rBHelper) ,m_aLogger( _rParentLogger, java::sql::ConnectionLog::RESULTSET ) ,m_pConnection(&_rConnection) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::java_sql_ResultSet" ); SDBThreadAttach::addRef(); osl_incrementInterlockedCount(&m_refCount); if ( pStmt ) m_xStatement = *pStmt; osl_decrementInterlockedCount(&m_refCount); } // ----------------------------------------------------------------------------- java_sql_ResultSet::~java_sql_ResultSet() { if ( !java_sql_ResultSet_BASE::rBHelper.bDisposed && !java_sql_ResultSet_BASE::rBHelper.bInDispose ) { // increment ref count to prevent double call of Dtor osl_incrementInterlockedCount( &m_refCount ); dispose(); } } jclass java_sql_ResultSet::getMyClass() const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getMyClass" ); // die Klasse muss nur einmal geholt werden, daher statisch if( !theClass ) theClass = findMyClass("java/sql/ResultSet"); return theClass; } // ------------------------------------------------------------------------- void java_sql_ResultSet::disposing(void) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::disposing" ); OPropertySetHelper::disposing(); ::osl::MutexGuard aGuard(m_aMutex); m_xMetaData.clear(); if( object ) { SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); callVoidMethod("close",mID); clearObject(*t.pEnv); } SDBThreadAttach::releaseRef(); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Any SAL_CALL java_sql_ResultSet::queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::queryInterface" ); ::com::sun::star::uno::Any aRet = OPropertySetHelper::queryInterface(rType); return aRet.hasValue() ? aRet : java_sql_ResultSet_BASE::queryInterface(rType); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL java_sql_ResultSet::getTypes( ) throw(::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getTypes" ); ::cppu::OTypeCollection aTypes( ::getCppuType( (const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet > *)0 ), ::getCppuType( (const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XFastPropertySet > *)0 ), ::getCppuType( (const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > *)0 )); return ::comphelper::concatSequences(aTypes.getTypes(),java_sql_ResultSet_BASE::getTypes()); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL java_sql_ResultSet::findColumn( const ::rtl::OUString& columnName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::findColumn" ); static jmethodID mID(NULL); return callIntMethodWithStringArg("findColumn",mID,columnName); } // ------------------------------------------------------------------------- Reference< ::com::sun::star::io::XInputStream > SAL_CALL java_sql_ResultSet::getBinaryStream( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getBinaryStream" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getBinaryStream","(I)Ljava/io/InputStream;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_io_InputStream( t.pEnv, out ); } // ------------------------------------------------------------------------- Reference< ::com::sun::star::io::XInputStream > SAL_CALL java_sql_ResultSet::getCharacterStream( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getCharacterStream" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getCharacterStream","(I)Ljava/io/Reader;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_io_Reader( t.pEnv, out ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::getBoolean( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getBoolean" ); static jmethodID mID(NULL); return callBooleanMethodWithIntArg( "getBoolean", mID,columnIndex ); } // ------------------------------------------------------------------------- sal_Int8 SAL_CALL java_sql_ResultSet::getByte( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getByte" ); static jmethodID mID(NULL); jbyte (JNIEnv::*pCallMethod)( jobject obj, jmethodID methodID, ... ) = &JNIEnv::CallByteMethod; return callMethodWithIntArg<jbyte>(pCallMethod,"getByte","(I)B",mID,columnIndex); } // ------------------------------------------------------------------------- Sequence< sal_Int8 > SAL_CALL java_sql_ResultSet::getBytes( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getBytes" ); Sequence< sal_Int8 > aSeq; SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jbyteArray out = (jbyteArray)callObjectMethodWithIntArg(t.pEnv,"getBytes","(I)[B", mID, columnIndex); if (out) { jboolean p = sal_False; aSeq.realloc(t.pEnv->GetArrayLength(out)); memcpy(aSeq.getArray(),t.pEnv->GetByteArrayElements(out,&p),aSeq.getLength()); t.pEnv->DeleteLocalRef(out); } return aSeq; } // ------------------------------------------------------------------------- ::com::sun::star::util::Date SAL_CALL java_sql_ResultSet::getDate( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getDate" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getDate","(I)Ljava/sql/Date;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out ? static_cast <com::sun::star::util::Date> (java_sql_Date( t.pEnv, out )) : ::com::sun::star::util::Date(); } // ------------------------------------------------------------------------- double SAL_CALL java_sql_ResultSet::getDouble( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getDouble" ); static jmethodID mID(NULL); jdouble (JNIEnv::*pCallMethod)( jobject obj, jmethodID methodID, ... ) = &JNIEnv::CallDoubleMethod; return callMethodWithIntArg<double>(pCallMethod,"getDouble","(I)D",mID,columnIndex); } // ------------------------------------------------------------------------- float SAL_CALL java_sql_ResultSet::getFloat( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getFloat" ); static jmethodID mID(NULL); jfloat (JNIEnv::*pCallMethod)( jobject obj, jmethodID methodID, ... ) = &JNIEnv::CallFloatMethod; return callMethodWithIntArg<jfloat>(pCallMethod,"getFloat","(I)F",mID,columnIndex); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL java_sql_ResultSet::getInt( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getInt" ); static jmethodID mID(NULL); return callIntMethodWithIntArg("getInt",mID,columnIndex); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL java_sql_ResultSet::getRow( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getRow" ); static jmethodID mID(NULL); return callIntMethod("getRow",mID); } // ------------------------------------------------------------------------- sal_Int64 SAL_CALL java_sql_ResultSet::getLong( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getLong" ); static jmethodID mID(NULL); jlong (JNIEnv::*pCallMethod)( jobject obj, jmethodID methodID, ... ) = &JNIEnv::CallLongMethod; return callMethodWithIntArg<jlong>(pCallMethod,"getLong","(I)J",mID,columnIndex); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL java_sql_ResultSet::getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getMetaData" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethod(t.pEnv,"getMetaData","()Ljava/sql/ResultSetMetaData;", mID); return out==0 ? 0 : new java_sql_ResultSetMetaData( t.pEnv, out, m_aLogger,*m_pConnection ); } // ------------------------------------------------------------------------- Reference< XArray > SAL_CALL java_sql_ResultSet::getArray( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getArray" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getArray","(I)Ljava/sql/Array;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_sql_Array( t.pEnv, out ); } // ------------------------------------------------------------------------- Reference< XClob > SAL_CALL java_sql_ResultSet::getClob( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getClob" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getClob","(I)Ljava/sql/Clob;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_sql_Clob( t.pEnv, out ); } // ------------------------------------------------------------------------- Reference< XBlob > SAL_CALL java_sql_ResultSet::getBlob( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getBlob" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getBlob","(I)Ljava/sql/Blob;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_sql_Blob( t.pEnv, out ); } // ------------------------------------------------------------------------- Reference< XRef > SAL_CALL java_sql_ResultSet::getRef( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getRef" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getRef","(I)Ljava/sql/Ref;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out==0 ? 0 : new java_sql_Ref( t.pEnv, out ); } // ------------------------------------------------------------------------- Any SAL_CALL java_sql_ResultSet::getObject( sal_Int32 columnIndex, const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getObject" ); jobject out(0); Any aRet; SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); { jvalue args[2]; // Parameter konvertieren args[0].i = (sal_Int32)columnIndex; args[1].l = convertTypeMapToJavaMap(t.pEnv,typeMap); // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(I)Ljava/lang/Object;"; static const char * cMethodName = "getObject"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } out = t.pEnv->CallObjectMethodA( object, mID, args); t.pEnv->DeleteLocalRef((jstring)args[1].l); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); // und aufraeumen if ( out ) { if ( t.pEnv->IsInstanceOf(out,java_lang_String::st_getMyClass()) ) { java_lang_String aVal(t.pEnv,out); aRet <<= (::rtl::OUString)aVal; } else if ( t.pEnv->IsInstanceOf(out,java_lang_Boolean::st_getMyClass()) ) { java_lang_Boolean aVal(t.pEnv,out); static jmethodID methodID = NULL; aRet <<= aVal.callBooleanMethod("booleanValue",methodID); } else if ( t.pEnv->IsInstanceOf(out,java_sql_Date::st_getMyClass()) ) { java_sql_Date aVal(t.pEnv,out); aRet <<= (::com::sun::star::util::Date)aVal; } else if ( t.pEnv->IsInstanceOf(out,java_sql_Time::st_getMyClass()) ) { java_sql_Time aVal(t.pEnv,out); aRet <<= (::com::sun::star::util::Time)aVal; } else if ( t.pEnv->IsInstanceOf(out,java_sql_Timestamp::st_getMyClass()) ) { java_sql_Timestamp aVal(t.pEnv,out); aRet <<= (::com::sun::star::util::DateTime)aVal; } else t.pEnv->DeleteLocalRef(out); } } //t.pEnv return aRet; } // ------------------------------------------------------------------------- sal_Int16 SAL_CALL java_sql_ResultSet::getShort( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getShort" ); static jmethodID mID(NULL); jshort (JNIEnv::*pCallMethod)( jobject obj, jmethodID methodID, ... ) = &JNIEnv::CallShortMethod; return callMethodWithIntArg<jshort>(pCallMethod,"getShort","(I)S",mID,columnIndex); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL java_sql_ResultSet::getString( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>.com", "java_sql_ResultSet::getString" ); static jmethodID mID(NULL); return callStringMethodWithIntArg("getString",mID,columnIndex); } // ------------------------------------------------------------------------- ::com::sun::star::util::Time SAL_CALL java_sql_ResultSet::getTime( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getTime" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getTime","(I)Ljava/sql/Time;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out ? static_cast <com::sun::star::util::Time> (java_sql_Time( t.pEnv, out )) : ::com::sun::star::util::Time(); } // ------------------------------------------------------------------------- ::com::sun::star::util::DateTime SAL_CALL java_sql_ResultSet::getTimestamp( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getTimestamp" ); SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!"); static jmethodID mID(NULL); jobject out = callObjectMethodWithIntArg(t.pEnv,"getTimestamp","(I)Ljava/sql/Timestamp;", mID, columnIndex); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! return out ? static_cast <com::sun::star::util::DateTime> (java_sql_Timestamp( t.pEnv, out )) : ::com::sun::star::util::DateTime(); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::isAfterLast( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::isAfterLast" ); static jmethodID mID(NULL); return callBooleanMethod( "isAfterLast", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::isFirst( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::isFirst" ); static jmethodID mID(NULL); return callBooleanMethod( "isFirst", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::isLast( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::isLast" ); static jmethodID mID(NULL); return callBooleanMethod( "isLast", mID ); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::beforeFirst( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::beforeFirst" ); static jmethodID mID(NULL); callVoidMethod("beforeFirst",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::afterLast( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::afterLast" ); static jmethodID mID(NULL); callVoidMethod("afterLast",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>.<EMAIL>", "java_sql_ResultSet::close" ); dispose(); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::first( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::first" ); static jmethodID mID(NULL); return callBooleanMethod( "first", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::last( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::last" ); static jmethodID mID(NULL); return callBooleanMethod( "last", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::absolute( sal_Int32 row ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::absolute" ); static jmethodID mID(NULL); return callBooleanMethodWithIntArg( "absolute", mID,row ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::relative( sal_Int32 row ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::relative" ); static jmethodID mID(NULL); return callBooleanMethodWithIntArg( "relative", mID,row ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::previous( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::previous" ); static jmethodID mID(NULL); return callBooleanMethod( "previous", mID ); } // ------------------------------------------------------------------------- Reference< XInterface > SAL_CALL java_sql_ResultSet::getStatement( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getStatement" ); return m_xStatement; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::rowDeleted( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::rowDeleted" ); static jmethodID mID(NULL); return callBooleanMethod( "rowDeleted", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::rowInserted( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::rowInserted" ); static jmethodID mID(NULL); return callBooleanMethod( "rowInserted", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::rowUpdated( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::rowUpdated" ); static jmethodID mID(NULL); return callBooleanMethod( "rowUpdated", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::isBeforeFirst( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::isBeforeFirst" ); static jmethodID mID(NULL); return callBooleanMethod( "isBeforeFirst", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::next( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::next" ); static jmethodID mID(NULL); return callBooleanMethod( "next", mID ); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL java_sql_ResultSet::wasNull( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::wasNull" ); static jmethodID mID(NULL); return callBooleanMethod( "wasNull", mID ); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::cancel( ) throw(::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::cancel" ); static jmethodID mID(NULL); callVoidMethod("cancel",mID); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::clearWarnings" ); static jmethodID mID(NULL); callVoidMethod("clearWarnings",mID); } // ------------------------------------------------------------------------- ::com::sun::star::uno::Any SAL_CALL java_sql_ResultSet::getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getWarnings" ); SDBThreadAttach t; static jmethodID mID(NULL); jobject out = callObjectMethod(t.pEnv,"getWarnings","()Ljava/sql/SQLWarning;", mID); // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!! if( out ) { java_sql_SQLWarning_BASE warn_base( t.pEnv, out ); return makeAny( static_cast< starsdbc::SQLException >( java_sql_SQLWarning(warn_base,*this))); } return ::com::sun::star::uno::Any(); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::insertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::insertRow" ); static jmethodID mID(NULL); callVoidMethod("insertRow",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateRow" ); static jmethodID mID(NULL); callVoidMethod("updateRow",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::deleteRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::deleteRow" ); static jmethodID mID(NULL); callVoidMethod("deleteRow",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::cancelRowUpdates( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::cancelRowUpdates" ); static jmethodID mID(NULL); callVoidMethod("cancelRowUpdates",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::moveToInsertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::moveToInsertRow" ); static jmethodID mID(NULL); callVoidMethod("moveToInsertRow",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::moveToCurrentRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::moveToCurrentRow" ); static jmethodID mID(NULL); callVoidMethod("moveToCurrentRow",mID); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateNull( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateNull" ); static jmethodID mID(NULL); callVoidMethodWithIntArg("updateNull",mID,columnIndex); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateBoolean( sal_Int32 columnIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateBoolean" ); static jmethodID mID(NULL); callVoidMethod("updateBoolean", "(IZ)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateByte( sal_Int32 columnIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateByte" ); static jmethodID mID(NULL); callVoidMethod("updateByte", "(IB)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateShort( sal_Int32 columnIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateShort" ); static jmethodID mID(NULL); callVoidMethod("updateShort", "(IS)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateInt( sal_Int32 columnIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateInt" ); static jmethodID mID(NULL); callVoidMethod("updateInt", "(II)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateLong( sal_Int32 columnIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateLong" ); static jmethodID mID(NULL); callVoidMethod("updateLong", "(IJ)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- // ----------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateFloat( sal_Int32 columnIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateFloat" ); static jmethodID mID(NULL); callVoidMethod("updateFloat", "(IF)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateDouble( sal_Int32 columnIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateDouble" ); static jmethodID mID(NULL); callVoidMethod("updateDouble", "(ID)V", mID, columnIndex, x); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateString( sal_Int32 columnIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateString" ); SDBThreadAttach t; { // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(ILjava/lang/String;)V"; static const char * cMethodName = "updateString"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } { // Parameter konvertieren jdbc::LocalRef< jstring > str( t.env(),convertwchar_tToJavaString(t.pEnv,x)); t.pEnv->CallVoidMethod( object, mID,columnIndex,str.get()); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); } } } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateBytes( sal_Int32 columnIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateBytes" ); SDBThreadAttach t; { // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(I[B)V"; static const char * cMethodName = "updateBytes"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } { jbyteArray aArray = t.pEnv->NewByteArray(x.getLength()); t.pEnv->SetByteArrayRegion(aArray,0,x.getLength(),(jbyte*)x.getConstArray()); // Parameter konvertieren t.pEnv->CallVoidMethod( object, mID,columnIndex,aArray); t.pEnv->DeleteLocalRef(aArray); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); } } } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateDate( sal_Int32 columnIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateDate" ); java_sql_Date aD(x); static jmethodID mID(NULL); callVoidMethod("updateDate", "(ILjava/sql/Date;)V", mID, columnIndex, aD.getJavaObject()); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateTime( sal_Int32 columnIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateTime" ); java_sql_Time aD(x); static jmethodID mID(NULL); callVoidMethod("updateTime", "(ILjava/sql/Time;)V", mID, columnIndex, aD.getJavaObject()); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateTimestamp( sal_Int32 columnIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateTimestamp" ); java_sql_Timestamp aD(x); static jmethodID mID(NULL); callVoidMethod("updateTimestamp", "(ILjava/sql/Timestamp;)V", mID, columnIndex, aD.getJavaObject()); } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateBinaryStream( sal_Int32 columnIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateBinaryStream" ); try { SDBThreadAttach t; { // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(ILjava/io/InputStream;I)V"; static const char * cMethodName = "updateBinaryStream"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } { // Parameter konvertieren jobject obj = createByteInputStream(x,length); t.pEnv->CallVoidMethod( object, mID, columnIndex,obj,length); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); } } } catch(Exception) { ::dbtools::throwFeatureNotImplementedException( "XRowUpdate::updateBinaryStream", *this ); } } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateCharacterStream( sal_Int32 columnIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateCharacterStream" ); try { SDBThreadAttach t; { // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(ILjava/io/Reader;I)V"; static const char * cMethodName = "updateCharacterStream"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } { // Parameter konvertieren jobject obj = createCharArrayReader(x,length); t.pEnv->CallVoidMethod( object, mID, columnIndex,obj,length); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); } } } catch(Exception) { ::dbtools::throwFeatureNotImplementedException( "XRowUpdate::updateCharacterStream", *this ); } } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateObject( sal_Int32 columnIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateObject" ); if(!::dbtools::implUpdateObject(this,columnIndex,x)) { ::connectivity::SharedResources aResources; const ::rtl::OUString sError( aResources.getResourceStringWithSubstitution( STR_UNKNOWN_COLUMN_TYPE, "$position$", ::rtl::OUString::valueOf(columnIndex) ) ); ::dbtools::throwGenericSQLException(sError,*this); } } // ------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::updateNumericObject( sal_Int32 columnIndex, const ::com::sun::star::uno::Any& x, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::updateNumericObject" ); // OSL_ENSURE(0,"java_sql_ResultSet::updateNumericObject: NYI"); try { SDBThreadAttach t; { // temporaere Variable initialisieren // Java-Call absetzen static jmethodID mID(NULL); if ( !mID ) { static const char * cSignature = "(ILjava/lang/Object;I)V"; static const char * cMethodName = "updateObject"; obtainMethodId(t.pEnv, cMethodName,cSignature, mID); } { // Parameter konvertieren double nTemp = 0.0; ::std::auto_ptr<java_math_BigDecimal> pBigDecimal; if ( x >>= nTemp) { pBigDecimal.reset(new java_math_BigDecimal(nTemp)); } else pBigDecimal.reset(new java_math_BigDecimal(::comphelper::getString(x))); //obj = convertwchar_tToJavaString(t.pEnv,::comphelper::getString(x)); t.pEnv->CallVoidMethod( object, mID, columnIndex,pBigDecimal->getJavaObject(),scale); ThrowLoggedSQLException( m_aLogger, t.pEnv, *this ); } } } catch(Exception) { updateObject( columnIndex,x); } } //------------------------------------------------------------------------------ sal_Int32 java_sql_ResultSet::getResultSetConcurrency() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getResultSetConcurrency" ); static jmethodID mID(NULL); return callIntMethod("getConcurrency",mID,true); } //------------------------------------------------------------------------------ sal_Int32 java_sql_ResultSet::getResultSetType() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getResultSetType" ); static jmethodID mID(NULL); return callIntMethod("getType",mID,true); } //------------------------------------------------------------------------------ sal_Int32 java_sql_ResultSet::getFetchDirection() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getFetchDirection" ); static jmethodID mID(NULL); return callIntMethod("getFetchDirection",mID,true); } //------------------------------------------------------------------------------ sal_Int32 java_sql_ResultSet::getFetchSize() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getFetchSize" ); static jmethodID mID(NULL); return callIntMethod("getFetchSize",mID,true); } //------------------------------------------------------------------------------ ::rtl::OUString java_sql_ResultSet::getCursorName() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "Ocke.<EMAIL>", "java_sql_ResultSet::getCursorName" ); static jmethodID mID(NULL); return callStringMethod("getCursorName",mID); } //------------------------------------------------------------------------------ void java_sql_ResultSet::setFetchDirection(sal_Int32 _par0) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::setFetchDirection" ); static jmethodID mID(NULL); callVoidMethodWithIntArg("setFetchDirection",mID,_par0,true); } //------------------------------------------------------------------------------ void SAL_CALL java_sql_ResultSet::refreshRow( ) throw(SQLException, RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::refreshRow" ); static jmethodID mID(NULL); callVoidMethod("refreshRow",mID); } //------------------------------------------------------------------------------ void java_sql_ResultSet::setFetchSize(sal_Int32 _par0) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::setFetchSize" ); static jmethodID mID(NULL); callVoidMethodWithIntArg("setFetchSize",mID,_par0,true); } // ------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper* java_sql_ResultSet::createArrayHelper( ) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::createArrayHelper" ); Sequence< Property > aProps(5); Property* pProperties = aProps.getArray(); sal_Int32 nPos = 0; DECL_PROP1IMPL(CURSORNAME, ::rtl::OUString) PropertyAttribute::READONLY); DECL_PROP0(FETCHDIRECTION, sal_Int32); DECL_PROP0(FETCHSIZE, sal_Int32); DECL_PROP1IMPL(RESULTSETCONCURRENCY,sal_Int32) PropertyAttribute::READONLY); DECL_PROP1IMPL(RESULTSETTYPE, sal_Int32) PropertyAttribute::READONLY); return new ::cppu::OPropertyArrayHelper(aProps); } // ------------------------------------------------------------------------- ::cppu::IPropertyArrayHelper & java_sql_ResultSet::getInfoHelper() { //RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getInfoHelper" ); return *const_cast<java_sql_ResultSet*>(this)->getArrayHelper(); } // ------------------------------------------------------------------------- sal_Bool java_sql_ResultSet::convertFastPropertyValue( ::com::sun::star::uno::Any & rConvertedValue, ::com::sun::star::uno::Any & rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::lang::IllegalArgumentException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::convertFastPropertyValue" ); sal_Bool bRet = sal_False; switch(nHandle) { case PROPERTY_ID_CURSORNAME: case PROPERTY_ID_RESULTSETCONCURRENCY: case PROPERTY_ID_RESULTSETTYPE: throw ::com::sun::star::lang::IllegalArgumentException(); case PROPERTY_ID_FETCHDIRECTION: bRet = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchDirection()); break; case PROPERTY_ID_FETCHSIZE: bRet = ::comphelper::tryPropertyValue(rConvertedValue, rOldValue, rValue, getFetchSize()); default: ; } return bRet; } // ------------------------------------------------------------------------- void java_sql_ResultSet::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue ) throw (::com::sun::star::uno::Exception) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::setFastPropertyValue_NoBroadcast" ); switch(nHandle) { case PROPERTY_ID_CURSORNAME: case PROPERTY_ID_RESULTSETCONCURRENCY: case PROPERTY_ID_RESULTSETTYPE: throw ::com::sun::star::uno::Exception(); case PROPERTY_ID_FETCHDIRECTION: setFetchDirection(comphelper::getINT32(rValue)); break; case PROPERTY_ID_FETCHSIZE: setFetchSize(comphelper::getINT32(rValue)); break; default: ; } } // ------------------------------------------------------------------------- void java_sql_ResultSet::getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getFastPropertyValue" ); try { switch(nHandle) { case PROPERTY_ID_CURSORNAME: rValue <<= getCursorName(); break; case PROPERTY_ID_RESULTSETCONCURRENCY: rValue <<= getResultSetConcurrency(); break; case PROPERTY_ID_RESULTSETTYPE: rValue <<= getResultSetType(); break; case PROPERTY_ID_FETCHDIRECTION: rValue <<= getFetchDirection(); break; case PROPERTY_ID_FETCHSIZE: rValue <<= getFetchSize(); break; } } catch(Exception&) { } } // ----------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::acquire() throw() { java_sql_ResultSet_BASE::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL java_sql_ResultSet::release() throw() { java_sql_ResultSet_BASE::release(); } // ----------------------------------------------------------------------------- ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL java_sql_ResultSet::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) { RTL_LOGFILE_CONTEXT_AUTHOR( aLogger, "jdbc", "<EMAIL>", "java_sql_ResultSet::getPropertySetInfo" ); return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); } // -----------------------------------------------------------------------------
18,163
315
<filename>include/Module/Channel/AWGN/Channel_AWGN_LLR.hpp /*! * \file * \brief Class module::Channel_AWGN_LLR. */ #ifndef CHANNEL_AWGN_LLR_HPP_ #define CHANNEL_AWGN_LLR_HPP_ #include <memory> #include "Tools/Algo/Draw_generator/Gaussian_noise_generator/Gaussian_noise_generator.hpp" #include "Module/Channel/Channel.hpp" namespace aff3ct { namespace module { template <typename R = float> class Channel_AWGN_LLR : public Channel<R> { private: const bool add_users; std::shared_ptr<tools::Gaussian_gen<R>> gaussian_generator; public: Channel_AWGN_LLR(const int N, const tools::Gaussian_gen<R> &noise_generator, const bool add_users = false); explicit Channel_AWGN_LLR(const int N, const tools::Gaussian_noise_generator_implem implem = tools::Gaussian_noise_generator_implem::STD, const int seed = 0, const bool add_users = false); virtual ~Channel_AWGN_LLR() = default; virtual Channel_AWGN_LLR<R>* clone() const; void set_seed(const int seed); protected: void _add_noise(const float *CP, const R *X_N, R *Y_N, const size_t frame_id); virtual void deep_copy(const Channel_AWGN_LLR<R>& m); }; } } #endif /* CHANNEL_AWGN_LLR_HPP_ */
569
1,144
// SPDX-License-Identifier: GPL-2.0+ /* * (C) Copyright 2002 * Sysgo Real-Time Solutions, GmbH <www.elinos.com> * <NAME> <<EMAIL>> * * (C) Copyright 2002 * <NAME>, ELSOFT AG, <<EMAIL>> * * (C) Copyright 2003 * Texas Instruments, <www.ti.com> * <NAME> <<EMAIL>> * * (C) Copyright 2004 * ARM Ltd. * <NAME>, <<EMAIL>> */ #include <common.h> #include <malloc.h> #include <errno.h> #include <netdev.h> #include <asm/io.h> #include <asm/mach-types.h> #include <asm/arch/systimer.h> #include <asm/arch/sysctrl.h> #include <asm/arch/wdt.h> #include "../drivers/mmc/arm_pl180_mmci.h" static struct systimer *systimer_base = (struct systimer *)V2M_TIMER01; static struct sysctrl *sysctrl_base = (struct sysctrl *)SCTL_BASE; static void flash__init(void); static void vexpress_timer_init(void); DECLARE_GLOBAL_DATA_PTR; #if defined(CONFIG_SHOW_BOOT_PROGRESS) void show_boot_progress(int progress) { printf("Boot reached stage %d\n", progress); } #endif static inline void delay(ulong loops) { __asm__ volatile ("1:\n" "subs %0, %1, #1\n" "bne 1b" : "=r" (loops) : "0" (loops)); } int board_init(void) { gd->bd->bi_boot_params = LINUX_BOOT_PARAM_ADDR; gd->bd->bi_arch_number = MACH_TYPE_VEXPRESS; gd->flags = 0; icache_enable(); flash__init(); vexpress_timer_init(); return 0; } int board_eth_init(bd_t *bis) { int rc = 0; #ifdef CONFIG_SMC911X rc = smc911x_initialize(0, CONFIG_SMC911X_BASE); #endif return rc; } int cpu_mmc_init(bd_t *bis) { int rc = 0; (void) bis; #ifdef CONFIG_ARM_PL180_MMCI struct pl180_mmc_host *host; struct mmc *mmc; host = malloc(sizeof(struct pl180_mmc_host)); if (!host) return -ENOMEM; memset(host, 0, sizeof(*host)); strcpy(host->name, "MMC"); host->base = (struct sdi_registers *)CONFIG_ARM_PL180_MMCI_BASE; host->pwr_init = INIT_PWR; host->clkdiv_init = SDI_CLKCR_CLKDIV_INIT_V1 | SDI_CLKCR_CLKEN; host->voltages = VOLTAGE_WINDOW_MMC; host->caps = 0; host->clock_in = ARM_MCLK; host->clock_min = ARM_MCLK / (2 * (SDI_CLKCR_CLKDIV_INIT_V1 + 1)); host->clock_max = CONFIG_ARM_PL180_MMCI_CLOCK_FREQ; rc = arm_pl180_mmci_init(host, &mmc); #endif return rc; } static void flash__init(void) { /* Setup the sytem control register to allow writing to flash */ writel(readl(&sysctrl_base->scflashctrl) | VEXPRESS_FLASHPROG_FLVPPEN, &sysctrl_base->scflashctrl); } int dram_init(void) { gd->ram_size = get_ram_size((long *)CONFIG_SYS_SDRAM_BASE, PHYS_SDRAM_1_SIZE); return 0; } int dram_init_banksize(void) { gd->bd->bi_dram[0].start = PHYS_SDRAM_1; gd->bd->bi_dram[0].size = get_ram_size((long *)PHYS_SDRAM_1, PHYS_SDRAM_1_SIZE); gd->bd->bi_dram[1].start = PHYS_SDRAM_2; gd->bd->bi_dram[1].size = get_ram_size((long *)PHYS_SDRAM_2, PHYS_SDRAM_2_SIZE); return 0; } /* * Start timer: * Setup a 32 bit timer, running at 1KHz * Versatile Express Motherboard provides 1 MHz timer */ static void vexpress_timer_init(void) { /* * Set clock frequency in system controller: * VEXPRESS_REFCLK is 32KHz * VEXPRESS_TIMCLK is 1MHz */ writel(SP810_TIMER0_ENSEL | SP810_TIMER1_ENSEL | SP810_TIMER2_ENSEL | SP810_TIMER3_ENSEL | readl(&sysctrl_base->scctrl), &sysctrl_base->scctrl); /* * Set Timer0 to be: * Enabled, free running, no interrupt, 32-bit, wrapping */ writel(SYSTIMER_RELOAD, &systimer_base->timer0load); writel(SYSTIMER_RELOAD, &systimer_base->timer0value); writel(SYSTIMER_EN | SYSTIMER_32BIT | readl(&systimer_base->timer0control), &systimer_base->timer0control); } int v2m_cfg_write(u32 devfn, u32 data) { /* Configuration interface broken? */ u32 val; devfn |= SYS_CFG_START | SYS_CFG_WRITE; val = readl(V2M_SYS_CFGSTAT); writel(val & ~SYS_CFG_COMPLETE, V2M_SYS_CFGSTAT); writel(data, V2M_SYS_CFGDATA); writel(devfn, V2M_SYS_CFGCTRL); do { val = readl(V2M_SYS_CFGSTAT); } while (val == 0); return !!(val & SYS_CFG_ERR); } /* Use the ARM Watchdog System to cause reset */ void reset_cpu(ulong addr) { if (v2m_cfg_write(SYS_CFG_REBOOT | SYS_CFG_SITE_MB, 0)) printf("Unable to reboot\n"); } void lowlevel_init(void) { } ulong get_board_rev(void){ return readl((u32 *)SYS_ID); } #ifdef CONFIG_ARMV7_NONSEC /* Setting the address at which secondary cores start from. * Versatile Express uses one address for all cores, so ignore corenr */ void smp_set_core_boot_addr(unsigned long addr, int corenr) { /* The SYSFLAGS register on VExpress needs to be cleared first * by writing to the next address, since any writes to the address * at offset 0 will only be ORed in */ writel(~0, CONFIG_SYSFLAGS_ADDR + 4); writel(addr, CONFIG_SYSFLAGS_ADDR); } #endif
2,066
877
<reponame>janrieke/checker-framework @interface A1 { String[] value() default {}; } @interface A2 { String[] value(); } public class Annotation { @A1({"a", "b"}) void m1() {} @A1(value = {"a", "b"}) void m2() {} @A2({"a", "b"}) void m3() {} @A2(value = {"a", "b"}) void m4() {} }
139
368
package ezvcard.util; import static ezvcard.util.TestUtils.assertEqualsAndHash; import static ezvcard.util.TestUtils.assertEqualsMethodEssentials; import static ezvcard.util.TestUtils.assertNothingIsEqual; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import java.io.UnsupportedEncodingException; import org.junit.Test; import ezvcard.util.org.apache.commons.codec.binary.Base64; /* Copyright (c) 2012-2021, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ /** * @author <NAME> */ public class DataUriTest { private final String dataString = "test-data"; private final byte[] dataBytes; { try { dataBytes = dataString.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private final String dataBase64 = Base64.encodeBase64String(dataBytes); @Test public void constructor() { DataUri uri = new DataUri("text"); assertEquals("text/plain", uri.getContentType()); assertNull(uri.getData()); assertEquals("text", uri.getText()); uri = new DataUri("text/html", "text"); assertEquals("text/html", uri.getContentType()); assertNull(uri.getData()); assertEquals("text", uri.getText()); //convert content type to lower case uri = new DataUri("TEXT/HTML", "text"); assertEquals("text/html", uri.getContentType()); assertNull(uri.getData()); assertEquals("text", uri.getText()); uri = new DataUri("image/png", dataBytes); assertEquals("image/png", uri.getContentType()); assertArrayEquals(dataBytes, uri.getData()); assertNull(uri.getText()); //convert null content type to empty string uri = new DataUri(null, dataBytes); assertEquals("", uri.getContentType()); } @Test public void copy() { DataUri uri = new DataUri("text/html", "text"); DataUri copy = new DataUri(uri); assertEquals("text/html", copy.getContentType()); assertNull(copy.getData()); assertEquals("text", copy.getText()); assertEqualsAndHash(uri, copy); uri = new DataUri("image/png", dataBytes); copy = new DataUri(uri); assertEquals("image/png", copy.getContentType()); assertArrayEquals(dataBytes, copy.getData()); assertNotSame(uri.getData(), copy.getData()); assertNull(copy.getText()); assertEqualsAndHash(uri, copy); } @Test public void parse() { DataUri expected = new DataUri("image/png", dataBytes); DataUri actual = DataUri.parse("data:image/png;base64," + dataBase64); assertEquals(expected, actual); expected = new DataUri("", dataBytes); actual = DataUri.parse("data:;base64," + dataBase64); assertEquals(expected, actual); expected = new DataUri("image/png", dataString); actual = DataUri.parse("data:image/png;charset=UTF-8;base64," + dataBase64); assertEquals(expected, actual); //order of charset and base64 matter expected = new DataUri("image/png", dataString); actual = DataUri.parse("data:image/png;base64;charset=UTF-8," + dataBase64); assertEquals(expected, actual); //ignore unknown tokens expected = new DataUri("image/png", dataString); actual = DataUri.parse("data:image/png;charset=UTF-8;foo;base64;bar," + dataBase64); assertEquals(expected, actual); expected = new DataUri("image/png", dataBase64); actual = DataUri.parse("data:image/png;charset=UTF-8," + dataBase64); assertEquals(expected, actual); expected = new DataUri("image/png", dataBase64); actual = DataUri.parse("data:image/png;charset=UTF-8;foobar," + dataBase64); assertEquals(expected, actual); } @Test public void parse_comma_in_content_type() { DataUri expected = new DataUri("text/pla", "in;base64," + dataBase64); DataUri actual = DataUri.parse("data:text/pla,in;base64," + dataBase64); assertEquals(expected, actual); } @Test(expected = IllegalArgumentException.class) public void parse_short_string() { DataUri.parse("a"); } @Test(expected = IllegalArgumentException.class) public void parse_not_a_uri() { DataUri.parse("not-valid"); } @Test(expected = IllegalArgumentException.class) public void parse_wrong_scheme() { DataUri.parse("mailto:<EMAIL>"); } @Test(expected = IllegalArgumentException.class) public void parse_no_comma() { DataUri.parse("data:text/plain;base64"); } @Test(expected = IllegalArgumentException.class) public void parse_bad_charset() { DataUri.parse("data:text/plain;charset=foobar;base64," + dataBase64); } @Test public void toString_() { DataUri uri = new DataUri("text/plain", dataBytes); assertEquals("data:text/plain;base64," + dataBase64, uri.toString()); uri = new DataUri("text/plain", dataBytes); assertEquals("data:text/plain;base64," + dataBase64, uri.toString("UTF-8")); uri = new DataUri("text/plain", dataString); assertEquals("data:text/plain," + dataString, uri.toString()); uri = new DataUri("text/plain", dataString); assertEquals("data:text/plain;charset=UTF-8;base64," + dataBase64, uri.toString("UTF-8")); uri = new DataUri("text/plain", (String) null); assertEquals("data:text/plain,", uri.toString()); } @Test(expected = IllegalArgumentException.class) public void toString_bad_charset() { DataUri uri = new DataUri("text/plain", dataString); uri.toString("foobar"); } @Test public void equals() { assertEqualsMethodEssentials(new DataUri("")); //@formatter:off assertNothingIsEqual( new DataUri("text/plain", dataBytes), new DataUri("image/png", dataBytes), new DataUri("text/plain", "other-string".getBytes()), new DataUri("text/plain", dataString), new DataUri("text/html", dataString), new DataUri("text/plain", "other-string"), new DataUri("text/plain", (String)null) ); //@formatter:on } }
2,492
835
import pytest import six import numbers pytest.importorskip("numpy") pytest.importorskip("pandas") import hypothesis from value_generator import api_and_values, series_api_and_values, dataframe_api_and_values # Check if the given value fits the defined api def fit_api(api, value): if api['type'] == 'VertaNull': return value is None if api['type'] == 'VertaBool': return isinstance(value, bool) if api['type'] == 'VertaFloat': return isinstance(value, numbers.Real) if api['type'] == 'VertaString': return isinstance(value, six.string_types) if api['type'] == 'VertaList': if not isinstance(value, list): return False for subapi, subvalue in zip(api['value'], value): if not fit_api(subapi, subvalue): return False if api['type'] == 'VertaJson': keys = sorted([v['name'] for v in api['value']]) actual_keys = sorted(list(value.keys())) if keys != actual_keys: return False subapi_dict = {v['name']: v for v in api['value']} for k in keys: if not fit_api(subapi_dict[k], value[k]): return False return True # Verify that the value generation system actually creates something that fits the api @hypothesis.given(api_and_values) def test_value_from_api(api_and_values): api, values = api_and_values for v in values: assert fit_api(api, v) @hypothesis.given(series_api_and_values) def test_series_from_api(api_and_values): api, values = api_and_values assert api['name'] == values.name for v in values.to_list(): assert fit_api(api, v) @hypothesis.given(dataframe_api_and_values) def test_dataframe_from_api(api_and_values): api, values = api_and_values assert api['name'] == '' assert api['type'] == 'VertaList' for subapi, c in zip(api['value'], values.columns): subvalues = values[c] assert subapi['name'] == subvalues.name for v in subvalues.to_list(): assert fit_api(subapi, v)
862
945
/* * 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.iotdb.db.utils; import org.apache.iotdb.commons.utils.SerializeUtils; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.TimeValuePair; import org.apache.iotdb.tsfile.read.common.BatchData; import org.apache.iotdb.tsfile.read.common.DescReadBatchData; import org.apache.iotdb.tsfile.read.common.DescReadWriteBatchData; import org.apache.iotdb.tsfile.utils.Binary; import org.apache.iotdb.tsfile.utils.TsPrimitiveType; import org.junit.Assert; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; public class SerializeUtilsTest { @Test public void serdesStringTest() { String str = "abcd%+/123\n\t"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serialize(str, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertEquals(str, SerializeUtils.deserializeString(buffer)); } @Test public void serdesStringListTest() { List<String> slist = Arrays.asList("abc", "123", "y87@", "9+&d\n"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeStringList(slist, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertEquals(slist, SerializeUtils.deserializeStringList(buffer)); } @Test public void serdesIntListTest() { List<Integer> intlist = Arrays.asList(12, 34, 567, 8910); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeIntList(intlist, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); List<Integer> anotherIntlist = new ArrayList<>(); SerializeUtils.deserializeIntList(anotherIntlist, buffer); Assert.assertEquals(intlist, anotherIntlist); } @Test public void serdesIntSetTest() { List<Integer> intlist = Arrays.asList(12, 34, 567, 8910); Set<Integer> intSet = new TreeSet<>(intlist); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeIntSet(intSet, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Set<Integer> anotherIntlist = new TreeSet<>(); SerializeUtils.deserializeIntSet(anotherIntlist, buffer); Assert.assertEquals(intSet, anotherIntlist); } @Test public void serdesINT32BatchDataTest() { BatchData batchData = new BatchData(TSDataType.INT32); int ivalue = 0; for (long time = 0; time < 10; time++) { batchData.putAnObject(time, ivalue); ivalue++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } @Test public void serdesINT64BatchDataTest() { BatchData batchData = new BatchData(TSDataType.INT64); long lvalue = 0; for (long time = 0; time < 10; time++) { batchData.putAnObject(time, lvalue); lvalue++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } @Test public void serdesFLOATBatchDataTest() { BatchData batchData = new BatchData(TSDataType.FLOAT); float fvalue = 0f; for (long time = 0; time < 10; time++) { batchData.putAnObject(time, fvalue); fvalue++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } @Test public void serdesDOUBLEBatchDataTest() { BatchData batchData = new BatchData(TSDataType.DOUBLE); double dvalue = 0d; for (long time = 0; time < 10; time++) { batchData.putAnObject(time, dvalue); dvalue++; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } @Test public void serdesBOOLEANBatchDataTest() { BatchData batchData = new BatchData(TSDataType.BOOLEAN); batchData.putAnObject(1, true); batchData.putAnObject(2, false); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } @Test public void serdesTEXTBatchDataTest() { BatchData batchData = new BatchData(TSDataType.TEXT); String svalue = ""; for (long time = 0; time < 10; time++) { batchData.putAnObject(time, Binary.valueOf(svalue)); svalue += String.valueOf(time); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(batchData, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData anotherBatch = SerializeUtils.deserializeBatchData(buffer); while (batchData.hasCurrent()) { Assert.assertEquals(batchData.currentValue(), anotherBatch.currentValue()); batchData.next(); anotherBatch.next(); } } /** This method tests SerializeUtils.serializeTVPair() and SerializeUtils.deserializeTVPair() */ @Test public void serdesTVPairTest() { List<TimeValuePair> TVPairs = new ArrayList<>(); TimeValuePair p1 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.BOOLEAN, true)); TVPairs.add(p1); TimeValuePair p2 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.INT32, 1)); TVPairs.add(p2); TimeValuePair p3 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.INT64, 1L)); TVPairs.add(p3); TimeValuePair p4 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.FLOAT, 1.0f)); TVPairs.add(p4); TimeValuePair p5 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.DOUBLE, 1.0d)); TVPairs.add(p5); TimeValuePair p6 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.TEXT, Binary.valueOf("a"))); TVPairs.add(p6); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); for (TimeValuePair tv : TVPairs) { SerializeUtils.serializeTVPair(tv, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertEquals(tv, SerializeUtils.deserializeTVPair(buffer)); baos.reset(); } } /** This method tests SerializeUtils.serializeTVPairs() and SerializeUtils.deserializeTVPairs() */ @Test public void serdesTVPairsTest() { List<List<TimeValuePair>> TVPairs = new ArrayList<>(); TimeValuePair p1 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.BOOLEAN, true)); TVPairs.add(Collections.singletonList(p1)); TimeValuePair p2 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.INT32, 1)); TVPairs.add(Collections.singletonList(p2)); TimeValuePair p3 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.INT64, 1L)); TVPairs.add(Collections.singletonList(p3)); TimeValuePair p4 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.FLOAT, 1.0f)); TVPairs.add(Collections.singletonList(p4)); TimeValuePair p5 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.DOUBLE, 1.0d)); TVPairs.add(Collections.singletonList(p5)); TimeValuePair p6 = new TimeValuePair(0, TsPrimitiveType.getByType(TSDataType.TEXT, Binary.valueOf("a"))); TVPairs.add(Collections.singletonList(p6)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); for (List<TimeValuePair> tv : TVPairs) { SerializeUtils.serializeTVPairs(tv, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertEquals(tv, SerializeUtils.deserializeTVPairs(buffer)); baos.reset(); } } /** This method tests SerializeUtils.serializeObject() and SerializeUtils.deserializeObject() */ @Test public void serdesObjectTest() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeObject(1, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertEquals(1, SerializeUtils.deserializeObject(buffer)); } /** This method tests SerializeUtils.serializeObjects() and SerializeUtils.deserializeObjects() */ @Test public void serdesObjectsTest() { Object[] objects = {1, "2", 3d}; ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeObjects(objects, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); Assert.assertArrayEquals(objects, SerializeUtils.deserializeObjects(buffer)); } /** This method tests SerializeUtils.serializeLongs() and SerializeUtils.deserializeLongs() */ @Test public void serdesLongsTest() { long[] array = {1, 10, 100, 1000, 10000}; ByteBuffer buffer = SerializeUtils.serializeLongs(array); Assert.assertArrayEquals(array, SerializeUtils.deserializeLongs(buffer)); } @Test public void descReadWriteBatchDataTest() { descReadWriteBatchDataSerializableTest(0); descReadWriteBatchDataSerializableTest(1); descReadWriteBatchDataSerializableTest(10); descReadWriteBatchDataSerializableTest(16); descReadWriteBatchDataSerializableTest(100); descReadWriteBatchDataSerializableTest(1000); descReadWriteBatchDataSerializableTest(1500); } @Test public void descReadBatchDataTest() { descReadBatchDataSerializableTest(0); descReadBatchDataSerializableTest(1); descReadBatchDataSerializableTest(10); descReadBatchDataSerializableTest(16); descReadBatchDataSerializableTest(100); descReadBatchDataSerializableTest(1000); descReadBatchDataSerializableTest(1500); } @Test public void batchDataTest() { batchDataSerializableTest(0); batchDataSerializableTest(1); batchDataSerializableTest(10); batchDataSerializableTest(16); batchDataSerializableTest(100); batchDataSerializableTest(1000); batchDataSerializableTest(1500); } // In DescReadWriteBatchData, read has the same order with descending write private void descReadWriteBatchDataSerializableTest(int dataSize) { double E = 0.00001; String debugMsg = "Data size: " + dataSize + ", Data type: "; // test INT64 TSDataType dataType = TSDataType.INT64; DescReadWriteBatchData data = new DescReadWriteBatchData(dataType); String fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putLong(i, i); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getLongByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getLong()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test INT32 dataType = TSDataType.INT32; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putInt(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getIntByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getInt()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test DOUBLE dataType = TSDataType.DOUBLE; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putDouble(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getDoubleByIndex(i), E); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getDouble(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test FLOAT dataType = TSDataType.FLOAT; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putFloat(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getFloatByIndex(i), E); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getFloat(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BOOLEAN dataType = TSDataType.BOOLEAN; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putBoolean(i, i % 3 == 0); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, (i + 1) % 3 == 0, data2.getBooleanByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i % 3 == 0, data2.getBoolean()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BINARY dataType = TSDataType.TEXT; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putBinary(i, Binary.valueOf(String.valueOf(i))); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals( fullMsg, String.valueOf(i + 1), data2.getBinaryByIndex(i).getStringValue()); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, String.valueOf(i), data2.getBinary().getStringValue()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test VECTOR dataType = TSDataType.VECTOR; data = new DescReadWriteBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = dataSize; i > 0; i--) { data.putVector( i, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadWriteBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i + 1), new TsPrimitiveType.TsInt(i + 1), new TsPrimitiveType.TsDouble(i + 1), new TsPrimitiveType.TsFloat(i + 1), new TsPrimitiveType.TsBoolean((i + 1) % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i + 1))), }, data2.getVectorByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }, data2.getVector()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); } // In DescReadBatchData, read has a reverse order with ascending write private void descReadBatchDataSerializableTest(int dataSize) { double E = 0.00001; String debugMsg = "Data size: " + dataSize + ", Data type: "; // test INT64 TSDataType dataType = TSDataType.INT64; DescReadBatchData data = new DescReadBatchData(dataType); String fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putLong(i, i); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getLongByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getLong()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test INT32 dataType = TSDataType.INT32; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putInt(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getIntByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getInt()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test DOUBLE dataType = TSDataType.DOUBLE; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putDouble(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getDoubleByIndex(i), E); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getDouble(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test FLOAT dataType = TSDataType.FLOAT; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putFloat(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getFloatByIndex(i), E); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getFloat(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BOOLEAN dataType = TSDataType.BOOLEAN; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putBoolean(i, i % 3 == 0); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, (i + 1) % 3 == 0, data2.getBooleanByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i % 3 == 0, data2.getBoolean()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BINARY dataType = TSDataType.TEXT; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putBinary(i, Binary.valueOf(String.valueOf(i))); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals( fullMsg, String.valueOf(i + 1), data2.getBinaryByIndex(i).getStringValue()); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, String.valueOf(i), data2.getBinary().getStringValue()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test VECTOR dataType = TSDataType.VECTOR; data = new DescReadBatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putVector( i, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertTrue(fullMsg, data2 instanceof DescReadBatchData); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i + 1), new TsPrimitiveType.TsInt(i + 1), new TsPrimitiveType.TsDouble(i + 1), new TsPrimitiveType.TsFloat(i + 1), new TsPrimitiveType.TsBoolean((i + 1) % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i + 1))), }, data2.getVectorByIndex(i)); } for (int i = dataSize; i > 0; i--) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }, data2.getVector()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); } // In BatchData, read has a reverse order with ascending write private void batchDataSerializableTest(int dataSize) { double E = 0.00001; String debugMsg = "Data size: " + dataSize + ", Data type: "; // test INT64 TSDataType dataType = TSDataType.INT64; BatchData data = new BatchData(dataType); String fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putLong(i, i); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); ByteBuffer buffer = ByteBuffer.wrap(baos.toByteArray()); BatchData data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getLongByIndex(i)); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getLong()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test INT32 dataType = TSDataType.INT32; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putInt(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getIntByIndex(i)); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getInt()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test DOUBLE dataType = TSDataType.DOUBLE; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putDouble(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getDoubleByIndex(i), E); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getDouble(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test FLOAT dataType = TSDataType.FLOAT; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putFloat(i, i); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, i + 1, data2.getFloatByIndex(i), E); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i, data2.getFloat(), E); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BOOLEAN dataType = TSDataType.BOOLEAN; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putBoolean(i, i % 3 == 0); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals(fullMsg, (i + 1) % 3 == 0, data2.getBooleanByIndex(i)); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, i % 3 == 0, data2.getBoolean()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test BINARY dataType = TSDataType.TEXT; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putBinary(i, Binary.valueOf(String.valueOf(i))); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertEquals( fullMsg, String.valueOf(i + 1), data2.getBinaryByIndex(i).getStringValue()); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertEquals(fullMsg, String.valueOf(i), data2.getBinary().getStringValue()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); // test VECTOR dataType = TSDataType.VECTOR; data = new BatchData(dataType); fullMsg = debugMsg + dataType; for (int i = 1; i <= dataSize; i++) { data.putVector( i, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }); } baos = new ByteArrayOutputStream(); outputStream = new DataOutputStream(baos); SerializeUtils.serializeBatchData(data, outputStream); buffer = ByteBuffer.wrap(baos.toByteArray()); data2 = SerializeUtils.deserializeBatchData(buffer); Assert.assertEquals(fullMsg, dataSize, data2.length()); if (dataSize > 0) { Assert.assertEquals(fullMsg, 1L, data2.getMinTimestamp()); Assert.assertEquals(fullMsg, dataSize, data2.getMaxTimestamp()); } for (int i = 0; i < dataSize; i++) { Assert.assertEquals(fullMsg, i + 1, data2.getTimeByIndex(i)); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i + 1), new TsPrimitiveType.TsInt(i + 1), new TsPrimitiveType.TsDouble(i + 1), new TsPrimitiveType.TsFloat(i + 1), new TsPrimitiveType.TsBoolean((i + 1) % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i + 1))), }, data2.getVectorByIndex(i)); } for (int i = 1; i <= dataSize; i++) { Assert.assertTrue(fullMsg, data2.hasCurrent()); Assert.assertEquals(fullMsg, i, data2.currentTime()); Assert.assertArrayEquals( fullMsg, new TsPrimitiveType[] { new TsPrimitiveType.TsLong(i), new TsPrimitiveType.TsInt(i), new TsPrimitiveType.TsDouble(i), new TsPrimitiveType.TsFloat(i), new TsPrimitiveType.TsBoolean(i % 3 == 0), new TsPrimitiveType.TsBinary(new Binary(String.valueOf(i))), }, data2.getVector()); data2.next(); } Assert.assertFalse(fullMsg, data2.hasCurrent()); } }
17,337
841
/* * Copyright 2021 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.jbpm.process.workitem.core.util; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.kie.api.runtime.process.WorkItem; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WorkItemHeaderUtilsTest { @Test public void testBuildHeaderList() { WorkItem workItem = mock(WorkItem.class); Map<String, Object> map = new HashMap<>(); map.put("HEADER_Pepito_Grillo", "fulanito"); map.put("header_param_NS_Pepito_Grillo", "http://pepito.com"); map.put("mamotreco", "power"); when(workItem.getParameters()).thenReturn(map); Collection<WorkItemHeaderInfo> headers = WorkItemHeaderUtils.getHeaderInfo(workItem); assertEquals(1, headers.size()); WorkItemHeaderInfo header = headers.iterator().next(); assertEquals("Pepito_Grillo", header.getName()); assertEquals("fulanito", header.getContent()); assertEquals("http://pepito.com", header.getParam("NS")); } @Test public void testBuildHeaderListWithCustomSeparator() { System.setProperty(WorkItemHeaderUtils.SEPARATOR_PROP, "//"); try { WorkItem workItem = mock(WorkItem.class); Map<String, Object> map = new HashMap<>(); map.put("HEADER_Pepito_Grillo", "fulanito"); map.put("header_param_NS_232//Pepito_Grillo", "http://pepito.com"); map.put("mamotreco", "power"); when(workItem.getParameters()).thenReturn(map); Collection<WorkItemHeaderInfo> headers = WorkItemHeaderUtils.getHeaderInfo(workItem); assertEquals(1, headers.size()); WorkItemHeaderInfo header = headers.iterator().next(); assertEquals("Pepito_Grillo", header.getName()); assertEquals("fulanito", header.getContent()); assertEquals("http://pepito.com", header.getParam("NS_232")); } finally { System.clearProperty(WorkItemHeaderUtils.SEPARATOR_PROP); } } }
860
355
/* Copyright 2017 yangchong211(github.com/yangchong211) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.yc.pagerlib.recycler; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.OrientationHelper; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import java.util.Locale; /** * <pre> * @author yangchong * blog : https://github.com/yangchong211 * time : 2018/3/18 * desc : 自定义SnapHelper,设置左对齐,滑动时候会限制item只滑动一个。可以设置gravity位置对齐 * revise: 关于SnapHelper源码分析可以看我博客:https://blog.csdn.net/m0_37700275/article/details/83901677 * </pre> */ public class ScrollPageHelper extends PagerSnapHelper { private OrientationHelper mHorizontalHelper, mVerticalHelper; private int gravity; private boolean snapLastItem; private boolean isRtlHorizontal; /** * 构造方法 * @param gravity 位置 * @param enableSnapLast 最后一个是否按照位置对齐 */ public ScrollPageHelper(int gravity, boolean enableSnapLast){ this.snapLastItem = enableSnapLast; this.gravity = gravity; } /** * 这个方法是与recyclerView绑定 * @param recyclerView recyclerView * @throws IllegalStateException */ @Override public void attachToRecyclerView(@Nullable RecyclerView recyclerView) throws IllegalStateException { if (recyclerView != null && !(recyclerView.getLayoutManager() instanceof LinearLayoutManager)) { throw new IllegalStateException("ScrollPageHelper needs a " + "RecyclerView with a LinearLayoutManager"); } if (recyclerView != null) { //设置fling监听为null recyclerView.setOnFlingListener(null); if ((gravity == Gravity.START || gravity == Gravity.END)) { isRtlHorizontal = isRtl(); } } super.attachToRecyclerView(recyclerView); } /** * * @param layoutManager layoutManager * @param targetView 目标view * @return */ @Nullable @Override public int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView) { //创建数组 int[] out = new int[2]; //判断是否是横向方法 if (layoutManager.canScrollHorizontally()) { if (gravity == Gravity.START) { out[0] = distanceToStart(targetView, getHorizontalHelper(layoutManager), false); } else { // END out[0] = distanceToEnd(targetView, getHorizontalHelper(layoutManager), false); } } else { out[0] = 0; } //判断是否是竖直方法 if (layoutManager.canScrollVertically()) { if (gravity == Gravity.TOP) { out[1] = distanceToStart(targetView, getVerticalHelper(layoutManager), false); } else { // BOTTOM out[1] = distanceToEnd(targetView, getVerticalHelper(layoutManager), false); } } else { out[1] = 0; } return out; } /** * 找到当前时刻的SnapView * @param layoutManager layoutManager * @return */ @Nullable @Override public View findSnapView(RecyclerView.LayoutManager layoutManager) { View snapView = null; if (layoutManager instanceof LinearLayoutManager) { switch (gravity) { case Gravity.START: snapView = findStartView(layoutManager, getHorizontalHelper(layoutManager)); break; case Gravity.END: snapView = findEndView(layoutManager, getHorizontalHelper(layoutManager)); break; case Gravity.TOP: snapView = findStartView(layoutManager, getVerticalHelper(layoutManager)); break; case Gravity.BOTTOM: snapView = findEndView(layoutManager, getVerticalHelper(layoutManager)); break; default: break; } } return snapView; } private boolean isRtl() { return TextUtils.getLayoutDirectionFromLocale( Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL; } @NonNull private OrientationHelper getVerticalHelper(@NonNull RecyclerView.LayoutManager layoutManager) { if (mVerticalHelper == null) { mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager); } return mVerticalHelper; } @NonNull private OrientationHelper getHorizontalHelper( @NonNull RecyclerView.LayoutManager layoutManager) { if (mHorizontalHelper == null) { mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager); } return mHorizontalHelper; } private int distanceToStart(View targetView, @NonNull OrientationHelper helper, boolean fromEnd) { if (isRtlHorizontal && !fromEnd) { return distanceToEnd(targetView, helper, true); } return helper.getDecoratedStart(targetView) - helper.getStartAfterPadding(); } private int distanceToEnd(View targetView, @NonNull OrientationHelper helper, boolean fromStart) { if (isRtlHorizontal && !fromStart) { return distanceToStart(targetView, helper, true); } return helper.getDecoratedEnd(targetView) - helper.getEndAfterPadding(); } @Nullable private View findStartView(RecyclerView.LayoutManager layoutManager, @NonNull OrientationHelper helper) { if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; boolean reverseLayout = linearLayoutManager.getReverseLayout(); int firstChild = reverseLayout ? linearLayoutManager.findLastVisibleItemPosition() : linearLayoutManager.findFirstVisibleItemPosition(); int offset = 1; if (layoutManager instanceof GridLayoutManager) { offset += ((GridLayoutManager) layoutManager).getSpanCount() - 1; } if (firstChild == RecyclerView.NO_POSITION) { return null; } View child = layoutManager.findViewByPosition(firstChild); float visibleWidth; if (isRtlHorizontal) { visibleWidth = (float) (helper.getTotalSpace() - helper.getDecoratedStart(child)) / helper.getDecoratedMeasurement(child); } else { visibleWidth = (float) helper.getDecoratedEnd(child) / helper.getDecoratedMeasurement(child); } boolean endOfList; if (!reverseLayout) { endOfList = ((LinearLayoutManager) layoutManager) .findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1; } else { endOfList = ((LinearLayoutManager) layoutManager) .findFirstCompletelyVisibleItemPosition() == 0; } if (visibleWidth > 0.5f && !endOfList) { return child; } else if (snapLastItem && endOfList) { return child; } else if (endOfList) { return null; } else { return reverseLayout ? layoutManager.findViewByPosition(firstChild - offset) : layoutManager.findViewByPosition(firstChild + offset); } } return null; } @Nullable private View findEndView(RecyclerView.LayoutManager layoutManager, @NonNull OrientationHelper helper) { if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; boolean reverseLayout = linearLayoutManager.getReverseLayout(); int lastChild = reverseLayout ? linearLayoutManager.findFirstVisibleItemPosition() : linearLayoutManager.findLastVisibleItemPosition(); int offset = 1; if (layoutManager instanceof GridLayoutManager) { offset += ((GridLayoutManager) layoutManager).getSpanCount() - 1; } if (lastChild == RecyclerView.NO_POSITION) { return null; } View child = layoutManager.findViewByPosition(lastChild); float visibleWidth; if (isRtlHorizontal) { visibleWidth = (float) helper.getDecoratedEnd(child) / helper.getDecoratedMeasurement(child); } else { visibleWidth = (float) (helper.getTotalSpace() - helper.getDecoratedStart(child)) / helper.getDecoratedMeasurement(child); } boolean startOfList; if (!reverseLayout) { startOfList = ((LinearLayoutManager) layoutManager) .findFirstCompletelyVisibleItemPosition() == 0; } else { startOfList = ((LinearLayoutManager) layoutManager) .findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1; } if (visibleWidth > 0.5f && !startOfList) { return child; } else if (snapLastItem && startOfList) { return child; } else if (startOfList) { return null; } else { return reverseLayout ? layoutManager.findViewByPosition(lastChild + offset) : layoutManager.findViewByPosition(lastChild - offset); } } return null; } }
5,119
1,068
package org.assertj.android.palette.v7.api.graphics; import android.support.v7.graphics.Palette; import org.assertj.core.api.AbstractAssert; import static org.assertj.core.api.Assertions.assertThat; /** * Assertions for {@link Palette} instances. */ public class PaletteAssert extends AbstractAssert<PaletteAssert, Palette> { public PaletteAssert(Palette actual) { super(actual, PaletteAssert.class); } public PaletteAssert hasVibrantColor(int color) { isNotNull(); int actualColor = actual.getVibrantColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected vibrant color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } public PaletteAssert hasDarkVibrantColor(int color) { isNotNull(); int actualColor = actual.getDarkVibrantColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected dark vibrant color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } public PaletteAssert hasLightVibrantColor(int color) { isNotNull(); int actualColor = actual.getLightVibrantColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected light vibrant color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } public PaletteAssert hasMutedColor(int color) { isNotNull(); int actualColor = actual.getMutedColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected muted color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } public PaletteAssert hasDarkMutedColor(int color) { isNotNull(); int actualColor = actual.getDarkMutedColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected dark muted color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } public PaletteAssert hasLightMutedColor(int color) { isNotNull(); int actualColor = actual.getLightMutedColor(getAnotherColor(color)); assertThat(color) // .overridingErrorMessage("Expected light muted color <%s> but was <%s>", color, actualColor) // .isEqualTo(actualColor); return this; } private static int getAnotherColor(int color) { return 0xFFFFFFFF - color; } }
899
348
<gh_stars>100-1000 {"nom":"Betoncourt-sur-Mance","circ":"1ère circonscription","dpt":"Haute-Saône","inscrits":38,"abs":22,"votants":16,"blancs":5,"nuls":1,"exp":10,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":6},{"nuance":"FN","nom":"M<NAME>","voix":4}]}
108
648
#define TEST_LIBNAME "fluxcapacitor_test.so" #define PRELOAD_LIBNAME "fluxcapacitor_preload.so" extern struct timespec uevent_now; #define ERRORF(x...) fprintf(stderr, x) #define FATAL(x...) do { \ ERRORF("[-] PROGRAM ABORT : " x); \ ERRORF("\n Location : %s(), %s:%u\n\n", \ __FUNCTION__, __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } while (0) #define PFATAL(x...) do { \ ERRORF("[-] SYSTEM ERROR : " x); \ ERRORF("\n Location : %s(), %s:%u\n", \ __FUNCTION__, __FILE__, __LINE__); \ perror(" OS message "); \ ERRORF("\n"); \ exit(127); \ } while (0) #define SHOUT(x...) do{ \ if (options.verbose) { \ fprintf(options.shoutstream, x); \ fprintf(options.shoutstream, "\n"); \ } \ } while (0) #define PRINT(x...) do{ \ if (options.verbose > 1) { \ fprintf(options.shoutstream, x); \ fprintf(options.shoutstream, "\n"); \ } \ } while (0) /* All the global state goes here */ struct options { /* Path to .so files */ char *libpath; int verbose; FILE *shoutstream; /* Should we exit? */ int exit_forced; /* Max exit status of the exited children (unsigned) */ unsigned exit_status; /* Signo we'll use to continue the child. Must not be used by the child application. */ int signo; /* Wait for `idleness_threshold` ns of not handling any * changes before speeding up time. */ u64 idleness_threshold; /* Don't advance time in tiny chunks */ u64 min_speedup; }; struct parent { int child_count; struct list_head list_of_children; int blocked_count; struct list_head list_of_blocked; int started; flux_time time_drift; }; struct trace_process; struct child { int pid; struct list_head in_children; struct list_head in_blocked; int blocked; flux_time blocked_until; struct parent *parent; struct trace_process *process; int interrupted; int syscall_no; int stat_fd; char stat; }; /* misc.c */ void pin_cpu(); char ***argv_split(char **argv, const char *delimiter, int upper_bound); char *argv_join(char **argv, const char *delimiter); void ensure_libpath(const char *argv_0); void ldpreload_extend(const char *lib_path, const char *file); const char *ldpreload_get(); void handle_backtrace(); int str_to_signal(const char *s); int str_to_time(const char *s, u64 *timens_ptr); const char *syscall_to_str(int no); int proc_running(); void ping_myself(); /* parent.c */ #define TIMEOUT_UNKNOWN (-1LL) /* 2**63 - 1, LLONG_MAX but not depending on limits.h */ #define TIMEOUT_FOREVER (-2LL) struct trace; struct trace_process; struct parent *parent_new(); void parent_run_one(struct parent *parent, struct trace *trace, char **child_argv); struct child *parent_min_timeout_child(struct parent *parent); struct child *parent_woken_child(struct parent *parent); void parent_kill_all(struct parent *parent, int signo); struct child *child_new(struct parent *parent, struct trace_process *process, int pid); void child_del(struct child *child); struct trace_sysarg; void child_mark_blocked(struct child *child); void child_mark_unblocked(struct child *child); void wrapper_syscall_enter(struct child *child, struct trace_sysarg *sysarg); int wrapper_syscall_exit(struct child *child, struct trace_sysarg *sysarg); void wrapper_pacify_signal(struct child *child, struct trace_sysarg *sysarg); void child_kill(struct child *child, int signo); void child_fake_response(struct child *child, struct trace_sysarg *sysarg); #define TIMESPEC_NSEC(ts) ((ts)->tv_sec * 1000000000ULL + (ts)->tv_nsec) #define TIMEVAL_NSEC(ts) ((ts)->tv_sec * 1000000000ULL + (ts)->tv_usec * 1000ULL) #define NSEC_TIMESPEC(ns) (struct timespec){(ns) / 1000000000ULL, \ (ns) % 1000000000ULL} #define NSEC_TIMEVAL(ns) (struct timeval){(ns) / 1000000000ULL, \ ((ns) % 1000000000ULL) / 1000ULL} #define MSEC_NSEC(ms) ((ms) * 1000000ULL)
1,630
467
<gh_stars>100-1000 import random import numpy as np import torch def set_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def is_whitespace(c): if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F: return True return False
149
1,146
''' Tokenization for the Vim command line. ''' from Vintageous.ex.ex_error import ERR_UNKNOWN_COMMAND from Vintageous.ex.ex_error import VimError from . import subscanners from .state import EOF from .state import ScannerState from .tokens import TokenComma from .tokens import TokenDigits from .tokens import TokenDollar from .tokens import TokenDot from .tokens import TokenEof from .tokens import TokenMark from .tokens import TokenOffset from .tokens import TokenPercent from .tokens import TokenSearchBackward from .tokens import TokenSearchForward from .tokens import TokenSemicolon # TODO: make this a function. We don't need state. class Scanner(object): ''' Produces ex command-line tokens from a string. ''' def __init__(self, source): self.state = ScannerState(source) def scan(self): ''' Generates ex command-line tokens for `source`. The scanner works its way through the source string by passing the current state to the next scanning function. ''' next_func = scan_range while True: # We return multiple tokens so that we can work around cyclic imports: # functions that need to, return TokenEof without having to call # a function in this module from a separate module. # # Keep scanning while we get a scanning function. (next_func, items) = next_func(self.state) yield from items if not next_func: break def scan_range(state): ''' Produces tokens found in a command line range. http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-ranges ''' c = state.consume() if c == EOF: return None, [TokenEof()] if c == '.': state.emit() return scan_range, [TokenDot()] if c == '$': state.emit() return scan_range, [TokenDollar()] if c in ',;': token = TokenComma if c == ',' else TokenSemicolon state.emit() return scan_range, [token()] if c == "'": return scan_mark(state) if c in '/?': return scan_search(state) if c in '+-': return scan_offset(state) if c == '%': state.emit() return scan_range, [TokenPercent()] if c in '\t ': state.skip_run(' \t') state.ignore() if c.isdigit(): return scan_digits(state) state.backup() return scan_command, [] def scan_mark(state): c = state.expect_match(r'[a-zA-Z\[\]()<>]') return scan_range, [TokenMark(c.group(0))] def scan_digits(state): while True: c = state.consume() if not c.isdigit(): if c == EOF: return None, [TokenDigits(state.emit()), TokenEof()] state.backup() break return scan_range, [TokenDigits(state.emit())] def scan_search(state): delim = state.source[state.position - 1] while True: c = state.consume() if c == delim: state.start += 1 state.backup() content = state.emit() state.consume() token = TokenSearchForward if c == '/' else TokenSearchBackward return scan_range , [token(content)] elif c == EOF: raise ValueError('unclosed search pattern: {0}'.format(state.source)) def scan_offset(state): offsets = [] to_int = lambda x: int(x, 10) sign = '-' if state.source[state.position - 1] == '-' else '' digits = state.expect_match(r'\s*(\d+)') offsets.append(sign + digits.group(1)) while True: c = state.consume() if c == EOF: state.ignore() return None, [TokenOffset(list(map(to_int, offsets))), TokenEof()] if c == '+' or c == '-': digits = state.expect_match(r'\s*(\d+)') sign = '-' if state.source[state.position - 1] == '-' else '' offsets.append(sign + digits.group(1)) continue if not c.isdigit(): state.backup() state.ignore() return scan_range, [TokenOffset(list(map(to_int, offsets)))] def scan_command(state): for (pattern, subscanner) in subscanners.patterns.items(): if state.match(pattern): state.ignore() return subscanner(state) state.expect(EOF, lambda: VimError(ERR_UNKNOWN_COMMAND)) return None, [TokenEof()]
1,949
438
{ "DESCRIPTION": "˙ǝloɹ ɐ uo uoᴉʇɐɯɹoɟuᴉ ʇǝפ", "USAGE": "role-info <ǝloɹ>", "NAME": "{{NAME}} | ǝloɹ", "MEMBERS": ":sɹǝqɯǝW", "COLOR": ":ɹoloƆ", "POSITION": ":uoᴉʇᴉsoԀ", "MENTION": ":uoᴉʇuǝW", "HOISTED": ":pǝʇsᴉoH", "MENTIONABLE": ":ǝlqɐuoᴉʇuǝW", "PERMISSION": ":suoᴉssᴉɯɹǝd ʎǝʞ", "CREATED": ":ʇɐ pǝʇɐǝɹƆ", "FOOTER": "{{ID}} :pI ǝloɹ | {{MEMBER}} ʎq pǝʇsǝnbǝɹ" }
310
328
/** * @file arp.c * */ /* Copyright (C) 2018-2019 by <NAME> mailto:<EMAIL> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdint.h> #include <string.h> #include <assert.h> #include "net.h" #include "net_packets.h" #include "net_debug.h" #ifndef ALIGNED # define ALIGNED __attribute__ ((aligned (4))) #endif extern void arp_cache_init(void); extern void arp_cache_update(uint8_t *, uint32_t); extern void emac_eth_send(void *, int); static struct t_arp s_arp_announce ALIGNED; static struct t_arp s_arp_request ALIGNED ; static struct t_arp s_arp_reply ALIGNED; typedef union pcast32 { uint32_t u32; uint8_t u8[4]; } _pcast32; void arp_announce(void) { DEBUG_ENTRY if(s_arp_announce.arp.sender_ip == 0) { DEBUG_EXIT return; } debug_dump(&s_arp_announce, sizeof(struct t_arp)); emac_eth_send((void *)&s_arp_announce, sizeof(struct t_arp)); DEBUG_EXIT } void arp_handle_request(struct t_arp *p_arp) { DEBUG2_ENTRY _pcast32 target; const uint8_t *p = (uint8_t *) &p_arp->arp.target_ip; memcpy(target.u8, p, 4); DEBUG_PRINTF("Sender "IPSTR" Target "IPSTR, IP2STR(p_arp->arp.sender_ip), IP2STR(target.u32)); if (target.u32 != s_arp_announce.arp.sender_ip) { DEBUG2_EXIT return; } // Ethernet header memcpy(s_arp_reply.ether.dst, p_arp->ether.src, ETH_ADDR_LEN); // ARP Header memcpy(s_arp_reply.arp.target_mac, p_arp->arp.sender_mac, ETH_ADDR_LEN); s_arp_reply.arp.target_ip = p_arp->arp.sender_ip; //debug_dump(&s_arp_reply, sizeof(struct t_arp)); emac_eth_send((void *)&s_arp_reply, sizeof(struct t_arp)); DEBUG2_EXIT } void arp_handle_reply(struct t_arp *p_arp) { DEBUG2_ENTRY arp_cache_update(p_arp->arp.sender_mac, p_arp->arp.sender_ip); DEBUG2_EXIT } void __attribute__((cold)) arp_init(const uint8_t *mac_address, const struct ip_info *p_ip_info) { arp_cache_init(); const uint32_t local_ip = p_ip_info->ip.addr; // ARP Announce // Ethernet header memcpy(s_arp_announce.ether.src, mac_address, ETH_ADDR_LEN); memset(s_arp_announce.ether.dst, 0xFF , ETH_ADDR_LEN); s_arp_announce.ether.type = __builtin_bswap16(ETHER_TYPE_ARP); // ARP Header s_arp_announce.arp.hardware_type = __builtin_bswap16(ARP_HWTYPE_ETHERNET); s_arp_announce.arp.protocol_type = __builtin_bswap16(ARP_PRTYPE_IPv4); s_arp_announce.arp.hardware_size = ARP_HARDWARE_SIZE; s_arp_announce.arp.protocol_size = ARP_PROTOCOL_SIZE; s_arp_announce.arp.opcode = __builtin_bswap16(ARP_OPCODE_RQST); memcpy(s_arp_announce.arp.sender_mac, mac_address, ETH_ADDR_LEN); s_arp_announce.arp.sender_ip = local_ip; memset(s_arp_announce.arp.target_mac, 0x00, ETH_ADDR_LEN); s_arp_announce.arp.target_ip = local_ip; // ARP Request template // Ethernet header memcpy(s_arp_request.ether.src, mac_address, ETH_ADDR_LEN); memset(s_arp_request.ether.dst, 0xFF , ETH_ADDR_LEN); s_arp_request.ether.type = __builtin_bswap16(ETHER_TYPE_ARP); // ARP Header s_arp_request.arp.hardware_type = __builtin_bswap16(ARP_HWTYPE_ETHERNET); s_arp_request.arp.protocol_type = __builtin_bswap16(ARP_PRTYPE_IPv4); s_arp_request.arp.hardware_size = ARP_HARDWARE_SIZE; s_arp_request.arp.protocol_size = ARP_PROTOCOL_SIZE; s_arp_request.arp.opcode = __builtin_bswap16(ARP_OPCODE_RQST); memcpy(s_arp_request.arp.sender_mac, mac_address, ETH_ADDR_LEN); s_arp_request.arp.sender_ip = local_ip; memset(s_arp_request.arp.target_mac, 0x00, ETH_ADDR_LEN); // ARP Reply Template // Ethernet header memcpy(s_arp_reply.ether.src, mac_address, ETH_ADDR_LEN); s_arp_reply.ether.type = __builtin_bswap16(ETHER_TYPE_ARP); // ARP Header s_arp_reply.arp.hardware_type = __builtin_bswap16(ARP_HWTYPE_ETHERNET); s_arp_reply.arp.protocol_type = __builtin_bswap16(ARP_PRTYPE_IPv4); s_arp_reply.arp.hardware_size = ARP_HARDWARE_SIZE; s_arp_reply.arp.protocol_size = ARP_PROTOCOL_SIZE; s_arp_reply.arp.opcode = __builtin_bswap16(ARP_OPCODE_REPLY); memcpy(s_arp_reply.arp.sender_mac, mac_address, ETH_ADDR_LEN); s_arp_reply.arp.sender_ip = local_ip; arp_announce(); } void arp_send_request(uint32_t ip) { DEBUG2_ENTRY // ARP Header s_arp_request.arp.target_ip = ip; DEBUG_PRINTF(IPSTR, IP2STR(ip)); debug_dump(&s_arp_request, sizeof(struct t_arp)); emac_eth_send((void *)&s_arp_request, sizeof(struct t_arp)); DEBUG2_EXIT } __attribute__((hot)) void arp_handle(struct t_arp *p_arp) { DEBUG1_ENTRY switch (p_arp->arp.opcode) { case __builtin_bswap16(ARP_OPCODE_RQST): arp_handle_request(p_arp); break; case __builtin_bswap16(ARP_OPCODE_REPLY): arp_handle_reply(p_arp); break; default: DEBUG_PRINTF("opcode %04x not handled", __builtin_bswap16(p_arp->arp.opcode)); break; } DEBUG1_EXIT }
2,359
378
package com.quickblox.sample.videochat.conference.java.fcm; import android.app.Activity; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import com.quickblox.sample.videochat.conference.java.utils.FcmConsts; import androidx.annotation.DrawableRes; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; class NotificationUtils { private static final String CHANNEL_ONE_ID = "QuickBlox Conference Chat Channel";// The id of the channel. private static final String CHANNEL_ONE_NAME = "Conference Chat Channel"; public static void showNotification(Context context, Class<? extends Activity> activityClass, String title, String message, @DrawableRes int icon, int notificationId) { NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager != null) { createChannelIfNotExist(notificationManager); } Notification notification = buildNotification(context, activityClass, title, message, icon); if (notificationManager != null) { notificationManager.notify(notificationId, notification); } } @RequiresApi(api = Build.VERSION_CODES.O) private static void createChannelIfNotExist(NotificationManager notificationManager) { if (notificationManager.getNotificationChannel(CHANNEL_ONE_ID) == null) { int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ONE_ID, CHANNEL_ONE_NAME, importance); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.BLUE); notificationChannel.setShowBadge(true); notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); notificationManager.createNotificationChannel(notificationChannel); } } private static Notification buildNotification(Context context, Class<? extends Activity> activityClass, String title, String message, @DrawableRes int icon) { Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); return new NotificationCompat.Builder(context, CHANNEL_ONE_ID) .setSmallIcon(icon) .setContentTitle(title) .setContentText(message) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(buildContentIntent(context, activityClass, message)) .build(); } private static PendingIntent buildContentIntent(Context context, Class<? extends Activity> activityClass, String message) { Intent intent = new Intent(context, activityClass); intent.putExtra(FcmConsts.EXTRA_FCM_MESSAGE, message); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } }
1,324
606
<filename>base/src/main/java/org/arend/typechecking/order/dependency/DummyDependencyListener.java package org.arend.typechecking.order.dependency; import org.arend.naming.reference.TCReferable; import java.util.Collections; import java.util.Set; public class DummyDependencyListener implements DependencyListener { public static final DummyDependencyListener INSTANCE = new DummyDependencyListener(); private DummyDependencyListener() { } @Override public void dependsOn(TCReferable def1, TCReferable def2) { } @Override public Set<? extends TCReferable> update(TCReferable definition) { return Collections.emptySet(); } @Override public Set<? extends TCReferable> getDependencies(TCReferable definition) { return Collections.emptySet(); } }
234
460
<reponame>juandesant/astrometry.net import os import shutil from astrometry.net.log import logmsg class TempfileMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. request.tempfiles = [] request.tempdirs = [] response = self.get_response(request) # Code to be executed for each request/response after # the view is called. for dirnm in request.tempdirs: if os.path.exists(dirnm): try: shutil.rmtree(dirnm) except OSError as e: logmsg('Failed to delete temp dir', dirnm, ':', e) for fn in request.tempfiles: if os.path.exists(fn): try: os.remove(fn) except OSError as e: logmsg('Failed to delete temp file', fn, ':', e) return response
531
1,056
/* * 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.netbeans.modules.hudson.impl; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import org.netbeans.modules.hudson.api.HudsonJob; import org.netbeans.modules.hudson.api.HudsonJob.Color; import org.netbeans.modules.hudson.api.HudsonJobBuild; import org.netbeans.modules.hudson.api.HudsonMavenModuleBuild; import org.netbeans.modules.hudson.api.ui.ConsoleDataDisplayer; import org.netbeans.modules.hudson.api.ui.FailureDataDisplayer; import org.netbeans.modules.hudson.api.ui.OpenableInBrowser; import static org.netbeans.modules.hudson.impl.Bundle.*; import org.netbeans.modules.hudson.impl.HudsonJobImpl.HudsonMavenModule; import org.netbeans.modules.hudson.spi.BuilderConnector; import org.netbeans.modules.hudson.spi.ConsoleDataDisplayerImpl; import org.netbeans.modules.hudson.spi.FailureDataDisplayerImpl; import org.netbeans.modules.hudson.spi.HudsonJobChangeItem; import org.openide.filesystems.FileSystem; import org.openide.util.NbBundle.Messages; public class HudsonJobBuildImpl implements HudsonJobBuild, OpenableInBrowser { private static final Logger LOG = Logger.getLogger(HudsonJobBuildImpl.class.getName()); private final HudsonJobImpl job; private final int build; private boolean building; private Result result; private final BuilderConnector connector; HudsonJobBuildImpl(BuilderConnector connector, HudsonJobImpl job, int build, boolean building, Result result) { this.connector = connector; this.job = job; this.build = build; this.building = building; this.result = result; } public HudsonJob getJob() { return job; } public int getNumber() { return build; } public String getUrl() { return job.getUrl() + build + "/"; // NOI18N } public @Override String toString() { return getUrl(); } public @Override boolean isBuilding() { getResult(); return building; } public @Override synchronized Result getResult() { if (result == null && !building) { AtomicBoolean _building = new AtomicBoolean(); AtomicReference<Result> _result = new AtomicReference<Result>(Result.NOT_BUILT); connector.getJobBuildResult(this, _building, _result); building = _building.get(); result = _result.get(); } return result != null ? result : Result.NOT_BUILT; } private Collection<? extends HudsonJobChangeItem> changes; public Collection<? extends HudsonJobChangeItem> getChanges() { if (changes == null || /* #171978 */changes.isEmpty()) { changes = connector.getJobBuildChanges(this); } return changes; } public FileSystem getArtifacts() { return job.getInstance().getArtifacts(this); } public Collection<? extends HudsonMavenModuleBuild> getMavenModules() { List<HudsonMavenModuleBuildImpl> modules = new ArrayList<HudsonMavenModuleBuildImpl>(); for (HudsonJobImpl.HudsonMavenModule module : job.mavenModules) { modules.add(new HudsonMavenModuleBuildImpl(module)); } return modules; } @Messages({"# {0} - job/module display name", "# {1} - build number", "HudsonJobBuildImpl.display_name={0} #{1,number,#}"}) public String getDisplayName() { return HudsonJobBuildImpl_display_name(job.getDisplayName(), getNumber()); } private ConsoleDataDisplayer createDisplayerFromImpl( final ConsoleDataDisplayerImpl displayerImpl) { return new ConsoleDataDisplayer() { @Override public void open() { displayerImpl.open(); } @Override public boolean writeLine(String line) { return displayerImpl.writeLine(line); } @Override public void close() { displayerImpl.close(); } }; } private FailureDataDisplayer createDisplayerFromImpl( final FailureDataDisplayerImpl displayerImpl) { return new FailureDataDisplayer() { @Override public void open() { displayerImpl.open(); } @Override public void showSuite(FailureDataDisplayer.Suite suite) { displayerImpl.showSuite(suite); } @Override public void close() { displayerImpl.close(); } }; } @Override public boolean canShowConsole() { return connector.getConsoleDataProvider() != null; } @Override public void showConsole(ConsoleDataDisplayerImpl displayer) { BuilderConnector.ConsoleDataProvider cd = connector.getConsoleDataProvider(); if (cd != null) { cd.showConsole(this, createDisplayerFromImpl(displayer)); } } @Override public boolean canShowFailures() { return connector.getFailureDataProvider() != null; } @Override public void showFailures(FailureDataDisplayerImpl displayer) { BuilderConnector.FailureDataProvider fd = connector.getFailureDataProvider(); if (fd != null) { fd.showFailures(this, createDisplayerFromImpl(displayer)); } } private final class HudsonMavenModuleBuildImpl implements HudsonMavenModuleBuild, OpenableInBrowser { private final HudsonJobImpl.HudsonMavenModule module; HudsonMavenModuleBuildImpl(HudsonMavenModule module) { this.module = module; } public String getName() { return module.name; } public String getDisplayName() { return module.displayName; } public Color getColor() { return module.color; } public String getUrl() { return module.url + build + "/"; // NOI18N } public HudsonJobBuild getBuild() { return HudsonJobBuildImpl.this; } public FileSystem getArtifacts() { return job.getInstance().getArtifacts(this); } public @Override String toString() { return getUrl(); } public String getBuildDisplayName() { return HudsonJobBuildImpl_display_name(getDisplayName(), getNumber()); } @Override public boolean canShowConsole() { return getBuild().canShowConsole(); } @Override public void showConsole(ConsoleDataDisplayerImpl displayer) { BuilderConnector.ConsoleDataProvider cd = connector.getConsoleDataProvider(); if (cd != null) { cd.showConsole(this, createDisplayerFromImpl(displayer)); } } @Override public boolean canShowFailures() { return getBuild().canShowFailures(); } @Override public void showFailures(FailureDataDisplayerImpl displayer) { BuilderConnector.FailureDataProvider fp = connector.getFailureDataProvider(); if (fp != null) { fp.showFailures(this, createDisplayerFromImpl(displayer)); } } } }
3,227
2,649
<filename>app/src/main/java/json/chao/com/wanandroid/presenter/wx/WxDetailArticlePresenter.java package json.chao.com.wanandroid.presenter.wx; import javax.inject.Inject; import json.chao.com.wanandroid.R; import json.chao.com.wanandroid.app.WanAndroidApp; import json.chao.com.wanandroid.base.presenter.BasePresenter; import json.chao.com.wanandroid.component.RxBus; import json.chao.com.wanandroid.contract.wx.WxDetailContract; import json.chao.com.wanandroid.core.DataManager; import json.chao.com.wanandroid.core.bean.main.collect.FeedArticleData; import json.chao.com.wanandroid.core.bean.main.collect.FeedArticleListData; import json.chao.com.wanandroid.core.event.CollectEvent; import json.chao.com.wanandroid.core.event.JumpToTheTopEvent; import json.chao.com.wanandroid.utils.RxUtils; import json.chao.com.wanandroid.widget.BaseObserver; /** * @author quchao * @date 2018/10/31 */ public class WxDetailArticlePresenter extends BasePresenter<WxDetailContract.View> implements WxDetailContract.Presenter { private DataManager mDataManager; @Inject public WxDetailArticlePresenter(DataManager dataManager) { super(dataManager); this.mDataManager = dataManager; } @Override public void attachView(WxDetailContract.View view) { super.attachView(view); registerEvent(); } private void registerEvent() { addSubscribe(RxBus.getDefault().toFlowable(CollectEvent.class) .filter(collectEvent -> !collectEvent.isCancelCollectSuccess()) .subscribe(collectEvent -> mView.showCollectSuccess())); addSubscribe(RxBus.getDefault().toFlowable(CollectEvent.class) .filter(CollectEvent::isCancelCollectSuccess) .subscribe(collectEvent -> mView.showCancelCollectSuccess())); addSubscribe(RxBus.getDefault().toFlowable(JumpToTheTopEvent.class) .subscribe(knowledgeJumpTopEvent -> mView.showJumpTheTop())); } @Override public void getWxSearchSumData(int id, int page, String k) { addSubscribe(mDataManager.getWxSearchSumData(id, page, k) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_search_data_list)) { @Override public void onNext(FeedArticleListData feedArticleListData) { mView.showWxSearchView(feedArticleListData); } })); } @Override public void getWxDetailData(int id, int page, boolean isShowError) { addSubscribe(mDataManager.getWxSumData(id, page) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.failed_to_obtain_wx_data), isShowError) { @Override public void onNext(FeedArticleListData wxSumData) { mView.showWxDetailView(wxSumData); } })); } @Override public void addCollectArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.addCollectArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { feedArticleData.setCollect(true); mView.showCollectArticleData(position, feedArticleData, feedArticleListData); } })); } @Override public void cancelCollectArticle(int position, FeedArticleData feedArticleData) { addSubscribe(mDataManager.cancelCollectArticle(feedArticleData.getId()) .compose(RxUtils.rxSchedulerHelper()) .compose(RxUtils.handleCollectResult()) .subscribeWith(new BaseObserver<FeedArticleListData>(mView, WanAndroidApp.getInstance().getString(R.string.cancel_collect_fail)) { @Override public void onNext(FeedArticleListData feedArticleListData) { feedArticleData.setCollect(false); mView.showCancelCollectArticleData(position, feedArticleData, feedArticleListData); } })); } }
2,268
1,144
package de.metas.bpartner.service; import org.adempiere.ad.persistence.ModelDynAttributeAccessor; import org.compiere.model.I_C_AllocationHdr; import org.compiere.model.I_C_BPartner_Stats; import com.google.common.collect.ImmutableSet; import de.metas.util.Check; import de.metas.util.ISingletonService; import lombok.Builder; import lombok.NonNull; import lombok.Singular; import lombok.Value; /** * Service used to update {@link I_C_BPartner_Stats#COLUMN_TotalOpenBalance}, {@link I_C_BPartner_Stats#COLUMN_SO_CreditUsed}, {@link I_C_BPartner_Stats#COLUMN_ActualLifeTimeValue} and {@link I_C_BPartner_Stats#COLUMN_SOCreditStatus} * * @author tsa * */ public interface IBPartnerStatisticsUpdater extends ISingletonService { ModelDynAttributeAccessor<I_C_AllocationHdr, Boolean> DYNATTR_DisableUpdateTotalOpenBalances = new ModelDynAttributeAccessor<>("org.adempiere.bpartner.service.IBPartnerTotalOpenBalanceUpdater.DisableUpdateTotalOpenBalances", Boolean.class); void updateBPartnerStatistics(@NonNull final BPartnerStatisticsUpdateRequest request); @Value public static class BPartnerStatisticsUpdateRequest { final ImmutableSet<Integer> bpartnerIds; /** * This flag decides if {@link IBPartnerStatsBL#resetCreditStatusFromBPGroup(org.compiere.model.I_C_BPartner)} will also be invoked */ final boolean alsoResetCreditStatusFromBPGroup; @Builder private BPartnerStatisticsUpdateRequest( @NonNull @Singular final ImmutableSet<Integer> bpartnerIds, final boolean alsoResetCreditStatusFromBPGroup) { this.bpartnerIds = bpartnerIds.stream() .filter(bpartnerId -> bpartnerId > 0) .collect(ImmutableSet.toImmutableSet()); Check.assumeNotEmpty(this.bpartnerIds, "bpartnerIds is not empty"); this.alsoResetCreditStatusFromBPGroup = alsoResetCreditStatusFromBPGroup; } } }
654
667
/* * Copyright © 2013-2017 <NAME> * * This file is part of FreshPlayerPlugin. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "compat.h" #include "config.h" #include "config_priv.h" #include "gtk_wrapper.h" #include "main_thread.h" #include "np_asynccall.h" #include "pp_interface.h" #include "ppb_core.h" #include "ppb_instance.h" #include "ppb_message_loop.h" #include "reverse_constant.h" #include "tables.h" #include "trace_core.h" #include "utils.h" #include <X11/Xlib.h> #include <dlfcn.h> #include <glib.h> #include <npapi/npapi.h> #include <npapi/npfunctions.h> #include <ppapi/c/pp_bool.h> #include <ppapi/c/pp_errors.h> #include <ppapi/c/pp_module.h> #include <ppapi/c/pp_resource.h> #include <ppapi/c/ppb.h> #include <pthread.h> #include <signal.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> static void *module_dl_handler; static struct pp_instance_s *aux_instance = NULL; static int np_initialize_was_called = 0; struct call_plugin_init_module_param_s { PP_Resource m_loop; int depth; int32_t (*ppp_initialize_module)(PP_Module module_id, PPB_GetInterface get_browser_interface); int result; }; static void call_plugin_init_module_comt(void *user_data, int32_t result) { struct call_plugin_init_module_param_s *p = user_data; // TODO: make module ids distinct // p->ppp_initialize_module is always non-NULL p->result = p->ppp_initialize_module(42, ppb_get_interface); ppb_message_loop_post_quit_depth(p->m_loop, PP_FALSE, p->depth); } static void call_plugin_init_module_prepare_comt(void *user_data, int32_t result) { ppb_core_trampoline_to_main_thread(PP_MakeCCB(call_plugin_init_module_comt, user_data), PP_OK, __func__); } static int call_plugin_init_module(void) { int32_t (*ppp_initialize_module)(PP_Module module_id, PPB_GetInterface get_browser_interface); if (!module_dl_handler) return 0; ppp_initialize_module = dlsym(module_dl_handler, "PPP_InitializeModule"); if (!ppp_initialize_module) return 0; struct call_plugin_init_module_param_s *p = g_slice_alloc(sizeof(*p)); p->m_loop = ppb_message_loop_get_for_browser_thread(); p->depth = ppb_message_loop_get_depth(p->m_loop) + 1; p->ppp_initialize_module = ppp_initialize_module; ppb_message_loop_post_work_with_result(p->m_loop, PP_MakeCCB(call_plugin_init_module_prepare_comt, p), 0, PP_OK, p->depth, __func__); ppb_message_loop_run_nested(p->m_loop); int res = p->result; g_slice_free1(sizeof(*p), p); return res; } static int probe_ppp_module(void) { fpp_config_initialize(); if (!fpp_config_get_plugin_path()) { config.quirks.plugin_missing = 1; trace_error("%s, can't find %s\n", __func__, fpp_config_get_plugin_file_name()); return 1; } return 0; } static uintptr_t load_ppp_module() { if (module_dl_handler) { // already loaded return 0; } // ensure we have a module name probe_ppp_module(); if (!fpp_config_get_plugin_path()) goto err; module_dl_handler = dlopen(fpp_config_get_plugin_path(), RTLD_LAZY); if (!module_dl_handler) { trace_info_f("%s, can't open %s\n", __func__, fpp_config_get_plugin_path()); goto err; } int32_t (*ppp_initialize_module)(PP_Module module_id, PPB_GetInterface get_browser_interface); ppp_initialize_module = dlsym(module_dl_handler, "PPP_InitializeModule"); ppp_get_interface = dlsym(module_dl_handler, "PPP_GetInterface"); if (!ppp_initialize_module || !ppp_get_interface) { trace_error("%s, one of required PPP_* is missing\n", __func__); if (module_dl_handler) dlclose(module_dl_handler); module_dl_handler = NULL; goto err; } // allocate auxiliary instance if (!aux_instance) { aux_instance = calloc(1, sizeof(*aux_instance)); if (!aux_instance) goto err; aux_instance->id = tables_generate_new_pp_instance_id(); tables_add_pp_instance(aux_instance->id, aux_instance); } // allocate message loop for browser thread if (ppb_message_loop_get_current() == 0) { PP_Resource message_loop = ppb_message_loop_create(aux_instance->id); ppb_message_loop_attach_to_current_thread(message_loop); ppb_message_loop_proclaim_this_thread_browser(); } // allocate message loop for plugin thread (main thread) if (ppb_message_loop_get_for_main_thread() == 0) { pthread_barrier_init(&aux_instance->main_thread_barrier, NULL, 2); pthread_create(&aux_instance->main_thread, NULL, fresh_wrapper_main_thread, aux_instance); pthread_detach(aux_instance->main_thread); pthread_barrier_wait(&aux_instance->main_thread_barrier); pthread_barrier_destroy(&aux_instance->main_thread_barrier); } return 0; err: config.quirks.plugin_missing = 1; return 1; } struct call_plugin_shutdown_module_param_s { PP_Resource m_loop; int depth; void (*ppp_shutdown_module)(void); }; static void call_plugin_shutdown_module_comt(void *user_data, int32_t result) { struct call_plugin_shutdown_module_param_s *p = user_data; p->ppp_shutdown_module(); // p->ppp_shutdown_module is always non-NULL ppb_message_loop_post_quit_depth(p->m_loop, PP_FALSE, p->depth); } static void call_plugin_shutdown_module_prepare_comt(void *user_data, int32_t result) { ppb_core_trampoline_to_main_thread(PP_MakeCCB(call_plugin_shutdown_module_comt, user_data), PP_OK, __func__); } static void call_plugin_shutdown_module(void) { if (!module_dl_handler) return; void (*ppp_shutdown_module)(void); ppp_shutdown_module = dlsym(module_dl_handler, "PPP_ShutdownModule"); if (!ppp_shutdown_module) return; struct call_plugin_shutdown_module_param_s *p = g_slice_alloc(sizeof(*p)); p->m_loop = ppb_message_loop_get_for_browser_thread(); p->depth = ppb_message_loop_get_depth(p->m_loop) + 1; p->ppp_shutdown_module = ppp_shutdown_module; ppb_message_loop_post_work_with_result(p->m_loop, PP_MakeCCB(call_plugin_shutdown_module_prepare_comt, p), 0, PP_OK, p->depth, __func__); ppb_message_loop_run_nested(p->m_loop); g_slice_free1(sizeof(*p), p); } static void unload_ppp_module(void) { // call module shutdown handler if exists call_plugin_shutdown_module(); if (module_dl_handler) dlclose(module_dl_handler); module_dl_handler = NULL; fpp_config_destroy(); } const char * NP_GetMIMEDescription(void) { trace_info_f("[NP] %s\n", __func__); return fpp_config_get_plugin_mime_type(); } char * NP_GetPluginVersion(void) { trace_info_f("[NP] %s\n", __func__); probe_ppp_module(); return (char *)fpp_config_get_plugin_version(); } NPError NP_GetValue(void *instance, NPPVariable variable, void *value) { trace_info_f("[NP] %s instance=%p, variable=%s, value=%p\n", __func__, instance, reverse_npp_variable(variable), value); probe_ppp_module(); switch (variable) { case NPPVpluginNameString: *(const char **)value = fpp_config_get_plugin_name(); break; case NPPVpluginDescriptionString: *(const char **)value = fpp_config_get_plugin_descr(); break; default: trace_info_z(" not implemented variable %d\n", variable); } return NPERR_NO_ERROR; } static int x_error_handler(Display *dpy, XErrorEvent *ee) { trace_error("[NP] caught Xlib error %d\n", ee->error_code); return 0; } static int x_io_error_hanlder(Display *dpy) { // IO errors can't be ignored, they always terminate program. // Let's crash here to get core file! trace_error("[NP] got Xlib IO error\n"); abort(); return 0; } static void call_gdb_signal_handler(int sig, siginfo_t *si, void *p) { static char cmd[4096]; pid_t pid = getpid(); time_t now = time(NULL); // ask gdb to debug this process snprintf(cmd, sizeof(cmd), "gdb --pid %d" " -ex 'set logging file /tmp/freshwrapper-backtrace-%d-%d.txt'" " -ex 'set logging on'" " -ex 'set pagination off'" " -ex 'echo === backtrace triggered by signal %d ===\\n'" " -ex 'echo === current thread ===\\n'" " -ex bt" " -ex 'echo === thread list ===\\n'" " -ex 'info threads'" " -ex 'echo === all threads ===\\n'" " -ex 'thread apply all bt full'" " -ex 'set confirm off'" " -ex 'quit'", (int)pid, (int)now, (int)pid, sig); // call gdb int ret = system(cmd); if (ret != 0) printf("gdb return status: %d\n", ret); exit(sig); } static void setup_sig_handlers(void) { int s[] = { SIGSEGV, SIGILL, SIGABRT }; struct sigaction sa = {}; sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); for (uintptr_t k = 0; k < sizeof(s) / sizeof(s[0]); k ++) sigaddset(&sa.sa_mask, s[k]); sa.sa_sigaction = call_gdb_signal_handler; for (uintptr_t k = 0; k < sizeof(s) / sizeof(s[0]); k ++) { struct sigaction prev; // ensure there were no handlers before if (sigaction(s[k], NULL, &prev) != 0) continue; if ((prev.sa_flags & SA_SIGINFO) && prev.sa_sigaction != NULL) continue; if (!(prev.sa_flags & SA_SIGINFO) && prev.sa_handler != NULL) continue; // install own handler if (sigaction(s[k], &sa, NULL) != 0) trace_error("%s, can't set signal %d handler\n", __func__, s[k]); } } NPError NP_Initialize(NPNetscapeFuncs *aNPNFuncs, NPPluginFuncs *aNPPFuncs) { trace_info_f("[NP] %s aNPNFuncs=%p, aNPPFuncs=%p, browser API version = %u\n", __func__, aNPNFuncs, aNPPFuncs, aNPNFuncs->version); if (np_initialize_was_called) { trace_warning("NP_Initialize was called more than once\n"); return NPERR_NO_ERROR; } np_initialize_was_called = 1; setup_sig_handlers(); gtk_wrapper_initialize(); if (!gw_gtk_available()) { trace_error("no GTK+ loaded\n"); return NPERR_NO_ERROR; } trace_info_f("found GTK+ %d.%d\n", gw_major_version(), gw_minor_version()); // set logging-only error handler. // Ignore a previous one, we have no plans to restore it (void)XSetErrorHandler(x_error_handler); (void)XSetIOErrorHandler(x_io_error_hanlder); memset(&npn, 0, sizeof(npn)); memcpy(&npn, aNPNFuncs, sizeof(npn) < aNPNFuncs->size ? sizeof(npn) : aNPNFuncs->size); if (npn.pluginthreadasynccall == NULL) { trace_info_f("browser have npn.pluginthreadasynccall == NULL\n"); if (np_asynccall_initialize() != 0) { trace_error("can't initialize async call emulation\n"); // It's required, can't continue. return NPERR_GENERIC_ERROR; } npn.pluginthreadasynccall = np_asynccall_call; } NPPluginFuncs pf; memset(&pf, 0, sizeof(NPPluginFuncs)); pf.size = MIN(aNPPFuncs->size, sizeof(NPPluginFuncs)); // browser is supposed to fill .size and .version pf.newp = NPP_New; pf.destroy = NPP_Destroy; pf.setwindow = NPP_SetWindow; pf.newstream = NPP_NewStream; pf.destroystream = NPP_DestroyStream; pf.asfile = NPP_StreamAsFile; pf.writeready = NPP_WriteReady; pf.write = NPP_Write; pf.print = NPP_Print; pf.event = NPP_HandleEvent; pf.urlnotify = NPP_URLNotify; pf.getvalue = NPP_GetValue; pf.setvalue = NPP_SetValue; pf.gotfocus = NPP_GotFocus; pf.lostfocus = NPP_LostFocus; pf.urlredirectnotify = NPP_URLRedirectNotify; pf.clearsitedata = NPP_ClearSiteData; pf.getsiteswithdata = NPP_GetSitesWithData; pf.didComposite = NPP_DidComposite; memcpy(aNPPFuncs, &pf, pf.size); if (aNPNFuncs->version < NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL) { config.quirks.plugin_missing = 1; config.quirks.incompatible_npapi_version = 1; } load_ppp_module(); if (tables_open_display() != 0) return NPERR_GENERIC_ERROR; int res = call_plugin_init_module(); if (res != 0) { trace_error("%s, PPP_InitializeModule returned %d\n", __func__, res); return NPERR_GENERIC_ERROR; } return NPERR_NO_ERROR; } NPError NP_Shutdown(void) { trace_info_f("[NP] %s\n", __func__); unload_ppp_module(); tables_close_display(); return NPERR_NO_ERROR; }
6,429
471
{ "extends": [ "config:base" ], "rangeStrategy": "replace", "node": { "supportPolicy": "lts_latest" }, "ignoreDeps": [ "@types/node" ] }
76
421
#using <System.Xml.dll> #using <System.dll> #using <System.Windows.Forms.dll> #using <System.Drawing.dll> #using <System.Data.dll> using namespace System; using namespace System::Data; using namespace System::Drawing; using namespace System::Windows::Forms; public ref class Form1: public Form { protected: DataGrid^ dataGrid1; DataSet^ ds; private: // <Snippet1> void EditValue() { int rowtoedit = 1; CurrencyManager^ myCurrencyManager = dynamic_cast<CurrencyManager^>(this->BindingContext[ ds->Tables[ "Suppliers" ] ]); myCurrencyManager->Position = rowtoedit; DataGridColumnStyle^ dgc = dataGrid1->TableStyles[ 0 ]->GridColumnStyles[ 0 ]; dataGrid1->BeginEdit( dgc, rowtoedit ); // Insert code to edit the value. dataGrid1->EndEdit( dgc, rowtoedit, false ); } // </Snippet1> };
365
778
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by <NAME> first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #include "CleanAstVisitor.h" #include <cassert> namespace tuplex { ASTNode* CleanAstVisitor::replace(ASTNode *parent, ASTNode *next) { // parent must always be set assert(parent); // next may be an empty field if(!next) return nullptr; // check what type next is and optimize away if possible switch(next->type()) { case ASTNodeType::Compare: { NCompare *cmp = static_cast<NCompare *>(next); // compare node can be eliminated when only left hand side is set // is an inefficiency of the python parser... if (cmp->_left && cmp->_ops.size() == 0 && cmp->_comps.size() == 0) { // remove the "next" node ASTNode *res = cmp->_left->clone(); delete cmp; return res; } // else just return the node itself return cmp; } case ASTNodeType::Suite: { // NOTE: when using try/except this does not work anymore!!! // in suite remove statements after return if there are any int returnIndex = -1; NSuite *suite = static_cast<NSuite*>(next); int pos = 0; for(auto stmt : suite->_statements) { if(stmt->type() == ASTNodeType::Return ) returnIndex = pos; pos++; } // return found? if(returnIndex != -1) { // statements after return? if(returnIndex != suite->_statements.size() - 1) { auto shrunken_stmts = std::vector<ASTNode*>(suite->_statements.begin(), suite->_statements.begin() + returnIndex + 1); suite->_statements = shrunken_stmts; return suite; } } return suite; } default: return next; } return next; } }
1,874
407
package com.alibaba.tesla.authproxy.util.audit; public enum AuditReasonEnum { UNAUTHORIZED, AUTHORIZED, NULL; @Override public String toString() { return super.toString().toLowerCase(); } }
94
372
/* * * (c) Copyright 1989 OPEN SOFTWARE FOUNDATION, INC. * (c) Copyright 1989 HEWLETT-PACKARD COMPANY * (c) Copyright 1989 DIGITAL EQUIPMENT CORPORATION * To anyone who acknowledges that this file is provided "AS IS" * without any express or implied warranty: * permission to use, copy, modify, and distribute this * file for any purpose is hereby granted without fee, provided that * the above copyright notices and this notice appears in all source * code copies, and that none of the names of Open Software * Foundation, Inc., Hewlett-Packard Company, or Digital Equipment * Corporation be used in advertising or publicity pertaining to * distribution of the software without specific, written prior * permission. Neither Open Software Foundation, Inc., Hewlett- * Packard Company, nor Digital Equipment Corporation makes any * representations about the suitability of this software for any * purpose. * */ /* ** ** NAME ** ** NIDL.H ** ** ** FACILITY: ** ** Remote Procedure Call (RPC) ** ** ABSTRACT: ** ** Mandatory header file containing all system dependent ** includes and common macros used by the IDL compiler. ** ** VERSION: DCE 1.0 */ #ifndef NIDLH_INCL #define NIDLH_INCL #define NIDLBASE_H #ifdef HAVE_CONFIG_H #include <config.h> #endif /* Base include files needed by all IDL compiler modules */ #include <stdio.h> #include <string.h> #ifdef HAVE_STDBOOL_H #include <stdbool.h> #else typedef enum { false = 0, true = 1 } bool; #ifndef true #define true true #endif #ifndef false #define false false #endif #endif #ifdef DUMPERS # define DEBUG_VERBOSE 1 #endif # include <stdlib.h> # ifndef CHAR_BIT # include <limits.h> /* Bring in limits.h if not cacaded in yet */ # endif # include <assert.h> #include <sysdep.h> /* * some generally useful types and macros */ typedef unsigned char unsigned8; typedef unsigned short int unsigned16; typedef unsigned long int unsigned32; typedef unsigned8 boolean; #ifndef TRUE #define TRUE true #define FALSE false #endif /* * IDL's model of the info in a UUID (see dce_uuid_t in nbase.idl) */ typedef struct { unsigned32 time_low; unsigned16 time_mid; unsigned16 time_hi_and_version; unsigned8 clock_seq_hi_and_reserved; unsigned8 clock_seq_low; unsigned8 node[6]; } nidl_uuid_t; /* * Include files needed by the remaining supplied definitions in this file. * These need to be here, since they depend on the above definitions. */ #include <errors.h> #include <nidlmsg.h> /* Language enum. Here for lack of any place else. */ typedef enum { lang_ada_k, lang_basic_k, lang_c_k, lang_cobol_k, lang_fortran_k, lang_pascal_k } language_k_t; /* * Macro jackets for each of the C memory management routines. * The macros guarantee that control will not return to the caller without * memory; therefore the call site doesn't have to test. */ /** * Returns pointer to a new allocated object of the specified type. * It behaves like C++ new. The returned pointer is already correctly typed to * type *. So you should not cast it. Let the compiler detect any errors * instead of casting. * * The the returned memory is cleared. * * @param type of the object that should be allocated * @return a valid pointer correctly typed */ #define NEW(type) \ ( __extension__ \ ({ \ type * __local_pointer = calloc(1, sizeof(type)); \ if (NULL == __local_pointer) \ error (NIDL_OUTOFMEM); \ __local_pointer; \ })) /** * Allocates and returns pointer to a vector of objects. * It behaves like C++ new. The returned pointer is already correctly typed to * type *. So you should not cast it. Let the compiler detect any errors * instead of casting. * * The the returned memory is cleared. * * @notice size is the _number_ of objects to be allocated * * @param type of the object that should be allocated * @param size number of objects to be allocated * @return a valid pointer correctly typed */ #define NEW_VEC(type, size) \ ( __extension__ \ ({ \ type * __local_pointer = calloc((size), sizeof(type)); \ if (NULL == __local_pointer) \ error (NIDL_OUTOFMEM); \ __local_pointer; \ })) /** * Reallocates prevoiusly allocated memory area and returns the pointer to it. * It behaves like C++ new and C realloc. The returned pointer is already * correctly typed to typeof(pointer). So you should not cast it. Let the compiler * detect any errors instead of casting. * * The the returned memory is _not_ cleared. * * @notice size is the _number_ of objects to be allocated * * @param pointer points to previously allocated vector * @param size number of objects to be allocated * @return a valid pointer correctly typed */ #define RENEW(pointer, size) \ ( __extension__ \ ({ \ __typeof__ (pointer) __local_pointer; \ __local_pointer = \ realloc((pointer), \ size * sizeof(__typeof__ (* (pointer)))); \ if (NULL == __local_pointer) \ error (NIDL_OUTOFMEM); \ __local_pointer; \ })) /** * Allocates some memory area. * The returned pointer is always valid. Do not use this function. The better * sollution is to use one of the above *NEW* function which return already * typed pointers. * * @param size of the area to be allocated * @return a valid pointer to the allocated memory */ #define MALLOC(size) \ ( __extension__ \ ({ \ void * __local_pointer = calloc(1, (size)); \ if (NULL == __local_pointer) \ error (NIDL_OUTOFMEM); \ __local_pointer; \ })) /** * Frees memory allocated with one of the above functions * * @param pointer to the memory to be freed */ #define FREE(pointer) free (pointer); /* * Enable YYDEBUG, and ASSERTION checking, if DUMPERS is defined */ #ifdef DUMPERS # define YYDEBUG 1 /* If ASSERTION expression is FALSE, then issue warning */ # define ASSERTION(x) if (!(x)) warning(NIDL_INTERNAL_ERROR, __FILE__, __LINE__) #else # define ASSERTION(x) do {;} while (0); #endif #endif
2,137
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_METRICS_STRUCTURED_NEUTRINO_LOGGING_UTIL_H_ #define COMPONENTS_METRICS_STRUCTURED_NEUTRINO_LOGGING_UTIL_H_ #include "components/metrics/structured/neutrino_logging.h" #include "components/prefs/pref_service.h" // This file is for functions that depend upon //components/metrics. // Thus, these functions cannot be called by code in //components/metrics. namespace metrics { namespace structured { // Log the location in the code and the client id to the NeutrinoDevices // structured metrics log. Extract the client id using the local state. void NeutrinoDevicesLogWithLocalState(PrefService* local_state, NeutrinoDevicesLocation location); // Log the enrollment status (managed or unmanged), location in the code and // the client id to the NeutrinoDevices structured metrics log. Extract the // client id using the local state. void NeutrinoDevicesLogEnrollmentWithLocalState( PrefService* local_state, bool is_managed, NeutrinoDevicesLocation location); } // namespace structured } // namespace metrics #endif // COMPONENTS_METRICS_STRUCTURED_NEUTRINO_LOGGING_UTIL_H_
432
2,027
<reponame>sullis/atomix /* * Copyright 2015-present Open Networking Foundation * * 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 io.atomix.storage.buffer; import java.nio.charset.Charset; /** * Writable bytes. * <p> * This interface exposes methods for writing bytes to specific positions in a byte array. * * @author <a href="http://github.com/kuujo"><NAME></a> */ public interface BytesOutput<T extends BytesOutput<T>> { /** * Zeros out all bytes in the array. * * @return The written bytes. */ T zero(); /** * Zeros out all bytes starting at the given offset in the array. * * @param offset The offset at which to start zeroing out bytes. * @return The written bytes. */ T zero(int offset); /** * Zeros out bytes starting at the given offset up to the given length. * * @param offset The offset at which to start zeroing out bytes. * @param length THe total number of bytes to zero out. * @return The written bytes. */ T zero(int offset, int length); /** * Writes an array of bytes to the buffer. * * @param offset The offset at which to start writing the bytes. * @param src The array of bytes to write. * @param srcOffset The offset at which to start reading bytes from the given source. * @param length The number of bytes from the provided byte array to write to the buffer. * @return The written buffer. */ T write(int offset, Bytes src, int srcOffset, int length); /** * Writes an array of bytes to the buffer. * * @param offset The offset at which to start writing the bytes. * @param src The array of bytes to write. * @param srcOffset The offset at which to start reading bytes from the given source. * @param length The number of bytes from the provided byte array to write to the buffer. * @return The written buffer. */ T write(int offset, byte[] src, int srcOffset, int length); /** * Writes a byte to the buffer at the given offset. * * @param offset The offset at which to write the byte. * @param b The byte to write. * @return The written buffer. */ T writeByte(int offset, int b); /** * Writes an unsigned byte to the buffer at the given position. * * @param offset The offset at which to write the byte. * @param b The byte to write. * @return The written buffer. */ T writeUnsignedByte(int offset, int b); /** * Writes a 16-bit character to the buffer at the given offset. * * @param offset The offset at which to write the character. * @param c The character to write. * @return The written buffer. */ T writeChar(int offset, char c); /** * Writes a 16-bit signed integer to the buffer at the given offset. * * @param offset The offset at which to write the short. * @param s The short to write. * @return The written buffer. */ T writeShort(int offset, short s); /** * Writes a 16-bit unsigned integer to the buffer at the given offset. * * @param offset The offset at which to write the short. * @param s The short to write. * @return The written buffer. */ T writeUnsignedShort(int offset, int s); /** * Writes a 24-bit signed integer to the buffer at the given offset. * * @param offset The offset at which to write the short. * @param m The short to write. * @return The written buffer. */ T writeMedium(int offset, int m); /** * Writes a 24-bit unsigned integer to the buffer at the given offset. * * @param offset The offset at which to write the short. * @param m The short to write. * @return The written buffer. */ T writeUnsignedMedium(int offset, int m); /** * Writes a 32-bit signed integer to the buffer at the given offset. * * @param offset The offset at which to write the integer. * @param i The integer to write. * @return The written buffer. */ T writeInt(int offset, int i); /** * Writes a 32-bit unsigned integer to the buffer at the given offset. * * @param offset The offset at which to write the integer. * @param i The integer to write. * @return The written buffer. */ T writeUnsignedInt(int offset, long i); /** * Writes a 64-bit signed integer to the buffer at the given offset. * * @param offset The offset at which to write the long. * @param l The long to write. * @return The written buffer. */ T writeLong(int offset, long l); /** * Writes a single-precision 32-bit floating point number to the buffer at the given offset. * * @param offset The offset at which to write the float. * @param f The float to write. * @return The written buffer. */ T writeFloat(int offset, float f); /** * Writes a double-precision 64-bit floating point number to the buffer at the given offset. * * @param offset The offset at which to write the double. * @param d The double to write. * @return The written buffer. */ T writeDouble(int offset, double d); /** * Writes a 1 byte boolean to the buffer at the given offset. * * @param offset The offset at which to write the boolean. * @param b The boolean to write. * @return The written buffer. */ T writeBoolean(int offset, boolean b); /** * Writes a string to the buffer at the given offset. * * @param offset The offset at which to write the string. * @param s The string to write. * @return The written buffer. */ T writeString(int offset, String s); /** * Writes a string to the buffer at the given offset. * * @param offset The offset at which to write the string. * @param s The string to write. * @param charset The character set with which to encode the string. * @return The written buffer. */ T writeString(int offset, String s, Charset charset); /** * Writes a UTF-8 string to the buffer at the given offset. * * @param offset The offset at which to write the string. * @param s The string to write. * @return The written buffer. */ T writeUTF8(int offset, String s); /** * Flushes the bytes to the underlying persistence layer. * * @return The flushed buffer. */ T flush(); }
2,180
3,913
package cn.iocoder.yudao.framework.sms.core.client.impl.aliyun; import cn.hutool.core.util.ReflectUtil; import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest; import cn.iocoder.yudao.framework.common.core.KeyValue; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsReceiveRespDTO; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsSendRespDTO; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO; import cn.iocoder.yudao.framework.sms.core.enums.SmsTemplateAuditStatusEnum; import cn.iocoder.yudao.framework.sms.core.property.SmsChannelProperties; import cn.iocoder.yudao.framework.common.util.collection.MapUtils; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.sms.core.enums.SmsFrameworkErrorCodeConstants; import com.aliyuncs.AcsRequest; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateRequest; import com.aliyuncs.dysmsapi.model.v20170525.QuerySmsTemplateResponse; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.google.common.collect.Lists; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Mock; import java.util.List; import java.util.function.Function; import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.when; /** * {@link AliyunSmsClient} 的单元测试 * * @author 芋道源码 */ public class AliyunSmsClientTest extends BaseMockitoUnitTest { private final SmsChannelProperties properties = new SmsChannelProperties() .setApiKey(randomString()) // 随机一个 apiKey,避免构建报错 .setApiSecret(randomString()) // 随机一个 apiSecret,避免构建报错 .setSignature("芋道源码"); @InjectMocks private final AliyunSmsClient smsClient = new AliyunSmsClient(properties); @Mock private IAcsClient client; @Test public void testDoInit() { // 准备参数 // mock 方法 // 调用 smsClient.doInit(); // 断言 assertNotSame(client, ReflectUtil.getFieldValue(smsClient, "acsClient")); } @Test @SuppressWarnings("unchecked") public void testDoSendSms() throws ClientException { // 准备参数 Long sendLogId = randomLongId(); String mobile = randomString(); String apiTemplateId = randomString(); List<KeyValue<String, Object>> templateParams = Lists.newArrayList( new KeyValue<>("code", 1234), new KeyValue<>("op", "login")); // mock 方法 SendSmsResponse response = randomPojo(SendSmsResponse.class, o -> o.setCode("OK")); when(client.getAcsResponse(argThat((ArgumentMatcher<SendSmsRequest>) acsRequest -> { assertEquals(mobile, acsRequest.getPhoneNumbers()); assertEquals(properties.getSignature(), acsRequest.getSignName()); assertEquals(apiTemplateId, acsRequest.getTemplateCode()); assertEquals(toJsonString(MapUtils.convertMap(templateParams)), acsRequest.getTemplateParam()); assertEquals(sendLogId.toString(), acsRequest.getOutId()); return true; }))).thenReturn(response); // 调用 SmsCommonResult<SmsSendRespDTO> result = smsClient.doSendSms(sendLogId, mobile, apiTemplateId, templateParams); // 断言 assertEquals(response.getCode(), result.getApiCode()); assertEquals(response.getMessage(), result.getApiMsg()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getCode(), result.getCode()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getMsg(), result.getMsg()); assertEquals(response.getRequestId(), result.getApiRequestId()); // 断言结果 assertEquals(response.getBizId(), result.getData().getSerialNo()); } @Test public void testDoTParseSmsReceiveStatus() throws Throwable { // 准备参数 String text = "[\n" + " {\n" + " \"phone_number\" : \"13900000001\",\n" + " \"send_time\" : \"2017-01-01 11:12:13\",\n" + " \"report_time\" : \"2017-02-02 22:23:24\",\n" + " \"success\" : true,\n" + " \"err_code\" : \"DELIVERED\",\n" + " \"err_msg\" : \"用户接收成功\",\n" + " \"sms_size\" : \"1\",\n" + " \"biz_id\" : \"12345\",\n" + " \"out_id\" : \"67890\"\n" + " }\n" + "]"; // mock 方法 // 调用 List<SmsReceiveRespDTO> statuses = smsClient.doParseSmsReceiveStatus(text); // 断言 assertEquals(1, statuses.size()); assertTrue(statuses.get(0).getSuccess()); assertEquals("DELIVERED", statuses.get(0).getErrorCode()); assertEquals("用户接收成功", statuses.get(0).getErrorMsg()); assertEquals("13900000001", statuses.get(0).getMobile()); assertEquals(DateUtils.buildTime(2017, 2, 2, 22, 23, 24), statuses.get(0).getReceiveTime()); assertEquals("12345", statuses.get(0).getSerialNo()); assertEquals(67890L, statuses.get(0).getLogId()); } @Test public void testDoGetSmsTemplate() throws ClientException { // 准备参数 String apiTemplateId = randomString(); // mock 方法 QuerySmsTemplateResponse response = randomPojo(QuerySmsTemplateResponse.class, o -> { o.setCode("OK"); o.setTemplateStatus(1); // 设置模板通过 }); when(client.getAcsResponse(argThat((ArgumentMatcher<QuerySmsTemplateRequest>) acsRequest -> { assertEquals(apiTemplateId, acsRequest.getTemplateCode()); return true; }))).thenReturn(response); // 调用 SmsCommonResult<SmsTemplateRespDTO> result = smsClient.doGetSmsTemplate(apiTemplateId); // 断言 assertEquals(response.getCode(), result.getApiCode()); assertEquals(response.getMessage(), result.getApiMsg()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getCode(), result.getCode()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getMsg(), result.getMsg()); assertEquals(response.getRequestId(), result.getApiRequestId()); // 断言结果 assertEquals(response.getTemplateCode(), result.getData().getId()); assertEquals(response.getTemplateContent(), result.getData().getContent()); assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(), result.getData().getAuditStatus()); assertEquals(response.getReason(), result.getData().getAuditReason()); } @Test public void testConvertSmsTemplateAuditStatus() { assertEquals(SmsTemplateAuditStatusEnum.CHECKING.getStatus(), smsClient.convertSmsTemplateAuditStatus(0)); assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(), smsClient.convertSmsTemplateAuditStatus(1)); assertEquals(SmsTemplateAuditStatusEnum.FAIL.getStatus(), smsClient.convertSmsTemplateAuditStatus(2)); assertThrows(IllegalArgumentException.class, () -> smsClient.convertSmsTemplateAuditStatus(3), "未知审核状态(3)"); } @Test @SuppressWarnings("unchecked") public void testInvoke_throwable() throws ClientException { // 准备参数 QuerySmsTemplateRequest request = new QuerySmsTemplateRequest(); // mock 方法 ClientException ex = new ClientException("isv.INVALID_PARAMETERS", "参数不正确", randomString()); when(client.getAcsResponse(any(AcsRequest.class))).thenThrow(ex); // 调用,并断言异常 SmsCommonResult<?> result = smsClient.invoke(request,null); // 断言 assertEquals(ex.getErrCode(), result.getApiCode()); assertEquals(ex.getErrMsg(), result.getApiMsg()); Assertions.assertEquals(SmsFrameworkErrorCodeConstants.SMS_API_PARAM_ERROR.getCode(), result.getCode()); Assertions.assertEquals(SmsFrameworkErrorCodeConstants.SMS_API_PARAM_ERROR.getMsg(), result.getMsg()); assertEquals(ex.getRequestId(), result.getApiRequestId()); } @Test public void testInvoke_success() throws ClientException { // 准备参数 QuerySmsTemplateRequest request = new QuerySmsTemplateRequest(); Function<QuerySmsTemplateResponse, SmsTemplateRespDTO> responseConsumer = response -> { SmsTemplateRespDTO data = new SmsTemplateRespDTO(); data.setId(response.getTemplateCode()).setContent(response.getTemplateContent()); data.setAuditStatus(SmsTemplateAuditStatusEnum.SUCCESS.getStatus()).setAuditReason(response.getReason()); return data; }; // mock 方法 QuerySmsTemplateResponse response = randomPojo(QuerySmsTemplateResponse.class, o -> { o.setCode("OK"); o.setTemplateStatus(1); // 设置模板通过 }); when(client.getAcsResponse(any(AcsRequest.class))).thenReturn(response); // 调用 SmsCommonResult<SmsTemplateRespDTO> result = smsClient.invoke(request, responseConsumer); // 断言 assertEquals(response.getCode(), result.getApiCode()); assertEquals(response.getMessage(), result.getApiMsg()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getCode(), result.getCode()); assertEquals(GlobalErrorCodeConstants.SUCCESS.getMsg(), result.getMsg()); assertEquals(response.getRequestId(), result.getApiRequestId()); // 断言结果 assertEquals(response.getTemplateCode(), result.getData().getId()); assertEquals(response.getTemplateContent(), result.getData().getContent()); assertEquals(SmsTemplateAuditStatusEnum.SUCCESS.getStatus(), result.getData().getAuditStatus()); assertEquals(response.getReason(), result.getData().getAuditReason()); } }
4,633
852
#include "FastSimulation/Tracking/interface/TrackingLayer.h" #include "FWCore/Utilities/interface/Exception.h" #include "DataFormats/SiStripDetId/interface/StripSubdetector.h" const TrackingLayer::eqfct TrackingLayer::_eqfct; TrackingLayer::TrackingLayer() : _subDet(Det::UNKNOWN), _side(Side::BARREL), _layerNumber(0) {} TrackingLayer TrackingLayer::createFromDetId(const DetId& detId, const TrackerTopology& trackerTopology) { TrackingLayer trackingLayer; uint32_t subdet = detId.subdetId(); //BPix if (subdet == PixelSubdetector::PixelBarrel) { trackingLayer._subDet = TrackingLayer::Det::PXB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = trackerTopology.pxbLayer(detId); } //FPix else if (subdet == PixelSubdetector::PixelEndcap) { trackingLayer._subDet = TrackingLayer::Det::PXD; if (trackerTopology.pxfSide(detId) == 1) { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else if (trackerTopology.pxfSide(detId) == 2) { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking") << "Tracker hit for seeding in FPix seems neither on positive nor on negative disk side: " << trackerTopology.print(detId).c_str(); } trackingLayer._layerNumber = trackerTopology.pxfDisk(detId); } //TIB else if (subdet == StripSubdetector::TIB) { trackingLayer._subDet = TrackingLayer::Det::TIB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = trackerTopology.tibLayer(detId); } //TID else if (subdet == StripSubdetector::TID) { trackingLayer._subDet = TrackingLayer::Det::TID; if (trackerTopology.tidSide(detId) == 1) { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else if (trackerTopology.tidSide(detId) == 2) { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking") << "Tracker hit for seeding in TID seems neither on positive nor on negative disk side: " << trackerTopology.print(detId).c_str(); } trackingLayer._layerNumber = trackerTopology.tidWheel(detId); } //TOB else if (subdet == StripSubdetector::TOB) { trackingLayer._subDet = TrackingLayer::Det::TOB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = trackerTopology.tobLayer(detId); } //TEC else if (subdet == StripSubdetector::TEC) { trackingLayer._subDet = TrackingLayer::Det::TEC; if (trackerTopology.tecSide(detId) == 1) { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else if (trackerTopology.tecSide(detId) == 2) { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking") << "Tracker hit for seeding in TEC seems neither on positive nor on negative disk side: " << trackerTopology.print(detId).c_str(); } trackingLayer._layerNumber = trackerTopology.tecWheel(detId); } else { throw cms::Exception("FastSimulation/Tracking") << "Cannot determine seeding layer from DetId:" << trackerTopology.print(detId).c_str() << std::endl; } //std::cout<<"LayerSpec::createFromDetId: "<<trackerTopology.print(detId).c_str()<<", parsed="<<seedingLayer.print().c_str()<<std::endl; return trackingLayer; } TrackingLayer TrackingLayer::createFromString(std::string layerSpecification) { TrackingLayer trackingLayer; if (layerSpecification.substr(0, 4) == "BPix") { trackingLayer._subDet = TrackingLayer::Det::PXB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); } else if (layerSpecification.substr(0, 4) == "FPix") { trackingLayer._subDet = TrackingLayer::Det::PXD; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); if (layerSpecification.substr(layerSpecification.size() - 3) == "pos") { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else if (layerSpecification.substr(layerSpecification.size() - 3) == "neg") { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking/python") << "FPix seeding layer configuration '" << layerSpecification.c_str() << "' does not specify the side correctly!"; } } else if (layerSpecification.substr(0, 3) == "TIB") { trackingLayer._subDet = TrackingLayer::Det::TIB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(3, 1).c_str()); } else if (layerSpecification.substr(0, 4) == "MTIB") { trackingLayer._subDet = TrackingLayer::Det::TIB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); } else if (layerSpecification.substr(0, 3) == "TID") { trackingLayer._subDet = TrackingLayer::Det::TID; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(3, 1).c_str()); if (layerSpecification.substr(layerSpecification.size() - 3) == "pos") { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else if (layerSpecification.substr(layerSpecification.size() - 3) == "neg") { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking/python") << "TID seeding layer configuration '" << layerSpecification.c_str() << "' does not specify the side correctly!"; } } else if (layerSpecification.substr(0, 4) == "MTID") { trackingLayer._subDet = TrackingLayer::Det::TID; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); if (layerSpecification.substr(layerSpecification.size() - 3) == "pos") { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else if (layerSpecification.substr(layerSpecification.size() - 3) == "neg") { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking/python") << "MTID seeding layer configuration '" << layerSpecification.c_str() << "' does not specify the side correctly!"; } } else if (layerSpecification.substr(0, 3) == "TOB") { trackingLayer._subDet = TrackingLayer::Det::TOB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(3, 1).c_str()); } else if (layerSpecification.substr(0, 4) == "MTOB") { trackingLayer._subDet = TrackingLayer::Det::TOB; trackingLayer._side = TrackingLayer::Side::BARREL; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); } else if (layerSpecification.substr(0, 3) == "TEC") { trackingLayer._subDet = TrackingLayer::Det::TEC; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(3, 1).c_str()); if (layerSpecification.substr(layerSpecification.size() - 3) == "pos") { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else if (layerSpecification.substr(layerSpecification.size() - 3) == "neg") { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking/python") << "TEC seeding layer configuration '" << layerSpecification.c_str() << "' does not specify the side correctly!"; } } else if (layerSpecification.substr(0, 4) == "MTEC") { trackingLayer._subDet = TrackingLayer::Det::TEC; trackingLayer._layerNumber = std::atoi(layerSpecification.substr(4, 1).c_str()); if (layerSpecification.substr(layerSpecification.size() - 3) == "pos") { trackingLayer._side = TrackingLayer::Side::POS_ENDCAP; } else if (layerSpecification.substr(layerSpecification.size() - 3) == "neg") { trackingLayer._side = TrackingLayer::Side::NEG_ENDCAP; } else { throw cms::Exception("FastSimulation/Tracking/python") << "MTEC seeding layer configuration '" << layerSpecification.c_str() << "' does not specify the side correctly!"; } } else { throw cms::Exception("FastSimulation/Tracking/python") << "Bad data naming in seeding layer configuration." << "no case sensitive name of ['BPix','FPix','TIB','MTIB','TID','MTID','TOB','TEC','MTEC'] matches '" << layerSpecification.c_str() << "'"; } //std::cout<<"LayerSpec::createFromString: "<<layerSpecification.c_str()<<", parsed="<<seedingLayer.print().c_str()<<std::endl; return trackingLayer; } std::string TrackingLayer::toString() const { std::stringstream ss; switch (_subDet) { case TrackingLayer::Det::UNKNOWN: ss << "unknown"; break; case TrackingLayer::Det::PXB: ss << " BPix"; break; case TrackingLayer::Det::PXD: ss << " FPix"; break; case TrackingLayer::Det::TIB: ss << " TIB"; break; case TrackingLayer::Det::TID: ss << " TID"; break; case TrackingLayer::Det::TOB: ss << " TOB"; break; case TrackingLayer::Det::TEC: ss << " TEC"; break; } ss << _layerNumber; switch (_side) { case TrackingLayer::Side::BARREL: break; case Side::NEG_ENDCAP: ss << "_neg"; break; case TrackingLayer::Side::POS_ENDCAP: ss << "_pos"; break; } return ss.str(); } std::string TrackingLayer::toIdString() const { std::stringstream ss; ss << getSubDetNumber() << ":" << getLayerNumber() << ":" << getSideNumber(); return ss.str(); }
3,606
19,628
<filename>Android/doraemonkit/src/main/java/com/didichuxing/doraemonkit/kit/network/stream/HttpOutputStreamProxy.java package com.didichuxing.doraemonkit.kit.network.stream; import com.didichuxing.doraemonkit.kit.network.NetworkManager; import com.didichuxing.doraemonkit.kit.network.bean.NetworkRecord; import com.didichuxing.doraemonkit.kit.network.core.NetworkInterpreter; import com.didichuxing.doraemonkit.kit.network.core.RequestBodyHelper; import java.io.IOException; import java.io.OutputStream; /** * @author: linjizong * 2019/3/14 * @desc: */ public class HttpOutputStreamProxy extends OutputStreamProxy { private final int mRequestId; private final NetworkInterpreter mInterpreter; public HttpOutputStreamProxy(OutputStream out,int requestId, NetworkInterpreter interpreter) { super(out); mRequestId = requestId; mInterpreter = interpreter; } @Override protected void onStreamComplete() throws IOException { NetworkRecord record = NetworkManager.get().getRecord(mRequestId); if (record != null && record.mRequest != null) { RequestBodyHelper requestBodyHelper = new RequestBodyHelper(); try { OutputStream out = requestBodyHelper.createBodySink(record.mRequest.encode); mOutputStream.writeTo(out); } finally { out.close(); } byte[] body = requestBodyHelper.getDisplayBody(); mInterpreter.fetRequestBody(record, body); } } }
594
1,493
<reponame>Air-TR/urule-springboot /******************************************************************************* * Copyright 2017 Bstek * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. ******************************************************************************/ package com.bstek.urule.runtime.rete; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.context.ApplicationContext; import com.bstek.urule.Utils; import com.bstek.urule.debug.MessageItem; import com.bstek.urule.debug.MsgType; import com.bstek.urule.runtime.ElCalculator; import com.bstek.urule.runtime.WorkingMemory; import com.bstek.urule.runtime.assertor.AssertorEvaluator; /** * @author Jacky.gao * @since 2015年1月8日 */ public class ContextImpl implements Context { private ApplicationContext applicationContext; private AssertorEvaluator assertorEvaluator; private Map<String,String> variableCategoryMap; private ValueCompute valueCompute; private WorkingMemory workingMemory; private List<MessageItem> debugMessageItems; private ElCalculator elCalculator=new ElCalculator(); public ContextImpl(WorkingMemory workingMemory,ApplicationContext applicationContext,Map<String,String> variableCategoryMap,List<MessageItem> debugMessageItems) { this.workingMemory=workingMemory; this.applicationContext = applicationContext; this.assertorEvaluator=(AssertorEvaluator)applicationContext.getBean(AssertorEvaluator.BEAN_ID); this.variableCategoryMap=variableCategoryMap; this.debugMessageItems=debugMessageItems; this.valueCompute=(ValueCompute)applicationContext.getBean(ValueCompute.BEAN_ID); } @Override public WorkingMemory getWorkingMemory() { return workingMemory; } public ApplicationContext getApplicationContext() { return applicationContext; } public AssertorEvaluator getAssertorEvaluator() { return assertorEvaluator; } @Override public Object parseExpression(String expression) { return elCalculator.eval(expression); } @Override public void debugMsg(String msg, MsgType type, boolean enableDebug) { if(!Utils.isDebug() || !enableDebug){ return; } if(!Utils.isDebugToFile()){ System.out.println(msg); return; } MessageItem item=new MessageItem(msg,type); debugMessageItems.add(item); } @Override public List<MessageItem> getDebugMessageItems() { return debugMessageItems; } public String getVariableCategoryClass(String variableCategory) { String clazz=variableCategoryMap.get(variableCategory); if(StringUtils.isEmpty(clazz)){ //throw new RuleException("Variable category ["+variableCategory+"] not exist."); clazz=HashMap.class.getName(); } return clazz; } public ValueCompute getValueCompute() { return valueCompute; } }
1,018
11,351
package com.netflix.discovery.shared.transport.jersey; import java.util.Collection; import java.util.Optional; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.EurekaClientConfig; import com.netflix.discovery.shared.transport.TransportClientFactory; public interface TransportClientFactories<F> { @Deprecated public TransportClientFactory newTransportClientFactory(final Collection<F> additionalFilters, final EurekaJerseyClient providedJerseyClient); public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<F> additionalFilters, final InstanceInfo myInstanceInfo); public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig, final Collection<F> additionalFilters, final InstanceInfo myInstanceInfo, final Optional<SSLContext> sslContext, final Optional<HostnameVerifier> hostnameVerifier); }
527
5,169
{ "name": "FancyAd", "version": "1.0.0", "summary": "A short description of FancyAd.", "description": "PTGAdFramework provides Union ADs which include native、banner、feed、splash、RewardVideo etc.", "homepage": "https://github.com/PTGAd/FancyAd", "license": "MIT", "authors": { "fancy": "<EMAIL>" }, "source": { "git": "https://github.com/PTGAd/FancyAd.git", "tag": "1.0.0" }, "platforms": { "ios": "9.0" }, "frameworks": [ "UIKit", "MapKit", "WebKit", "MediaPlayer", "AdSupport", "CoreMedia", "AVFoundation", "CoreTelephony", "StoreKit", "SystemConfiguration", "MobileCoreServices", "CoreMotion", "Accelerate" ], "libraries": [ "c++", "resolv", "z", "sqlite3" ], "vendored_frameworks": "Frameworks/FancyAdSDK.framework", "resources": "Frameworks/FancyAdSDK.bundle", "xcconfig": { "VALID_ARCHS": "armv7 armv7s x86_64 arm64" } }
426
315
def prettier(name, args): native.sh_binary( name = name, srcs = ["prettier.sh"], args = [ "$(location @nodejs//:node)", "$(location @npm//:node_modules/prettier/bin-prettier.js)", ] + args, data = [ "@nodejs//:node", "@npm//:node_modules/prettier/bin-prettier.js", ], )
207
384
<gh_stars>100-1000 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Imperative mode for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow import * # pylint: disable=wildcard-import from tensorflow.contrib.imperative import imperative_mode class _InteractiveMode(object): """Imperative mode suitable for interactive execution. This module has a global _InteractiveMode object that enables writing code as follows: ```python import tensorflow.contrib.imperative as tf print(tf.constant(42)) ``` """ def __init__(self, target=None): if not target: target = train.Server.create_local_server().target self.target = target self.imperative_mode = imperative_mode.ImperativeMode(self.target) self.imperative_mode.__enter__() def new_step(self): return self.imperative_mode.new_step() _default_interactive_mode = _InteractiveMode() def new_step(): return _default_interactive_mode.new_step()
477
1,178
/* * Copyright 2020 Makani Technologies LLC * * 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. */ #include "avionics/motor/firmware/gio.h" #include <assert.h> #include <stdbool.h> #include <stdint.h> #include "avionics/firmware/cpu/gio.h" #include "avionics/firmware/cpu/io.h" #include "avionics/firmware/cpu/vim.h" #include "avionics/firmware/serial/motor_serial_params.h" #include "avionics/motor/firmware/flags.h" #include "avionics/motor/firmware/isr.h" #include "avionics/motor/firmware/svpwm.h" static MotorHardware g_motor_controller_type = -1; void MotorPositionControlInit(MotorHardware motor_controller_type) { if (motor_controller_type == kMotorHardwareOzoneA1) { // Set up GPIO to pull nTMS570-POS-CTRL low. This allows the TMS570 to // control the position sensor on an Ozone controller. IoConfigureAsOutputPushPull(kIoDcan3PinTx, false); } // On Gin controllers, the TMS570 automatically has control of the position // sensor and kIoDcan3PinTx is instead used for power good detection. } void MotorGdbPowerGoodInit(MotorHardware motor_controller_type) { g_motor_controller_type = motor_controller_type; if (motor_controller_type == kMotorHardwareOzoneA1) { // Due to IO limitations, the TMS570 on the Ozone only has access to the // anded signal from all gate driver boards. However, this signal is // latched; set up a GPIO pin as PGOOD latch nreset. IoConfigureAsOutputPushPull(kIoDcan3PinRx, true); // nDesat pin configuration. GioConfigureAsInput(kGioPinA2); IoConfigureAsOutputOpenDrain(kIoDcan2PinTx, true); } else { // With the Gin controllers, individual power good signals from the high and // low sides of each gate driver board are fed (more or less) directly into // the TMS570. Meanwhile, no latching is present. IoConfigureAsInput(kIoDcan2PinTx); IoConfigureAsInput(kIoDcan2PinRx); IoConfigureAsInput(kIoDcan3PinTx); IoConfigureAsInput(kIoDcan3PinRx); IoConfigureAsInput(kIoSpi3PinScs4); IoConfigureAsInput(kIoSpi3PinMosi0); } // Set up FIQ interrupt for GDB power loss. VimRegisterFiq(kVimChannelGioLowLevel, MotorGdbPowerGoodInterruptHandler); VimEnableInterrupt(kVimChannelGioLowLevel); // Anded GDB PGOOD signals are connected to GIOA[5]. GioConfigureAsInput(kGioPinA5); GioSetInterruptDetect(kGioPinA5, kGioInterruptDetectFallingEdge); GioSetInterruptPriorityAsLow(kGioPinA5); GioClearInterruptFlag(kGioPinA5); GioEnableInterrupt(kGioPinA5); } uint32_t MotorGdbProcessPowerGoodInterrupt(void) { GioClearInterruptFlag(kGioPinA5); uint32_t warnings = MotorGdbGetPowerGoodStatus(); // Signal phantom interrupt. if (!warnings) { warnings = kMotorWarningPowerGoodPhantom; } return warnings; } uint32_t MotorGdbGetPowerGoodStatus(void) { uint32_t warnings = kMotorWarningNone; assert(g_motor_controller_type >= 0); if (g_motor_controller_type != kMotorHardwareOzoneA1) { // Poll power good pins. if (!IoGetValue(kIoDcan2PinTx)) warnings |= kMotorWarningPowerGood1Hs; if (!IoGetValue(kIoDcan2PinRx)) warnings |= kMotorWarningPowerGood2Hs; if (!IoGetValue(kIoDcan3PinTx)) warnings |= kMotorWarningPowerGood3Hs; if (!IoGetValue(kIoDcan3PinRx)) warnings |= kMotorWarningPowerGood1Ls; if (!IoGetValue(kIoSpi3PinScs4)) warnings |= kMotorWarningPowerGood2Ls; if (!IoGetValue(kIoSpi3PinMosi0)) warnings |= kMotorWarningPowerGood3Ls; } // Look for undetected falling edge interrupt via N2HET's HETPINENA. if (!SvpwmCheckHetPinEna()) { warnings |= kMotorWarningPowerGoodHetPinEna; } return warnings; } void MotorGdbPowerGoodReset(void) { assert(g_motor_controller_type >= 0); if (g_motor_controller_type == kMotorHardwareOzoneA1) { IoSetOutputLow(kIoDcan3PinRx); IoSetOutputHigh(kIoDcan3PinRx); } } uint32_t MotorGdbDesatStatus(void) { uint32_t warnings = kMotorWarningNone; assert(g_motor_controller_type >= 0); if (g_motor_controller_type == kMotorHardwareOzoneA1) { // Poll latched nDesat input. if (!GioGetValue(kGioPinA2)) { warnings |= kMotorWarningDesat; } } return warnings; } void MotorGdbDesatReset(void) { assert(g_motor_controller_type >= 0); if (g_motor_controller_type == kMotorHardwareOzoneA1) { IoSetOutputLow(kIoDcan2PinTx); IoSetOutputHigh(kIoDcan2PinTx); } }
1,827
1,179
<gh_stars>1000+ # encoding: utf-8 from opendatatools.common import RestAgent from bs4 import BeautifulSoup import pandas as pd import json anjuke_city_map = { '北京' : 'bj', '上海' : 'sh', '杭州' : 'hz', '广州' : 'gz', '深圳' : 'sz', '厦门' : 'xm', '苏州' : 'su', '重庆' : 'cq', '长沙' : 'cs', '海口' : 'hk', '合肥' : 'hf', '济南' : 'jn', '青岛' : 'qd', '南京' : 'nj', '石家庄': 'sjz', '沈阳' : 'sy', '天津' : 'tj', '武汉' : 'wh', '无锡' : 'wx', '西安' : 'xa', '珠海' : 'zh', '郑州' : 'zz', } class AnjukeAgent(RestAgent): def __init__(self): RestAgent.__init__(self) self.city_map = {} def load_city(self): url = 'https://www.anjuke.com/sy-city.html' response = self.do_request(url) if response is None: return {} soup = BeautifulSoup(response, "html5lib") divs = soup.find_all('div') for div in divs: if div.has_attr('class') and 'letter_city' in div['class']: links = div.find_all('a') for link in links: url = link['href'] city = link.text self.city_map[city] = url @staticmethod def extract_word(text, start_tag, end_tag): index1 = text.find(start_tag) index2 = text.find(end_tag, index1) return text[index1 + len(start_tag): index2] def get_city_list(self): if len(self.city_map) == 0: self.load_city() return self.city_map.keys() def get_real_house_price(self, city): if len(self.city_map) == 0: self.load_city() if city not in self.city_map: return None, "城市输入错误" url = self.city_map[city] url_market = url + "/market/" response = self.do_request(url_market) if response is None: return None, '获取数据失败' content = AnjukeAgent.extract_word(response, 'drawChart(', ');') xyear = json.loads('{' + AnjukeAgent.extract_word(content, 'xyear:{', '},') + '}') ydata = json.loads(AnjukeAgent.extract_word(content, 'ydata:', '] ')) list_date = [] for month, year in xyear.items(): month = int(month.replace('月', '')) year = int(year.replace('年', '')) date = '%04d%02d' % (year, month) list_date.append(date) list_price = ydata[0]['data'] df = pd.DataFrame({'date': list_date, 'price': list_price}) df['city'] = city return df, '' def get_rent(self, city, page_no): url = "https://%s.zu.anjuke.com/p%s/" % (city, page_no) response = self.do_request(url, encoding='utf-8') soup = BeautifulSoup(response, 'html5lib') divs = soup.find_all('div') data_list = [] for div in divs: if div.has_attr('class') and 'zu-itemmod' in div['class']: try: title = div.find_all('h3')[0].a.text row1 = div.find_all('p')[0].text.split('|') type = row1[0].replace('\n', '').replace(' ', '') area = row1[1].replace('\n', '').replace(' ', '') height = row1[2].split('层')[0] row2 = div.find_all('p')[1].text.replace(' ', '').split('\n') part = row2[1] direction = row2[2] trans = row2[3] price = div.find_all('p')[2].text row3 = div.find_all('address')[0].text.split('\n') addr = row3[1].replace(' ', '') location = row3[2].replace(' ', '').split(r"\\")[0] data_list.append([type, area, height, part, direction, trans, price, addr, location, title]) except: print('error occurs on this item') return data_list, ''
2,188
11,811
<reponame>maximmenshikov/antlr4 # # Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. # from __future__ import unicode_literals import sys def is_leading_surrogate(code_unit): return 0xD800 <= code_unit <= 0xDBFF def is_trailing_surrogate(code_unit): return 0xDC00 <= code_unit <= 0xDFFF def decode_surrogate_pair(leading, trailing): return ((leading - 0xD800) << 10) + (trailing - 0xDC00) + 0x10000 def _from_unicode(unistr): return (ord(c) for c in unistr) def _from_utf16(unistr): assert sys.maxunicode == 0xFFFF leading_surrogate = -1 for utf16 in unistr: code_unit = ord(utf16) if leading_surrogate == -1: if is_leading_surrogate(code_unit): leading_surrogate = code_unit else: yield code_unit else: if is_trailing_surrogate(code_unit): # Valid surrogate pair code_point = decode_surrogate_pair(leading_surrogate, code_unit) yield code_point leading_surrogate = -1 else: # Leading surrogate without trailing surrogate yield leading_surrogate if is_leading_surrogate(code_unit): leading_surrogate = code_unit else: yield code_point leading_surrogate = -1 # Dangling surrogate at end of input if leading_surrogate != -1: yield leading_surrogate def _to_utf16(code_points): for code_point in code_points: if code_point <= 0xFFFF: yield unichr(code_point) else: base = code_point - 0x10000 high_surrogate = (base >> 10) + 0xD800 low_surrogate = (base & 0x3FF) + 0xDC00 yield unichr(high_surrogate) yield unichr(low_surrogate) def _to_chars(code_points): return (unichr(cp) for cp in code_points) if sys.maxunicode == 0xFFFF: from_unicode = _from_utf16 to_chars = _to_utf16 else: assert sys.maxunicode == 0x10FFFF from_unicode = _from_unicode to_chars = _to_chars def to_unicode(code_points): return u''.join(to_chars(code_points))
1,116