text
stringlengths
27
775k
--- title: 微软Bing疑似服务中断,已恢复 date: 2021-12-16 18:00:00 +0800 tags: Bing 微软 categories: article --- 备用域名似乎可用 https://www4.bing.com/ 2021.12.18 更新 目前服务正常
# 回调函数 WebSocket除了接收`Swoole\Server`和`Swoole\Http\Server`基类的回调函数外,额外增加了3个回调函数设置。其中: * `onMessage`回调函数为**必选** * `onOpen`和`onHandShake`回调函数为可选
--- layout: post microblog: true date: 2016-08-21 21:28 +1300 guid: http://JacksonOfTrades.micro.blog/2016/08/21/t767277179046539264.html --- @HowEChia I usually have a triple shot mocha, but I may need to try that now.
use components::{event::Event, snapshot::Snapshot}; use downcast_rs::{impl_downcast, Downcast}; pub trait State: Downcast { fn handle_event(&mut self, snapshot: &Snapshot, event: &Event); } impl_downcast!(State);
param ( [Parameter(Mandatory)] [string] $TxtFilePath, [Parameter(Mandatory)] [string] $RtfFilePath ) $txtFileContent = (Get-Content -LiteralPath $TxtFilePath -Encoding UTF8 -Raw). Replace('\', '\\'). Replace('{', '\{'). Replace('}', '\}'). Replace([System.Environment]::NewLine, ' \par ') $rtfFileContnet = '{\rtf1\ansi{\fonttbl\f0\fswiss Calibri;}\f0\fs17\pard ' + $txtFileContent + ' }' Set-Content -LiteralPath $RtfFilePath -Encoding Ascii -NoNewline -Value $rtfFileContnet
import Cart from "@components/cart/cart"; import { useUI } from "@contexts/ui.context"; import { Drawer } from "@components/common/drawer/drawer"; import { useRouter } from "next/router"; import { getDirection } from "@utils/get-direction"; const ManagedDrawer = () => { const { displayCart, closeCart } = useUI(); const { locale } = useRouter(); const dir = getDirection(locale); const contentWrapperCSS = dir === "ltr" ? { right: 0 } : { left: 0 }; return ( <Drawer open={displayCart} placement={dir === "rtl" ? "left" : "right"} onClose={closeCart} handler={false} showMask={true} level={null} contentWrapperStyle={contentWrapperCSS} > <Cart /> </Drawer> ); }; export default ManagedDrawer;
bp_require File.join(*%w[net-mdns lib net dns mdns-sd]) Thread.abort_on_exception = true DNSSD = Net::DNS::MDNSSD class Bonjour def initialize(args) end def browse(bp, args) service = DNSSD.browse(args['service']) do |b| DNSSD.resolve(b.name, b.type) do |r| log(r.target) log(r.port) # next if same host next if r.target == Socket.gethostname args['callback'].invoke( b.name, r.target, r.port ) end end sleep(args['timeout'] || 3) service.stop bp.complete(true) end def register(bp, args) DNSSD.register(args['name'], args['service'], 'local', args['port']) bp.complete(true) end private def log(d) bp_log("info", d.inspect) end end # http://browserplus.yahoo.com/developer/services/ruby/ rubyCoreletDefinition = { 'class' => "Bonjour", 'name' => "Bonjour", 'major_version' => 1, 'minor_version' => 0, 'micro_version' => 6, 'documentation' => 'A Bonjour service.', 'functions' => [ { 'name' => 'browse', 'documentation' => "Browse for Bonjour services", 'arguments' => [ { 'name' => 'service', 'type' => 'string', 'required' => true, 'documentation' => 'Type of service, e.g. _example._tcp' }, { 'name' => 'callback', 'type' => 'callback', 'required' => true, 'documentation' => 'Callback invoked with services are found' }, { 'name' => 'timeout', 'type' => 'integer', 'required' => false, 'documentation' => 'Timeout' } ] }, { 'name' => 'register', 'documentation' => "Register a Bonjour service", 'arguments' => [ { 'name' => 'name', 'type' => 'string', 'required' => true, 'documentation' => 'Name of service' }, { 'name' => 'service', 'type' => 'string', 'required' => true, 'documentation' => 'Type of service, e.g. _example._tcp' }, { 'name' => 'port', 'type' => 'integer', 'required' => true, 'documentation' => 'Port of service' } ] } ] }
import React from 'react' import Layout from '../components/Layout' import SEO from '../components/SEO' function NotFound() { return ( <Layout> <SEO title="Ronaldo Gjini - Not Found" description="404 Not Found." /> <div className="w-screen h-screen flex justify-center content-center flex-wrap"> <h1 className="text-6xl font-bold "> 404 Not Found </h1> </div> </Layout> ) } export default NotFound
package ltbs.uniform package common.web import cats.~> import cats.implicits._ import common.web._ import scala.concurrent.duration._ import scala.concurrent.{Future, ExecutionContext} import java.time.LocalDateTime object FutureAdapter { private def sha256Hash(in: String): String = { import java.security.MessageDigest import java.math.BigInteger val bytes = in.getBytes("UTF-8") val digest = MessageDigest.getInstance("SHA-256").digest(bytes) String.format("%032x", new BigInteger(1, digest)) } /** Adapt any future into a web monad, use this if you're happy to * keep re-running the code. * * This will be rerun very aggressively - you can expect this code * to execute *twice* per apparent page request (once for the POST * and once for the redirected GET) at every point in the journey * after the call to convert. * * For this reason if your code calls a remote service or performs * an expensive operation you may be better using * rerunOnPriorStateChange. * * This does however has the advantage that it doesn't need any * knowledge of the underlying datatype. * * {{{ * import FutureAdapter.alwaysRerun * * interpret(myProgram(fastService)).run(targetId) { ... } * }}} */ implicit def alwaysRerun[Html]: Future ~> WebMonad[Html, *] = new (Future ~> WebMonad[Html, *]) { def apply[A](fa: Future[A]): WebMonad[Html, A] = new WebMonad[Html, A] { def apply(pageIn: PageIn[Html])(implicit ec: ExecutionContext): Future[PageOut[Html,A]] = fa.map{ x => pageIn.toPageOut(AskResult.Success[Html,A](x)) } } } /** Adapts any future into a web monad but only re-runs if the * answer to a previous question in the journey has changed, or if * the supplied lifetime has expired. Use this if you want to * cache responses or otherwise avoid overwhelming a fragile * upstream service. * * Will only work if a Codec is in implicit scope for the given datatype * * {{{ * val adapter = FutureAdapter.rerunOnStateChange[Html](lifetime = 15.minutes) * import adapter._ * * interpret(myProgram(myUpstreamService)).run(targetId) { ... } * }}} */ case class rerunOnStateChange[Html](lifetime: Duration) { implicit def apply[A]( implicit codec: Codec[A] ) = new Converter[Future, WebMonad[Html, *], A] { override def apply(cacheId: String, fa: () => Future[A]): WebMonad[Html, A] = new WebMonad[Html, A] { def apply(pageIn: PageIn[Html])(implicit ec: ExecutionContext): Future[PageOut[Html,A]] = { import pageIn._ val triggerValues: List[String] = breadcrumbs.sorted.flatMap{ state.get } val trigger: String = sha256Hash(triggerValues.mkString) val oldTrigger: Option[String] = state.get(List(cacheId, "trigger")) val timestamp: Option[LocalDateTime] = state .get(List(cacheId, "timestamp")) .map{LocalDateTime.parse} if (oldTrigger == Some(trigger) && timestamp.fold(false)(_ + lifetime > LocalDateTime.now)) { val oldValue: Either[ErrorTree,A] = Input.fromUrlEncodedString(state(List(cacheId, "value")).tail) >>= codec.decode val Right(oldie) = oldValue pageIn.toPageOut(AskResult.Success[Html, A](oldie)).pure[Future] } else { fa().map{ result => val value = codec.encode(result) val newData = Map( List(cacheId, "value") -> ("V" + value.toUrlEncodedString), List(cacheId, "trigger") -> trigger, List(cacheId, "timestamp") -> LocalDateTime.now.toString ) pageIn.toPageOut(AskResult.Success[Html, A](result)).copy ( db = pageIn.state ++ newData ) } } } } } } }
--- title: "Class" metaTitle: "Class" metaDescription: "This is the meta description" --- ## 클래스 생성 클래스는 객체 지향 프로그래밍에서 특정 객체를 생성하기 위해 변수와 메소드를 정의하는 일종의 틀로, 객체를 정의하기 위한 상태(멤버 변수)와 메서드(함수)로 구성됩니다. ```js class User { constructor(name) { this.name = name; } sayHi() { alert("Hi!!!"); } } const john = new User("John"); john.sayHi(); ``` class는 `new`라는 명령어에 의해 객체가 생성되게 됩니다. &nbsp; 위처럼 `new User("John")` 처럼 객체가 생성될 때, `constructor()` 메서드가 호출되는데 이것을 `생성자`라고 합니다. &nbsp; 위의 예제에서 `constructor`가 호출될때 `name`이라는 `argument`를 넘겨받는데 이때 `name`은 `this.name`에 할당되게 됩니다. 이를 간단하게 이야기하면 위에서 생성된 객체는 `John`이라는 이름을 가진 사람이고 동시에 `sayHi()`라는 말을 할수 있는(기능을 가진) 사람(객체)이 생긴 것 이라고 생각하면됩니다. ## getter, setter getter와 setter는 말 그대로 어떤 객체의 값을 가져오거나, 설정해주는 역할을 하는 메소드를 말합니다. ```ts // getter setter export class User { private _name: string; constructor(name:string) { this._name = name; } // getter는 객체의 변수의 정보를 가져올때 사용 get name(): string { return this._name } // setter는 객체의 변수에 값을 세팅할 때 사용 set name(value) { console.log('호출') this._name = value } } const user = new User("John"); console.log(user.name); // getter로 John이라는 이름을 가져옴 new User("man"); // man이라는 name을 가진 객체 생성 user.name = "fe"; // setter로 기존에 John이었던 이름을 fe로 바꿈 ``` ## 클래스의 상속 ### 상속이란? 상속은 부모 클래스의 필드/메소드를 자식 클래스가 물려받아 그대로 사용 가능하게 해주는 것입니다. &nbsp; 여기서 부모클래스를 superclass, 자식클래스를 subclass라 부릅니다. &nbsp; 자식클래스에서 A라는 기능을 처리하는데 부모클래스에서 이미 똑같은 A라는 기능을 처리하고 있다면 자식클래스는 이를 상속받아 그대로 사용할 수 있으며, 코드의 중복을 막아주게 됩니다. &nbsp; 아래의 예제를 토대로 상속이 어떻게 이루어지는지 확인해봅니다. ```ts export class Animal { speed: number; name: string; constructor(name:string) { this.name = name; this.speed = 0; } run(speed: number) { this.speed = speed; console.log(`${this.name}은/는 속도 ${this.speed}로 달립니다.`); } stop() { this.speed = 0; console.log(`${this.name}이/가 멈췄습니다.`); } } export class Rabbit extends Animal { hide() { console.log(`${this.name}이/가 숨었습니다!`) } } ``` 위의 구조는 동물의 특성을 토끼한테 상속해주는 내용입니다. 그렇다면 상속이 이루어짐으로서 어떤 효과를 보게될까요? &nbsp; ![dd](../../../src/images/class1.png) 기존에 `Rabbit` 클래스는 `hide()`아는 메서드만 있지만 `Animal`을 상속받아 `Animal`에 있는 메서드, 필드들을 사용할 수 있게됩니다. 아래와 같이 말이죠. ```ts const rabbit = new Rabbit("Tomas"); // 기존에 Rabbit 객체가 사용할 수 있는 메서드 rabbit.hide() // Tomas이/가 숨었습니다! // Rabbit 객체가 Animal 객체를 상속받아 Animal 객체의 변수, 메서드를 활용하는 부문 console.log(rabbit.name) // Tomas rabbit.run(100) // Tomas은/는 속도 100로 달립니다. console.log(rabbit.speed) // 100 rabbit.stop() // Tomas이/가 멈췄습니다. ``` ### 메서드 오버라이드 오버라이드는 상속받은 메서드를 자식 클래스에서 재구성해서 사용하는 것입니다. 오버라이드된 메서드를 호출하면 부모 클래스의 메서드 기준이 아닌 오버라이드해서 재구성한 자식 메서드 기준의 코드가 작동되게 됩니다. &nbsp; 부모 클래스의 `stop()`메서드를 자식 클래스에서 오버라이드하여 재구성하여 사용해보겠습니다. ```ts export class Rabbit extends Animal { hide() { console.log(`${this.name}이/가 숨었습니다!`) } // 오버라이드 stop() { console.log('오버라이드 된 메서드'); super.stop(); this.hide(); } } const rabbit = new Rabbit("Tomas"); rabbit.stop() /* 결과 오버라이드 된 메서드 Tomas이/가 멈췄습니다. Tomas이/가 숨었습니다! */ ``` 위와 같이 오버라이드된 메서드가 실행되었습니다. #### 생성자 오버라이드 ```ts export class Cat extends Animal { sound: String; constructor(name: string) { super(name); this.sound = "Meow"; } } ``` 만약 생성자를 오버라이드 한다면 `super()`로 가져와야합니다. &nbsp; 상속 클래스의 생성자에선 super를 호출해 부모 생성자를 실행해 주어야 합니다. 그렇지 않으면 this가 될 객체가 만들어지지 않아 에러가 발생합니다.
package dev.gumil.nookbot.telegram import dev.gumil.nookbot.Component import dev.gumil.nookbot.telegram.entities.Update import dev.gumil.nookbot.utils.TestMockEngine import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.MethodSource import java.util.stream.Stream internal class TelegramApiImplTest { private val mockEngine = TestMockEngine() private val client = Component.provideHttpClient(mockEngine.get()) private val telegramApiImpl = TelegramApiImpl(client) @ParameterizedTest @MethodSource("provideGetUpdatesArgs") fun `getUpdates returns list of updates from bot command`(file: String, expected: List<Update>) = runBlocking { mockEngine.enqueueResponseFromFile(file) val actual = telegramApiImpl.getUpdates(1, 1) assertEquals(expected, actual) } @Test fun `sendMessage returns message sent`() = runBlocking { mockEngine.enqueueResponseFromFile("sendMessage.json") val actual = telegramApiImpl.sendMessage(TelegramApiFactory.sendMessageRequest()) assertEquals(TelegramApiFactory.getMessageResponse(), actual) } @Test fun `editMessage returns message edited`() = runBlocking { mockEngine.enqueueResponseFromFile("editMessageMarkup.json") val actual = telegramApiImpl.sendMessage(TelegramApiFactory.sendMessageRequest()) assertEquals(TelegramApiFactory.getMessageResponse(null), actual) } companion object { @JvmStatic @Suppress("unused") fun provideGetUpdatesArgs(): Stream<Arguments> { return Stream.of( Arguments.of("getUpdates/botCommand.json", TelegramApiFactory.getUpdatesBotCommand()), Arguments.of("getUpdates/groupChatCreated.json", TelegramApiFactory.getUpdatesGroupChatCreated()), Arguments.of("getUpdates/private.json", TelegramApiFactory.getUpdatesPrivate()) ) } } }
import 'dart:convert'; import 'Elements.dart'; import 'htmlparser.dart'; class MarkupUtils { ///Converts [Map] to [Node] static Node mapToNode(Map<String, dynamic> json) { dynamic node; switch (json["type"]) { case NodeType.ROOT: node = RootNode(null); break; case NodeType.ELEMENT: node = ElementNode(tag: json["tag"]); break; case NodeType.TEXT: node = TextNode(json["text"]); break; case NodeType.COMMENT: node = CommentNode(json["text"]); break; } if (json["children"] != null) { node.children = (json["children"] as List<dynamic>).map((c) => mapToNode(c)).toList(); } if (json["attributes"] != null) { node.attributes = (json["attributes"] as List<dynamic>) .map((attr) => Attribute(attr["name"], attr["value"], attr["valueOriginal"])) .toList(); } return node; } ///Converts json to [Node] static Node jsonToNode(String jsonString) { return mapToNode(jsonDecode(jsonString)); } ///Removes DOCTYPE static _removeDOCTYPE(String html) { String xmlType; if ((xmlType = RegExp(r"<\?xml.*\?>").stringMatch(html)) != null) { html = html.replaceFirst(xmlType, ''); } String hxmlType1; if ((hxmlType1 = RegExp(r"<!doctype.*\>").stringMatch(html)) != null) { html = html.replaceFirst(hxmlType1, ''); } String hxmlType2; if ((hxmlType2 = RegExp(r"<!DOCTYPE.*\>").stringMatch(html)) != null) { html = html.replaceFirst(hxmlType2, ''); } return html; } ///Converts HTML/XML string to [Node] static Node markup2json(String markupString) { markupString = _removeDOCTYPE(markupString); List<Node> bufArray = []; RootNode results = RootNode([]); HTMLParser(markupString, { "start": (String tag, List<Attribute> attrs, bool unary) { ElementNode elementNode = ElementNode(tag: tag.trim()); if (attrs.isNotEmpty) { elementNode.attributes = attrs; } if (unary) { var parent = (bufArray.isNotEmpty ? bufArray[0] : results) as ElementNode; if (parent.children == null) { parent.children = []; } parent.children.add(elementNode); } else { bufArray.insert(0, elementNode); } }, "end": (String tag) { if (tag.trim().isEmpty) return; var node = bufArray.removeAt(0) as ElementNode; if (node.tag != tag) print('invalid state: mismatch end tag: $node'); if (bufArray.isEmpty) { results.children.add(node); } else { var parent = bufArray[0] as ElementNode; if (parent.children == null) { parent.children = []; } parent.children.add(node); } }, "chars": (String text) { if (text.trim().isEmpty) { return; } TextNode textNode = TextNode(text); if (bufArray.isEmpty) { results.children.add(textNode); } else { var parent = bufArray[0] as ElementNode; if (parent.children == null) { parent.children = []; } parent.children.add(textNode); } }, "comment": (String text) { CommentNode commentNode = CommentNode(text); var parent = bufArray[0] as ElementNode; if (parent.children == null) { parent.children = []; } parent.children.add(commentNode); } }); return results; } ///Converts jsonString to markupString static String jsonToMarkup(String jsonString) => _parse(jsonDecode(jsonString)); ///Converts [Map] to markupString static String mapToMarkup(Map<String, dynamic> jsonMap) => _parse(jsonMap); ///Converts [Map] to markupString static String _parse(Map<String, dynamic> json) { var child = ''; if (json["children"] != null) { child = (json["children"] as List<dynamic>).map((c) { return _parse(c); }).join(''); } var attr = ''; if (json["attributes"] != null) { attr = (json["attributes"] as List<dynamic>).map((attrObj) { if (attrObj['valueOriginal'].toString().isEmpty) return attrObj['name']; return '${attrObj['name']}=${attrObj['valueOriginal']}'; }).join(' '); if (attr.isNotEmpty) attr = ' ' + attr; } if (json["type"] == NodeType.ELEMENT) { var tag = json["tag"].toString(); if (json["children"] == null) { return '<' + tag + attr + '/>'; } var open = '<' + tag + attr + '>'; var close = '</' + tag + '>'; return open + child + close; } if (json["type"] == NodeType.TEXT) { return json["text"]; } if (json["type"] == NodeType.COMMENT) { return '<!--' + json["text"] + '-->'; } if (json["type"] == NodeType.ROOT) { return child; } return child; } } ///These are node types that are supported. class NodeType { static const String ROOT = "root"; static const String ELEMENT = "element"; static const String TEXT = "text"; static const String COMMENT = "comment"; }
import pymongo from pymongo import MongoClient # CONNECT TO THE DB client = MongoClient() ## Add your connection info here client = pymongo.MongoClient("mongodb+srv://<username>:<password>@<cluster>/test?retryWrites=true&w=majority") db = client.CityHall # THE ID OF THE USER WHOSE PROFILE WE WILL BE RETRIEVING AND UPDATING userId = 1 # GET THE USER'S PROFILE INFORMATION ## We can pull all of the info from the same document since we used embedding user = db['Users'].find_one({"_id": userId}) # UPDATE THE USER DICTIONARY BASED ON USER INPUT IN THE APP ## We'll just update the user dictionary manually to save space user.update( { "city": "Washington, DC", "location": [-77.036809, 38.897760], "hobbies": ["scrapbooking", "eating waffles", "signing bills"] } ) # UPDATE THE USER'S PROFILE IN THE DATABASE ## Since the user's data is stored in a single document, we only have to make one update result = db['Users'].update_one({"_id": userId}, {"$set": user})
#!/usr/bin/env python3 """radarbot - a demo robot driver for controlling a battle ship This example file can be copied as a basis for your own robot. Copy it into a local folder, rename it to e.g. yourbot.py, start editing and run it from the command line as: $ python3 yourbot.py You'll want to edit the default name of your bots in the last line of this file, e.g. player_main("yourbot", driver) """ from dataclasses import dataclass from battle.player import player_main from battle.robots import Robot, RobotCommand, RobotCommandType @dataclass class RadarDriver: """Stationary driver with a radar search mechanism that improves locking on to targets.""" turret_dir: float = 90.0 radar_pinged_last_time: bool = False def get_next_command(self, r: Robot): if r.cmd_q_len: return None if r.radar_ping is not None: if r.weapon_energy >= 3 and abs(self.turret_dir) < 5: return RobotCommand(RobotCommandType.FIRE, 100) self.turret_dir = -self.turret_dir / 2 elif not self.radar_pinged_last_time: self.turret_dir = -self.turret_dir * 2 self.radar_pinged_last_time = r.radar_ping is not None self.turret_dir = max(-15, min(90, self.turret_dir)) return RobotCommand(RobotCommandType.TURN_TURRET, self.turret_dir) def main(): driver = RadarDriver() player_main("radarbot", driver) if __name__ == "__main__": main()
import os import pandas as pd import xml.etree.cElementTree as ET XML_FOLDER = "/home/abhijitcbim/data/PedDetectionIMDB/annotations" DEST_FOLDER = "/home/abhijitcbim/data/PedDetectionIMDB/annotations_xml" ROOT_FOLDER = "/home/abhijitcbim/data/PedDetectionIMDB" def splitall(path): allparts = [] while 1: parts = os.path.split(path) if parts[0] == path: # sentinel for absolute paths allparts.insert(0, parts[0]) break elif parts[1] == path: # sentinel for relative paths allparts.insert(0, parts[1]) break else: path = parts[0] allparts.insert(0, parts[1]) return allparts def save_list_readable(ip_list, filename): with open(filename, 'w') as f: for s in ip_list: f.write(s + '\n') def load_list_readable(filename): with open(filename, 'r') as f: return [line.rstrip('\n') for line in f] def get_unique_name(filename): file_paths = splitall(filename) l = len(file_paths) target_file = os.path.join(DEST_FOLDER, ( file_paths[l - 3] + "_" + file_paths[l - 2] + "_" + file_paths[l - 1])) return target_file VOC_XML = "format/voc_xml.xml" VOC_OBJECT_XML = "format/voc_object_xml.xml" class VocXml(object): def __init__(self, voc_xml_dict): self.__pageDocTree = ET.parse(VOC_XML) root = self.__pageDocTree.getroot() # update the __pageDocTree element for key, val in voc_xml_dict.iteritems(): root.find(key).text = val def add_object(self, obj_dict): objectTree = ET.parse(VOC_OBJECT_XML) root = objectTree.getroot() # Update the xtree for key, val in obj_dict.iteritems(): root.find(key).text = val self.__pageDocTree.getroot().append(root) def add_objects(self, obj_dicts): for i in range(len(obj_dicts)): self.add_object(obj_dicts[i]) def save_xml(self, filename): self.__pageDocTree.write(filename) def convert_to_xml(folder): columns = ["lbl", "bb_x", "bb_y", "bb_w", "bb_h", "occ", "bbv_x", "bbv_y", "bbv_w", "bbv_h", "ign", "ang"] i = 0 for path, subdirs, files in os.walk(folder): for name in files: i += 1 txt_file = os.path.join(path, name) filename,_=os.path.splitext(txt_file) filename +=".xml" # print txt_file if os.stat(txt_file).st_size != 0: target_name = get_unique_name(filename) voc_dict = {} voc_dict['filename'] = target_name voc_dict['size/width'] = "480" voc_dict['size/height'] = "640" voc_dict['size/depth'] = "3" voc_xml = VocXml(voc_dict) df = pd.read_csv(txt_file, header=None, sep=r"\s+", names=columns) for index, row in df.iterrows(): obj_dict = {} obj_dict['name'] = row['lbl'] obj_dict['bndbox/xmin'] = str(row['bb_x']) obj_dict['bndbox/ymin'] = str(row['bb_y']) obj_dict['bndbox/xmax'] = str(row['bb_x'] + row['bb_w']) obj_dict['bndbox/ymax'] = str(row['bb_y'] + row['bb_h']) obj_dict['vbndbox/xmin'] = str(row['bbv_x']) obj_dict['vbndbox/ymin'] = str(row['bbv_y']) obj_dict['vbndbox/xmax'] = str(row['bbv_x'] + row['bbv_w']) obj_dict['vbndbox/ymax'] = str(row['bbv_y'] + row['bbv_h']) obj_dict['occ'] = str(row['occ']) obj_dict['ign'] = str(row['ign']) obj_dict['ang'] = str(row['ang']) voc_xml.add_object(obj_dict) voc_xml.save_xml(os.path.join(DEST_FOLDER, target_name)) if i % 100 == 0: print ".", if i % 1000 == 0: print i, " done" def convert_to_csv(folder): df_final = pd.DataFrame() columns = ["lbl", "bb_x", "bb_y", "bb_w", "bb_h", "occ", "bbv_x", "bbv_y", "bbv_w", "bbv_h", "ign", "ang"] empty_files = [] i = 0 for path, subdirs, files in os.walk(folder): for name in files: i += 1 txt_file = os.path.join(path, name) # print txt_file if os.stat(txt_file).st_size == 0: empty_files.append(get_unique_name(txt_file)) else: df = pd.read_csv(txt_file, header=None, sep=r"\s+", names=columns) df["fname"] = get_unique_name(txt_file) df_final = df_final.append(df) if i % 100 == 0: print ".", if i % 1000 == 0: print i, " done" df_final.to_csv(os.path.join(ROOT_FOLDER, "annotations.csv")) save_list_readable(empty_files, os.path.join(ROOT_FOLDER, "empty_files.txt")) if __name__ == '__main__': convert_to_csv(XML_FOLDER) convert_to_xml(XML_FOLDER)
package com.lingga.themoviedb.ui.ticket import android.content.Context import com.lingga.themoviedb.R import com.lingga.themoviedb.databinding.FragmentTicketBinding import com.lingga.themoviedb.ui.base.BaseFragment import kotlinx.coroutines.ExperimentalCoroutinesApi @ExperimentalCoroutinesApi class TicketFragment : BaseFragment<FragmentTicketBinding>(R.layout.fragment_ticket) { override fun onAttach(context: Context) { super.onAttach(context) appComponent.inject(this) } }
class Dir: major, minor, patch = 0, 0, 0 def __init__(self, name=None): if not name: return if name.count('.') is not 2: raise Exception('Invalid directory name:', name) tokens = name.split('.') for i in range(len(tokens)): if not tokens[i].isnumeric(): raise Exception('Invalid directory name: %s' % name) value = int(tokens[i]) if i == 0: self.major = value elif i == 1: self.minor = value elif i == 2: self.patch = value def __str__(self): return "%d.%d.%d" % (self.major, self.minor, self.patch) def toInt(self): return (self.major << 24) | (self.minor << 16) | self.patch
<?php namespace Aws\DynamoDbStreams; use Aws\Common\Client\AbstractClient; use Aws\Common\Client\ClientBuilder; use Aws\Common\Enum\ClientOptions as Options; use Aws\Common\Exception\Parser\JsonQueryExceptionParser; use Aws\DynamoDb\DynamoDbClient; use Guzzle\Common\Collection; use Guzzle\Plugin\Backoff\BackoffPlugin; use Guzzle\Service\Resource\Model; /** * Client to interact with Amazon DynamoDB Streams * * @method Model describeStream(array $args = array()) {@command DynamoDbstreams DescribeStream} * @method Model getRecords(array $args = array()) {@command DynamoDbstreams GetRecords} * @method Model getShardIterator(array $args = array()) {@command DynamoDbstreams GetShardIterator} * @method Model listStreams(array $args = array()) {@command DynamoDbstreams ListStreams} * * @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-dynamodbstreams.html User guide * @link http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.DynamoDbstreams.DynamoDbstreamsClient.html API docs */ class DynamoDbStreamsClient extends AbstractClient { const LATEST_API_VERSION = '2012-08-10'; /** * Factory method to create a new Amazon DynamoDB Streams client using an array of configuration options. * * See http://docs.aws.amazon.com/aws-sdk-php/v2/guide/configuration.html#client-configuration-options * * @param array|Collection $config Client configuration data * * @return self * @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/configuration.html#client-configuration-options */ public static function factory($config = array()) { // Configure the custom exponential backoff plugin for DynamoDB throttling $exceptionParser = new JsonQueryExceptionParser(); if (!isset($config[Options::BACKOFF])) { $config[Options::BACKOFF] = new BackoffPlugin( DynamoDbClient::createDynamoDbBackoffStrategy($exceptionParser) ); } return ClientBuilder::factory(__NAMESPACE__) ->setConfig($config) ->setConfigDefaults(array( Options::VERSION => self::LATEST_API_VERSION, Options::SERVICE_DESCRIPTION => __DIR__ . '/Resources/dynamodbstreams-%s.php' )) ->setExceptionParser($exceptionParser) ->build(); } }
<?php class Clogin extends CI_controller { function __construct(){ parent::__construct(); $this->load->model('mlogin'); } public function index(){ $data['mensaje']= ""; $this->load->view('vlogin',$data); } public function ingresar(){ // print "<script type=\"text/javascript\">alert('logint');</script>"; $usu = $this->input->post('txtUsuario'); $pass = $this->input->post('txtClave'); $res = $this->mlogin->ingresar($usu,$pass); if($res ==1){ redirect(base_url()); }else{ $data['mensaje']= "Nombre o Clave Incorrectos"; $this->load->view('vlogin',$data); } } public function logout() { $this->session->unset_userdata('s_idPersona'); $this->session->unset_userdata('s_idUsuario'); $this->session->unset_userdata('s_usuario'); $this->session->sess_destroy(); redirect(base_url()); } } ?>
# frozen_string_literal: true p('Ruby' * 5) p([1, 2, 3] * 5) p(%w[A B C] * 5)
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup BaseGroups Base classes for groups modules * @ingroup UnaModules * * @{ */ /* * Groups module representation. */ class BxBaseModGroupsTemplate extends BxBaseModProfileTemplate { function __construct(&$oConfig, &$oDb) { parent::__construct($oConfig, $oDb); } function unitVars ($aData, $isCheckPrivateContent = true, $sTemplateName = 'unit.html') { $aVars = parent::unitVars ($aData, $isCheckPrivateContent, $sTemplateName); $CNF = &$this->_oConfig->CNF; $oPrivacy = BxDolPrivacy::getObjectInstance($CNF['OBJECT_PRIVACY_VIEW']); $isPublic = CHECK_ACTION_RESULT_ALLOWED === $this->getModule()->checkAllowedView($aData) || $oPrivacy->isPartiallyVisible($aData[$CNF['FIELD_ALLOW_VIEW_TO']]); $oConn = BxDolConnection::getObjectInstance($CNF['OBJECT_CONNECTIONS']); $oGroupProfile = BxDolProfile::getInstanceByContentAndType($aData[$CNF['FIELD_ID']], $this->MODULE); $aVars['title'] = $isPublic ? bx_process_output($aData[$CNF['FIELD_NAME']]) : _t($CNF['T']['txt_private_group']); $aVars['bx_if:info']['condition'] = true; $aVars['bx_if:info']['content']['members'] = $isPublic ? _t($CNF['T']['txt_N_fans'], $oConn ? $oConn->getConnectedInitiatorsCount($oGroupProfile->id(), true) : 0) : '&nbsp;'; $aVars['bx_if:info']['content']['bx_if:btn'] = array ( 'condition' => isLogged() && $isPublic && !$oConn->isConnected(bx_get_logged_profile_id(), $oGroupProfile->id(), true), 'content' => array ( 'id' => $oGroupProfile->id(), 'title' => $oConn->isConnectedNotMutual(bx_get_logged_profile_id(), $oGroupProfile->id()) ? _t($CNF['T']['menu_item_title_become_fan_sent']) : _t($CNF['T']['menu_item_title_become_fan']), 'object' => $CNF['OBJECT_CONNECTIONS'], ), ); return $aVars; } } /** @} */
from django.apps import AppConfig import logging logger = logging.getLogger("bornhack.%s" % __name__) class ShopConfig(AppConfig): name = "shop"
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: 14-Set-2018 às 23:13 -- Versão do servidor: 10.1.30-MariaDB -- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `quiz_gti` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `alternativas` -- CREATE TABLE `alternativas` ( `id` int(11) NOT NULL, `pergunta_id` int(11) NOT NULL, `descricao` text NOT NULL, `correto` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `alternativas` -- INSERT INTO `alternativas` (`id`, `pergunta_id`, `descricao`, `correto`) VALUES (1, 1, 'Alternativa 1', 1), (2, 1, 'Alternativa 2', 0), (3, 1, 'Alternativa 3', 0), (4, 1, 'Alternativa 4', 0), (5, 1, 'Alternativa 5', 0), (6, 2, 'Alternativa 1', 0), (7, 2, 'Alternativa 2', 1), (8, 2, 'Alternativa 3', 0), (9, 2, 'Alternativa 4', 0), (10, 2, 'Alternativa 5', 0), (11, 3, 'Alternativa 1', 0), (12, 3, 'Alternativa 2', 0), (13, 3, 'Alternativa 3', 1), (14, 3, 'Alternativa 4', 0), (15, 3, 'Alternativa 5', 0); -- -------------------------------------------------------- -- -- Estrutura da tabela `config` -- CREATE TABLE `config` ( `id` int(11) NOT NULL, `liberado` tinyint(1) NOT NULL, `finalizado` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `equipes` -- CREATE TABLE `equipes` ( `id` int(11) NOT NULL, `nome` varchar(255) NOT NULL, `conectada` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `equipes` -- INSERT INTO `equipes` (`id`, `nome`, `conectada`) VALUES (1, 'Blue', 0), (2, 'Gold', 0), (3, 'Green', 0); -- -------------------------------------------------------- -- -- Estrutura da tabela `equipes_alternativas` -- CREATE TABLE `equipes_alternativas` ( `id` int(11) NOT NULL, `equipe_id` int(11) NOT NULL, `alternativa_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `perguntas` -- CREATE TABLE `perguntas` ( `id` int(11) NOT NULL, `enunciado` text NOT NULL, `ordem` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Extraindo dados da tabela `perguntas` -- INSERT INTO `perguntas` (`id`, `enunciado`, `ordem`) VALUES (1, 'Pergunta 1', 1), (2, 'Pergunta 2', 2), (3, 'Pergunta 3', 3); -- -------------------------------------------------------- -- -- Estrutura da tabela `phinxlog` -- CREATE TABLE `phinxlog` ( `version` bigint(20) NOT NULL, `migration_name` varchar(100) DEFAULT NULL, `start_time` timestamp NULL DEFAULT NULL, `end_time` timestamp NULL DEFAULT NULL, `breakpoint` tinyint(1) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Extraindo dados da tabela `phinxlog` -- INSERT INTO `phinxlog` (`version`, `migration_name`, `start_time`, `end_time`, `breakpoint`) VALUES (20180824221639, 'CriarTabelaEquipes', '2018-08-25 01:24:35', '2018-08-25 01:24:35', 0), (20180824221652, 'CriarTabelaPerguntas', '2018-08-25 01:24:35', '2018-08-25 01:24:35', 0), (20180824221659, 'CriarTabelaAlternativas', '2018-08-25 01:24:35', '2018-08-25 01:24:37', 0), (20180824221726, 'CriarTabelaEquipesAlternativas', '2018-08-25 01:24:37', '2018-08-25 01:24:38', 0), (20180824221750, 'CriarTabelaConfig', '2018-08-25 01:24:38', '2018-08-25 01:24:38', 0), (20180824224501, 'AlterarTabelaEquipeVerificarEquipeConectada', '2018-08-25 01:45:43', '2018-08-25 01:45:44', 0); -- -- Indexes for dumped tables -- -- -- Indexes for table `alternativas` -- ALTER TABLE `alternativas` ADD PRIMARY KEY (`id`), ADD KEY `pergunta_id` (`pergunta_id`); -- -- Indexes for table `config` -- ALTER TABLE `config` ADD PRIMARY KEY (`id`); -- -- Indexes for table `equipes` -- ALTER TABLE `equipes` ADD PRIMARY KEY (`id`); -- -- Indexes for table `equipes_alternativas` -- ALTER TABLE `equipes_alternativas` ADD PRIMARY KEY (`id`), ADD KEY `equipe_id` (`equipe_id`), ADD KEY `alternativa_id` (`alternativa_id`); -- -- Indexes for table `perguntas` -- ALTER TABLE `perguntas` ADD PRIMARY KEY (`id`); -- -- Indexes for table `phinxlog` -- ALTER TABLE `phinxlog` ADD PRIMARY KEY (`version`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `alternativas` -- ALTER TABLE `alternativas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT for table `config` -- ALTER TABLE `config` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `equipes` -- ALTER TABLE `equipes` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `equipes_alternativas` -- ALTER TABLE `equipes_alternativas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=51; -- -- AUTO_INCREMENT for table `perguntas` -- ALTER TABLE `perguntas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Constraints for dumped tables -- -- -- Limitadores para a tabela `alternativas` -- ALTER TABLE `alternativas` ADD CONSTRAINT `alternativas_ibfk_1` FOREIGN KEY (`pergunta_id`) REFERENCES `perguntas` (`id`); -- -- Limitadores para a tabela `equipes_alternativas` -- ALTER TABLE `equipes_alternativas` ADD CONSTRAINT `equipes_alternativas_ibfk_1` FOREIGN KEY (`equipe_id`) REFERENCES `equipes` (`id`), ADD CONSTRAINT `equipes_alternativas_ibfk_2` FOREIGN KEY (`alternativa_id`) REFERENCES `alternativas` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
require File.join(File.dirname(__FILE__), "lib", "archieml", "version") Gem::Specification.new do |gem| gem.name = "archieml" gem.version = Archieml::VERSION gem.authors = ["Michael Strickland"] gem.email = ["michael.strickland@nytimes.com"] gem.description = %q{Parse Archie Markup Language documents} gem.summary = %q{Archieml is a Ruby parser for the Archie Markup Language (ArchieML)} gem.homepage = "http://archieml.org" gem.license = "Apache License 2.0" gem.files = `git ls-files`.split($\) gem.test_files = gem.files.grep(%r{^spec/}) gem.require_paths = ["lib"] end
// <copyright file="DataRateIndex.cs" company="Poul Erik Venø Hansen"> // Copyright (c) Poul Erik Venø Hansen. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> namespace FosterBuster.IU880B.Messaging { /// <summary> /// Data Rate Index. /// </summary> public enum DataRateIndex : byte { /// <summary> /// LoRa / SF12. Bandwith kHz: 125. Indicative physical bit rate: 250. Maximum payload size: 51. /// </summary> SpreadingFactor12 = 0x00, /// <summary> /// LoRa / SF11. Bandwith kHz: 125. Indicative physical bit rate: 440. Maximum payload size: 51. /// </summary> SpreadingFactor11 = 0x01, /// <summary> /// LoRa / SF10. Bandwith kHz: 125. Indicative physical bit rate: 890. Maximum payload size: 51. /// </summary> SpreadingFactor10 = 0x02, /// <summary> /// LoRa / SF9. Bandwith kHz: 125. Indicative physical bit rate: 1760. Maximum payload size: 115. /// </summary> SpreadingFactor9 = 0x03, /// <summary> /// LoRa / SF8. Bandwith kHz: 125. Indicative physical bit rate: 3125. Maximum payload size: 242. /// </summary> SpreadingFactor8 = 0x04, /// <summary> /// LoRa / SF12. Bandwith kHz: 125. Indicative physical bit rate: 5470. Maximum payload size: 242. /// </summary> SpreadingFactor7 = 0x05, #pragma warning disable SA1005 // Single line comments should begin with single space ///// <summary> ///// LoRa / SF12. Bandwith kHz: 250. Indicative physical bit rate: 11000. Maximum payload size: 242. ///// </summary> //SpreadingFactor7_250 = 0x06, ///// <summary> ///// LoRa / SF12. Bandwith kHz: 250?. Indicative physical bit rate: 50kbps. ///// </summary> //FSK = 0x07, #pragma warning restore SA1005 // Single line comments should begin with single space } }
# -*- coding: utf-8 -*- """ This is a SublimeText 2 adaptation of `Vincent Driessen's vim-rst-tables` [1]_ code by Martín Gaitán <gaitan@gmail.com> .. [1]: https://github.com/nvie/vim-rst-tables Usage ----- 1. Set reStructuredText as syntax (or open a .rst) 2. Create some kind of table outline:: This is paragraph text *before* the table. Column 1 Column 2 Foo Put two (or more) spaces as a field separator. Bar Even very very long lines like these are fine, as long as you do not put in line endings here. Qux This is the last line. This is paragraph text *after* the table. 2. Put your cursor somewhere in the content to convert as table. 3. Press ``ctrl+t`` (to create the table). The output will look something like this:: This is paragraph text *before* the table. +----------+---------------------------------------------------------+ | Column 1 | Column 2 | +==========+=========================================================+ | Foo | Put two (or more) spaces as a field separator. | +----------+---------------------------------------------------------+ | Bar | Even very very long lines like these are fine, as long | | | as you do not put in line endings here. | +----------+---------------------------------------------------------+ | Qux | This is the last line. | +----------+---------------------------------------------------------+ This is paragraph text *after* the table. .. tip:: Change something in the output table and run ``ctrl+t`` again: Magically, it will be fixed. And ``ctrl+r+t`` reflows the table fixing the current column width. """ import re import textwrap try: from .helpers import BaseBlockCommand except ValueError: from helpers import BaseBlockCommand # NOQA import os import sys wcwidth_dir = os.path.join(os.path.dirname(__file__), 'wcwidth') sys.path.insert(0, wcwidth_dir) import wcwidth class TableCommand(BaseBlockCommand): def get_withs(self, lines): return None def get_result(self, indent, table, widths): result = '\n'.join(draw_table(indent, table, widths)) result += '\n' return result def run(self, edit): region, lines, indent = self.get_block_bounds() table = parse_table(lines) widths = self.get_withs(lines) result = self.get_result(indent, table, widths) self.view.replace(edit, region, result) class FlowtableCommand(TableCommand): def get_withs(self, lines): return get_column_widths_from_border_spec(lines) class BaseMergeCellsCommand(BaseBlockCommand): def get_column_index(self, raw_line, col_position): """given the raw line and the column col cursor position, return the table column index to merge""" return raw_line[:col_position].count('|') class MergeCellsDownCommand(BaseMergeCellsCommand): offset = 1 def run(self, edit): region, lines, indent= self.get_block_bounds() raw_table = self.view.substr(region).split('\n') begin = self.view.rowcol(region.begin())[0] # end = self.view.rowcol(region.end())[0] cursor = self.get_cursor_position() actual_line = raw_table[cursor[0] - begin] col = self.get_column_index(actual_line, cursor[1]) sep_line = raw_table[cursor[0] + self.offset - begin] new_sep_line = self.update_sep_line(sep_line, col) raw_table[cursor[0] + self.offset - begin] = indent + new_sep_line result = '\n'.join(raw_table) self.view.replace(edit, region, result) def update_sep_line(self, original, col): segments = original.strip().split('+') segments[col] = ' ' * len(segments[col]) new_sep_line = '+'.join(segments) # replace ghost ``+`` new_sep_line = re.sub('(^\+ )|( \+ )|( \+)$', lambda m: m.group().replace('+', '|'), new_sep_line) return new_sep_line class MergeCellsUpCommand(MergeCellsDownCommand): offset = -1 class MergeCellsRightCommand(BaseMergeCellsCommand): offset = 0 def run(self, edit): region, lines, indent= self.get_block_bounds() raw_table = self.view.substr(region).split('\n') begin = self.view.rowcol(region.begin())[0] # end = self.view.rowcol(region.end())[0] cursor = self.get_cursor_position() actual_line = raw_table[cursor[0] - begin] col = self.get_column_index(actual_line, cursor[1]) separator_indexes = [match.start() for match in re.finditer(re.escape('|'), actual_line)] actual_line = list(actual_line) actual_line[separator_indexes[col + self.offset]] = ' ' actual_line = ''.join(actual_line) raw_table[cursor[0] - begin] = actual_line result = '\n'.join(raw_table) self.view.replace(edit, region, result) class MergeCellsLeftCommand(MergeCellsRightCommand): offset = -1 def join_rows(rows, sep='\n'): """Given a list of rows (a list of lists) this function returns a flattened list where each the individual columns of all rows are joined together using the line separator. """ output = [] for row in rows: # grow output array, if necessary if len(output) <= len(row): for i in range(len(row) - len(output)): output.extend([[]]) for i, field in enumerate(row): field_text = field.strip() if field_text: output[i].append(field_text) return [sep.join(lines) for lines in output] def line_is_separator(line): return re.match('^[\t +=-]+$', line) def has_line_seps(raw_lines): for line in raw_lines: if line_is_separator(line): return True return False def partition_raw_lines(raw_lines): """Partitions a list of raw input lines so that between each partition, a table row separator can be placed. """ if not has_line_seps(raw_lines): return [[x] for x in raw_lines] curr_part = [] parts = [curr_part] for line in raw_lines: if line_is_separator(line): curr_part = [] parts.append(curr_part) else: curr_part.append(line) # remove any empty partitions (typically the first and last ones) return [x for x in parts if x] def unify_table(table): """Given a list of rows (i.e. a table), this function returns a new table in which all rows have an equal amount of columns. If all full column is empty (i.e. all rows have that field empty), the column is removed. """ max_fields = max([len(row) for row in table]) empty_cols = [True] * max_fields output = [] for row in table: curr_len = len(row) if curr_len < max_fields: row += [''] * (max_fields - curr_len) output.append(row) # register empty columns (to be removed at the end) for i in range(len(row)): if row[i].strip(): empty_cols[i] = False # remove empty columns from all rows table = output output = [] for row in table: cols = [] for i in range(len(row)): should_remove = empty_cols[i] if not should_remove: cols.append(row[i]) output.append(cols) return output def split_table_row(row_string): if row_string.find("|") >= 0: # first, strip off the outer table drawings row_string = re.sub(r'^\s*\||\|\s*$', '', row_string) return re.split(r'\s*\|\s*', row_string.strip()) return re.split(r'\s\s+', row_string.rstrip()) def parse_table(raw_lines): row_partition = partition_raw_lines(raw_lines) lines = [] for row_string in row_partition: lines.append(join_rows([split_table_row(cell) for cell in row_string])) return unify_table(lines) def table_line(widths, header=False): if header: linechar = '=' else: linechar = '-' sep = '+' parts = [] for width in widths: parts.append(linechar * width) if parts: parts = [''] + parts + [''] return sep.join(parts) def get_field_width(field_text): return max([wcwidth.wcswidth(s) for s in field_text.split('\n')]) def split_row_into_lines(row): row = [field.split('\n') for field in row] height = max([len(field_lines) for field_lines in row]) turn_table = [] for i in range(height): fields = [] for field_lines in row: if i < len(field_lines): fields.append(field_lines[i]) else: fields.append('') turn_table.append(fields) return turn_table def get_column_widths(table): widths = [] for row in table: num_fields = len(row) # dynamically grow if num_fields >= len(widths): widths.extend([0] * (num_fields - len(widths))) for i in range(num_fields): field_text = row[i] field_width = get_field_width(field_text) widths[i] = max(widths[i], field_width) return widths def get_column_widths_from_border_spec(slice): border = None for row in slice: if line_is_separator(row): border = row.strip() break if border is None: raise RuntimeError('Cannot reflow this table. Top table border not found.') left = right = None if border[0] == '+': left = 1 if border[-1] == '+': right = -1 return [max(0, len(drawing) - 2) for drawing in border[left:right].split('+')] def pad_fields(row, widths): """Pads fields of the given row, so each field lines up nicely with the others. """ wgaps = [wcwidth.wcswidth(c) - len(c) for c in row] widths = [w-wgaps[i] for i, w in enumerate(widths)] widths = [(' %-' + str(w) + 's ') for w in widths] # Pad all fields using the calculated widths new_row = [] for i in range(len(row)): col = row[i] col = widths[i] % col.strip() new_row.append(col) return new_row def reflow_row_contents(row, widths): new_row = [] for i, field in enumerate(row): wrapped_lines = textwrap.wrap(field.replace('\n', ' '), widths[i]) new_row.append("\n".join(wrapped_lines)) return new_row def draw_table(indent, table, manual_widths=None): if table == []: return [] if manual_widths is None: col_widths = get_column_widths(table) else: col_widths = manual_widths # Reserve room for the spaces sep_col_widths = [(col + 2) for col in col_widths] header_line = table_line(sep_col_widths, header=True) normal_line = table_line(sep_col_widths, header=False) output = [indent + normal_line] first = True for row in table: if manual_widths: row = reflow_row_contents(row, manual_widths) row_lines = split_row_into_lines(row) # draw the lines (num_lines) for this row for row_line in row_lines: row_line = pad_fields(row_line, col_widths) output.append(indent + "|".join([''] + row_line + [''])) # then, draw the separator if first: output.append(indent + header_line) first = False else: output.append(indent + normal_line) return output
import { combineReducers } from 'redux' import control from './control' export default combineReducers({ control })
# Challenge name: Number of good pairs # # Given an array of integers nums. # A pair (i,j) is called good if nums[i] == nums[j] and i < j. # Return the number of good pairs. # # @param {Integer[]} nums # @return {Integer} # # # Approach 1: Hash # # Time Complexity: O(n) def num_identical_pairs(nums) hash = Hash.new(0) nums.each do |num| hash[num] = hash[num] + 1 end counter = 0 # Count how many times each number appears. # If a number appears n times, then n * (n – 1) / 2 good pairs # can be made with this number. hash.values.each do |val| counter += (val * (val - 1) / 2) end counter end nums = [1, 2, 3, 1, 1, 3] puts(num_identical_pairs(nums)) # Output: 4 nums = [1, 1, 1, 1] puts(num_identical_pairs(nums)) # Output: 6 nums = [1, 2, 3] puts(num_identical_pairs(nums)) # Output: 0
<?php class Object_Inquiry_List extends Object_List_Concrete { public $classId = 3; public $className = "inquiry"; }
#!/bin/bash docker build --target travis -t pybm -f packages/docker/Dockerfile.bionic . docker run pybm
package org.jetbrains.ktor.content import org.jetbrains.ktor.application.* import org.jetbrains.ktor.cio.* import org.jetbrains.ktor.http.* import org.jetbrains.ktor.util.* import java.io.* import kotlin.coroutines.experimental.* sealed class FinalContent { open val status: HttpStatusCode? get() = null open val headers: ValuesMap get() = ValuesMap.Empty abstract class NoContent : FinalContent() abstract class ReadChannelContent : FinalContent() { abstract fun readFrom(): ReadChannel } abstract class WriteChannelContent : FinalContent() { abstract suspend fun writeTo(channel: WriteChannel) } abstract class ByteArrayContent : FinalContent() { abstract fun bytes(): ByteArray } abstract class ProtocolUpgrade : FinalContent() { abstract suspend fun upgrade(input: ReadChannel, output: WriteChannel, channel: Closeable, hostContext: CoroutineContext, userAppContext: CoroutineContext): Closeable } } fun FinalContent.contentLength(): Long? { if (this is Resource) { return contentLength } return headers[HttpHeaders.ContentLength]?.let(String::toLong) } fun FinalContent.contentType(): ContentType? { if (this is Resource) { return contentType } return headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } }
package br.com.helpdev.kleanarch.core.usecase.user.impl import br.com.helpdev.kleanarch.core.entity.user.User import br.com.helpdev.kleanarch.core.entity.user.vo.Age import br.com.helpdev.kleanarch.core.entity.user.vo.Name interface UserGetter { fun getByNameAndAge(name: Name, age: Age): User? fun getAllEnabledUsers(): List<User> }
namespace Autofac { public class Service2 : IService2 { public void Service2Method() { // Service Method Implementation } } }
# 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. """Short-stack board analog hardware monitor configuration.""" from makani.avionics.firmware.monitors import analog_types from makani.avionics.firmware.serial import short_stack_serial_params as rev # Output value = (input - input_offset) / input_divider. analog_default = { 'name': '', 'channel': -1, 'type': analog_types.kAnalogTypeVoltage, 'input_divider': 1.0, 'input_offset': 0.0, 'nominal': 0.0, 'min': 0.0, 'max': 0.0, } voltage = dict(analog_default, type=analog_types.kAnalogTypeVoltage) v_72vfire = dict(voltage, nominal=70.0, min=4.0, max=80.0) # [V] v_5v = dict(voltage, nominal=5.0, min=5.0 * 0.95, max=5.0 * 1.05) # [V] v_3v3 = dict(voltage, nominal=3.3, min=3.3 * 0.95, max=3.3 * 1.05) # [V] v_block = dict(voltage, nominal=1200.0, min=0.0, max=2000.0, # [V] input_divider=(20.0 / (10000.0 + 20.0)) * (20.0 / (20.0 + 10.0))) v_full_stack = dict(voltage, nominal=4400.0, min=0.0, max=6000.0, # [V] input_divider=(20.0 / 10020.0) * (1.03 / (1.03 + 3.09))) v_frame = dict(voltage, nominal=0.0, min=-3000.0, max=3000.0, # [V] input_divider=(20.0 / 10020.0) * (1.03 / (1.03 + 3.09)), input_offset=1.37) common_set = [ dict(v_block, name='block0', channel=17), # +MV/2 to +MV. dict(v_block, name='block1', channel=15), # -MV/2 to MID. dict(v_block, name='block2', channel=14), # -MV to -MV/2. dict(v_block, name='block3', channel=16), # MID to +MV/2. dict(v_full_stack, name='main', channel=18), dict(v_frame, name='frame', channel=19), dict(v_72vfire, name='72vfire', channel=20, input_divider=10.0 / 497.0), dict(v_3v3, name='3v3', channel=21, input_divider=23.2 / 123.2), dict(v_5v, name='5v', channel=22, input_divider=23.2 / 123.2), ] rev_01 = common_set analog_config = (rev.ShortStackHardware, { rev.ShortStackHardware.REV01: rev_01, })
require 'minitest/spec' module MiniTest class Spec class << self alias_method :context, :describe end end end if defined? ActiveSupport::TestCase class ActiveSupport::TestCase class << self alias_method :context, :describe end end end
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS=FLAG_AF ;TEST_FILE_META_END ; AND16rr mov cx, 0x0 mov dx, 0x1 ;TEST_BEGIN_RECORDING and cx, dx ;TEST_END_RECORDING
import 'jest-extended'; declare const expect: (R, T?) => jest.Matchers<R, T>;
using System; using System.Text.RegularExpressions; namespace MathAPI.Extensions { public static class StringExtensions { public static bool IsNumber(this string value) { if (string.IsNullOrEmpty(value)) return false; Regex regex = new Regex("^-?[0-9]*$"); if (!regex.IsMatch(value)) return false; return true; } public static string RemoveNegativeSign(this string value) { if (value.IsNumber() && value[0].Equals('-')) return value.Remove(0, 1); return value; } } }
# frozen_string_literal: true module EventSource module AsyncApi # Contains information about the server representation class ServerBinding < Dry::Struct end end end
#!/usr/bin/env python # -*- coding: utf-8 -*- def solve(): one = two = three = five = 0 five = 65_536 two = 2_238_642 end = False while not end: three = five & 255 two += three two &= 16_777_215 two *= 65_899 two &= 16_777_215 if 256 > five: break three = 0 while five >= 256: one = three + 1 one *= 256 if one > five: five = three break three += 1 return two if __name__ == '__main__': from timeit import default_timer as timer start = timer() solution = solve() print(solution) end = timer() print() print("-" * 80) print("Time elapsed: {:.3f}s".format(end - start))
<?php use Strata\Strata; use Strata\Model\Model; use Strata\Model\CustomPostType\CustomPostType; use Strata\Model\CustomPostType\Registrar\Registrar; class ModelTest extends PHPUnit_Framework_TestCase { public $wordpress; public $model; public $customPostType; public function setUp() { $this->wordpress = wordpress(); $this->wordpress->reset(); $this->model = Model::factory("TestStateless"); $this->customPostType = CustomPostType::factory("TestCustomPostType"); } public function testCanBeInstanciated() { $this->assertTrue($this->model instanceof Model); $this->assertTrue($this->customPostType instanceof CustomPostType); } /** * @expectedException Exception */ public function testInvalidModel() { Model::factory("I_dont_exist"); } public function testCtpRegistered() { $this->wordpress->reset(); $strata = Strata::app(); $strata->setConfig("custom-post-types", array("TestCustomPostType")); $strata->run(); $this->assertArrayHasKey('init', $this->wordpress->actions); $this->assertEquals('register', $this->wordpress->actions['init'][0][1]); } public function testCtpAdminMenuRegistered() { $this->wordpress->reset(); $strata = Strata::app(); $strata->setConfig("custom-post-types", array("TestCustomPostType")); $strata->run(); $this->assertArrayHasKey('admin_menu', $this->wordpress->actions); $this->assertTrue($this->wordpress->actions['admin_menu'][0][0] instanceof Registrar); } }
function Base.show(io::IO, drv::Driver) if drv == C_NULL print(io, "Null Driver") else print(io, "Driver: $(getshortname(drv))/$(getlongname(drv))") # provide creation options too end end function Base.show(io::IO, dataset::Dataset) if dataset == C_NULL print(io, "Closed Dataset") else nrasters = nraster(dataset) println(io, "GDAL Dataset ($(getdriver(dataset)))") print(io, "File(s): ") for (i,filename) in enumerate(filelist(dataset)) print(io, "$filename ") if i % 4 == 0 println() end end # print(io, "\nDataset (width x height): ") # println(io, "$(width(dataset)) x $(height(dataset)) (pixels)\n") println(io, "\nNumber of raster bands: $(nrasters)") for i in 1:min(nrasters, 3) print(io, " ") summarize(io, fetchband(dataset, i)) end nrasters > 3 && println(io, " ...") nlayers = nlayer(dataset) println(io, "Number of feature layers: $(nlayers)") for i in 1:min(nlayers, 3) layer = fetchlayer(dataset, i-1) layergeomtype = _geomname[getgeomtype(layer)] print(io, " Layer $(i-1): $(getname(layer)) ") println(io, "($layergeomtype), nfeatures = $(nfeature(layer))") end nlayers > 3 && print(io, " ...") end end function summarize(io::IO, rasterband::RasterBand) if rasterband == C_NULL print(io, "Null RasterBand") else access = _access[getaccess(rasterband)] color = getcolorinterpname(getcolorinterp(rasterband)) xsize = width(rasterband) ysize = height(rasterband) i = indexof(rasterband) pxtype = getdatatype(rasterband) println(io, "[$access] Band $i ($color): $xsize x $ysize ($pxtype)") end end function Base.show(io::IO, rasterband::RasterBand) summarize(io, rasterband) (x,y) = getblocksize(rasterband) sc = getscale(rasterband) ofs = getoffset(rasterband) norvw = noverview(rasterband) ut = getunittype(rasterband) nv = getnodatavalue(rasterband) println(io, " blocksize: $(x)x$(y), nodata: $nv, units: $(sc)px + $(ofs)$ut") print(io, " overviews: ") for i in 1:norvw ovr_band = fetchoverview(rasterband, i) print(io, "$(width(ovr_band))x$(height(ovr_band)), ") if i % 5 == 0 println(io, "") print(io, " ") end end end function Base.show(io::IO, layer::FeatureLayer) layergeomtype = _geomname[getgeomtype(layer)] print(io, "Layer: $(getname(layer)) ") println(io, "($layergeomtype), nfeatures = $(nfeature(layer))") println("Feature Definition:") featuredefn = getlayerdefn(layer) n = ngeomfield(featuredefn) for i in 1:min(n, 3) gfd = fetchgeomfielddefn(featuredefn, i-1) println(io, " Geometry (index $(i-1)): $(getname(gfd)) ($(_geomname[gettype(gfd)]))") end n > 3 && println(io, " ...\n Number of Geometries: $n") n = nfield(featuredefn) for i in 1:min(n, 10) fd = fetchfielddefn(featuredefn, i-1) println(io, " Field (index $(i-1)): $(getname(fd)) ($(_fieldtype[gettype(fd)]))") end n > 10 && print(io, "...\n Number of Fields: $n") end function Base.show(io::IO, feature::Feature) println(io, "Feature") n = ngeomfield(feature) for i in 1:min(n, 3) println(io, " (index $(i-1)) geom => $(getgeomname(fetchgeomfield(feature, i-1)))") end n > 3 && println(io, "...\n Number of geometries: $n") n = nfield(feature) for i in 1:min(n, 10) print(io, " (index $(i-1)) $(getname(fetchfielddefn(feature, i-1))) => ") println("$(fetchfield(feature, i-1))") end n > 10 && print(io, "...\n Number of Fields: $n") end function Base.show(io::IO, spref::SpatialRef) println(io, "Spatial Reference System") print(io, "$(toWKT(spref, true))") end
#!/bin/bash INFILE=${1:-pages.csv} OUTFILE=${2:-cptable.js} JSVAR=${3:-cptable} VERSION=$(cat package.json | grep version | tr -dc [0-9.]) mkdir -p codepages bits rm -f $OUTFILE $OUTFILE.tmp echo "/*! $OUTFILE (C) 2013-present SheetJS -- http://sheetjs.com */" > $OUTFILE.tmp echo "/*jshint -W100 */" >> $OUTFILE.tmp echo "var $JSVAR = {version:\"$VERSION\"};" >> $OUTFILE.tmp if [ -e dotnet.sh ]; then bash dotnet.sh; fi awk -F, '{print $1, $2, $3}' $INFILE | while read cp url cptype; do echo $cp $url if [ ! -e codepages/$cp.TBL ]; then curl $url | sed 's/#.*//g' | awk 'NF==2' > codepages/$cp.TBL fi echo "if(typeof $JSVAR === 'undefined') $JSVAR = {};" > bits/$cp.js.tmp node make.njs $cp $JSVAR | tee -a bits/$cp.js.tmp >> $OUTFILE.tmp sed 's/"\([0-9]+\)":/\1:/g' <bits/$cp.js.tmp >bits/$cp.js rm -f bits/$cp.js.tmp done echo "// eslint-disable-next-line no-undef" >> $OUTFILE.tmp echo "if (typeof module !== 'undefined' && module.exports && typeof DO_NOT_EXPORT_CODEPAGE === 'undefined') module.exports = $JSVAR;" >> $OUTFILE.tmp sed 's/"\([0-9]+\)":/\1:/g' <$OUTFILE.tmp >$OUTFILE rm -f $OUTFILE.tmp
package weco.storage_service.bag_tracker.models import java.time.Instant import weco.storage_service.bagit.models.{BagId, BagVersion} case class BagVersionEntry( version: BagVersion, createdDate: Instant ) case class BagVersionList( id: BagId, versions: Seq[BagVersionEntry] )
package posidon.android.conveniencelib import android.app.Activity import android.graphics.Point import android.os.Build import android.util.DisplayMetrics import android.view.View import android.view.WindowInsets import android.view.WindowManager import android.view.inputmethod.InputMethodManager import kotlin.math.min inline fun Activity.hideKeyboard() { val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager var view = currentFocus if (view == null) { view = View(this) } imm.hideSoftInputFromWindow(view.windowToken, 0) } inline fun Activity.getNavigationBarHeight(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { windowManager.currentWindowMetrics.windowInsets.getInsets(WindowInsets.Type.navigationBars()).bottom } else { val display = display ?: return 0 val metrics = DisplayMetrics() display.getMetrics(metrics) val usableHeight = metrics.heightPixels display.getRealMetrics(metrics) val realHeight = metrics.heightPixels val navbarHeight = if (realHeight > usableHeight) realHeight - usableHeight else 0 val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android") min(if (resourceId > 0) resources.getDimensionPixelSize(resourceId) else 0, navbarHeight) } }
const SEP = process.platform.startsWith('win') ? '\\' : '/' module.exports = async (files, pkg) => { // map the files object to only the names // then filter in only the ones in the top level folder if (pkg.main) return pkg.main const fnames = files .map(o => o.file) .filter(name => name.split(SEP).length === 1) if (fnames.includes('notebook.ipynb')) return 'notebook.ipynb' if (fnames.includes('notebook.rmd')) return 'notebook.rmd' if (fnames.includes('notebook.md')) return 'notebook.md' if (fnames.includes('notebook.txt')) return 'notebook.txt' return false }
import Record from '@models/Record'; export default class Credential extends Record({ email: '', }) { constructor(data) { super(data); } static of(data) { if (data && data.user) { return new Credential({ email: data.user.user.email, }) } } };
#include "RTMidiOutDevice.h" #include "System/Console/Trace.h" RTMidiOutDevice::RTMidiOutDevice(RtMidiOut &out,int index,const char *name): MidiOutDevice(name), rtMidiOut_(out), running_(false), index_(index) { } ; RTMidiOutDevice::~RTMidiOutDevice() { } ; bool RTMidiOutDevice::Init(){ return true ; } ; void RTMidiOutDevice::Close(){ } ; bool RTMidiOutDevice::Start(){ rtMidiOut_.openPort( index_ ); running_=true ; return true ; } ; void RTMidiOutDevice::Stop(){ running_=false ; rtMidiOut_.closePort() ; } ; void RTMidiOutDevice::SendMessage(MidiMessage &msg) { if (running_) { std::vector<unsigned char> message; message.push_back(msg.status_) ; if (msg.data1_ != MidiMessage::UNUSED_BYTE) { message.push_back(msg.data1_) ; } if (msg.data2_ != MidiMessage::UNUSED_BYTE) { message.push_back(msg.data2_) ; } rtMidiOut_.sendMessage( &message ); } }
paju-mensch_wui =============== Play Framework Web UI
package heroku import "fmt" // SetConfigVars sets the requires config vars for challenge validation func (s *Client) SetConfigVars(appName string, index int, key, token string) error { var keyConfig, tokenConfig string if index == 0 { keyConfig = "ACME_KEY" tokenConfig = "ACME_TOKEN" } else { keyConfig = fmt.Sprintf("ACME_KEY_%d", index) tokenConfig = fmt.Sprintf("ACME_TOKEN_%d", index) } var body = make(map[string]string) body[keyConfig] = key body[tokenConfig] = token var res struct{} return s.Patch(&res, fmt.Sprintf("/apps/%s/config-vars", appName), body) }
/********** Descricao: Funcoes auxiliares para criação do MergeSort e HeapSort **********/ #ifdef __cplusplus extern "C" { #endif #ifndef UTILS_H #define UTILS_H #include <stdlib.h> #include <stdio.h> void generate(int *v, size_t size); void generateCrescente(int *v, size_t size); void generateDecrescente(int *v, size_t size); void printArray(int *v, size_t size); void swap(int *a, int *b); #ifdef __cplusplus } #endif #endif
import CustomerObject from './obj.customer' export default interface EndUserObject extends CustomerObject { /** * The unique UUID Flatfile assigns to the user of your import */ id: string }
package com.chataway.ui.login import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.chataway.R import com.chataway.ui.utility.Login import com.google.firebase.auth.FirebaseAuth const val TAG = "login-task" class LoginViewModel(private val firebaseAuth: FirebaseAuth) : ViewModel() { private val _loginForm = MutableLiveData<LoginFormState>() val loginFormState: LiveData<LoginFormState> = _loginForm private val _loginResult: MutableLiveData<LoginResult> by lazy { if(firebaseAuth.currentUser != null && firebaseAuth.currentUser?.isAnonymous == false) MutableLiveData(LoginResult(success = firebaseAuth.currentUser)) else MutableLiveData() } val loginResult: LiveData<LoginResult> = _loginResult fun login(email: String, password: String) { // either a guest session or a logged in session val result = firebaseAuth.signInWithEmailAndPassword(email, password) result.addOnCompleteListener { task -> if(task.isSuccessful) { Log.i(TAG, "Login successfully") _loginResult.value = LoginResult(success = firebaseAuth.currentUser) } else { Log.i(TAG, "Login failed") _loginResult.value = LoginResult(error = R.string.login_failed) } } } fun loginDataChanged(email: String, password: String) { if (!Login.isEmailValid(email)) { _loginForm.value = LoginFormState(emailError = R.string.invalid_username) } else if (!Login.isPasswordValid(password)) { _loginForm.value = LoginFormState(passwordError = R.string.invalid_password) } else { _loginForm.value = LoginFormState(isDataValid = true) } } }
import 'package:clean_framework/clean_framework_providers.dart'; import 'package:either_dart/either.dart'; import 'package:flutter_test/flutter_test.dart'; class UseCaseFake<I extends SuccessInput> extends Fake implements UseCase<EntityFake> { EntityFake _entity = EntityFake(); late Function subscription; I? successInput; final Output? output; UseCaseFake({this.output}); @override EntityFake get entity => _entity; @override Future<void> request<O extends Output, S extends SuccessInput>(O output, {required EntityFake Function(S successInput) onSuccess, required EntityFake Function(FailureInput failureInput) onFailure}) async { final Either<FailureInput, S> either = await subscription.call(output); _entity = either.fold( (FailureInput failureInput) => onFailure(failureInput), (S successInput) => onSuccess(successInput)); } @override void setInput<I extends Input>(I input) { _entity = _entity.merge('success with input'); } @override void subscribe(Type outputType, Function callback) { subscription = callback; } Future<void> doFakeRequest<O extends Output>(O output) async { await request(output, onFailure: (failure) => _entity.merge('failure'), onSuccess: (success) { successInput = success as I; return _entity.merge('success'); }); } } class EntityFake extends Entity { final String value; EntityFake({this.value = 'initial'}); @override List<Object?> get props => [value]; EntityFake merge(newValue) => EntityFake(value: newValue); }
package metrik.project.rest.validation import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext class EnumValidator : ConstraintValidator<EnumConstraint, String> { private lateinit var valueList: MutableList<String> override fun initialize(constraintAnnotation: EnumConstraint) { valueList = mutableListOf() constraintAnnotation.acceptedValues.forEach { valueList.add(it.toUpperCase()) } } override fun isValid(value: String?, context: ConstraintValidatorContext?): Boolean { return if (value.isNullOrBlank()) { false } else { valueList.contains(value.toUpperCase()) } } }
/** * @file retrieveAccount.dto.ts * @author Youtao Xing <youtao.xing@icloud.com> * @date 2020 */ import { Request } from './request.dto'; import { Response } from './response.dto'; export declare type RetrieveAccountParams = [string]; export declare type RetrieveAccountResult = { address: string; privateKey?: string; publicKey: string; compressedPublicKey: string; }; export declare type RetrieveAccountRequestDto = Request<'retrieveAccount', RetrieveAccountParams>; export declare type RetrieveAccountRsponseDto = Response<RetrieveAccountResult>;
A pytorch prototype implementation of "Masked Language Model Scoring" (https://arxiv.org/pdf/1910.14659.pdf) Baseline BERT code is referenced from https://github.com/shehzaadzd/pytorch-pretrained-BERT.git To run, please execute > bash run.sh
declare const Inline: any; import { LinkParam } from 'jimu-ui/advanced/setting-components'; import { LinkTarget } from 'jimu-ui'; export interface LinkFormatValue { uniqueid: string; dsid: string; href: string; target: LinkTarget; link?: LinkParam; } export declare class Link extends Inline { static SANITIZED_URL: any; statics: any; domNode: HTMLLinkElement; static blotName: string; static tagName: string; static PROTOCOL_WHITELIST: Array<string>; static create(value: LinkFormatValue | string): any; static formats(domNode: any): { uniqueid: any; dsid: any; href: any; target: any; link: any; }; static sanitize(url: any): any; format(name: any, value: LinkFormatValue | string): any; } export {};
import 'package:flutter/material.dart'; enum SlideTransitionType { ltr, rtl, ttb, btt, bl, br, tl, tr } class Navigate<T> { /// Replace the top widget with another widget Future<T?> pushReplace(BuildContext context, Widget widget, {bool isDialog = false, bool isRootNavigator = true, SlideTransitionType slideTransitionType = SlideTransitionType.tr}) async { final T value = await Navigator.of(context, rootNavigator: isRootNavigator) .pushReplacement(NavigateRoute(widget, type: slideTransitionType)); return value; } Future<T?> push(BuildContext context, Widget widget, {bool isDialog = false, bool isRootNavigator = true, SlideTransitionType slideTransitionType = SlideTransitionType.btt}) async { final T value = await Navigator.of(context, rootNavigator: isRootNavigator) .push(NavigateRoute(widget, type: slideTransitionType)); return value; } // pop all Routes except first static void popToFirst(BuildContext context, {bool isRootNavigator = true}) => Navigator.of(context, rootNavigator: isRootNavigator) .popUntil((route) => route.isFirst); Future<void>popView(BuildContext context, {T? value, bool isRootNavigator = true}) async => Navigator.of(context, rootNavigator: isRootNavigator).pop(value); Future<T?> pushAndPopAll(BuildContext context, Widget widget, {bool isRootNavigator = true, SlideTransitionType slideTransitionType = SlideTransitionType.tr}) async { final T value = await Navigator.of(context, rootNavigator: isRootNavigator) .pushAndRemoveUntil(NavigateRoute(widget, type: slideTransitionType), (Route<dynamic> route) => false); return value; } } Offset getTransitionOffset(SlideTransitionType type) { switch (type) { case SlideTransitionType.ltr: return Offset(-1.0, 0.0); case SlideTransitionType.rtl: return Offset(1.0, 0.0); case SlideTransitionType.ttb: return Offset(0.0, -1.0); case SlideTransitionType.btt: return Offset(0.0, 1.0); case SlideTransitionType.bl: return Offset(-1.0, 1.0); case SlideTransitionType.br: return Offset(1.0, 1.0); case SlideTransitionType.tl: return Offset(-1.0, -1.0); case SlideTransitionType.tr: return Offset(1.0, 1.0); default: return Offset(1.0, 0.0); } } class NavigateRoute extends PageRouteBuilder { final Widget widget; final bool? rootNavigator; final SlideTransitionType type; NavigateRoute(this.widget, {this.rootNavigator, required this.type}) : super( pageBuilder: (context, animation, secondaryAnimation) => widget, transitionsBuilder: (context, animation, secondaryAnimation, child) { var begin = getTransitionOffset(type); var end = Offset.zero; var curve = Curves.ease; var tween = Tween(begin: begin, end: end).chain(CurveTween(curve: curve)); return SlideTransition( position: animation.drive(tween), child: child, ); }, ); }
# Design of `percy` This section is intended to be a deep dive into how `percy`'s different internal pieces work today.
import styled from 'styled-components'; import { withProp, prop, ifProp } from 'styled-tools'; import { transparentize } from 'polished'; import getFromTheme from '../../utils/getFromTheme'; import { Subtitle } from '../Subtitle'; export const StyledCard = styled.div` position: absolute; z-index: ${getFromTheme('zIndex.z6')}; top: ${prop('position.top')}px; left: ${prop('position.left')}px; min-width: 160px; width: fit-content; opacity: ${ifProp('fadeIn', '1', '0')}; border-radius: 4px; background-color: ${getFromTheme('palette.misc.white')}; padding: 8px 0; box-shadow: 0 5px 10px ${withProp(getFromTheme('palette.black.900'), transparentize(0.8))}; transition-property: opacity; transition-duration: .1s; transition-timing-function: ease; `; export const Trigger = styled.div` display: inline-block; `; export const Divider = styled.div` display: block; width: 100%; height: 0; border-top: 1px solid ${withProp(getFromTheme('palette.black.900'), transparentize(0.9))}; margin: 8px 0; `; export const StyledTitle = styled(Subtitle)` margin: 0; padding: 8px 16px 4px; color: ${getFromTheme('palette.black.400')}; `;
#ifndef SCENARIOHANDLER_H #define SCENARIOHANDLER_H #include "include/cef_client.h" class ScenarioHandler : public CefClient { public: ScenarioHandler(); private: IMPLEMENT_REFCOUNTING(ScenarioHandler); }; #endif // SCENARIOHANDLER_H
import commonLogic from '@/locale/logic/common/common-logic'; function getLocaleResourceBase(){ const data:any = { fields: { value_key: commonLogic.appcommonhandle("标识",null), catalog_id: commonLogic.appcommonhandle("目录代码",null), catalog_name: commonLogic.appcommonhandle("目录",null), value: commonLogic.appcommonhandle("代码值",null), label: commonLogic.appcommonhandle("名称",null), parent: commonLogic.appcommonhandle("父代码值",null), filter: commonLogic.appcommonhandle("过滤项",null), cls: commonLogic.appcommonhandle("栏目样式",null), icon_class: commonLogic.appcommonhandle("图标",null), disabled: commonLogic.appcommonhandle("是否禁用",null), expired: commonLogic.appcommonhandle("过期/失效",null), showorder: commonLogic.appcommonhandle("排序",null), extension: commonLogic.appcommonhandle("扩展",null), updatedate: commonLogic.appcommonhandle("最后修改时间",null), }, views: { editview: { caption: commonLogic.appcommonhandle("字典项",null), title: commonLogic.appcommonhandle("字典项",null), }, gridview: { caption: commonLogic.appcommonhandle("字典项",null), title: commonLogic.appcommonhandle("字典项",null), }, grideditview: { caption: commonLogic.appcommonhandle("字典项",null), title: commonLogic.appcommonhandle("字典项",null), }, }, main_form: { details: { group1: commonLogic.appcommonhandle("字典项基本信息",null), formpage1: commonLogic.appcommonhandle("基本信息",null), srfupdatedate: commonLogic.appcommonhandle("最后修改时间",null), srforikey: commonLogic.appcommonhandle("",null), srfkey: commonLogic.appcommonhandle("标识",null), srfmajortext: commonLogic.appcommonhandle("名称",null), srftempmode: commonLogic.appcommonhandle("",null), srfuf: commonLogic.appcommonhandle("",null), srfdeid: commonLogic.appcommonhandle("",null), srfsourcekey: commonLogic.appcommonhandle("",null), cname: commonLogic.appcommonhandle("目录",null), val: commonLogic.appcommonhandle("代码值",null), label: commonLogic.appcommonhandle("名称",null), pval: commonLogic.appcommonhandle("父代码值",null), showorder: commonLogic.appcommonhandle("排序",null), disabled: commonLogic.appcommonhandle("是否禁用",null), expired: commonLogic.appcommonhandle("过期/失效",null), vfilter: commonLogic.appcommonhandle("过滤项",null), iconcls: commonLogic.appcommonhandle("图标",null), cls: commonLogic.appcommonhandle("栏目样式",null), extension: commonLogic.appcommonhandle("扩展",null), cid: commonLogic.appcommonhandle("目录代码",null), vkey: commonLogic.appcommonhandle("标识",null), }, uiactions: { }, }, main_grid: { columns: { cid: commonLogic.appcommonhandle("目录代码",null), val: commonLogic.appcommonhandle("代码值",null), label: commonLogic.appcommonhandle("名称",null), pval: commonLogic.appcommonhandle("父代码值",null), showorder: commonLogic.appcommonhandle("排序",null), cname: commonLogic.appcommonhandle("目录",null), cls: commonLogic.appcommonhandle("栏目样式",null), iconcls: commonLogic.appcommonhandle("图标",null), vfilter: commonLogic.appcommonhandle("过滤项",null), disabled: commonLogic.appcommonhandle("是否禁用",null), expired: commonLogic.appcommonhandle("过期/失效",null), extension: commonLogic.appcommonhandle("扩展",null), updatedate: commonLogic.appcommonhandle("最后修改时间",null), }, nodata:commonLogic.appcommonhandle("",null), uiactions: { }, }, options_grid: { columns: { cid: commonLogic.appcommonhandle("目录代码",null), val: commonLogic.appcommonhandle("代码值",null), label: commonLogic.appcommonhandle("名称",null), pval: commonLogic.appcommonhandle("父代码值",null), showorder: commonLogic.appcommonhandle("排序",null), cname: commonLogic.appcommonhandle("目录",null), cls: commonLogic.appcommonhandle("栏目样式",null), iconcls: commonLogic.appcommonhandle("图标",null), vfilter: commonLogic.appcommonhandle("过滤项",null), disabled: commonLogic.appcommonhandle("是否禁用",null), expired: commonLogic.appcommonhandle("过期/失效",null), extension: commonLogic.appcommonhandle("扩展",null), }, nodata:commonLogic.appcommonhandle("",null), uiactions: { }, }, default_searchform: { details: { formpage1: commonLogic.appcommonhandle("常规条件",null), n_cname_like: commonLogic.appcommonhandle("目录(文本包含(%))",null), n_val_like: commonLogic.appcommonhandle("代码值(文本包含(%))",null), n_label_like: commonLogic.appcommonhandle("名称(文本包含(%))",null), }, uiactions: { }, }, editviewtoolbar_toolbar: { tbitem1: { caption: commonLogic.appcommonhandle("Save And Close",null), tip: commonLogic.appcommonhandle("Save And Close Window",null), }, tbitem2: { caption: commonLogic.appcommonhandle("关闭",null), tip: commonLogic.appcommonhandle("关闭",null), }, }, gridviewtoolbar_toolbar: { tbitem3: { caption: commonLogic.appcommonhandle("New",null), tip: commonLogic.appcommonhandle("New",null), }, tbitem4: { caption: commonLogic.appcommonhandle("Edit",null), tip: commonLogic.appcommonhandle("Edit {0}",null), }, tbitem6: { caption: commonLogic.appcommonhandle("Copy",null), tip: commonLogic.appcommonhandle("Copy {0}",null), }, tbitem7: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem24: { caption: commonLogic.appcommonhandle("行编辑",null), tip: commonLogic.appcommonhandle("行编辑",null), }, tbitem25: { caption: commonLogic.appcommonhandle("新建行",null), tip: commonLogic.appcommonhandle("新建行",null), }, deuiaction1: { caption: commonLogic.appcommonhandle("保存行",null), tip: commonLogic.appcommonhandle("保存行",null), }, tbitem26: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem8: { caption: commonLogic.appcommonhandle("Remove",null), tip: commonLogic.appcommonhandle("Remove {0}",null), }, tbitem9: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem13: { caption: commonLogic.appcommonhandle("Export",null), tip: commonLogic.appcommonhandle("Export {0} Data To Excel",null), }, tbitem10: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, deuiaction2: { caption: commonLogic.appcommonhandle("Filter",null), tip: commonLogic.appcommonhandle("Filter",null), }, }, grideditviewtoolbar_toolbar: { tbitem3: { caption: commonLogic.appcommonhandle("New",null), tip: commonLogic.appcommonhandle("New",null), }, tbitem4: { caption: commonLogic.appcommonhandle("Edit",null), tip: commonLogic.appcommonhandle("Edit {0}",null), }, tbitem6: { caption: commonLogic.appcommonhandle("Copy",null), tip: commonLogic.appcommonhandle("Copy {0}",null), }, tbitem7: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem24: { caption: commonLogic.appcommonhandle("行编辑",null), tip: commonLogic.appcommonhandle("行编辑",null), }, tbitem25: { caption: commonLogic.appcommonhandle("新建行",null), tip: commonLogic.appcommonhandle("新建行",null), }, deuiaction1: { caption: commonLogic.appcommonhandle("保存行",null), tip: commonLogic.appcommonhandle("保存行",null), }, tbitem26: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem8: { caption: commonLogic.appcommonhandle("Remove",null), tip: commonLogic.appcommonhandle("Remove {0}",null), }, tbitem9: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, tbitem13: { caption: commonLogic.appcommonhandle("Export",null), tip: commonLogic.appcommonhandle("Export {0} Data To Excel",null), }, tbitem10: { caption: commonLogic.appcommonhandle("-",null), tip: commonLogic.appcommonhandle("",null), }, deuiaction2: { caption: commonLogic.appcommonhandle("Filter",null), tip: commonLogic.appcommonhandle("Filter",null), }, }, }; return data; } export default getLocaleResourceBase;
#!/bin/bash #SBATCH -p debug #SBATCH -N 40 #SBATCH -t 00:15:00 #SBATCH -J spectractor #SBATCH -C haswell #SBATCH --image=nersc/spark-2.3.0:v1 #SBATCH -A m1727 module load spark module load sbt # Parameters (put your file) outpath="/global/cscratch1/sd/peloton/output_ctio" logfile="/global/homes/p/peloton/Spectractor/ctiofulllogbook_jun2017_v5.csv" # For NERSC only (direct glob) datapath="/global/cscratch1/sd/peloton/ctio/CTIODataJune2017_reduced_RG715_v2" # Do not forget to produce a ZIP with the latest change # You can find below the command to execute --> # cd /global/homes/p/peloton/Spectractor # rm spectractor.zip # zip -r spectractor.zip spectractor # cd /global/homes/p/peloton/Spectractor/spark_test # Run it! start-all.sh # Run it! shifter spark-submit \ --master $SPARKURL \ --driver-memory 15g --executor-memory 50g --executor-cores 32 --total-executor-cores 1280 \ --py-files /global/homes/p/peloton/Spectractor/spectractor.zip \ /global/homes/p/peloton/Spectractor/spark_test/sparktractor.py \ -datapath $datapath -outpath $outpath -filesystem lustre -logfile $logfile -log_level ERROR stop-all.sh
SELECT FirstName FROM Employees WHERE DepartmentID IN (3, 10) AND DATEPART(YEAR, HireDate) BETWEEN 1995 AND 2005
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyAss.Compiler.Tests { public static class TestModels { public static String Model_TurnstaleDemo { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands Server STORAGE 1 ; ?9ds Инициализация турникета START 10000 GENERATE 7,5 ;Люди прибывают QUEUE Turn ;Вхождение в очередь ENTER Server ;Начало использования турникета DEPART Turn ;Отбывание из очереди ADVANCE 5,3 ;Задержка использования турникета LEAVE Server ;Конец использования турникета TERMINATE 1 ;Один человек проходит "; } } public static String MM3Model_Simple_FullQual { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands @usingp MyAss.Framework.BuiltIn.SNA.SavevalueSNA @usingp MyAss.Framework.BuiltIn.SNA.QueueSNA @usingp MyAss.Framework.BuiltIn.Procedures.Distributions Server MyAss.Framework.BuiltIn.Commands.STORAGE 3 MyAss.Framework.BuiltIn.Commands.START 1000 MyAss.Framework.BuiltIn.Blocks.GENERATE (Exponential(1,0,1/2)) SAVEVALUE GenerateCounter,(X$GenerateCounter+1) TEST L MyAss.Framework.BuiltIn.SNA.QueueSNA.Q$Tail,20,GoAway ;Jump if in Stack >20 QUEUE Tail ENTER Server,1 DEPART Tail ADVANCE (MyAss.Framework.BuiltIn.Procedures.Distributions.Exponential(2,0,1/0.2)) LEAVE Server,1 SAVEVALUE RejetionProb,(X$RejectCounter/X$GenerateCounter) TERMINATE 1 GoAway SAVEVALUE RejectCounter,(X$RejectCounter+1) TERMINATE ;Delete rejected. "; } } public static String MM3Model_Simple { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands @usingp MyAss.Framework.BuiltIn.SNA.SavevalueSNA @usingp MyAss.Framework.BuiltIn.SNA.QueueSNA @usingp MyAss.Framework.BuiltIn.Procedures.Distributions Server STORAGE 3 START 1000 GENERATE (Exponential(1,0,1/2)) SAVEVALUE GenerateCounter,(X$GenerateCounter+1) TEST L Q$Tail,20,GoAway ;Jump if in Stack >20 QUEUE Tail ENTER Server,1 DEPART Tail ADVANCE (Exponential(2,0,1/0.2)) LEAVE Server,1 SAVEVALUE RejetionProb,(X$RejectCounter/X$GenerateCounter) TERMINATE 1 GoAway SAVEVALUE RejectCounter,(X$RejectCounter+1) TERMINATE ;Delete rejected. "; } } public static String MM3Model_Dynamic { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands @usingp MyAss.Framework.BuiltIn.SNA.SavevalueSNA @usingp MyAss.Framework.BuiltIn.SNA.QueueSNA @usingp MyAss.Framework.BuiltIn.Procedures.Distributions Server STORAGE 3 START 1000 GENERATE (Exponential(1,0,1/2)) SAVEVALUE GenerateCounter,X$GenerateCounter+1 TEST L Q$Tail,20,GoAway ;Jump if in Stack >20 QUEUE Tail ENTER Server,1 DEPART Tail ADVANCE (Exponential(2,0,1/0.2)) LEAVE Server,1 SAVEVALUE RejetionProb,(X$RejectCounter/X$GenerateCounter) TERMINATE 1 GoAway SAVEVALUE RejectCounter,X$RejectCounter+1 TERMINATE ;Delete rejected. "; } } public static String MM3Model_WithTable { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands @usingp MyAss.Framework.BuiltIn.SNA.SystemSNA @usingp MyAss.Framework.BuiltIn.SNA.SavevalueSNA @usingp MyAss.Framework.BuiltIn.SNA.QueueSNA @usingp MyAss.Framework.BuiltIn.Procedures.Distributions Server STORAGE 3 InSystem TABLE MP$InSystemTime,0,4,20 OnServer TABLE MP$OnServTime,0,2,20 OnQueue TABLE MP$OnQueueTime,0,4,20 START 1000 GENERATE (Exponential(1,0,1/2)) MARK InSystemTime MARK OnQueueTime SAVEVALUE GenerateCounter,(X$GenerateCounter+1) TEST L Q$Tail,20,GoAway ;Jump if in Stack >20 QUEUE Tail ENTER Server,1 DEPART Tail TABULATE OnQueue MARK OnServTime ADVANCE (Exponential(2,0,1/0.2)) LEAVE Server,1 TABULATE OnServer TABULATE InSystem SAVEVALUE RejetionProb,(X$RejectCounter/X$GenerateCounter) TERMINATE 1 GoAway SAVEVALUE RejectCounter,(X$RejectCounter+1) TERMINATE ;Delete rejected. "; } } public static String TableStdSevTest { get { return @" @using MyAss.Framework.BuiltIn.Blocks @using MyAss.Framework.BuiltIn.Commands @usingp MyAss.Framework.BuiltIn.SNA.SystemSNA @usingp MyAss.Framework.BuiltIn.SNA.SavevalueSNA @usingp MyAss.Framework.BuiltIn.SNA.QueueSNA @usingp MyAss.Framework.BuiltIn.Procedures.Distributions TheTable TABLE P$const,0,1,20 START 1 GENERATE ,,1,1 ASSIGN const,3 TABULATE TheTable TERMINATE GENERATE ,,2,1 ASSIGN const,8 TABULATE TheTable TERMINATE GENERATE ,,3,1 ASSIGN const,1 TABULATE TheTable TERMINATE GENERATE ,,4,1 ASSIGN const,5 TABULATE TheTable TERMINATE GENERATE ,,5,1 ASSIGN const,14 TABULATE TheTable TERMINATE GENERATE ,,6,1 ASSIGN const,6 TABULATE TheTable TERMINATE 1 "; } } } }
class Drink: def __init__(self, **entries): self.nextMove = None self.ingredients = 0 self.sugar = 0 self.ice = 0 self.black_tea = 0 self.wm_tea = 0 self.id = None self.order_id = None self.manufacturingProcess = [] self.__dict__.update(entries) def getVolume(self,station): volumeDic = {'ingredients':self.ingredients,'ice':self.ice, 'black_tea':self.black_tea,'wm_tea':self.wm_tea} return volumeDic[station]
package typingsSlinky.prettyFormat import org.scalablytyped.runtime.Shortcut import typingsSlinky.prettyFormat.typesMod.Config import typingsSlinky.prettyFormat.typesMod.NewPlugin import typingsSlinky.prettyFormat.typesMod.Printer import typingsSlinky.prettyFormat.typesMod.Refs import typingsSlinky.prettyFormat.typesMod.Test import typingsSlinky.std.Record import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object reactTestComponentMod extends Shortcut { @JSImport("pretty-format/build/plugins/ReactTestComponent", JSImport.Default) @js.native val default: NewPlugin = js.native @JSImport("pretty-format/build/plugins/ReactTestComponent", "serialize") @js.native val serialize: js.Function6[ /* val */ js.Any, /* config */ Config, /* indentation */ String, /* depth */ Double, /* refs */ Refs, /* printer */ Printer, String ] = js.native @JSImport("pretty-format/build/plugins/ReactTestComponent", "test") @js.native val test: Test = js.native type ReactTestChild = ReactTestObject | String | Double @js.native trait ReactTestObject extends StObject { @JSName("$$typeof") var DollarDollartypeof: js.Symbol = js.native var children: js.UndefOr[Null | js.Array[ReactTestChild]] = js.native var props: js.UndefOr[Record[String, _]] = js.native var `type`: String = js.native } object ReactTestObject { @scala.inline def apply(DollarDollartypeof: js.Symbol, `type`: String): ReactTestObject = { val __obj = js.Dynamic.literal() __obj.updateDynamic("$$typeof")(DollarDollartypeof.asInstanceOf[js.Any]) __obj.updateDynamic("type")(`type`.asInstanceOf[js.Any]) __obj.asInstanceOf[ReactTestObject] } @scala.inline implicit class ReactTestObjectMutableBuilder[Self <: ReactTestObject] (val x: Self) extends AnyVal { @scala.inline def setChildren(value: js.Array[ReactTestChild]): Self = StObject.set(x, "children", value.asInstanceOf[js.Any]) @scala.inline def setChildrenNull: Self = StObject.set(x, "children", null) @scala.inline def setChildrenUndefined: Self = StObject.set(x, "children", js.undefined) @scala.inline def setChildrenVarargs(value: ReactTestChild*): Self = StObject.set(x, "children", js.Array(value :_*)) @scala.inline def setDollarDollartypeof(value: js.Symbol): Self = StObject.set(x, "$$typeof", value.asInstanceOf[js.Any]) @scala.inline def setProps(value: Record[String, _]): Self = StObject.set(x, "props", value.asInstanceOf[js.Any]) @scala.inline def setPropsUndefined: Self = StObject.set(x, "props", js.undefined) @scala.inline def setType(value: String): Self = StObject.set(x, "type", value.asInstanceOf[js.Any]) } } type _To = NewPlugin /* This means you don't have to write `default`, but can instead just say `reactTestComponentMod.foo` */ override def _to: NewPlugin = default }
# -*- coding: utf-8 -*- import json import logging from django.conf import settings from django.template.context import RequestContext from django.utils import translation, six from djangojs.conf import settings from djangojs.utils import LazyJsonEncoder logger = logging.getLogger(__name__) __all__ = ( 'ContextSerializer', ) SERIALIZABLE_TYPES = six.string_types + six.integer_types + (six.text_type, tuple, list, dict, bool, set) class ContextSerializer(object): ''' Serialize context and user from requests. Inherits from this class and set your :ref:`settings.JS_CONTEXT_PROCESSOR <js-context-processor>` to customize the serialization. To add a custom variable serialization handler, add a method named ``process_VARNAME(self, value, data)``. ''' def __init__(self, request): self.request = request def as_dict(self): ''' Serialize the context as a dictionnary from a given request. ''' data = {} if settings.JS_CONTEXT_ENABLED: for context in RequestContext(self.request): for key, value in six.iteritems(context): if settings.JS_CONTEXT and key not in settings.JS_CONTEXT: continue if settings.JS_CONTEXT_EXCLUDE and key in settings.JS_CONTEXT_EXCLUDE: continue handler_name = 'process_%s' % key if hasattr(self, handler_name): handler = getattr(self, handler_name) data[key] = handler(value, data) elif isinstance(value, SERIALIZABLE_TYPES): data[key] = value if settings.JS_USER_ENABLED: self.handle_user(data) # Monkey patch for https://github.com/noirbizarre/django.js/issues/53 data.update({ 'STATIC_URL': settings.STATIC_URL, 'MEDIA_URL': settings.MEDIA_URL, 'LANGUAGES': settings.LANGUAGES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, }) return data def as_json(self): ''' Serialize the context as JSON. ''' return json.dumps(self.as_dict(), cls=LazyJsonEncoder) def process_LANGUAGES(self, languages, data): '''Serialize LANGUAGES as a localized dictionnary.''' return dict(languages) def process_LANGUAGE_CODE(self, language_code, data): ''' Fix language code when set to non included default `en` and add the extra variables ``LANGUAGE_NAME`` and ``LANGUAGE_NAME_LOCAL``. ''' # Dirty hack to fix non included default language_code = 'en-us' if language_code == 'en' else language_code language = translation.get_language_info('en' if language_code == 'en-us' else language_code) if not settings.JS_CONTEXT or 'LANGUAGE_NAME' in settings.JS_CONTEXT \ or (settings.JS_CONTEXT_EXCLUDE and 'LANGUAGE_NAME' in settings.JS_CONTEXT_EXCLUDE): data['LANGUAGE_NAME'] = language['name'] if not settings.JS_CONTEXT or 'LANGUAGE_NAME_LOCAL' in settings.JS_CONTEXT \ or (settings.JS_CONTEXT_EXCLUDE and 'LANGUAGE_NAME_LOCAL' in settings.JS_CONTEXT_EXCLUDE): data['LANGUAGE_NAME_LOCAL'] = language['name_local'] return language_code def handle_user(self, data): ''' Insert user informations in data Override it to add extra user attributes. ''' # Default to unauthenticated anonymous user data['user'] = { 'username': '', 'is_authenticated': False, 'is_staff': False, 'is_superuser': False, 'permissions': tuple(), } if 'django.contrib.sessions.middleware.SessionMiddleware' in settings.MIDDLEWARE_CLASSES: user = self.request.user data['user']['is_authenticated'] = user.is_authenticated() if hasattr(user, 'username'): data['user']['username'] = user.username elif hasattr(user, 'get_username'): data['user']['username'] = user.get_username() if hasattr(user, 'is_staff'): data['user']['is_staff'] = user.is_staff if hasattr(user, 'is_superuser'): data['user']['is_superuser'] = user.is_superuser if hasattr(user, 'get_all_permissions'): data['user']['permissions'] = tuple(user.get_all_permissions())
/// <reference path="../external/Jupyter.d.ts" /> import React from "react"; import { EditableText } from "./EditableText"; interface SelectionItemProps { isActive: boolean; selectionName: string; onDelete: () => void; onClick: () => void; } interface SelectionItemState { selectionName: string; } export class SelectionItem extends React.Component<SelectionItemProps, SelectionItemState> { constructor(props: SelectionItemProps) { super(props); this.state = { selectionName: this.props.selectionName, }; } onSave(val: string) { Jupyter.keyboard_manager.enable(); // do nothing else // const prevName = this.state.selectionName; // // TODO: somehow use prevstate for this? But can't seem to access in callback... // this.setState({selectionName: val}, () => { // const execute = `m.js_update_selection_shelf_selection_name('${prevName}', '${val}')`; // console.log("clicked, and executing", execute); // IPython.notebook.kernel.execute(execute); // }); } render() { return ( <div className={`midas-shelf-selection-item`}> <EditableText isActive={this.props.isActive} value={this.state.selectionName} onSave={(val) => this.onSave(val)} onDeleteButtonClicked={this.props.onDelete} onTextClicked={this.props.onClick} onEditStart={() => Jupyter.keyboard_manager.disable()} /> </div> ); } }
using System.Collections.Generic; namespace HelpByPros.BusinessLogic { public class Member:User { /// <summary> /// List of questions posted by this user. /// </summary> public List<Question> MyQuestion { get; set; } = new List<Question>(); /// <summary> /// Points available to this user. /// </summary> public int PointAvailable { get; set; } /// <summary> /// List of answers posted by this user. /// </summary> public List<Answer> MyAnswers { get; set; } = new List<Answer>(); } }
# GPG Vault Simple GPG based file encryption utility. Allows viewing and editing of encrypted files with passphrase caching. ## Installing Using PIP: ``` % pip3 install gpg-vault ``` ## Viewing files ``` % vcat file.txt.gpg Passphrase: ************ Hello [Use CMD-K to clear sensitve information from the screen] % % vcat file.txt.gpg Hello [Use CMD-K to clear sensitve information from the screen] % ``` ## Editing files ``` % vedit file.txt Passphrase: ************ [wiping file file.txt.gpg] [encrypting file /tmp/v/37795/37795 to file.txt.gpg] [wiping directory/tmp/v/37795] % % vcat file.txt.gpg Hello [Use CMD-K to clear sensitve information from the screen] % ``` ## Encrypting files ``` % vencrypt file.txt Passphrase: ************ Confirm Passphrase: ************ [encrypting file file.txt to file.txt.gpg] [wiping file file.txt] ``` ## Clearing cached passphrases ``` % vclear ```
#Get the NetworkconfigPolicy to delete $NetworkconfigPolicy = Remove-IntersightNetworkconfigPolicy -Name NetworkconfigPolicyName $NetworkconfigPolicy | Remove-IntersightNetworkconfigPolicy #Remove the server profile by Moid. Remove-IntersightNetworkconfigPolicy -Moid 123bc2222287wee
# FB2018, as of 2018.04.07 roboRIO serial number: 030a4a34 ## CAN * 2 = Left Master - PDP:3 : CANTalon(2) * 3 = Left Slave - PDP:2 : CANTalon(3) * 4 = Right Master - PDP:1 : CANTalon(4) * 5 = Right Slave - PDP:0 : CANTalon(5) * 11 = leftSpinner : CANTalon(11) * 12 = rightSpinner : CANTalon(12) * 13 = leftIntake : CANTalon(13) * 14 = rightIntake : CANTalon(14) ## DIO * 0 = Grabber Down Position : edu.wpi.first.wpilibj.DigitalInput@163006a * 1 = Grabber Up Position : edu.wpi.first.wpilibj.DigitalInput@1be847c * 2 = Tape Finder : edu.wpi.first.wpilibj.DigitalInput@f0a63f * 4 = Cube Detector : edu.wpi.first.wpilibj.DigitalInput@1f4c3 ## ANALOG IN * 0 = Range Finder : edu.wpi.first.wpilibj.AnalogInput@104e3b2 * 1 = Range Finder 2 : edu.wpi.first.wpilibj.AnalogInput@19619aa * 2 = Pressure Sensor : edu.wpi.first.wpilibj.AnalogInput@ac736f ## Other Configuration * 4 = Trinket I2C Address ## Pneumatics * [0,1,0] = leftPneumatics : edu.wpi.first.wpilibj.DoubleSolenoid@774085 * [0,3,2] = rightPneumatics : edu.wpi.first.wpilibj.DoubleSolenoid@8102c8 * [0,5,4] = leftOpenClose : edu.wpi.first.wpilibj.DoubleSolenoid@996db8 * [0,7,6] = rightOpenClose : edu.wpi.first.wpilibj.DoubleSolenoid@163006a * [1,1,0] = leftUpDown : edu.wpi.first.wpilibj.DoubleSolenoid@1be847c * [1,3,2] = rightUpDown : edu.wpi.first.wpilibj.DoubleSolenoid@1975e01 ## Joysticks * 0 = Joystick 1 : edu.wpi.first.wpilibj.Joystick@d072a9 * 7 = Test Motors Forward : TestMotors * 9 = Test Motors Backward : TestMotors * 1 = Joystick 2 : edu.wpi.first.wpilibj.Joystick@75222b * 1 = Shoot : FireCubeCommand * 7 = Arm Down : GrabberDownCommand * 9 = Arm Up : GrabberUpCommand * 11 = Spinner wheels : SpinGrabberWheelsCommand * 12 = Grabber wheels : SpinGrabberWheelsCommand * 13 = Celebrate : CelebrateCommand * 14 = Toggle arms open/closed : OpenGrabberCommand * 2 = Right-side : Autonomous * 3 = Left-side : Autonomous * 8 = Split : Autonomous * 15 = Switch/Scale : Autonomous * 16 = Cross/Dont-cross : Autonomous
--TEST-- Bug #45373 (php crash on query with errors in params) --SKIPIF-- <?php include("skipif.inc"); ?> --FILE-- <?php require("interbase.inc"); $db = ibase_connect($test_base); $sql = "select * from test1 where i = ? and c = ?"; $q = ibase_prepare($db, $sql); $r = ibase_execute($q, 1, 'test table not created with isql'); var_dump(ibase_fetch_assoc($r)); ibase_free_result($r); $r = ibase_execute($q, 1, 'test table not created with isql', 1); var_dump(ibase_fetch_assoc($r)); ibase_free_result($r); $r = ibase_execute($q, 1); var_dump(ibase_fetch_assoc($r)); ?> --EXPECTF-- array(2) { ["I"]=> int(1) ["C"]=> string(32) "test table not created with isql" } Notice: ibase_execute(): Statement expects 2 arguments, 3 given in %s on line %d array(2) { ["I"]=> int(1) ["C"]=> string(32) "test table not created with isql" } Warning: ibase_execute(): Statement expects 2 arguments, 1 given in %s on line %d Warning: ibase_fetch_assoc() expects parameter 1 to be resource, boolean given in %s on line %d NULL
#!/bin/bash if [ "${APP_MODE}" == "install" ] then php bin/console cache:warmup --env=${APP_ENV}; php bin/console doctrine:database:create --if-not-exists --env=${APP_ENV}; php bin/console doctrine:schema:update --em=default --force --env=${APP_ENV}; php bin/console yay:integration:enable default integration/default --env=${APP_ENV}; php bin/console yay:integration:enable demo integration/demo --env=${APP_ENV}; while sleep 3600; do :; done; fi if [ "${APP_MODE}" == "web" ] then php bin/console cache:warmup --env=${APP_ENV}; php bin/console yay:integration:enable default integration/default --config-only --env=${APP_ENV}; php bin/console yay:integration:enable demo integration/demo --config-only --env=${APP_ENV}; apache2-foreground fi
--- layout: entry name: Into the Gungeon author: Mr. Screw On Head genre: action summary: "Bullet Hell Hack" cost: "$0.00" subtext1: subtext2: subtext3: subtext4: category: - hacks source: blog source-url: https://wasitlikely.blogspot.com/2019/05/into-gungeon-run-n-gunbullet-hell-hack.html ---
@extends('admin.layout.index') @section('content') <section class="wrapper"> <h2 class="text-center">添加轮播图</h2> <center> <div class="row mt text-center" style="width:1200px;"> <div class="col-lg-12" > <div class="form-panel"> <!-- 提示错误信息 --> @if (count($errors) > 0) <div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="form-horizontal" action="/admin/slide" method="post" enctype="multipart/form-data"> {{ csrf_field() }} <div class="form-group"> <label class="col-sm-2 "><span class="user_add">轮 播 图 名</span></label> <div class="col-sm-10"> <input type="text" class="form-control" name="slide_name" value="{{ old('slide_name') }}"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label"><span class="user_add">详 细 描 述</span></label> <div class="col-sm-offset-2 col-sm-10"> <textarea name="slide_note" id="" cols="50" rows="6" placeholder="填写图片的详细描述">{{ old('slide_note') }}</textarea> </div> </div> <div class="form-group"> <label class="col-sm-2 col-sm-2 control-label"><span class="user_add">对 应 商 品</span></label> <div class="col-sm-10"> <select class="form-control input-sm" name="goods_id"> @foreach ($goods as $v) <option value="{{ $v->id }}">{{ $v->goods_name }}</option> @endforeach </select> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label"><span class="user_add">选 择 图 片</span></label> <div class="col-sm-offset-2 col-sm-10"> <img src="" alt="" id="img0" width="100" /><br> <span id="info"></span><br> <input type="file" name="slide_pic" id="pic" class="file0"> </div> </div> <center> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">添加</button> </div> </div> </center> </form> </div> </div> </div> </section> @endsection()
use Test; use Distribution::Dependencies; my %result = explore; is %result<JSON::Fast>, 1, "Auto-exploration works"; done-testing;
/* Navicat MySQL Data Transfer Source Server : localhost3306 Source Server Version : 50505 Source Host : localhost:3306 Source Database : taobao Target Server Type : MYSQL Target Server Version : 50505 File Encoding : 65001 Date: 2018-06-20 11:56:16 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for item -- ---------------------------- DROP TABLE IF EXISTS `item`; CREATE TABLE `item` ( `item_id` bigint(20) NOT NULL, `title` varchar(255) NOT NULL, `userid` int(15) NOT NULL, `nick` varchar(255) DEFAULT NULL, `price` decimal(10,2) NOT NULL, `originalPrice` decimal(10,2) DEFAULT NULL, `sold` int(15) DEFAULT NULL, `shipping` decimal(8,2) NOT NULL, `fastPostFee` decimal(8,2) DEFAULT NULL, `img2` varchar(255) DEFAULT NULL, `location` varchar(15) DEFAULT NULL, `area` varchar(15) DEFAULT NULL, `commentCount` int(10) DEFAULT NULL, PRIMARY KEY (`item_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Table structure for rate -- ---------------------------- DROP TABLE IF EXISTS `rate`; CREATE TABLE `rate` ( `itemId` bigint(15) NOT NULL, `rateId` bigint(15) NOT NULL, `rateDate` bigint(13) NOT NULL, `rateContent` text, `photos` text, PRIMARY KEY (`rateId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `userId` bigint(15) NOT NULL, `nick` varchar(20) NOT NULL, `avatar` varchar(255) DEFAULT NULL, PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- View structure for select_all -- ---------------------------- DROP VIEW IF EXISTS `select_all`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` VIEW `select_all` AS SELECT item.item_id, rate.photos, rate.rateContent, rate.rateDate, rate.rateId, item.title, item.userid, item.nick, item.price, item.originalPrice, item.sold, item.shipping, item.fastPostFee, item.img2, item.location, item.area, item.commentCount FROM item INNER JOIN rate ON item.item_id = rate.itemId INNER JOIN `user` ON rate.rateId = `user`.userId WHERE item.item_id = 529501838768 ;
library(shiny) library(ggplot2) library(ggvis) # Data processing libraries library(data.table) library(reshape2) library(dplyr) library(mapproj) library(maps) # Load data dt <- fread('data/gdp.csv') world_map <- map_data("world") shinyServer( function(input,output){ output$gdpMap <- renderPlot({ year = input$year world_map$gdp_percapita <- nchar(dt[ , year]) + sample(nrow(world_map)) # Prepare map based on GDP data gg <- ggplot(world_map,aes(map_id=region)) gg <- gg + geom_map(data=world_map, map=world_map, aes(map_id=region, x=long, y=lat, fill=gdp_percapita)) gg <- gg + scale_fill_gradient(low = "red", high = "green", guide = "colourbar") gg <- gg + coord_equal() print( gg ) }) } )
using System.Linq; using GenericSearch.Data; using Xunit; namespace GenericSearch.Core { public class TextSearchTest { [Fact] public void ApplyToQuery_ContainsText_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "Text"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "abcdef"; criteria.Comparator = TextComparators.Contains; Assert.Equal(2, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } [Fact] public void ApplyToQuery_EqualsText_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "Text"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "abcdef"; criteria.Comparator = TextComparators.Equals; Assert.Equal(1, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } [Fact] public void ApplyToQuery_EqualsNestedText_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "Nested.TextNested"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "qwerty"; criteria.Comparator = TextComparators.Equals; Assert.Equal(2, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } [Fact] public void ApplyToQuery_EqualsNestedNestedText_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "Nested.Nested.TextNested"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "qwerty"; criteria.Comparator = TextComparators.Equals; Assert.Equal(0, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } [Fact] public void ApplyToQuery_EqualsTextInCollectionSimple_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "CollectionString"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "simple_123"; criteria.Comparator = TextComparators.Equals; Assert.Equal(8, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } [Fact] public void ApplyToQuery_EqualsTextInCollectionComplex_CorrectResultReturned() { var criteria = new TextSearch(); criteria.Property = "CollectionComplex.TextNested"; criteria.TargetTypeName = typeof(SomeClass).AssemblyQualifiedName; criteria.SearchTerm = "complex_678"; criteria.Comparator = TextComparators.Equals; Assert.Equal(8, criteria.ApplyToQuery(new Repository().GetQuery()).Count()); } } }
class CreateExpandedTextAds < ActiveRecord::Migration[5.0] def change create_table :expanded_text_ads do |t| t.string :xsi_type t.integer :ad_group_id t.string :headline_part1 t.string :headline_part2 t.string :description t.string :path1 t.string :path2 t.timestamps end end end
declare namespace JSX { import HTMLAttributes = JSXInternal.HTMLAttributes; interface IntrinsicElements { 'confusion-matrix-element': HTMLAttributes<AngularElement>; } } declare interface AngularElement extends HTMLElement { labelsAnalysis: any; }
/* Создание виртуальной функции для вычисления площади фигур на примере создания классов с наследованиями: Shape, Triangle, Circle, Rectangle, Square. */ #include "stdafx.h" #include <iostream> using namespace std; //число Пи const double PI = 3.14159265; //Класс Shape + виртуальная функция class Shape { public: virtual double Calculate_Area() const = 0; }; //Класс Triangle наследуется от класса Shape class Triangle : public Shape { private: double base, hight; public: Triangle(double, double); double Calculate_Area() const; //const }; //Конструктор по умолчанию Triangle::Triangle(double b, double h) :base(b), hight(h) {} //Использование виртуальной функции для вычисления площади double Triangle::Calculate_Area() const { return 0.5*base*hight; } //Класс Circle наследуется от класса Shape class Circle : public Shape { private: double radius; public: Circle(double); double Calculate_Area() const; }; //Конструктор по умолчанию Circle::Circle(double r) : radius(r) {} //Использование виртуальной функции для вычисления площади double Circle::Calculate_Area() const { return PI*radius*radius; } //Класс Rectangle наследуется от класса Shape class Rectangle : public Shape { protected: double side_a, side_b; public: Rectangle(double, double); double Calculate_Area() const; }; //Конструктор по умолчанию Rectangle::Rectangle(double a, double b) : side_a(a), side_b(b) {} //Использование виртуальной функции для вычисления площади double Rectangle::Calculate_Area() const { return side_a*side_b; } //Класс Square наследуется от класса Rectangle class Square : public Rectangle { public: Square(double); double Calculate_Area() const; }; //Коснтруктор класса квадрата вызывает конструктор класса прямоугольника Square::Square(double a) : Rectangle(a,a) { } //Использование виртуальной функции для вычисления площади double Square::Calculate_Area() const { return side_a*side_b; } int main() { Shape *S; Circle c(5); Triangle t(3, 8); Rectangle r(2, 4); Square sq(3); S = &c; cout << S->Calculate_Area() << endl; //площадь круга S = &t; cout << S->Calculate_Area() << endl; //площадь треугольника S = &r; cout << S->Calculate_Area() << endl; //площадь прямоугольника S = &sq; cout << S->Calculate_Area() << endl; //площадь прямоугольника return 0; }
@JS("bridge") library bridge; import 'package:js/js.dart'; import 'dart:async'; @JS("load") external Future<dynamic> load(dynamic buffer); @JS("call") external Future<dynamic> call(dynamic buffer, List<Object?> lengths);
#### 1.5.0 - Unreleased * Implement Go to Metadata #### 1.4.5 - August 28 2014 * Fix forcing saving projects when project items change * Fix various issues on unused open declarations #### 1.4.0 - August 10 2014 * Improve rename refactoring validation * Add support for VS 14 * Implement Gray out unused open statements * Handle included files while working on F# scripts * Add VS unit tests for multiple features * Implement unused declaration scrollbar markers #### 1.3.0 - July 10 2014 * Add report progress and cancellation to Rename Refactoring * Add report progress to Find All References * Enhance Xaml support * Implement Resolve unopened namespaces * Implement Gray out unused declarations * Add a NuGet package for the core project #### 1.2.0 - June 17 2014 * Implement Union type pattern generation * Fix various bugs on syntax coloring * Improve responsiveness on big solutions * Improve memory usage * Protect against intermittent crashes #### 1.1.0 - May 22 2014 * Add Implement Interface feature * Fix duplicated symbols and missing private symbols in Find All References * Enhance syntax coloring of type-provider-related source code * Reduce the size of VSIX output * Implement record stub generation * Fix the issue where VFPT is active during CPU idles * Return correct symbol information on dirty files and dirty projects #### 1.0.0 - April 26 2014 * Implement Find all references * Improve robustness of XmlDoc generation * Improve performance on large solutions * Add validation after reformatting #### 0.6.1 - April 14 2014 * Fix the issue where rename refactoring is applied after cancelled by 'Esc' #### 0.6.0 - April 14 2014 * Add folder organization support * Enhance syntax coloring (now with coloring modules and quotations) * Implement solution-wide rename refactoring * Add logging facilities #### 0.5.0 - March 24 2014 * Improve Rename dialog * Improve performance of NavigateTo feature * Implement semantic highlighting * Migrate to XAML provider in FsXaml * Improve lexing performance * Fix intermittent navigation bar configuration * Setup integration tests #### 0.4.1 - March 13 2014 * Fix the issue with standalone fs files * Fix the issue with failing source code formatting feature #### 0.4.0 - March 11 2014 * Import depth colorizer * Implement NavigateTo command * Fix performance issues with highlight references and rename refactoring * Support highlight references, rename refactoring and NavigateTo on standalone files * Listen to events due to project changes * Improve F# project system #### 0.3.2 - February 26 2014 * Fix the NRE when there is no project or solution #### 0.3.1 - February 25 2014 * Fix the issue where multiple replacements are wrong if performed in a single line * Use Ctrl + R, Ctrl + R key binding for rename refactoring #### 0.3.0 - February 25 2014 * Implement major improvements on highlight references * Support operator highlighting * Reuse C#'s highlighted reference marker * Add rename refactoring #### 0.2.0 - February 12 2014 * Add navigation bar setting * XML doc comments are generated as the first '<' char in a blank "///" comment is entered * Implement highlight references #### 0.1.1 - February 5 2014 * Add options to disable constituent parts #### 0.1.0 - February 5 2014 * Import Fantomas extension * Import FSharpXMLDoc extension * Add basic documentation
package test import ( "context" "encoding/hex" "github.com/capnpVSgrpc/config" pb "github.com/capnpVSgrpc/protobuff" "google.golang.org/grpc" "log" "testing" "time" ) func BenchmarkGrpc(b *testing.B) { var acc pb.Account acc.AccountId = &pb.AccountId{} acc.Name = config.AccountName acc.Balance = config.Balance acc.AccountId.AccountId = make([]byte, 32) acc.AccountId.AccountId, _ = hex.DecodeString(config.AccountId) ctx, cancel := context.WithTimeout(context.Background(), time.Second*60) defer cancel() conn, err := grpc.Dial(config.GrpcAddress, grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() cb := pb.NewCoreBankingClient(conn) for i := 0; i < b.N; i++ { res, err := cb.EchoAccount(ctx, &acc) if err != nil { log.Fatalf("could not greet: %v, %v", err, res) } //log.Printf("\n\nGRPC Client Result :\n", hex.EncodeToString(res.AccountId.AccountId)) } }
export type IsA = (x: any) => boolean; export const aString: IsA = x => typeof x === 'string'; export const aNumber: IsA = x => typeof x === 'number'; export const anArray: IsA = x => Array.isArray(x); export const notNull: IsA = x => x !== null; export const notUndefined: IsA = x => x !== undefined; export const present: IsA = x => x != null; export const longerThan = (n: number): IsA => x => aString(x) || anArray(x) ? (x as string | any[]).length > n : false; export const shorterThan = (n: number): IsA => x => aString(x) || anArray(x) ? (x as string | any[]).length < n : false; export const length = (n: number): IsA => x => aString(x) || anArray(x) ? (x as string | any[]).length === n : false;
import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:immich_mobile/modules/search/models/curated_location.model.dart'; import 'package:immich_mobile/modules/search/models/curated_object.model.dart'; import 'package:immich_mobile/modules/search/models/search_page_state.model.dart'; import 'package:immich_mobile/modules/search/services/search.service.dart'; class SearchPageStateNotifier extends StateNotifier<SearchPageState> { SearchPageStateNotifier() : super( SearchPageState( searchTerm: "", isSearchEnabled: false, searchSuggestion: [], userSuggestedSearchTerms: [], ), ); final SearchService _searchService = SearchService(); void enableSearch() { state = state.copyWith(isSearchEnabled: true); } void disableSearch() { state = state.copyWith(isSearchEnabled: false); } void setSearchTerm(String value) { state = state.copyWith(searchTerm: value); _getSearchSuggestion(state.searchTerm); } void _getSearchSuggestion(String searchTerm) { var searchList = state.userSuggestedSearchTerms; var newList = searchList.where((e) => e.toLowerCase().contains(searchTerm)); state = state.copyWith(searchSuggestion: [...newList]); if (searchTerm.isEmpty) { state = state.copyWith(searchSuggestion: []); } } void getSuggestedSearchTerms() async { var userSuggestedSearchTerms = await _searchService.getUserSuggestedSearchTerms(); state = state.copyWith(userSuggestedSearchTerms: userSuggestedSearchTerms); } } final searchPageStateProvider = StateNotifierProvider<SearchPageStateNotifier, SearchPageState>((ref) { return SearchPageStateNotifier(); }); final getCuratedLocationProvider = FutureProvider.autoDispose<List<CuratedLocation>>((ref) async { final SearchService _searchService = SearchService(); var curatedLocation = await _searchService.getCuratedLocation(); if (curatedLocation != null) { return curatedLocation; } else { return []; } }); final getCuratedObjectProvider = FutureProvider.autoDispose<List<CuratedObject>>((ref) async { final SearchService _searchService = SearchService(); var curatedObject = await _searchService.getCuratedObjects(); if (curatedObject != null) { return curatedObject; } else { return []; } });
import * as Yup from 'yup'; export const formSchema = Yup.object({ name: Yup.string().required('Name is required.'), email: Yup.string().email().required('Email is required.'), city: Yup.string().required('City is required'), username: Yup.string().required('Username is required.'), });
En la configuración de B2C, haga clic en **Aplicaciones** y luego en **Agregar**. ![Botón + Agregar de las aplicaciones](./media/active-directory-b2c-portal-add-application/b2c-applications-add.png)
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const ListNode_1 = __importDefault(require("./ListNode")); /** * Implements a singly linked list. * * {@link https://en.wikipedia.org/wiki/Linked_list Linked List on Wikipedia} */ class LinkedList { /** * Creates a LinkedList. * @time O(1) * @constructs LinkedList * @param {*} value A value. */ constructor(value) { this.head = new ListNode_1.default(value); this.tail = this.head; this.size = 1; } /** * Appends a new value to the tail of the LinkedList. * @param {*} value * @time O(1) * @return {LinkedList} this instance. */ append(value) { const newNode = new ListNode_1.default(value); this.tail.next = newNode; this.tail = newNode; this.size++; return this; } /** * Prepends a new value to the head of the LinkedList. * @param {*} value * @time O(1) * @return {LinkedList} this instance. */ prepend(value) { const newNode = new ListNode_1.default(value); newNode.next = this.head; this.head = newNode; this.size++; return this; } /** * Maps the values to an array, `head.value` is at the 0th index and the `tail.value` is at the ultimate index. * @time O(n) * @return {any[]} An array of node values. */ asArray() { const array = []; let currentNode = this.head; while (currentNode !== null) { array.push(currentNode.value); currentNode = currentNode.next; } return array; } /** * Inserts a value at a particular index * @time O(n) * @param {number} index * @param {any} value * @return {LinkedList} this instance. */ insert(index, value) { if (index >= this.size) { return this.append(value); } const newNode = new ListNode_1.default(value); const leader = this.traverseToIndex(index - 1); const holdingPointer = leader.next; leader.next = newNode; newNode.next = holdingPointer; this.size++; return this; } /** * Removes a node at a particular index. * @param {number} index * @time O(n) * @return {LinkedList} this instance. */ remove(index) { const leader = this.traverseToIndex(index - 1); const unwantedNode = leader.next; leader.next = unwantedNode.next; this.size--; return this; } /** * Reverse a LinkedList in place. * @time O(n) * @return {LinkedList} this instance. */ reverse() { if (!this.head.next) { return this; } let first = this.head; this.tail = this.head; let second = first.next; while (second) { const temp = second.next; second.next = first; first = second; second = temp; } this.head.next = null; this.head = first; return this; } /** * Traverses to a node at a particular index. * @time O(n) * @param {number} index * @return {LinkedNode} List Node is returned */ traverseToIndex(index) { let counter = 0; let currentNode = this.head; while (counter !== index) { currentNode = currentNode.next; counter++; } return currentNode; } } exports.default = LinkedList; //# sourceMappingURL=LinkedList.js.map
import React from "react"; import { Layout, LayoutColumn, Text } from "@kiwicom/orbit-components"; import defaultTheme from "@kiwicom/orbit-components/lib/defaultTheme"; export default { Example: () => { const divStyle: React.CSSProperties = { minHeight: `${defaultTheme.orbit.heightIllustrationMedium}`, background: `${defaultTheme.orbit.backgroundBody}`, }; return ( <Layout type="Booking"> <LayoutColumn> <div style={divStyle}> <Text>This column is designed for the main content.</Text> </div> </LayoutColumn> <LayoutColumn> <div style={divStyle}> <Text> This column is designed for summaries. It appears on the right on <code>tablet</code>{" "} and wider screens. On <code>largeMobile</code> and smaller screens, it appears below the first column. </Text> </div> </LayoutColumn> </Layout> ); }, };
import * as fs from 'fs'; import { Option } from 'funfix'; import * as path from 'path'; import { IStoreReader, IStoreWriter } from './types'; /** * This File: * * Contains the class `FileStore` - An implementation that uses the file system. * * This demonstrates the "Interface Segregation Principle" which is the "I" in * SOLID. Note that we could easily define an `IStore` interface in `types.ts` * which would extend both `IStoreReader` and `IStoreWriter` - but this would be * premature as this would constrain the way the `FileStore` class could be * used too early. This constraint is part of `index.ts` which does indeed * define this interface `IStore` for convenience. */ export class FileStore implements IStoreReader, IStoreWriter { public cwd: string = ''; constructor(cwd: string) { this.cwd = cwd; } private get workingDirectory(): string { return this.cwd; } public read(id: number): Option<string> { const file = path.join(this.workingDirectory, id + '.txt'); let value: Option<string>; try { value = Option.of(fs.readFileSync(file).toString()); } catch (error) { // how do we communicate this error? value = Option.none(); } return value; } public save(id: number, message: string): void { const file = path.join(this.workingDirectory, id + '.txt'); fs.writeFileSync(file, message); } }
<?php $username = filter_input(INPUT_POST, 'username'); $password = filter_input(INPUT_POST, 'password'); if(!empty($username)){ if(!empty($password)){ $host = "hsc-ctsc-development:3306"; $dbusername = "dbuser"; $dbpassword = "CTSC_2019"; $dbname = "PubmedDailyUpdate"; //Create connection $conn = new mysqli($host, $dbusername, $dbpassword, $dbname); if(mysqli_connect_error()){ die('Connect Error ('.mysqli_connect_errno().') '.mysqli_connect_error()); } else{ $sql = "INSERT INTO account(username, password) values('$username','$password')"; if($conn->query($sql)){ echo "New record is inserted successfully"; } else{ echo "Error: ". $sql ."<br>". $conn->error; } $conn->close(); } } else{ echo "Password should not be empty"; die(); } } else{ echo "Username should not be empty"; die(); } ?>
--- layout: archive title: "Documents" permalink: /documents/ author_profile: true --- {% include base_path %} Github Repositories ====== * Control of One-Dof Arm with Gazebo and ROS <u><a href="https://oguzhankose.github.io/one-dof-arm/">[ Documentation ]</a>.</u> * A docker container for PX4 SITL Simulator for Multiple Vehicles <u><a href="https://oguzhankose.github.io/px4-multi-sitl/">[ Documentation ]</a>.</u>
# Interactive_UI ## Introduction Tips and tricks on making reproducible Shiny apps. ## Run App Yourself Run the following lines of code in `R`. ```R # install necessary packages install.packages( c( "shiny" # Web Application Framework for R , "shinydashboard" # Create Dashboards with 'Shiny' , "leaflet" # Create Interactive Web Maps with the JavaScript 'Leaflet' Library , "htmltools" # Tools for HTML , "htmlwidgets" # HTML Widgets for R , "webshot" # Take a screenshot of a URL , "dplyr" # A Grammar of Data Manipulation , "magrittr" # Ceci n'est pas une pipe , "DT" # A Wrapper of the JavaScript Library 'DataTables' , "mapview" # Interactive Viewing of Spatial Data in R ) ) # load necessary packages library( shiny ) # call Shiny app from GitHub shiny::runUrl( url = "https://github.com/cenuno/shiny/archive/master.zip" , subdir = "Interactive_UI/Dynamic_Pizza/app.R" ) ## end of script ## ``` ## Session Info RStudio version [‘1.1.383’](https://www.rstudio.com/products/rstudio/release-notes/). ``` R version 3.4.2 (2017-09-28) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: macOS Sierra 10.12.6 Matrix products: default BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib locale: [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8 attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] mapview_2.2.0 DT_0.2 magrittr_1.5 dplyr_0.7.4 [5] htmlwidgets_0.9 htmltools_0.3.6 leaflet_1.1.0 shinydashboard_0.6.1 [9] shiny_1.0.5 loaded via a namespace (and not attached): [1] sf_0.5-5 lattice_0.20-35 colorspace_1.3-2 stats4_3.4.2 viridisLite_0.2.0 [6] yaml_2.1.14 base64enc_0.1-3 rlang_0.1.4 R.oo_1.21.0 e1071_1.6-8 [11] glue_1.2.0 DBI_0.7 R.utils_2.6.0 sp_1.2-5 bindrcpp_0.2 [16] foreach_1.4.3 bindr_0.1 plyr_1.8.4 munsell_0.4.3 raster_2.5-8 [21] R.methodsS3_1.7.1 codetools_0.2-15 httpuv_1.3.5 crosstalk_1.0.0 gdalUtils_2.0.1.7 [26] class_7.3-14 markdown_0.8 Rcpp_0.12.13 xtable_1.8-2 udunits2_0.13 [31] scales_0.5.0 classInt_0.1-24 satellite_1.0.1 webshot_0.4.2 jsonlite_1.5 [36] mime_0.5 png_0.1-7 digest_0.6.12 grid_3.4.2 rgdal_1.2-15 [41] tools_3.4.2 tibble_1.3.4 pkgconfig_2.0.1 rsconnect_0.8.5 assertthat_0.2.0 [46] iterators_1.0.8 R6_2.2.2 units_0.4-6 compiler_3.4.2 ```
const int bigp=8388067; ULL hash[10000007]; int hash2[10000007]; void pushhash(ULL s) { int e=s&bigp; while ((hash[e]!=0)&&(hash[e]!=s)) ++e; if (hash[e]==0) hash[e]=s,hash2[e]=1; else hash2[e]++; } int findhash(ULL s) { int e=s&bigp; while ((hash[e]!=0)&&(hash[e]!=s)) ++e; if (hash[e]==0) return 0; else return hash2[e]; }
# frozen_string_literal: true class AddGroupColumnToEvents < ActiveRecord::Migration[5.2] DOWNTIME = false def change add_reference :events, :group, index: true, foreign_key: { to_table: :namespaces, on_delete: :cascade } end end