language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
496
2.640625
3
[]
no_license
//////////////////////////////////////////////// // FUNCION DE SETEO DE DATOS EN LOCAL STORAGE // //////////////////////////////////////////////// function setLocalStorage (key, list) { var gettedData = localStorage.getItem(key) var parsedData = JSON.parse(gettedData) if (parsedData == null) { parsedData = [] } parsedData.push(list) var strList = JSON.stringify(parsedData) localStorage.setItem(key, strList) } export default setLocalStorage
PHP
UTF-8
4,876
2.78125
3
[]
no_license
<?php class Inspecciones{ public $IS_lector; public $IS_sector; public $IS_Hruta; public $IS_secuencia; public $IS_descri; public $IS_fecha; public $IS_fechaO; public $IS_grupo; public $id; public function __construct($_IS_lector=NULL, $_IS_sector=NULL, $_IS_Hruta=NULL, $_IS_secuencia=NULL, $_IS_descri=NULL, $_IS_fecha=NULL, $_IS_fechaO=NULL, $_IS_grupo=NULL, $_id=NULL ){ $this->islector = $_IS_lector; $this->issector = $_IS_sector; $this->isruta = $_IS_Hruta; $this->issecuencia = $_IS_secuencia; $this->isdecri = $_IS_descri; $this->isfecha = $_IS_fecha; $this->isfechaO = $_IS_fechaO; $this->isgrupo = $_IS_grupo; $this->id = $_id; } public function add(){ $pdo= new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO inspecciones VALUES (:islect, :issector, :isruta, :issec, :isdec, :fecha, :fechaO, :isgrupo, :id)"; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(array( ":islect" => $this->islector, ":issector"=> $this->issector, ":isruta" => $this->isruta, ":issec" => $this->issecuencia, ":isdec" => $this->isdecri, ":fecha" => $this->isfecha, ":fechaO" => $this->isfechaO, ":isgrupo" => $this->isgrupo, ":id" => $this->id ) ); return $sth->rowCount(); } public function update(){ $pdo= new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "UPDATE inspecciones SET in_codigo_lector=:islect, in_sector=:issector, in_ruta=:isruta, in_secuencia=:issec, in_descripcion=:isdec, in_fechaOrigen=:fecha, in_fecha=:fechaO, in_grupo=:isgrupo WHERE idINSP=$this->id"; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(array( ":islect" => $this->islector, ":issector"=> $this->issector, ":isruta" => $this->isruta, ":issec" => $this->issecuencia, ":isdec" => $this->isdecri, ":fecha" => $this->isfecha, ":fechaO" => $this->isfechaO, ":isgrupo" => $this->isgrupo ) ); return $sth->rowCount(); } public function delete() { $pdo = new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "DELETE FROM inspecciones WHERE idINSP=:islect"; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(array(":islect"=>$this->islector)); return $sth->rowCount(); } public function getcon() { $pdo = new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "select nombre, in_grupo, id_sector, n_ruta, in_secuencia, in_descripcion, in_fechaOrigen, idINSP from inspecciones, sector,ruta, lectorAvisador where id=in_sector and Rid=in_ruta and codiglector=in_codigo_lector; "; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(); $rows = $sth->fetchAll(PDO::FETCH_CLASS); return $rows; } public function getbuscar() { $pdo = new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT nombre, in_grupo, id_sector, n_ruta, in_secuencia, in_descripcion, in_fechaOrigen, idINSP from inspecciones, sector,ruta, lectorAvisador where id=in_sector and Rid=in_ruta and codiglector=in_codigo_lector AND in_fechaOrigen like '%$this->islector%' ; "; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(); $rows = $sth->fetchAll(PDO::FETCH_CLASS); return $rows; } public function getcondiario() { $mesactual = date('y-m-d'); $pdo = new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT nombre, in_grupo, id_sector, n_ruta, in_secuencia, in_descripcion, in_fechaOrigen, idINSP, id_grupo, codiglector,id,Rid from grupo, inspecciones, sector,ruta, lectorAvisador where id_grupo=in_grupo and in_fechaOrigen='$mesactual' and id=in_sector and Rid=in_ruta and codiglector=in_codigo_lector AND in_fechaOrigen='$mesactual' ; "; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(); $rows = $sth->fetchAll(PDO::FETCH_CLASS); return $rows; } public function getcondiario2() { $pdo = new coneccion(); $pdo->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * from grupo, inspecciones, sector,ruta, lectorAvisador where id_grupo=in_grupo and id=in_sector and Rid=in_ruta and codiglector=in_codigo_lector and codiglector like '%$this->islector%' order by in_fechaOrigen desc ; "; $sth = $pdo->db->prepare($sql); $sth->setFetchMode(PDO::FETCH_CLASS, "inspecciones"); $sth->execute(); $rows = $sth->fetchAll(PDO::FETCH_CLASS); return $rows; } } ?>
Python
UTF-8
2,938
2.546875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/python # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for the prefix utilities.""" import pytest import hypothesis.strategies as st from hypothesis import given import uv.util.attachment as a @given(st.dictionaries(st.text(min_size=1), st.integers())) def test_by_prefix(m): wrapped = a.by_prefix({"test": m, "train": m}) for k, vs in m.items(): assert wrapped.get(a.attach_s(k, "test")) == vs assert wrapped.get(a.attach_s(k, "train")) == vs assert wrapped.get(a.attach_s(k, "random")) is None @given(st.dictionaries(st.text(min_size=1), st.integers())) def test_by_suffix(m): wrapped = a.by_suffix({"test": m, "train": m}) for k, vs in m.items(): assert wrapped.get(a.attach_s(k, "test", prefix=False)) == vs assert wrapped.get(a.attach_s(k, "train", prefix=False)) == vs assert wrapped.get(a.attach_s(k, "random", prefix=False)) is None @given(st.dictionaries(st.text(min_size=1), st.integers())) def test_flatten_flat(m): # Tests that flattening does not affect dictionaries which are already flat flattened = a.flatten(m) assert flattened == m @given( st.dictionaries(st.text(min_size=1), st.dictionaries(st.text(min_size=1), st.integers()))) def test_flatten_idempotence(m): # Tests that flattening a dictionary twice does the same thing as # flattening it once, i.e. the flattening operation is idempotent assert a.flatten(m) == a.flatten(a.flatten(m)) @given( st.dictionaries(st.text(min_size=1), st.dictionaries(st.text(min_size=1), st.integers()))) def test_flatten_notflat(m): # Tests that flattening properly handles dictionaries which are not flat flattened = a.flatten(m) for k, vs in m.items(): for v_k, v_vs in vs.items(): assert flattened[k + '.' + v_k] == v_vs @given( st.dictionaries(st.text(min_size=1), st.dictionaries(st.text(min_size=1), st.integers(), min_size=1), min_size=1)) def test_flatten_error(m): # Tests that flattening returns an error when it is given dictionaries # which would have a key collision after flattening k = list(m.keys())[0] k_1 = list(m[k].keys())[0] collision_key = k + '.' + k_1 m.update({collision_key: "ANYTHING"}) with pytest.raises(ValueError): flattened = a.flatten(m)
Shell
UTF-8
1,018
2.671875
3
[]
no_license
# Maintainer: carstene1ns <arch carsten-teibes de> - http://git.io/ctPKG # Contributor: Sam S. <smls75@gmail.com> # Contributor: Daniel Scharrer <daniel@constexpr.org> pkgname=innoextract pkgver=1.6 pkgrel=1 pkgdesc="A tool to extract installers created by Inno Setup" url='http://constexpr.org/innoextract/' arch=('i686' 'x86_64') license=('ZLIB') depends=('boost-libs' 'xz') makedepends=('boost' 'cmake') source=("http://constexpr.org/innoextract/files/$pkgname-$pkgver.tar.gz"{,.sig}) sha256sums=('66463f145fffd4d5883c6b3e2f7b2c2837d6f07095810114e514233a88c1033e' 'SKIP') validpgpkeys=("ADE9653703D4ADE0E997758128555A66D7E1DEC9") # Daniel Scharrer build() { cd $pkgname-$pkgver cmake . -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release make } package() { cd $pkgname-$pkgver make DESTDIR="$pkgdir/" install install -Dm644 README.md "$pkgdir"/usr/share/doc/$pkgname/README.md install -m644 CHANGELOG "$pkgdir"/usr/share/doc/$pkgname/CHANGELOG install -Dm644 LICENSE "$pkgdir"/usr/share/licenses/$pkgname/LICENSE }
Ruby
UTF-8
3,162
2.96875
3
[]
no_license
# -*- coding: utf-8 -*- require "psbot/open_ended_queue" module PSBot # Manages all outgoing messages, applying rate throttling # and fair distribution. # # @api private class MessageQueue def initialize(socket, bot) @socket = socket @queues = {:private => OpenEndedQueue.new, :generic => OpenEndedQueue.new} @queues_to_process = Queue.new @queued_queues = Set.new @mutex = Mutex.new @time_since_last_send = nil @bot = bot @log = [] end # @return [String] def inspect "#<MessageQueue @queues=#{@queues} @queues_to_process=#{@queues_to_process} @queued_queues=#{@queued_queues} @time_since_last_send=#{@time_since_last_send}>" end # Add messages that will be sent and displayed to the queue. # Outgoing messages are formatted as follows. Note that pms are # sent in the form of messages with the /pm command. # # [ROOM]|[REST] # # There are two ways to send messages, in a room and via pm. # # techcode|how do i code lol?? # |/pm scotteh, party animal # # @param message [String] The raw message being sent to the socket. # @return [void] def queue(message) room, *rest = message.split("|") command = nil if rest[0] == "/" && rest[1] != "/" command, *params = rest.split(" ") end queue = nil case command when "/pm" @mutex.synchronize do queue = @queues[:private] end else queue = @queues[:generic] end queue << message @mutex.synchronize do unless @queued_queues.include?(queue) @queued_queues << queue @queues_to_process << queue end end end # @return [void] def process! while true wait queue = @queues_to_process.pop message = queue.pop.to_s.chomp if queue.empty? @mutex.synchronize do @queued_queues.delete(queue) end else @queues_to_process << queue end begin to_send = PSBot::Utilities::Encoding.encode_outgoing(message, @bot.config.encoding) @socket.send to_send @log << Time.now @bot.loggers.outgoing(message) @time_since_last_send = Time.now rescue IOError @bot.loggers.error "Could not send message (connectivity problems): #{message}" end end end private def wait mps = @bot.config.messages_per_second max_queue_size = @bot.config.server_queue_size if @log.size > 1 time_passed = 0 @log.each_with_index do |one, index| second = @log[index+1] time_passed += second - one break if index == @log.size - 2 end messages_processed = (time_passed * mps).floor effective_size = @log.size - messages_processed if effective_size <= 0 @log.clear elsif effective_size >= max_queue_size sleep 1.0/mps end end end end end
C#
UTF-8
1,776
2.515625
3
[]
no_license
using MySql.Data.Entity; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Linq; using System.Web; using InvestingMVC.Models; namespace InvestingMVC { [DbConfigurationType(typeof(MySqlEFConfiguration))] public class MySqlContext : DbContext { // DbSets.... public DbSet<TranType> types { get; set; } public DbSet<InvestingTax> records { get; set; } public MySqlContext() : base(@"MyInvesting") { this.Configuration.LazyLoadingEnabled = false; // Database.SetInitializer<MySqlContext>(); } public MySqlContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } public static MySqlContext GetMySqlContext() { return null; } public void GetAllData() { types.Load(); } public void InsertNewRec(InvestingTax rec) { records.Add(rec); } public void InsertData() { types.Add(new TranType {name = @"Cash Transfer" }); types.Add(new TranType {name = @"Cash 3" }); this.SaveChanges(); } //public void Update(Int32 id, Car ent) //{ // // cars.Load(); // Car tmp = this.cars.SingleOrDefault(a => a.id == id); // if (tmp != null) // { // ent.id = id; // tmp = ent; //} public System.Data.DataTable GetAllRecords() { Console.WriteLine(this.Database.Connection); return null; } } }
Java
UTF-8
30,285
2.375
2
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * #%L * Parsington: the SciJava mathematical expression parser. * %% * Copyright (C) 2015 - 2023 Board of Regents of the University of * Wisconsin-Madison. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package org.scijava.parsington.eval; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.scijava.parsington.AbstractTest; import org.scijava.parsington.Operators; import org.scijava.parsington.SyntaxTree; import org.scijava.parsington.Variable; /** Abstract base class for testing {@link StandardEvaluator} implementations. */ public abstract class AbstractStandardEvaluatorTest extends AbstractTest { protected StandardEvaluator e; @BeforeEach public void setUp() { e = createEvaluator(); } public abstract StandardEvaluator createEvaluator(); /** Tests {@link Evaluator#evaluate(String)}. */ @Test public void testEvaluate() { assertEquals(26, e.evaluate("(2*3)+(4*5)")); } /** Tests strict mode; see {@link Evaluator#setStrict(boolean)}. */ @Test public void testStrict() { assertThrows(IllegalArgumentException.class, () -> e.evaluate("foo=bar")); } /** Tests non-strict mode; see {@link Evaluator#setStrict(boolean)}. */ @Test public void testNonStrict() { e.setStrict(false); e.evaluate("foo=bar"); final Object bar = e.get(new Variable("foo")); assertTrue(bar instanceof Unresolved); assertEquals("bar", ((Unresolved) bar).getToken()); } /** * Tests that {@link Evaluator#evaluate(String)} handles the built-in * {@code postfix} and {@code tree} functions as expected. */ @Test public void testBuiltIns() { final Object[] o = {1, 2, 3, Operators.MUL, Operators.ADD}; final List<Object> postfix = Arrays.asList(o); assertEquals(postfix, e.evaluate("postfix('1+2*3')")); final SyntaxTree tree = new SyntaxTree(new LinkedList<>(postfix)); assertEquals(tree, e.evaluate("tree('1+2*3')")); } // -- function -- /** Tests {@link StandardEvaluator#function(Object, Object)}. */ @Test public void testFunction() { // test list access final Variable v = new Variable("v"); e.set(v, Arrays.asList("a", "b", "c")); assertEquals("a", e.function(v, Arrays.asList(0))); assertEquals("b", e.function(v, Arrays.asList(1))); assertEquals("c", e.function(v, Arrays.asList(2))); assertNull(e.function(o(0), o(1))); } // -- dot -- /** Tests {@link StandardEvaluator#dot(Object, Object)}. */ @Test public void testDot() { assertNull(e.dot(o(0), o(1))); } // -- groups -- /** Tests {@link StandardEvaluator#parens(Object[])}. */ @Test public void testParens() { final Object[] o = {1, 2, 3}; assertEquals(Arrays.asList(o), e.parens(o)); // test empty parentheses assertEquals(Collections.emptyList(), e.parens()); // test collapse of single elements assertEquals(4, e.parens(4)); } /** Tests {@link StandardEvaluator#brackets(Object[])}. */ @Test public void testBrackets() { final Object[] o = {1, 2, 3}; assertEquals(Arrays.asList(o), e.brackets(o)); // test empty brackets assertEquals(Collections.emptyList(), e.brackets()); } /** Tests {@link StandardEvaluator#braces(Object[])}. */ @Test public void testBraces() { final Object[] o = {1, 2, 3}; assertEquals(Arrays.asList(o), e.braces(o)); // test empty braces assertEquals(Collections.emptyList(), e.braces()); } // -- transpose, power -- /** Tests {@link StandardEvaluator#transpose(Object)}. */ @Test public void testTranspose() { assertNull(e.transpose(o(0))); } /** Tests {@link StandardEvaluator#dotTranspose(Object)}. */ @Test public void testDotTranspose() { assertNull(e.dotTranspose(o(0))); } /** Tests {@link StandardEvaluator#pow(Object, Object)}. */ @Test public void testPow() { assertNumber(15.625d, e.pow(o(2.5d), o(3d))); assertNumber(bi(15625), e.pow(o(bi(5)), o(6))); assertNumber(bd(15.625), e.pow(o(bd(2.5d)), o(3))); } /** Tests {@link StandardEvaluator#dotPow(Object, Object)}. */ @Test public void testDotPow() { assertNull(e.dotPow(o(0), o(0))); } // -- postfix -- /** Tests {@link StandardEvaluator#postInc(Object)}. */ @Test public void testPostInc() { final Variable v = new Variable("v"); e.set(v, 2); assertEquals(2, e.postInc(v)); assertEquals(3, e.get(v)); e.set(v, 4L); assertEquals(4L, e.postInc(v)); assertEquals(5L, e.get(v)); e.set(v, 6f); assertEquals(6f, e.postInc(v)); assertEquals(7f, e.get(v)); e.set(v, 8d); assertEquals(8d, e.postInc(v)); assertEquals(9d, e.get(v)); e.set(v, bi(10)); assertEquals(bi(10), e.postInc(v)); assertEquals(bi(11), e.get(v)); e.set(v, bd(12)); assertEquals(bd(12), e.postInc(v)); assertEquals(bd(13), e.get(v)); } /** Tests {@link StandardEvaluator#postDec(Object)}. */ @Test public void testPostDec() { final Variable v = new Variable("v"); e.set(v, 2); assertEquals(2, e.postDec(v)); assertEquals(1, e.get(v)); e.set(v, 4L); assertEquals(4L, e.postDec(v)); assertEquals(3L, e.get(v)); e.set(v, 6f); assertEquals(6f, e.postDec(v)); assertEquals(5f, e.get(v)); e.set(v, 8d); assertEquals(8d, e.postDec(v)); assertEquals(7d, e.get(v)); e.set(v, bi(10)); assertEquals(bi(10), e.postDec(v)); assertEquals(bi(9), e.get(v)); e.set(v, bd(12)); assertEquals(bd(12), e.postDec(v)); assertEquals(bd(11), e.get(v)); } // -- unary -- /** Tests {@link StandardEvaluator#preInc(Object)}. */ @Test public void testPreInc() { final Variable v = new Variable("v"); e.set(v, 2); assertEquals(3, e.preInc(v)); assertEquals(3, e.get(v)); e.set(v, 4L); assertEquals(5L, e.preInc(v)); assertEquals(5L, e.get(v)); e.set(v, 6f); assertEquals(7f, e.preInc(v)); assertEquals(7f, e.get(v)); e.set(v, 8d); assertEquals(9d, e.preInc(v)); assertEquals(9d, e.get(v)); e.set(v, bi(10)); assertEquals(bi(11), e.preInc(v)); assertEquals(bi(11), e.get(v)); e.set(v, bd(12)); assertEquals(bd(13), e.preInc(v)); assertEquals(bd(13), e.get(v)); } /** Tests {@link StandardEvaluator#preDec(Object)}. */ @Test public void testPreDec() { final Variable v = new Variable("v"); e.set(v, 2); assertEquals(1, e.preDec(v)); assertEquals(1, e.get(v)); e.set(v, 4L); assertEquals(3L, e.preDec(v)); assertEquals(3L, e.get(v)); e.set(v, 6f); assertEquals(5f, e.preDec(v)); assertEquals(5f, e.get(v)); e.set(v, 8d); assertEquals(7d, e.preDec(v)); assertEquals(7d, e.get(v)); e.set(v, bi(10)); assertEquals(bi(9), e.preDec(v)); assertEquals(bi(9), e.get(v)); e.set(v, bd(12)); assertEquals(bd(11), e.preDec(v)); assertEquals(bd(11), e.get(v)); } /** Tests {@link StandardEvaluator#pos(Object)}. */ @Test public void testPos() { assertNumber(7, e.pos(o(7))); assertNumber(7L, e.pos(o(7L))); assertNumber(7.8d, e.pos(o(7.8d))); assertNumber(7.8f, e.pos(o(7.8f))); assertSame(BigInteger.ZERO, e.pos(BigInteger.ZERO)); assertSame(BigInteger.ONE, e.pos(BigInteger.ONE)); assertSame(BigInteger.TEN, e.pos(BigInteger.TEN)); assertSame(BigDecimal.ZERO, e.pos(BigDecimal.ZERO)); assertSame(BigDecimal.ONE, e.pos(BigDecimal.ONE)); assertSame(BigDecimal.TEN, e.pos(BigDecimal.TEN)); } /** Tests {@link StandardEvaluator#neg(Object)}. */ @Test public void testNeg() { assertNumber(7, e.neg(o(-7))); assertNumber(7L, e.neg(o(-7L))); assertNumber(7.8f, e.neg(o(-7.8f))); assertNumber(7.8d, e.neg(o(-7.8d))); assertNumber(bi(7), e.neg(o(bi(-7)))); assertNumber(bd(7.8), e.neg(o(bd(-7.8)))); assertNumber(-7, e.neg(o(7))); assertNumber(-7L, e.neg(o(7L))); assertNumber(-7.8f, e.neg(o(7.8f))); assertNumber(-7.8d, e.neg(o(7.8d))); assertNumber(bi(-7), e.neg(o(bi(7)))); assertNumber(bd(-7.8), e.neg(o(bd(7.8)))); } /** Tests {@link StandardEvaluator#complement(Object)}. */ @Test public void testComplement() { assertNumber(0x35014541, e.complement(o(0xcafebabe))); assertNumber(0x2152350141104541L, e.complement(o(0xdeadcafebeefbabeL))); } /** Tests {@link StandardEvaluator#not(Object)}. */ @Test public void testNot() { assertSame(false, e.not(o(true))); assertSame(true, e.not(o(false))); } // -- multiplicative -- /** Tests {@link StandardEvaluator#mul(Object, Object)}. */ @Test public void testMul() { assertNumber(24, e.mul(o(4), o(6))); assertNumber(24L, e.mul(o(4L), o(6L))); assertNumber(8.75f, e.mul(o(2.5f), o(3.5f))); assertNumber(8.75d, e.mul(o(2.5d), o(3.5d))); assertNumber(bi(24), e.mul(o(bi(4)), o(bi(6)))); assertNumber(bd(8.75), e.mul(o(bd(2.5)), o(bd(3.5)))); } /** Tests {@link StandardEvaluator#div(Object, Object)}. */ @Test public void testDiv() { assertNumber(4, e.div(o(27), o(6))); assertNumber(4L, e.div(o(27L), o(6L))); assertNumber(2.5f, e.div(o(8.75f), o(3.5f))); assertNumber(2.5d, e.div(o(8.75d), o(3.5d))); assertNumber(bi(4), e.div(o(bi(27)), o(bi(6)))); assertNumber(bd(2.5), e.div(o(bd(8.75)), o(bd(3.5)))); } /** Tests {@link StandardEvaluator#mod(Object, Object)}. */ @Test public void testMod() { assertNumber(3, e.mod(o(27), o(6))); assertNumber(3L, e.mod(o(27L), o(6L))); assertNumber(1.75f, e.mod(o(8.75f), o(3.5f))); assertNumber(1.75d, e.mod(o(8.75d), o(3.5d))); assertNumber(bi(3), e.mod(o(bi(27)), o(bi(6)))); assertNumber(bd(1.75), e.mod(o(bd(8.75)), o(bd(3.5)))); } /** Tests {@link StandardEvaluator#rightDiv(Object, Object)}. */ @Test public void testRightDiv() { assertNull(e.rightDiv(o(0), o(0))); } /** Tests {@link StandardEvaluator#dotDiv(Object, Object)}. */ @Test public void testDotDiv() { assertNull(e.dotDiv(o(0), o(0))); } /** Tests {@link StandardEvaluator#dotRightDiv(Object, Object)}. */ @Test public void testDotRightDiv() { assertNull(e.dotRightDiv(o(0), o(0))); } // -- additive -- /** Tests {@link StandardEvaluator#add(Object, Object)}. */ @Test public void testAdd() { assertEquals("Hello, world", e.add(o("Hello,"), o(" world"))); assertNumber(10, e.add(o(4), o(6))); assertNumber(10L, e.add(o(4L), o(6L))); assertNumber(3.6f, e.add(o(1.5f), o(2.1f))); assertNumber(3.6d, e.add(o(1.5d), o(2.1d))); assertNumber(bi(10), e.add(o(bi(4)), o(bi(6)))); assertNumber(bd(3.6), e.add(o(bd(1.5)), o(bd(2.1)))); } /** Tests {@link StandardEvaluator#sub(Object, Object)}. */ @Test public void testSub() { assertNumber(4, e.sub(o(10), o(6))); assertNumber(4L, e.sub(o(10L), o(6L))); assertNumber(1.5f, e.sub(o(3.6f), o(2.1f))); assertNumber(1.5d, e.sub(o(3.6d), o(2.1d))); assertNumber(bi(4), e.sub(o(bi(10)), o(bi(6)))); assertNumber(bd(1.5), e.sub(o(bd(3.6)), o(bd(2.1)))); } // -- shift -- /** Tests {@link StandardEvaluator#leftShift(Object, Object)}. */ @Test public void testLeftShift() { assertNumber(0xafebabe0, e.leftShift(o(0xcafebabe), o(4))); assertNumber(0xdcafebeefbabe000L, e.leftShift(o(0xdeadcafebeefbabeL), o(12))); assertNumber(bi(7296), e.leftShift(o(bi(57)), o(7))); } /** Tests {@link StandardEvaluator#rightShift(Object, Object)}. */ @Test public void testRightShift() { assertNumber(0xfcafebab, e.rightShift(o(0xcafebabe), o(4))); assertNumber(0xfffdeadcafebeefbL, e.rightShift(o(0xdeadcafebeefbabeL), o(12))); assertNumber(bi(278), e.rightShift(o(bi(8920)), o(5))); } /** Tests {@link StandardEvaluator#unsignedRightShift(Object, Object)}. */ @Test public void testUnsignedRightShift() { assertNumber(0x0cafebab, e.unsignedRightShift(o(0xcafebabe), o(4))); assertNumber(0x000deadcafebeefbL, e.unsignedRightShift(o(0xdeadcafebeefbabeL), o(12))); } // -- relational -- /** Tests {@link StandardEvaluator#lessThan(Object, Object)}. */ @Test public void testLessThan() { assertSame(true, e.lessThan(o(false), o(true))); assertSame(false, e.lessThan(o(false), o(false))); assertSame(false, e.lessThan(o(true), o(false))); assertSame(true, e.lessThan(o("hello"), o("world"))); assertSame(false, e.lessThan(o("hello"), o("hello"))); assertSame(false, e.lessThan(o("young"), o("world"))); assertSame(true, e.lessThan(o(2), o(3))); assertSame(false, e.lessThan(o(2), o(2))); assertSame(false, e.lessThan(o(2), o(1))); assertSame(true, e.lessThan(o(5L), o(6L))); assertSame(false, e.lessThan(o(5L), o(5L))); assertSame(false, e.lessThan(o(5L), o(4L))); assertSame(true, e.lessThan(o(8f), o(9f))); assertSame(false, e.lessThan(o(8f), o(8f))); assertSame(false, e.lessThan(o(8f), o(7f))); assertSame(true, e.lessThan(o(11d), o(12d))); assertSame(false, e.lessThan(o(11d), o(11d))); assertSame(false, e.lessThan(o(11d), o(10d))); assertSame(true, e.lessThan(o(bi(14)), o(bi(15)))); assertSame(false, e.lessThan(o(bi(14)), o(bi(14)))); assertSame(false, e.lessThan(o(bi(14)), o(bi(13)))); assertSame(true, e.lessThan(o(bd(17)), o(bd(18)))); assertSame(false, e.lessThan(o(bd(17)), o(bd(17)))); assertSame(false, e.lessThan(o(bd(17)), o(bd(16)))); } /** Tests {@link StandardEvaluator#greaterThan(Object, Object)}. */ @Test public void testGreaterThan() { assertSame(false, e.greaterThan(o(false), o(true))); assertSame(false, e.greaterThan(o(false), o(false))); assertSame(true, e.greaterThan(o(true), o(false))); assertSame(false, e.greaterThan(o("hello"), o("world"))); assertSame(false, e.greaterThan(o("hello"), o("hello"))); assertSame(true, e.greaterThan(o("young"), o("world"))); assertSame(false, e.greaterThan(o(2), o(3))); assertSame(false, e.greaterThan(o(2), o(2))); assertSame(true, e.greaterThan(o(2), o(1))); assertSame(false, e.greaterThan(o(5L), o(6L))); assertSame(false, e.greaterThan(o(5L), o(5L))); assertSame(true, e.greaterThan(o(5L), o(4L))); assertSame(false, e.greaterThan(o(8f), o(9f))); assertSame(false, e.greaterThan(o(8f), o(8f))); assertSame(true, e.greaterThan(o(8f), o(7f))); assertSame(false, e.greaterThan(o(11d), o(12d))); assertSame(false, e.greaterThan(o(11d), o(11d))); assertSame(true, e.greaterThan(o(11d), o(10d))); assertSame(false, e.greaterThan(o(bi(14)), o(bi(15)))); assertSame(false, e.greaterThan(o(bi(14)), o(bi(14)))); assertSame(true, e.greaterThan(o(bi(14)), o(bi(13)))); assertSame(false, e.greaterThan(o(bd(17)), o(bd(18)))); assertSame(false, e.greaterThan(o(bd(17)), o(bd(17)))); assertSame(true, e.greaterThan(o(bd(17)), o(bd(16)))); } /** Tests {@link StandardEvaluator#lessThanOrEqual(Object, Object)}. */ @Test public void testLessThanOrEqual() { assertSame(true, e.lessThanOrEqual(o(false), o(true))); assertSame(true, e.lessThanOrEqual(o(false), o(false))); assertSame(false, e.lessThanOrEqual(o(true), o(false))); assertSame(true, e.lessThanOrEqual(o("hello"), o("world"))); assertSame(true, e.lessThanOrEqual(o("hello"), o("hello"))); assertSame(false, e.lessThanOrEqual(o("young"), o("world"))); assertSame(true, e.lessThanOrEqual(o(2), o(3))); assertSame(true, e.lessThanOrEqual(o(2), o(2))); assertSame(false, e.lessThanOrEqual(o(2), o(1))); assertSame(true, e.lessThanOrEqual(o(5L), o(6L))); assertSame(true, e.lessThanOrEqual(o(5L), o(5L))); assertSame(false, e.lessThanOrEqual(o(5L), o(4L))); assertSame(true, e.lessThanOrEqual(o(8f), o(9f))); assertSame(true, e.lessThanOrEqual(o(8f), o(8f))); assertSame(false, e.lessThanOrEqual(o(8f), o(7f))); assertSame(true, e.lessThanOrEqual(o(11d), o(12d))); assertSame(true, e.lessThanOrEqual(o(11d), o(11d))); assertSame(false, e.lessThanOrEqual(o(11d), o(10d))); assertSame(true, e.lessThanOrEqual(o(bi(14)), o(bi(15)))); assertSame(true, e.lessThanOrEqual(o(bi(14)), o(bi(14)))); assertSame(false, e.lessThanOrEqual(o(bi(14)), o(bi(13)))); assertSame(true, e.lessThanOrEqual(o(bd(17)), o(bd(18)))); assertSame(true, e.lessThanOrEqual(o(bd(17)), o(bd(17)))); assertSame(false, e.lessThanOrEqual(o(bd(17)), o(bd(16)))); } /** Tests {@link StandardEvaluator#greaterThanOrEqual(Object, Object)}. */ @Test public void testGreaterThanOrEqual() { assertSame(false, e.greaterThanOrEqual(o(false), o(true))); assertSame(true, e.greaterThanOrEqual(o(false), o(false))); assertSame(true, e.greaterThanOrEqual(o(true), o(false))); assertSame(false, e.greaterThanOrEqual(o("hello"), o("world"))); assertSame(true, e.greaterThanOrEqual(o("hello"), o("hello"))); assertSame(true, e.greaterThanOrEqual(o("young"), o("world"))); assertSame(false, e.greaterThanOrEqual(o(2), o(3))); assertSame(true, e.greaterThanOrEqual(o(2), o(2))); assertSame(true, e.greaterThanOrEqual(o(2), o(1))); assertSame(false, e.greaterThanOrEqual(o(5L), o(6L))); assertSame(true, e.greaterThanOrEqual(o(5L), o(5L))); assertSame(true, e.greaterThanOrEqual(o(5L), o(4L))); assertSame(false, e.greaterThanOrEqual(o(8f), o(9f))); assertSame(true, e.greaterThanOrEqual(o(8f), o(8f))); assertSame(true, e.greaterThanOrEqual(o(8f), o(7f))); assertSame(false, e.greaterThanOrEqual(o(11d), o(12d))); assertSame(true, e.greaterThanOrEqual(o(11d), o(11d))); assertSame(true, e.greaterThanOrEqual(o(11d), o(10d))); assertSame(false, e.greaterThanOrEqual(o(bi(14)), o(bi(15)))); assertSame(true, e.greaterThanOrEqual(o(bi(14)), o(bi(14)))); assertSame(true, e.greaterThanOrEqual(o(bi(14)), o(bi(13)))); assertSame(false, e.greaterThanOrEqual(o(bd(17)), o(bd(18)))); assertSame(true, e.greaterThanOrEqual(o(bd(17)), o(bd(17)))); assertSame(true, e.greaterThanOrEqual(o(bd(17)), o(bd(16)))); } /** Tests {@link StandardEvaluator#instanceOf(Object, Object)}. */ @Test public void testInstanceOf() { assertNull(e.instanceOf(o(0), o(0))); } // -- equality -- /** Tests {@link StandardEvaluator#equal(Object, Object)}. */ @Test public void testEqual() { assertSame(false, e.equal(o(false), o(true))); assertSame(true, e.equal(o(false), o(false))); assertSame(false, e.equal(o(true), o(false))); assertSame(false, e.equal(o("hello"), o("world"))); assertSame(true, e.equal(o("hello"), o("hello"))); assertSame(false, e.equal(o("young"), o("world"))); assertSame(false, e.equal(o(2), o(3))); assertSame(true, e.equal(o(2), o(2))); assertSame(false, e.equal(o(2), o(1))); assertSame(false, e.equal(o(5L), o(6L))); assertSame(true, e.equal(o(5L), o(5L))); assertSame(false, e.equal(o(5L), o(4L))); assertSame(false, e.equal(o(8f), o(9f))); assertSame(true, e.equal(o(8f), o(8f))); assertSame(false, e.equal(o(8f), o(7f))); assertSame(false, e.equal(o(11d), o(12d))); assertSame(true, e.equal(o(11d), o(11d))); assertSame(false, e.equal(o(11d), o(10d))); assertSame(false, e.equal(o(bi(14)), o(bi(15)))); assertSame(true, e.equal(o(bi(14)), o(bi(14)))); assertSame(false, e.equal(o(bi(14)), o(bi(13)))); assertSame(false, e.equal(o(bd(17)), o(bd(18)))); assertSame(true, e.equal(o(bd(17)), o(bd(17)))); assertSame(false, e.equal(o(bd(17)), o(bd(16)))); } /** Tests {@link StandardEvaluator#notEqual(Object, Object)}. */ @Test public void testNotEqual() { assertSame(true, e.notEqual(o(false), o(true))); assertSame(false, e.notEqual(o(false), o(false))); assertSame(true, e.notEqual(o(true), o(false))); assertSame(true, e.notEqual(o("hello"), o("world"))); assertSame(false, e.notEqual(o("hello"), o("hello"))); assertSame(true, e.notEqual(o("young"), o("world"))); assertSame(true, e.notEqual(o(2), o(3))); assertSame(false, e.notEqual(o(2), o(2))); assertSame(true, e.notEqual(o(2), o(1))); assertSame(true, e.notEqual(o(5L), o(6L))); assertSame(false, e.notEqual(o(5L), o(5L))); assertSame(true, e.notEqual(o(5L), o(4L))); assertSame(true, e.notEqual(o(8f), o(9f))); assertSame(false, e.notEqual(o(8f), o(8f))); assertSame(true, e.notEqual(o(8f), o(7f))); assertSame(true, e.notEqual(o(11d), o(12d))); assertSame(false, e.notEqual(o(11d), o(11d))); assertSame(true, e.notEqual(o(11d), o(10d))); assertSame(true, e.notEqual(o(bi(14)), o(bi(15)))); assertSame(false, e.notEqual(o(bi(14)), o(bi(14)))); assertSame(true, e.notEqual(o(bi(14)), o(bi(13)))); assertSame(true, e.notEqual(o(bd(17)), o(bd(18)))); assertSame(false, e.notEqual(o(bd(17)), o(bd(17)))); assertSame(true, e.notEqual(o(bd(17)), o(bd(16)))); } // -- bitwise -- /** Tests {@link StandardEvaluator#bitwiseAnd(Object, Object)}. */ @Test public void testBitwiseAnd() { assertNumber(0xcaacbaae, e.bitwiseAnd(o(0xcafebabe), o(0xdeadbeef))); assertNumber(0L, e.bitwiseAnd(o(0x0d0e0a0d0c0a0f0eL), o(0xb0e0e0f0b0a0b0e0L))); assertNumber(bi(0xcaacbaae), e.bitwiseAnd(o(bi(0xcafebabe)), o(bi(0xdeadbeef)))); } /** Tests {@link StandardEvaluator#bitwiseOr(Object, Object)}. */ @Test public void testBitwiseOr() { assertNumber(0xdeffbeff, e.bitwiseOr(o(0xcafebabe), o(0xdeadbeef))); assertNumber(0xbdeeeafdbcaabfeeL, e.bitwiseOr(o(0x0d0e0a0d0c0a0f0eL), o(0xb0e0e0f0b0a0b0e0L))); assertNumber(bi(0xdeffbeff), e.bitwiseOr(o(bi(0xcafebabe)), o(bi(0xdeadbeef)))); } // -- logical -- /** Tests {@link StandardEvaluator#logicalAnd(Object, Object)}. */ @Test public void testLogicalAnd() { assertSame(false, e.logicalAnd(o(false), o(false))); assertSame(false, e.logicalAnd(o(false), o(true))); assertSame(false, e.logicalAnd(o(true), o(false))); assertSame(true, e.logicalAnd(o(true), o(true))); } /** Tests {@link StandardEvaluator#logicalOr(Object, Object)}. */ @Test public void testLogicalOr() { assertSame(false, e.logicalOr(o(false), o(false))); assertSame(true, e.logicalOr(o(false), o(true))); assertSame(true, e.logicalOr(o(true), o(false))); assertSame(true, e.logicalOr(o(true), o(true))); } // -- ternary -- /** Tests {@link StandardEvaluator#question(Object, Object)}. */ @Test public void testQuestion() { assertNull(e.question(o(0), o(0))); } /** Tests {@link StandardEvaluator#colon(Object, Object)}. */ @Test public void testColon() { assertNull(e.colon(o(0), o(0))); } // -- assignment -- /** Tests {@link StandardEvaluator#assign(Object, Object)}. */ @Test public void testAssign() { final Variable v = new Variable("v"); assertAssigned(true, v, e.assign(v, true)); assertAssigned("hello", v, e.assign(v, "hello")); assertAssigned(1, v, e.assign(v, 1)); assertAssigned(2L, v, e.assign(v, 2L)); assertAssigned(3f, v, e.assign(v, 3f)); assertAssigned(4d, v, e.assign(v, 4d)); assertAssigned(bi(5), v, e.assign(v, bi(5))); assertAssigned(bd(6), v, e.assign(v, bd(6))); } /** Tests {@link StandardEvaluator#powAssign(Object, Object)}. */ @Test public void testPowAssign() { final Variable v = new Variable("v"); e.set(v, 2.5d); assertAssigned(15.625d, v, e.powAssign(v, 3)); e.set(v, bi(5)); assertAssigned(bi(15625), v, e.powAssign(v, 6)); e.set(v, bd(2.5)); assertAssigned(bd(15.625), v, e.powAssign(v, 3)); } /** Tests {@link StandardEvaluator#dotPowAssign(Object, Object)}. */ @Test public void testDotPowAssign() { // NB: Nothing to test; dotPow is unimplemented. } /** Tests {@link StandardEvaluator#mulAssign(Object, Object)}. */ @Test public void testMulAssign() { final Variable v = new Variable("v"); e.set(v, 4); assertAssigned(24, v, e.mulAssign(v, 6)); e.set(v, 4L); assertAssigned(24L, v, e.mulAssign(v, 6L)); e.set(v, 2.5f); assertAssigned(8.75f, v, e.mulAssign(v, 3.5f)); e.set(v, 2.5d); assertAssigned(8.75d, v, e.mulAssign(v, 3.5d)); e.set(v, bi(4)); assertAssigned(bi(24), v, e.mulAssign(v, bi(6))); e.set(v, bd(2.5)); assertAssigned(bd(8.75), v, e.mulAssign(v, bd(3.5))); } /** Tests {@link StandardEvaluator#divAssign(Object, Object)}. */ @Test public void testDivAssign() { final Variable v = new Variable("v"); e.set(v, 27); assertAssigned(4, v, e.divAssign(v, 6)); e.set(v, 27L); assertAssigned(4L, v, e.divAssign(v, 6L)); e.set(v, 8.75f); assertAssigned(2.5f, v, e.divAssign(v, 3.5f)); e.set(v, 8.75d); assertAssigned(2.5d, v, e.divAssign(v, 3.5d)); e.set(v, bi(27)); assertAssigned(bi(4), v, e.divAssign(v, bi(6))); e.set(v, bd(8.75)); assertAssigned(bd(2.5), v, e.divAssign(v, bd(3.5))); } /** Tests {@link StandardEvaluator#modAssign(Object, Object)}. */ @Test public void testModAssign() { final Variable v = new Variable("v"); e.set(v, 27); assertAssigned(3, v, e.modAssign(v, 6)); e.set(v, 27L); assertAssigned(3L, v, e.modAssign(v, 6L)); e.set(v, 8.75f); assertAssigned(1.75f, v, e.modAssign(v, 3.5f)); e.set(v, 8.75d); assertAssigned(1.75d, v, e.modAssign(v, 3.5d)); e.set(v, bi(27)); assertAssigned(bi(3), v, e.modAssign(v, bi(6))); e.set(v, bd(8.75)); assertAssigned(bd(1.75), v, e.modAssign(v, bd(3.5))); } /** Tests {@link StandardEvaluator#rightDivAssign(Object, Object)}. */ @Test public void testRightDivAssign() { // NB: Nothing to test; rightDiv is unimplemented. } /** Tests {@link StandardEvaluator#dotDivAssign(Object, Object)}. */ @Test public void testDotDivAssign() { // NB: Nothing to test; dotDiv is unimplemented. } /** Tests {@link StandardEvaluator#dotRightDivAssign(Object, Object)}. */ @Test public void testDotRightDivAssign() { // NB: Nothing to test; dotRightDiv is unimplemented. } /** Tests {@link StandardEvaluator#addAssign(Object, Object)}. */ @Test public void testAddAssign() { final Variable v = new Variable("v"); e.set(v, "Hello,"); assertAssigned("Hello, world", v, e.addAssign(v, " world")); e.set(v, 4); assertAssigned(10, v, e.addAssign(v, 6)); e.set(v, 4L); assertAssigned(10L, v, e.addAssign(v, 6L)); e.set(v, 1.5f); assertAssigned(3.6f, v, e.addAssign(v, 2.1f)); e.set(v, 1.5d); assertAssigned(3.6d, v, e.addAssign(v, 2.1d)); e.set(v, bi(4)); assertAssigned(bi(10), v, e.addAssign(v, bi(6))); e.set(v, bd(1.5)); assertAssigned(bd(3.6), v, e.addAssign(v, bd(2.1))); } /** Tests {@link StandardEvaluator#subAssign(Object, Object)}. */ @Test public void testSubAssign() { final Variable v = new Variable("v"); e.set(v, 10); assertAssigned(4, v, e.subAssign(v, 6)); e.set(v, 10L); assertAssigned(4L, v, e.subAssign(v, 6L)); e.set(v, 3.6f); assertAssigned(1.5f, v, e.subAssign(v, 2.1f)); e.set(v, 3.6d); assertAssigned(1.5d, v, e.subAssign(v, 2.1d)); e.set(v, bi(10)); assertAssigned(bi(4), v, e.subAssign(v, bi(6))); e.set(v, bd(3.6)); assertAssigned(bd(1.5), v, e.subAssign(v, bd(2.1))); } /** Tests {@link StandardEvaluator#andAssign(Object, Object)}. */ @Test public void testAndAssign() { final Variable v = new Variable("v"); e.set(v, 0xcafebabe); assertAssigned(0xcaacbaae, v, e.andAssign(v, 0xdeadbeef)); e.set(v, 0x0d0e0a0d0c0a0f0eL); assertAssigned(0L, v, e.andAssign(v, 0xb0e0e0f0b0a0b0e0L)); e.set(v, bi(0xcafebabeL)); assertAssigned(bi(0xcaacbaaeL), v, e.andAssign(v, bi(0xdeadbeefL))); } /** Tests {@link StandardEvaluator#orAssign(Object, Object)}. */ @Test public void testOrAssign() { final Variable v = new Variable("v"); e.set(v, 0xcafebabe); assertAssigned(0xdeffbeff, v, e.orAssign(v, 0xdeadbeef)); e.set(v, 0x0d0e0a0d0c0a0f0eL); assertAssigned(0xbdeeeafdbcaabfeeL, v, e.orAssign(v, 0xb0e0e0f0b0a0b0e0L)); e.set(v, bi(0xcafebabeL)); assertAssigned(bi(0xdeffbeffL), v, e.orAssign(v, bi(0xdeadbeefL))); } /** Tests {@link StandardEvaluator#leftShiftAssign(Object, Object)}. */ @Test public void testLeftShiftAssign() { final Variable v = new Variable("v"); e.set(v, 0xcafebabe); assertAssigned(0xafebabe0, v, e.leftShiftAssign(v, 4)); e.set(v, 0xdeadcafebeefbabeL); assertAssigned(0xdcafebeefbabe000L, v, e.leftShiftAssign(v, 12)); e.set(v, bi(57)); assertAssigned(bi(7296), v, e.leftShiftAssign(v, 7)); } /** Tests {@link StandardEvaluator#rightShiftAssign(Object, Object)}. */ @Test public void testRightShiftAssign() { final Variable v = new Variable("v"); e.set(v, 0xcafebabe); assertAssigned(0xfcafebab, v, e.rightShiftAssign(v, 4)); e.set(v, 0xdeadcafebeefbabeL); assertAssigned(0xfffdeadcafebeefbL, v, e.rightShiftAssign(v, 12)); e.set(v, bi(8920)); assertAssigned(bi(278), v, e.rightShiftAssign(v, 5)); } /** Tests {@link StandardEvaluator#unsignedRightShiftAssign(Object, Object)}. */ @Test public void testUnsignedRightShiftAssign() { final Variable v = new Variable("v"); e.set(v, 0xcafebabe); assertAssigned(0x0cafebab, v, e.unsignedRightShiftAssign(v, 4)); e.set(v, 0xdeadcafebeefbabeL); assertAssigned(0x000deadcafebeefbL, v, e.unsignedRightShiftAssign(v, 12)); } // -- Helper methods -- /** Widens the given object to an {@link Object}. */ private Object o(final Object o) { return o; } private BigInteger bi(final Object o) { return new BigInteger(o.toString()); } private BigDecimal bd(final Object o) { return new BigDecimal(o.toString()); } private void assertAssigned(final Object expected, final Variable v, final Object result) { assertSame(v, result); assertEquals(expected, e.get(v)); } }
C
UTF-8
2,153
3.1875
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <math.h> #define XMAX 320 #define YMAX 200 #undef min #define min(a, b) ((a) < (b) ? (a) : (b)) #undef max #define max(a, b) ((a) > (b) ? (a) : (b)) struct point { int x; int y; }; struct rect { struct point pt1; struct point pt2; }; struct point pt = { 100, 100 }; struct point maxpt = { XMAX, YMAX }; struct rect screen; struct point middle; struct point makepoint(int, int); struct point addpoint(struct point, struct point); int ptinrect(struct point, struct rect); struct rect canonrect(struct rect r); int main() { printf("%d, %d\n", pt.x, pt.y); double dist; //sqrt(double); dist = sqrt((double)pt.x * pt.x + (double)pt.y * pt.y); printf("%g\n", dist); screen.pt1 = pt; screen.pt2 = maxpt; printf("%d\n", screen.pt1.x); screen.pt1 = makepoint(0, 0); screen.pt2 = makepoint(XMAX, YMAX); middle = makepoint((screen.pt1.x + screen.pt2.x) / 2, (screen.pt1.y + screen.pt2.y) / 2); printf("middle is (%d, %d)\n", middle.x, middle.y); struct point origin, *pp; origin = pt; pp = &origin; printf("origin is (%d, %d)\n", (*pp).x, (*pp).y); printf("origin is (%d, %d)\n", pp->x, pp->y); struct rect r, *rp = &r; r.pt1 = pt; r.pt2 = maxpt; printf("r.pt1.x is %d\n", r.pt1.x); printf("(r.pt1).x is %d\n", (r.pt1).x); printf("rp->pt1.x is %d\n", rp->pt1.x); printf("(rp->pt1).x is %d\n", (rp->pt1).x); struct Test { int len; char *str; } *p; p = (struct Test *)malloc(sizeof(struct Test)); p->len = 1; ++p->len; printf("++p->len is %d\n", p->len); getchar(); } struct point makepoint(int x, int y) { struct point temp; temp.x = x; temp.y = y; return temp; } struct point addpoint(struct point p1, struct point p2) { p1.x += p2.x; p1.y += p2.y; return p1; } int ptinrect(struct point p, struct rect r) { return p.x >= r.pt1.x && p.x < r.pt2.x && p.y >= r.pt2.y && p.y < r.pt2.y; } struct rect canonrect(struct rect r) { struct rect temp; temp.pt1.x = min(r.pt1.x, r.pt2.x); temp.pt1.y = min(r.pt1.y, r.pt2.y); temp.pt2.x = max(r.pt1.x, r.pt2.x); temp.pt2.y = max(r.pt1.y, r.pt2.y); return temp; }
Go
UTF-8
4,663
2.96875
3
[]
no_license
package runners import ( "fmt" "github.com/gokadin/ml-framework/telemetry" "strconv" "time" ) type metricEvents struct { trainingStarted chan bool trainingFinished chan bool epochStarted chan int epochFinished chan float32 batchStarted chan int batchFinished chan bool batchLoss chan float32 forwardStarted chan bool forwardFinished chan bool backwardStarted chan bool backwardFinished chan bool optimizerStarted chan bool optimizerFinished chan bool gameWon chan bool } func makeMetricEvents() metricEvents { return metricEvents{ trainingStarted: make(chan bool), trainingFinished: make(chan bool), epochStarted: make(chan int), epochFinished: make(chan float32), batchStarted: make(chan int), batchFinished: make(chan bool), batchLoss: make(chan float32), forwardStarted: make(chan bool), forwardFinished: make(chan bool), backwardStarted: make(chan bool), backwardFinished: make(chan bool), optimizerStarted: make(chan bool), optimizerFinished: make(chan bool), } } type metricTiming struct { timeMs int64 timeAveMs int64 iteration int } type metric struct { modelConfig *ModelConfig timings map[string]*metricTiming events metricEvents logger *telemetry.Logger } func newMetric(modelConfig *ModelConfig, logger *telemetry.Logger) *metric { m := &metric{ modelConfig: modelConfig, events: makeMetricEvents(), timings: make(map[string]*metricTiming), logger: logger, } m.timings["epoch"] = &metricTiming{} m.timings["batch"] = &metricTiming{} m.timings["forward"] = &metricTiming{} m.timings["backward"] = &metricTiming{} m.timings["optimizer"] = &metricTiming{} return m } func (m *metric) start() { go m.receiveEvents() } func (m *metric) receiveEvents() { for { select { case <-m.events.trainingStarted: m.logger.Info("training started") case <-m.events.trainingFinished: m.logger.Info("training finished") case epoch := <-m.events.epochStarted: m.timings["epoch"].iteration = epoch m.timings["epoch"].timeMs = time.Now().UnixNano() case epochLoss := <-m.events.epochFinished: epochTimeMs := (time.Now().UnixNano() - m.timings["epoch"].timeMs) / int64(time.Millisecond) batchTimeAveMs := m.timings["batch"].timeAveMs / (int64(m.timings["batch"].iteration) + 1) m.timings["batch"].timeAveMs = 0 forwardTimeAveMs := m.timings["forward"].timeAveMs / (int64(m.timings["forward"].iteration) + 1) m.timings["forward"].timeAveMs = 0 m.timings["forward"].iteration = 0 backwardTimeAveMs := m.timings["backward"].timeAveMs / (int64(m.timings["backward"].iteration) + 1) m.timings["backward"].timeAveMs = 0 m.timings["backward"].iteration = 0 optimizerTimeAveMs := m.timings["optimizer"].timeAveMs / (int64(m.timings["optimizer"].iteration) + 1) m.timings["optimizer"].timeAveMs = 0 m.timings["optimizer"].iteration = 0 m.logger.Info(fmt.Sprintf("epoch %d finished in %dms with loss %f", m.timings["epoch"].iteration, epochTimeMs, epochLoss)) m.logger.Info(fmt.Sprintf("ave batch: %dms ave forward: %dms ave backward: %dms ave optim %dms", batchTimeAveMs, forwardTimeAveMs, backwardTimeAveMs, optimizerTimeAveMs)) case batch := <-m.events.batchStarted: m.timings["batch"].iteration = batch m.timings["batch"].timeMs = time.Now().UnixNano() case <-m.events.batchFinished: batchTimeMs := (time.Now().UnixNano() - m.timings["batch"].timeMs) / int64(time.Millisecond) m.timings["batch"].timeAveMs += batchTimeMs case batchLoss := <-m.events.batchLoss: m.logger.Event("loss", strconv.FormatFloat(float64(batchLoss), 'f', -1, 32)) case <-m.events.forwardStarted: m.timings["forward"].iteration++ m.timings["forward"].timeMs = time.Now().UnixNano() case <-m.events.forwardFinished: forwardTimeMs := (time.Now().UnixNano() - m.timings["forward"].timeMs) / int64(time.Millisecond) m.timings["forward"].timeAveMs += forwardTimeMs case <-m.events.backwardStarted: m.timings["backward"].iteration++ m.timings["backward"].timeMs = time.Now().UnixNano() case <-m.events.backwardFinished: backwardTimeMs := (time.Now().UnixNano() - m.timings["backward"].timeMs) / int64(time.Millisecond) m.timings["backward"].timeAveMs += backwardTimeMs case <-m.events.optimizerStarted: m.timings["optimizer"].iteration++ m.timings["optimizer"].timeMs = time.Now().UnixNano() case <-m.events.optimizerFinished: forwardTimeMs := (time.Now().UnixNano() - m.timings["optimizer"].timeMs) / int64(time.Millisecond) m.timings["optimizer"].timeAveMs += forwardTimeMs } } }
Java
UTF-8
6,378
1.898438
2
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*L * Copyright Leidos * Copyright Leidos Biomedical * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cananolab/LICENSE.txt for details. */ package gov.nih.nci.cananolab.system.applicationservice.impl; import gov.nih.nci.cananolab.domain.particle.Sample; import gov.nih.nci.cananolab.dto.common.AccessibilityBean; import gov.nih.nci.cananolab.system.applicationservice.CaNanoLabApplicationService; import gov.nih.nci.cananolab.system.dao.orm.CaNanoLabORMDAO; import gov.nih.nci.cananolab.system.applicationservice.ApplicationException; import gov.nih.nci.cananolab.system.util.ClassCache; //import org.hibernate.type.StandardBasicTypes; import java.io.Serializable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.Hibernate; import org.springframework.aop.framework.Advised; /** * Customized to contain more CRUD operations. * * @author pansu * */ public class CaNanoLabApplicationServiceImpl extends WritableApplicationServiceImpl implements CaNanoLabApplicationService { private ClassCache classCache; private static Logger logger = LogManager.getLogger(CaNanoLabApplicationServiceImpl.class.getName()); public CaNanoLabApplicationServiceImpl(ClassCache classCache) { super(classCache); this.classCache = classCache; } public Object load(Class domainClass, Serializable id) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache.getDAOForClass(domainClass.getCanonicalName()); return dao.load(domainClass, id); } public Object get(Class domainClass, Serializable id) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache.getDAOForClass(domainClass.getCanonicalName()); return dao.get(domainClass, id); } public void saveOrUpdate(Object object) throws ApplicationException { try { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache.getDAOForClass(object.getClass().getCanonicalName()); dao.saveOrUpdate(object); } catch (Exception e) { e.printStackTrace(); String err = "Could not save or update for class " + object.getClass().getCanonicalName(); logger.error(err); throw new ApplicationException(err, e); } } public void delete(Object object) throws ApplicationException { try { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache .getDAOForClass(object.getClass().getCanonicalName()); dao.delete(object); } catch (Exception e) { String err = "Could not delete for class " + object.getClass().getCanonicalName(); logger.error(err); throw new ApplicationException(err, e); } } public void deleteById(Class domainClass, Serializable id) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache .getDAOForClass(domainClass.getCanonicalName()); try { dao.deleteById(domainClass, id); } catch (Exception e) { String err = "Could not delete by Id for class " + domainClass.getCanonicalName() + " with Id: " + id; logger.error(err); throw new ApplicationException(err, e); } } public List getAll(Class domainClass) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache .getDAOForClass(domainClass.getCanonicalName()); try { return dao.getAll(domainClass); } catch (Exception e) { String err = "Could not get all for class " + domainClass.getCanonicalName(); logger.error(err); throw new ApplicationException(err, e); } } public Object getObject(Class domainClass, String uniqueKeyName, Object uniqueKeyValue) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache .getDAOForClass(domainClass.getCanonicalName()); try { return dao.getObject(domainClass, uniqueKeyName, uniqueKeyValue); } catch (Exception e) { String err = "Could not get unique object for class " + domainClass.getCanonicalName(); logger.error(err); throw new ApplicationException(err, e); } } public List directSQL(String directSQL, String[] columns, Object[] columnTypes) throws ApplicationException { CaNanoLabORMDAO dao = (CaNanoLabORMDAO) classCache .getDAOForClass(Sample.class.getCanonicalName()); try { return dao.directSQL(directSQL, columns, columnTypes); } catch (Exception e) { String err = "Could not execute direct sql query "; logger.error(err); throw new ApplicationException(err, e); } } private Object unwrap(Object proxy) throws Exception { try { Object interceptor = null; int i = 0; while (true) { Field field = proxy.getClass().getDeclaredField( "CGLIB$CALLBACK_" + i); field.setAccessible(true); Object value = field.get(proxy); if (value.getClass().getName().contains("EqualsInterceptor")) { interceptor = value; break; } i++; } Field field = interceptor.getClass().getDeclaredField("advised"); field.setAccessible(true); Advised advised = (Advised) field.get(interceptor); return advised.getTargetSource().getTarget(); } catch (Exception e) { return proxy; } } /** * Return a list of data (csm protected_group_name) marked public in the * database * * @return * @throws Exception */ public List<String> getAllPublicData() throws ApplicationException { List<String> publicData = new ArrayList<String>(); try { String query = "select a.protection_group_name protection_group_name from csm_protection_group a, csm_role b, csm_user_group_role_pg c, csm_group d " + "where a.protection_group_id=c.protection_group_id and b.role_id=c.role_id and c.group_id=d.group_id and " + "d.group_name='" + AccessibilityBean.CSM_PUBLIC_GROUP + "' and b.role_name='" + AccessibilityBean.CSM_READ_ROLE + "'"; String[] columns = new String[] { "protection_group_name" }; Object[] columnTypes = new Object[] { Hibernate.STRING }; List results = directSQL(query, columns, columnTypes); for (int i = 0; i < results.size(); i++) { if (results.get(i) != null) { publicData.add(((String) results.get(i))); } } } catch (Exception e) { String err = "Could not execute direct sql query to find all public data"; logger.error(err); throw new ApplicationException(err, e); } return publicData; } }
Python
UTF-8
2,417
2.65625
3
[]
no_license
import requests, json from lxml import etree from utils import get_headers_cookies # pip install requests[socks] -U proxies = { 'http': 'socks5://127.0.0.1:1080', 'https': 'socks5://127.0.0.1:1080' } proxies = None def get_all_after_2016(years = ['2017', '2018', '2019'], write_to_json = False): # only for 2017 2018 2019 org = 'KDD' res_dict = {} for year in years: start_url = f'https://www.kdd.org/kdd{year}/accepted-papers' names_list = [] urls_list_1 = [] urls_list_2 = [] urls_list_3 = [] headers_1, cookies_1 = get_headers_cookies(org, which = 1) headers_2, cookies_2 = get_headers_cookies(org, which = 2) with requests.Session() as s: response1 = s.get(start_url, headers = headers_1, cookies = cookies_1, proxies=proxies) x_path = '//a[contains(@href, "/papers/view/")]' if year == '2017' else '//div[@class="media-body"]/span/a' for item in etree.HTML(response1.text).xpath(x_path): names_list.append(item.xpath('string(.)')) urls_list_1.append(item.xpath('@href')[0]) print(len(urls_list_1)) for url in urls_list_1: response2 = s.get(url, headers = headers_1, cookies = cookies_1, proxies=proxies) href = etree.HTML(response2.text).xpath('//a[contains(@href,"authorize")]/@href')[0] urls_list_2.append(href) print(len(urls_list_2)) for url in urls_list_2: response3 = s.get(url, headers = headers_2, cookies = cookies_2, proxies=proxies, allow_redirects=True) code1 = response3.url.split('/')[-2] code2 = response3.url.split('/')[-1] pdf_download_url = f'https://dl.acm.org/doi/pdf/{code1}/{code2}?download=true' urls_list_3.append(pdf_download_url) print(len(urls_list_3)) org_year = f'{org}_{year}' res_dict[org_year] = {} for name,url in zip(names_list,urls_list_3): res_dict[org_year][name] = url if not write_to_json: return res_dict temp = '_'.join(years) file_name = f'{org}_{temp}.json' with open(file_name, 'w', encoding='utf8') as f: json.dump(res_dict, f) print(f'DONE! write to: {file_name}') if __name__ == "__main__": get_all_after_2016(write_to_json=True)
Java
UTF-8
1,125
2.203125
2
[]
no_license
package com.android.andi.mytrip.Fragments; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.android.andi.mytrip.R; import com.android.andi.mytrip.models.Business; public class BusinessListFragment extends Fragment { public static BusinessListFragment newInstance() { BusinessListFragment fragment = new BusinessListFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_business_list, container, false); } public interface OnListFragmentInteractionListener { // TODO: Update argument type and name void onListFragmentInteraction(Business item); } }
Markdown
UTF-8
1,326
2.796875
3
[]
no_license
--- title: tmp_Android_get_ip abbrlink: 16faf7d3 tags: --- Get IP address === ``` /** * Get IP address from first non-localhost interface * @param useIPv4 true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port suffix return delim<0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception e) { e.printStackTrace(); return "0.0.0.0"; } return "0.0.0.0"; } ```
Python
UTF-8
899
2.78125
3
[ "MIT" ]
permissive
from planner.frame.figure import Figure from svgwrite import shapes class Rect(Figure): """ Rectangle representation """ def __init__(self, x=0, y=0, width=1, height=1, **attribs): """ x, y - coordinates of left top corner """ self.corner = (x, y) self.size = (width, height) self.attribs = attribs def _draw(self): res = [] rect_params = self.attribs.copy() if hasattr(self, "hatch") and self.hatch: rect_params['style'] = "fill: url(#{})".format(self._hatching_id) res.append(self.hatch) if hasattr(self, "filling"): rect_params['fill'] = self.filling else: if 'fill' not in self.attribs: rect_params['fill'] = "#fff" rect = shapes.Rect(self.corner, self.size, **rect_params) res.append(rect) return res
Java
UTF-8
303
2.171875
2
[ "MIT" ]
permissive
package nl.eernie.jmoribus; import nl.eernie.jmoribus.annotation.Given; import nl.eernie.jmoribus.annotation.RequiredVariables; public class RequiredVariableSteps { @RequiredVariables("requiredVariableA") @Given("step a") public void methodA() { // do something with requiredVariableA here } }
Python
UTF-8
7,039
3.0625
3
[]
no_license
# Vladislav 25.02.21 # Fitting procedure import numpy as np from scipy.optimize import curve_fit class FitFunctionClassAbstract: def __init__(self, gamma, small_delta, big_delta): self.fit_function = None self.gamma = gamma self.small_delta = small_delta self.big_delta = big_delta def fit(self, difflist, integrals): initial_parameters = np.array([1.0, 1e-6]) popt, pcov = curve_fit(self.fit_function, difflist, integrals, initial_parameters) params = popt A = params[0] D = params[1] g = np.linspace(0, max(difflist)) y = self.fit_function(g, A, D) y_for_rmsd = self.fit_function(difflist, A, D) RMSD = self.rmsd_calculation(integrals, y_for_rmsd) y = y / A return A, D, y, pcov, RMSD def rmsd_calculation(self, integrals, function): # stats (from other answer) absError = integrals - function SE = np.square(absError) # squared errors MSE = np.mean(SE) # mean squared errors RMSD = np.sqrt(MSE) # Root Mean Squared Deviation, RMSD return RMSD # standard class FitFunctionClassSTE(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta): super().__init__(gamma, small_delta, big_delta) self.fit_function = self.fit_function_ste_gradients def function_ste(self, gamma, small_delta, big_delta, gradients, A, D): return A * np.exp(-1 * (2*np.pi*gamma * small_delta * gradients) ** 2 * (big_delta - small_delta / 3) * D) def fit_function_ste_gradients(self, gradients, A, D): return self.function_ste(self.gamma, self.small_delta, self.big_delta, gradients, A, D) class FitFunctionClassSTEbp(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, p1, d16): super().__init__(gamma, small_delta, big_delta) self.fit_function = self.fit_function_ste_gradients self.d16 = d16 self.p1 = p1 def function_stebp(self, gamma, small_delta, big_delta, gradients, A, D, d16, p1): d20 = big_delta p30 = small_delta return A * np.exp(-1 * (2*np.pi*gamma * 2 * p30 * gradients) ** 2 * (d20 - 2 * p30 / 3 - d16 / 2 - 4 * p1) * D) def fit_function_ste_gradients(self, gradients, A, D): return self.function_stebp(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.d16, self.p1) class FitFunctionClassDSTE(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, p1, d16): super().__init__(gamma, small_delta, big_delta) self.p1 = p1 self.d16 = d16 self.fit_function = self.fit_function_dste_gradients def function_dste(self, gamma, small_delta, big_delta, gradients, A, D, p1, d16): DELAY20 = big_delta PULSE30 = small_delta DELAY16 = d16 # delay for gradient recovery PULSE1 = p1 # duration of 90 degree pulse alpha = 2 * np.pi*gamma * PULSE30 * gradients beta = DELAY20 - 5 / 3 * PULSE30 - DELAY16 - 4 * PULSE1 return A * np.exp(-alpha ** 2 * beta * D) def fit_function_dste_gradients(self, gradients, A, D): return self.function_dste(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.p1, self.d16) class FitFunctionClassDSTEbp(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, p1, d16): super().__init__(gamma, small_delta, big_delta) self.p1 = p1 self.d16 = d16 self.fit_function = self.fit_function_dste_gradients def function_dste_bp(self, gamma, small_delta, big_delta, gradients, A, D, p1, d16): DELAY20 = big_delta PULSE30 = small_delta DELAY16 = d16 # delay for gradient recovery PULSE1 = p1 # duration of 90 degree pulse alpha = 2 * np.pi * gamma * (2 * PULSE30) * gradients beta = DELAY20 - 10/3 * PULSE30 - 3 * DELAY16 - 8 * PULSE1 return A * np.exp(-alpha ** 2 * beta * D) def fit_function_dste_gradients(self, gradients, A, D): return self.function_dste_bp(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.p1, self.d16) # non-standard # small_delta = small_delta, big_delta = big_T, d16 = tau1, p1 = tau2 class FitFunctionClassSTEn(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta): super().__init__(gamma, small_delta, big_delta) self.fit_function = self.fit_function_ste_gradients def function_ste_n(self, gamma, small_delta, big_delta, gradients, A, D): return A * np.exp(-1 * (2*np.pi*gamma * small_delta * gradients) ** 2 * (big_delta - small_delta / 3) * D) def fit_function_ste_gradients(self, gradients, A, D): return self.function_ste_n(self.gamma, self.small_delta, self.big_delta, gradients, A, D) class FitFunctionClassSTEbpn(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, d16): super().__init__(gamma, small_delta, big_delta) self.fit_function = self.fit_function_ste_gradients self.d16 = d16 def function_stebp_n(self, gamma, small_delta, big_delta, gradients, A, D, d16): T = big_delta tau = d16 return A * np.exp(-1 * (2*np.pi*gamma * small_delta * gradients) ** 2 * (T + 2 * small_delta / 3 + 3 * tau / 4 ) * D) def fit_function_ste_gradients(self, gradients, A, D): return self.function_stebp_n(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.d16) class FitFunctionClassDSTEn(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, d16): super().__init__(gamma, small_delta, big_delta) self.d16 = d16 self.fit_function = self.fit_function_dste_gradients def function_dste_n(self, gamma, small_delta, big_delta, gradients, A, D, d16): T = big_delta tau = d16 alpha = 2 * np.pi*gamma * small_delta * gradients beta = T + 4 / 3 * small_delta + 2 * tau return A * np.exp(-alpha ** 2 * beta * D) def fit_function_dste_gradients(self, gradients, A, D): return self.function_dste_n(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.d16) class FitFunctionClassDSTEbpn(FitFunctionClassAbstract): def __init__(self, gamma, small_delta, big_delta, p1, d16): super().__init__(gamma, small_delta, big_delta) self.p1 = p1 self.d16 = d16 self.fit_function = self.fit_function_dste_gradients def function_dste_bp_n(self, gamma, small_delta, big_delta, gradients, A, D, p1, d16): T = big_delta tau1 = d16 tau2 = p1 alpha = 2 * np.pi*gamma * small_delta * gradients beta = T + 4/3 * small_delta + 5/4 * tau1 + tau2 / 4 return A * np.exp(-alpha ** 2 * beta * D) def fit_function_dste_gradients(self, gradients, A, D): return self.function_dste_bp_n(self.gamma, self.small_delta, self.big_delta, gradients, A, D, self.p1, self.d16)
Markdown
UTF-8
1,676
3.890625
4
[]
no_license
# Vue Basics Quick notes on Vue.js * [Basics](#basics) * [Computed Properties](#computed-properties) ## Basics ### The simplest Vue app ```html <div id="app"> {{ message}} </div> ``` ```js var app = new Vue({ el: '#app', data: { message: 'Hello world!' } }) ``` Output ```html <div id="app"> Hello World! </div> ``` A Vue instance is created by invoking `new Vue()` and passing in an object with certain properties defined. #### el The `el` property specifices whate element on the page Vue should bind to. In this simple example, Vue uses the existing HTML at this location as its template. #### data The `data` property holds the local state of this instance. Properties of this data can be referenced in the template (HTML generally) or in Javascript. For example, the `{{ message }}` in the HTML above will be replaced with the contents of `message` Data properties are reactive. That means if the message property is updated, the HTML rendered at `{{ message }}` will be updated as well. There are some limitations to how this works, and understanding those limits is an important part of using Vue. ## Computed Properties On a Vue object you might see something like ```js ..., computed: { message() { return `Hello ${this.name}!` } }, ... ``` This is a computed property. Computed properties are implemented as functions that return a value. They are accessed just like you would access a normal data property. Computed properties are only reevaluated when the underlying data changes (`this.name` in this case). Computed properties should be used instead of methods wherever possible. [https://vuejs.org/v2/guide/computed.html]()
Markdown
UTF-8
1,767
3.546875
4
[]
no_license
# day23 日常学习 ## 概要 --- ## 知识点 ### 1. shader ​ float用于位置和纹理坐标,half用于其他所有内容。fixed通常可以等价于half。 ### 2. WeakReference ```c 1.强引用 我们实例化一个对象,直接引用了这个对象就是强引用。在这个对象被强引用的时,GC无法回收这个对象。 只有当该对象所有的强引用都失去的时候,GC才会回收该对象。 2.弱引用 弱引用可以让您保持对对象的引用,同时允许GC在必要时释放对象,回收内存。 一般使用场景:对象过大,并且不经常访问。这样我们就可以创建一个弱引用,当不常用该对象的时候,GC可以回收该对象,当需要引用对象,可以先判断弱引用的对象是不是存在,如果存在,就直接使用,如果弱引用的对象已经被回收,那就重新创建一个对象来使用。 ``` c# 例子 ```c# Person person = new Person() { Id = 1, Name = "demo" }; //实例化弱引用传递一个对象 WeakReference wk = new WeakReference(person); Person p1; if (wk.IsAlive) //如果person没有被回收 { p1 = wk.Target as Person; //直接引用原对象 } else //如果person已经被回收了 重新创建一个对象 { p1 = new Person() { Id = 1, Name = "demo" }; } ``` 总结: ``` 弱引用运行创建和使用对象,但是垃圾回收器运行时,就会回收对象释放内存。但始终存在这样的风险:垃圾回收器在重新建立强引用之前先处理该对象。但是在特定的情况下使用弱引用是很合理的。 使用 WeakReference类创建弱引用。因为对象可能在任意时刻被回收,所以在引用前必须确认它存在。 ```
Java
UTF-8
13,145
1.820313
2
[]
no_license
package com.github.wangfeng.mybatis_generator.entity; import java.util.Date; public class AdminSysMenuDO { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Long id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.name * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.left * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Long left; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.right * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Long right; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.level * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Integer level; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.icon * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String icon; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.url * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String url; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.create_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Date createDate; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.create_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String createBy; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.update_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Date updateDate; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.update_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String updateBy; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.status * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Integer status; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.permission * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private String permission; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column admin_sys_menu.p_id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ private Long pId; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.id * * @return the value of admin_sys_menu.id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Long getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.id * * @param id the value for admin_sys_menu.id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setId(Long id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.name * * @return the value of admin_sys_menu.name * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.name * * @param name the value for admin_sys_menu.name * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.left * * @return the value of admin_sys_menu.left * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Long getLeft() { return left; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.left * * @param left the value for admin_sys_menu.left * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setLeft(Long left) { this.left = left; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.right * * @return the value of admin_sys_menu.right * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Long getRight() { return right; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.right * * @param right the value for admin_sys_menu.right * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setRight(Long right) { this.right = right; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.level * * @return the value of admin_sys_menu.level * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Integer getLevel() { return level; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.level * * @param level the value for admin_sys_menu.level * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setLevel(Integer level) { this.level = level; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.icon * * @return the value of admin_sys_menu.icon * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getIcon() { return icon; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.icon * * @param icon the value for admin_sys_menu.icon * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setIcon(String icon) { this.icon = icon == null ? null : icon.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.url * * @return the value of admin_sys_menu.url * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getUrl() { return url; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.url * * @param url the value for admin_sys_menu.url * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setUrl(String url) { this.url = url == null ? null : url.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.create_date * * @return the value of admin_sys_menu.create_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Date getCreateDate() { return createDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.create_date * * @param createDate the value for admin_sys_menu.create_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setCreateDate(Date createDate) { this.createDate = createDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.create_by * * @return the value of admin_sys_menu.create_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getCreateBy() { return createBy; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.create_by * * @param createBy the value for admin_sys_menu.create_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setCreateBy(String createBy) { this.createBy = createBy == null ? null : createBy.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.update_date * * @return the value of admin_sys_menu.update_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Date getUpdateDate() { return updateDate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.update_date * * @param updateDate the value for admin_sys_menu.update_date * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.update_by * * @return the value of admin_sys_menu.update_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getUpdateBy() { return updateBy; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.update_by * * @param updateBy the value for admin_sys_menu.update_by * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setUpdateBy(String updateBy) { this.updateBy = updateBy == null ? null : updateBy.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.status * * @return the value of admin_sys_menu.status * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Integer getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.status * * @param status the value for admin_sys_menu.status * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setStatus(Integer status) { this.status = status; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.permission * * @return the value of admin_sys_menu.permission * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public String getPermission() { return permission; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.permission * * @param permission the value for admin_sys_menu.permission * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setPermission(String permission) { this.permission = permission == null ? null : permission.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column admin_sys_menu.p_id * * @return the value of admin_sys_menu.p_id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public Long getpId() { return pId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column admin_sys_menu.p_id * * @param pId the value for admin_sys_menu.p_id * * @mbg.generated Sun Sep 08 16:48:42 CST 2019 */ public void setpId(Long pId) { this.pId = pId; } }
TypeScript
UTF-8
366
2.75
3
[]
no_license
import { initialState } from "../store/InitialState" import * as Actions from "./Action" import { Action } from "./ActionType" export const BooleanReducer = (state = initialState.boolean, action: Action) => { switch (action.type) { case Actions.SKELETON: return { ...state, ...action.payload } default: return state } }
PHP
UTF-8
3,040
3.171875
3
[ "MIT" ]
permissive
<?php namespace Arcanedev\Stripe\Utilities; use Arcanedev\Stripe\Contracts\Utilities\UtilSet as UtilSetContract; use ArrayIterator; use Countable; use IteratorAggregate; /** * Class UtilSet * * @package Arcanedev\Stripe\Utilities * @author ARCANEDEV <arcanedev.maroc@gmail.com> */ class UtilSet implements UtilSetContract, IteratorAggregate, Countable { /* ------------------------------------------------------------------------------------------------ | Properties | ------------------------------------------------------------------------------------------------ */ /** @var array */ private $items; /* ------------------------------------------------------------------------------------------------ | Constructor | ------------------------------------------------------------------------------------------------ */ public function __construct($attributes = []) { $this->items = []; foreach ($attributes as $attribute) { $this->add($attribute); } } /* ------------------------------------------------------------------------------------------------ | Main Functions | ------------------------------------------------------------------------------------------------ */ /** * Check if attribute is included. * * @param string $attribute * * @return bool */ public function includes($attribute) { return isset($this->items[$attribute]); } /** * Add attribute * * @param $attribute */ public function add($attribute) { $this->items[$attribute] = true; } /** * @param $attribute */ public function discard($attribute) { unset($this->items[$attribute]); } /** * Get all attributes key * * @return array */ public function keys() { return array_keys($this->items); } /** * Diff Keys * * @param array $keys * * @return array */ public function diffKeys(array $keys = []) { return array_diff($this->keys(), $keys); } /** * Get all Attributes * * @return array */ public function toArray() { return $this->count() ? $this->keys() : []; } /** * @return ArrayIterator */ public function getIterator() { return new ArrayIterator($this->toArray()); } /** * Count items * * @return int The custom count as an integer. */ public function count() { return count($this->items); } /* ------------------------------------------------------------------------------------------------ | Check Functions | ------------------------------------------------------------------------------------------------ */ /** * Check if the items are empty. * * @return bool */ public function isEmpty() { return empty($this->items); } }
Java
UTF-8
833
4.1875
4
[]
no_license
package miniExceptionLizard; public class Lizard { public String name; public Lizard(String name) throws IllegalArgumentException { if (name == null) { throw new IllegalArgumentException(); } this.name = name; } public static void main(String[] args) { Lizard thingy = new Lizard(null); System.out.println(thingy.name); // if string where null is then that string will appear } } // Write a class called Lizard with one instance variable, String name, and a constructor that takes one argument, a String name. The constructor should throw an illegal argument exception if the a null value is passed into the name parameter. Optional: find out how to check if a string is empty or blank, and throw an illegal argument exception in that case, too.
Java
UTF-8
1,234
3.265625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; /** * Created by Kenneth Mintah on 11/11/15. * This class receives current date and time from the middle server */ public class DateClient { public static void main(String args[]) throws IOException { //check if arguments have been passed if(args.length != 2){ System.out.println("Usage DateClient <ip address> " + "<port> eg. DateClient 10.10.20.93 9090"); return; } //ip address String ipAddress = args[0]; //port Integer port = Integer.parseInt(args[1]); //client socket to receive data from middle ware Socket client = new Socket(ipAddress, port); try { InputStream in = client.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String date; while ((date = bin.readLine()) != null) { System.out.println("Date: " + date); } client.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
C++
UTF-8
2,203
2.515625
3
[ "MIT" ]
permissive
#pragma once #include "BaseContentsInterface.h" class Radiation : public BaseContentsInterface { float radius; int startAngle; int stopAngle; int mSpeed; vector<vector<float> > mWaves; public: Radiation() { radius = 400; startAngle = 0; stopAngle = 0; mSpeed = 1; } void update() { updateWaves(); startAngle += mSpeed; stopAngle = startAngle + data::bufferLength; // startAngle = startAngle % 360; // stopAngle = stopAngle % 360; } void updateWaves() { int j = 0; mWaves.clear(); for (DATASET_IT it = DATASET.begin(); it != DATASET.end(); it++) { vector<float> v; for (int i = 0; i < data::bufferLength; i++) { v.push_back((*it)->getTargetData(i)->voltage); } mWaves.push_back(v); j++; } } void draw() { ofPushMatrix(); ofTranslate(getWidth() * 0.5, getHeight() * 0.5); // mesh.addColor(ofColor(255)); // mesh.addVertex(ofVec3f(0)); int br = 2; for (int i = 0; i < mWaves.size(); i++) { ofVboMesh mesh; int l = mWaves[i].size() - 1; int size = mWaves[i].size(); for (int j = 0; j < mWaves[i].size(); j++,l --) { float voltage = mWaves[i][l]; float offset = ((float)ofGetFrameNum() / (float)data::bufferLength) * TWO_PI; float f = -ofMap(j, 0, size, 0, 1) * TWO_PI + offset; float x = radius * cos(f) * voltage; float y = radius * sin(f) * voltage; int min = size; unsigned char a = j <= min ? ofMap(j, 0, min, 255, 0) : 255; mesh.addColor(ofColor(0, 255, 0, a)); mesh.addVertex(ofVec3f(x, y, 0)); } mesh.setMode(OF_PRIMITIVE_LINE_STRIP); mesh.drawWireframe(); // ofTranslate(ofRandom(-5, 5), 0); // mesh.setMode(OF_PRIMITIVE_POINTS); // mesh.drawVertices(); } ofPopMatrix(); } };
PHP
UTF-8
170
3.109375
3
[]
no_license
<?php // display function function display($nameValues) { foreach ($nameValues as $name => $value) { echo($name . ": " . $value . "<br />"); } } ?>
Markdown
UTF-8
704
2.65625
3
[]
no_license
# Pint Of Sale System Requirements 1) Invetory entry via code-reader 2) Generate receipts, and variuos financial reports System cost 1) 23 000-patrial,no M-PESA,no online backup,no SMS sending 2) 60 000 full system including online backup and M-PESA module Cost per module part A 1) Print receipt 8000 2) Finacial Reports 15000 ****TOTALS = 23000 part B 3) Seding SMSes 12000 NB: 8700-SenderID-excluding SMS sending charges) 4) Email sending 5000 This includes online backup 5) M-PESA API 20000 NB: This excludes The money charged by Safaricom for using Their API ****TOTALS 60000
Java
UTF-8
832
3.375
3
[]
no_license
public class OffByOne implements CharacterComparator { @Override public boolean equalChars(char x, char y) { int intX = x; // System.out.println(intX); int intY = y; // System.out.println(intY); if ( intX - intY == 1 || intX - intY == -1) { return true; } return false; } public static void main(String[] args) { OffByOne obo = new OffByOne(); System.out.println(obo.equalChars('a', 'b')); // true System.out.println(obo.equalChars('r', 'q')); // true System.out.println(obo.equalChars('a', 'e')); // false System.out.println(obo.equalChars('z', 'a')); // false System.out.println(obo.equalChars('a', 'a')); // false System.out.println(obo.equalChars('&', '%')); // true } }
Python
UTF-8
812
2.609375
3
[]
no_license
#!/usr/bin/env python3 # USAGE: call this file on file or directory to return predicted results import pickle from NBfunc import * from spamkeys import sorted_spam_keys import os import sys def TestModel(filepath,filename): test_matrix = CreateSingleFeatureMatrix(filepath,sorted_spam_keys) result = int(loaded_model.predict(test_matrix)) if result == 1: print(filename,"\t\t\t -- spam") elif result ==0: print(filename,"\t\t\t -- not spam") spam_model = 'spam_model.sav' loaded_model = pickle.load(open(spam_model,'rb')) if os.path.isfile(sys.argv[1]): filename = sys.argv[1] filepath = filename TestModel(filepath, filename) elif os.path.isdir(sys.argv[1]): dirname = sys.argv[1] for filename in os.listdir(dirname): filepath = dirname+"/"+filename TestModel(filepath, filename)
Python
UTF-8
3,466
2.828125
3
[]
no_license
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from time import sleep import settings import platform import pywhatkit as kit ''' For each time that we init our programawe should know what OS we're using, so, It just gonna be adjusted when it start ''' driver =webdriver.Chrome() def iniciar_mensajero(): # Checks if on Mac or Windows print("Opening Chrome") if platform.system() == "Windows": driver = webdriver.Chrome('chromedriver.exe') else: driver = webdriver.Chrome('/home/iangarcia/Documentos/Shelby/resources/chromeDriver/chromedriver') def send_whatssapp_message(friend_name): settings.friend_name=friend_name # Opens Whatsapp driver.get('https://web.whatsapp.com/') # Waits for you to scan the whatsapp QR code def page_load(): get_users = driver.find_elements_by_xpath("//*[contains(text(), '" + settings.friend_name + "')]") if len(get_users) > 0: # waits 4 seconds to make sure page is loaded sleep(4) get_users[0].click() settings.found_page = 1 #Send messages from our own file def start_sending_messages(my_script, iteraciones): settings.script=my_script settings.iterations=iteraciones print("Starting messages...") with open(settings.script, "r") as f: for line in f.readlines(): for i in range(settings.iterations): for word in line.split(): print("Sending: " + word) # Types words and submits actions = ActionChains(driver) actions.send_keys(word, Keys.ENTER) actions.perform() sleep(float(settings.delay)) def sending_message(mensaje): message=str(mensaje) print("Sending" + message) actions= ActionChains(driver) actions.send_keys(message, Keys.ENTER) actions.perform() sleep(float(settings.delay)) def mensajea_por_whatsapp_directo(nombre_contacto, mensaje, iteraciones): nombre_contacto=str(nombre_contacto) mi_mensaje=str(mensaje) mis_iteraciones=int(iteraciones) send_whatssapp_message(nombre_contacto) page_load() while settings.found_page==0: page_load() print("PLEASE SCAN QR CODE WITH PHONE") sleep(2) for i in range(mis_iteraciones): sending_message(mi_mensaje) #Envia mensajes desde un archivo de Texto def mensajea_por_whatssapp(nombre_del_contacto, archivo, iteraciones): nombre_contacto=str(nombre_del_contacto) nombre_archivo=str(archivo) send_whatssapp_message(nombre_contacto)#Busca el contacto en Whatssapp Web page_load() while settings.found_page == 0: page_load() print("PLEASE SCAN QR CODE WITH PHONE") sleep(2) start_sending_messages(nombre_archivo, int(iteraciones)) def send_message_by_messenger(friend): settings.friend_name=str(friend) # Opens Facebook Messenger settings.source='Messenger' driver.get('https://www.messenger.com/') sleep(5) # Login driver.find_element_by_xpath('//*[@id="email"]').send_keys(settings.username_email) driver.find_element_by_xpath('//*[@id="pass"]').send_keys(settings.password) sleep(10) driver.find_element_by_xpath('//*[@id="loginbutton"]').click() # Waits 8 seconds to finish loading page print("Waiting for a few seconds...") sleep(8) if settings.source != "Whatsapp": driver.find_element_by_xpath("//*[contains(text(), '" + settings.friend_name + "')]").click() if settings.source == "Messenger": driver.refresh() sleep(5) sending_message("Hola paps, ai loviu") send_message_by_messenger('Carlos Andrade Hdez')
Rust
UTF-8
1,613
3.125
3
[]
no_license
use super::*; #[skip_serializing_none] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EntryQuote<'a> { #[serde(flatten)] pub base: EntryBaseData<'a>, pub entries: Entries<'a>, pub by: Option<&'a str>, pub from: Option<&'a str>, /// If the automatically-inserted quotation marks should be skipped. #[serde(default)] pub skip_marks: Option<bool>, } impl<'a> From<EntryQuote<'a>> for EntryKind<'a> { fn from(value: EntryQuote<'a>) -> Self { EntryKind::Quote(value) } } #[cfg(test)] mod tests { use super::test_utils::*; use super::*; #[test] fn serde_entry_quote() { let json = r#"{ "type": "quote", "name": "Running the Game", "entries": [ "Rules enable you and your players to have fun at the table. The rules serve you, not vice versa...", "There are the rules of the game, and there are table rules for how the game is played." ], "by": "Korfel Nailo", "from": "The Book of Many Names", "skipMarks": true }"#; let object: Entry = EntryQuote { base: base(Some("Running the Game")), entries: vec![ "Rules enable you and your players to have fun at the table. The rules serve you, not vice versa...".into(), "There are the rules of the game, and there are table rules for how the game is played.".into(), ], by: Some("Korfel Nailo"), from: Some("The Book of Many Names"), skip_marks: Some(true), }.into(); check_serde(json, object); } }
C++
UTF-8
5,070
3.34375
3
[]
no_license
#include <StackArray.h> /** * L: left * R: right * S: straight * B: return */ StackArray <char> movements; const char LEFT = 'L'; const char STRAIGHT = 'S'; const char RIGHT = 'R'; const char RETURN = 'B'; int avanza1 = 6; int avanza2 = 3; int infra1 = 8; int infra2 = 9; int valorInfra = 1; void setup() { pinMode(avanza1, OUTPUT); pinMode(avanza2, OUTPUT); pinMode(infra1, INPUT); pinMode(infra2, INPUT); } void loop() { if(existSavedRoad()){ deleteSavedRoad(); }else{ //While we have not reached the goal while(!detectGoal()){ while((!detectIntersection()) || (!detectEndOfRoad())){ //Move the robot move(); } if(detectIntersection()){ //First Movement if(!movements.isEmpty()){ if(existLeftRoad()){ movements.push(LEFT); moveLeft(); }else if(existStraightRoad()){ movements.push(STRAIGHT); moveStraight(); }else if(existRightRoad()){ movements.push(RIGHT); moveRight(); }else{ Serial.print ("This Lab doesn't have solution."); break; } //Other Movement }else{ /* * If the last movement is return, the robot needs to choose * a new way based on the movement before return */ if(peek(movements) == RETURN){ movements.pop(); char lastMovement = movements.pop(); /* * If the last movement was left, the robot has three options: * 1. Go Straight (Robot will turn to the left) * 2. Go to the right (Robot will continue Straight) * 3. Return (Robot will turn to the right= */ if(lastMovement == LEFT){ //Option 1 if(existStraightRoad()){ movements.push(STRAIGHT); //For the new perspective of the robot, it needs to move to the LEFT moveLeft(); //Option 2 }else if(existRightRoad()){ movements.push(RIGHT); //For the new perspective of the robot, it needs to move to STRAIGHT moveStraight(); //Option 3 }else{ movements.push(RETURN); turningAround(); } /* * If the last movement was STRAIGHT, the robot has two options: * 1. Go to the RIGHT (Robot will turn to the LEFT) * 2. RETURN (Robot will continue in the same direcction) */ }else if(lastMovement == STRAIGHT){ //Option 1 if(existRightRoad()){ movements.push(RIGHT); //For the new perspective of the robot, it needs to move to the left moveLeft(); //Option 2 }else{ movements.push(RETURN); //For the new perspective of the robot, it needs to move to the left moveLeft(); } /* * If the lastMovement was RIGTH, the Robot only has one Opetion * 1. RETURN (The robot will tur to the left) */ }else{ movements.push(RETURN); turningAround(); } /* * The Robot need exploring the Lab */ }else{ if(existLeftRoad()){ movements.push(LEFT); moveLeft(); }else if(existStraightRoad()){ movements.push(STRAIGHT); moveStraight(); }else if(existRightRoad()){ movements.push(RIGHT); moveRight(); //The robot need RETURN }else{ movements.push(RETURN); turningAround(); } } } }else if(detectEndOfRoad()){ movements.push(RETURN); turningAround(); } } setSavedRoad(movements); } } char peek(StackArray <char> stack){ char lastValue = stack.pop(); stack.push(lastValue); return lastValue; } void move(){ if(valorInfra = '1'){ valorInfra = digitalRead(infra1); valorInfra = !valorInfra; digitalWrite (avanza1, valorInfra); } if(valorInfra = '1'){ valorInfra = digitalRead(infra2); } } //Rotate the robot 180º void turningAround(){ //Rotate the robot until it detects black line again } void moveLeft(){ } void moveStraight(){ } void moveRight(){ } boolean existLeftRoad(){ return false; } boolean existStraightRoad(){ return false; } boolean existRightRoad(){ return false; } boolean detectIntersection(){ } boolean detectEndOfRoad(){ return false; } boolean detectGoal(){ return false; } boolean existSavedRoad(){ return false; } void getSavedRoad(){ } void deleteSavedRoad(){ } void setSavedRoad(StackArray <char> stack){ }
C
UTF-8
1,569
3.515625
4
[]
no_license
typedef struct No { unsigned int digito; struct No *prox; } No; /* Esse TAD é uma lista ligada que representa um número grande de maneira inversa. Ou seja, se quisermos armazenar 1234567, ele será representado como 7->6->5->4->3->2->1. */ typedef No* NumeroGrande; /* Inicializa um NumeroGrande. */ NumeroGrande criar_numero_grande(NumeroGrande numeroGrande); /* Destroi, liberando da memória, um NumeroGrande. */ void destruir_numero_grande(NumeroGrande numeroGrande); /* Insere um dígito no ínicio do NumeroGrande, into é, à direita. */ NumeroGrande inserir_no_inicio(NumeroGrande numeroGrande, int info); /* Inverte o NumeroGrande (de 7->6->5->4->3->2->1 para 1->2->3->4->5->6->7). */ NumeroGrande inverter(NumeroGrande numeroGrande); /* Copia todos os dígitos de um NumeroGrande para outro e retorna essa cópia. */ NumeroGrande copiar(NumeroGrande numeroGrande); /* Retorna 0 se numeroGrande1 é igual ao numerogrande2, < 0 se o segundo é maior e > 0 se o primeiro é maior. */ int comparar(NumeroGrande numeroGrande1, NumeroGrande numeroGrande2); /* Soma dois números grandes. */ NumeroGrande somar(NumeroGrande numeroGrande1, NumeroGrande numeroGrande2); /* Subtrai dois números grandes. */ NumeroGrande subtrair(NumeroGrande numeroGrande1, NumeroGrande numeroGrande2); /* Multiplica dois números grandes. */ NumeroGrande multiplicar(NumeroGrande numeroGrande1, NumeroGrande numeroGrande2); /* Divide dois números grandes (divisão inteira). */ NumeroGrande dividir(NumeroGrande numeroGrande1, NumeroGrande numeroGrande2);
C++
UTF-8
819
3.734375
4
[]
no_license
//WAP to input PRICE and calculate and print DISCOUNT and NET PRICE by using DISCOUNT as Friend class and NET as friend function #include<iostream> using namespace std; class DISCOUNT; class PRICE { float P; public: void input() { cout<<"\nEnter Price:"; cin>>P; } void show() { cout<<"\nPrice="<<P; } friend void Net(PRICE,DISCOUNT); friend DISCOUNT; }; class DISCOUNT { float D; public: void process(PRICE obj) { D=obj.P*10/100; } void show() { cout<<"\nDiscount="<<D; } friend void Net(PRICE,DISCOUNT); }; void Net(PRICE Pobj,DISCOUNT Dobj) { float net; net=Pobj.P-Dobj.D; cout<<"\nNet Price="<<net; } int main() { PRICE p; p.input(); DISCOUNT d; d.process(p); p.show(); d.show(); Net(p,d); return 0; }
Python
UTF-8
1,742
3.171875
3
[]
no_license
def get_probs(Q_s, epsilon, nA): #nA is no. of actions in the action space # obtains the action probabilities corresponding to epsilon-greedy policy policy_s = np.ones(nA) * epsilon / nA best_a = np.argmax(Q_s) policy_s[best_a] = 1 - epsilon + (epsilon / nA) return policy_s ''' Now we will use this get_probs func in generating the episode. Note that we are no longer using the stochastic policy we started with, instead building upon it in an epsilon greedy way. ''' def generate_episode_from_Q(env, Q, epsilon, nA): # generates an episode from following the epsilon-greedy policy episode = [] state = env.reset() while True: action = np.random.choice(np.arange(nA), p=get_probs(Q[state], epsilon, nA)) \ if state in Q else env.action_space.sample() next_state, reward, done, info = env.step(action) episode.append((state, action, reward)) state = next_state if done: break return episode ''' Finally Q values are approximated by taking average of corresponding returns. But instead we can write it using incremental mean and constant alpha. As we are using constant alpha we need not keep a track of N-table, ie how many times we visited that state. ''' def update_Q(env, episode, Q, alpha, gamma): # updates the action-value function estimate using the most recent episode states, actions, rewards = zip(*episode) # prepare for discounting discounts = np.array([gamma**i for i in range(len(rewards)+1)]) for i, state in enumerate(states): old_Q = Q[state][actions[i]] Q[state][actions[i]] = old_Q + alpha*(sum(rewards[i:]*discounts[:-(1+i)]) - old_Q) return Q
Markdown
UTF-8
472
2.6875
3
[]
no_license
Train Scheduler ### Overview A train schedule application that incorporates Firebase to host arrival and departure data. Information is retrieved and manipulated with Moment.js. This website will provide up-to-date information about various trains, namely their arrival times and how many minutes remain until they arrive at their station. Technologies Used: `Firebase` `Javascript` `jQuery` `Moment js` `Google Fonts` Screenshots: ![screenshot](img/screenshot.png)
PHP
UTF-8
1,518
2.578125
3
[]
no_license
<?php class HeruValidator extends Illuminate\Validation\Validator { /** * validasi nama sekarang * * @param array $attribute * @param array $value * @param array $parameters * @return bool */ public function validateNamaSekarang($attribute, $value, $parameters) { return strtolower($value) == strtolower(Auth::user()->nama); } /** * validasi username sekarang * * @param array $attribute * @param array $value * @param array $parameters * @return bool */ public function validateUsernameSekarang($attribute, $value, $parameters) { return $value == Auth::user()->username; } /** * validasi password sekarang * * @param array $attribute * @param array $value * @param array $parameters * @return bool */ public function validatePasswordSekarang($attribute, $value, $parameters) { return Hash::check($value, Auth::user()->password); } /** * validasi ramalan * * @param array $attribute * @param array $value * @param array $parameters * @return bool */ public function validateRamalan($attribute, $value, $parameters) { $zodiak = trim(Input::get('zodiak')); $tanggal = date('Y-m-d', strtotime(trim($value))); $cek = Ramal::cek($zodiak, $tanggal); return $cek == 0; } public function replaceRamalan($message, $attribute, $rule, $parameters) { $zodiak = trim(Input::get('zodiak')); $tanggal = trim(Input::get('tanggal')); $pesan = array('zodiak' => $zodiak, 'tanggal' => $tanggal); return strtr($message, $pesan); } }
Java
ISO-8859-1
1,074
3.71875
4
[]
no_license
import java.util.Scanner; public class Ejercicio4 { public static void main(String args []){ char c; int num; Scanner teclado = new Scanner (System.in); num = teclado.next().charAt(0); c = (char) num; System.out.println("Introduce un caracter :"); //c = (char) teclado.nextInt(); // c = teclado.next().charAt(0); if(c >= 'a' && c<= 'z'){ System.out.println("Es un caracter"); } if(c >= 'A' && c<= 'Z'){ System.out.println("Es un caracter"); } if (c== '.' || c==',' || c== ':' || c == ';');{ System.out.println("Es un caracter"); } /* System.out.println("introduce un nmero ="); n = teclado.nextInt(); if (n >= '0' && n<='9') System.out.println("Es un nmero"); System.out.println("Introduce un signo"); x = teclado.next().charAt(0); if( x<= '.' && x>= ':') System.out.println("es un signo de puntuacin"); */ } }
JavaScript
UTF-8
3,910
2.828125
3
[]
no_license
let express = require('express'); let app = express(); let http = require('http'); let server = http.Server(app); let socketIO = require('socket.io'); let io = socketIO(server); io.origins('*:*') const port = process.env.PORT || 80; server.listen(port, () => { console.log(`started on port: ${port}`); }); const wordlist = require('./words'); let users = []; let userIndex = -1; let turnDuration = 65; let endTurnDuration = 5; let timeLeft = turnDuration; let currentWord; let nextWord; let guessed = 0; setInterval(() => { timeLeft--; io.emit('time-left', timeLeft - endTurnDuration); if (timeLeft === endTurnDuration) { if (users.length > 1) { const nextPlayer = users[userIndex + 1] ? users[userIndex + 1].name : users[0].name; nextWord = wordlist[Math.floor(Math.random() * wordlist.length)]; const data = { nextPlayer: nextPlayer, currentWord: currentWord, nextWord: nextWord } io.emit('turn-end', data); } } if (timeLeft === 0) { chooseArtist(); timeLeft = turnDuration; } }, 1000) function chooseArtist() { if (users.length < 2) return; userIndex++; if (userIndex >= users.length) userIndex = 0; nextWord ? currentWord = nextWord : currentWord = wordlist[Math.floor(Math.random() * wordlist.length)]; io.to(users[userIndex].id).emit('current-word', currentWord); users[userIndex].currentArtist = true; timeLeft = turnDuration; } io.sockets.on('connection', function (socket) { socket.on('name', function (name) { const user = { name: name, score: 0, currentArtist: false, id: socket.id }; users.push(user); socket.broadcast.emit("new-message", name + ' joined the game!'); if (users.length === 1) { io.emit('waiting', true); } if (users.length === 2) { io.emit('waiting', false); chooseArtist(); } io.emit('users', users); }); socket.on('disconnect', function () { const user = users.find(user => user.id === socket.id); if(user) { let username = user.name; io.emit("new-message", username + ' has left the game!'); } if (users[userIndex] && socket.id === users[userIndex].id) { timeLeft = endTurnDuration + 1; } users = users.filter(function (user) { return user.id !== socket.id; }); if (!users.length) return; if (users.length === 1) { io.emit('waiting', true); } io.emit('users', users); }); socket.on('mouse', function (data) { socket.broadcast.emit('mouse', data); }); socket.on('clear', function () { io.emit('clear'); }); socket.on('guess', function (message) { const user = users.find(user => user.id === socket.id); if (message.toLowerCase() === currentWord) { user.score += (timeLeft-endTurnDuration) * 10; io.emit('users', users); io.to(socket.id).emit('disable-input'); io.emit('new-message', user.name + ' guessed the word!'); guessed++; if (guessed === users.length-1) timeLeft = endTurnDuration + 1; } else { message = user.name + ': ' + message; io.emit("new-message", message); } }); socket.on('reset-turn', () => { timeLeft = turnDuration; if (users.length > 1) { const artist = users.find(user => user.currentArtist === true); artist.score += guessed * 100; guessed = 0; } users.forEach(user => user.currentArtist = false); users.find(user => user.id === socket.id).currentArtist = true; io.emit('users', users); io.emit('change-color', 'black'); io.emit('time-left', timeLeft - endTurnDuration); }); socket.on('change-color', color => { io.emit('change-color', color); }) } );
Java
UTF-8
14,787
2.234375
2
[]
no_license
package media.interaktif; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class Stukas extends javax.swing.JFrame { private DefaultTableModel tabmode; private ResultSet hasil; CRUDstukas stukas = new CRUDstukas(); CRUDjawab jwb = new CRUDjawab(); public Stukas() { initComponents(); setLocationRelativeTo(null); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); btn_upload = new javax.swing.JButton(); btn_ok = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); cb_pilih = new javax.swing.JComboBox(); jLabel9 = new javax.swing.JLabel(); cb_kembali = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); tbl_stukas = new javax.swing.JTable(); jScrollPane3 = new javax.swing.JScrollPane(); ta_stukas = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); ta_jawaban = new javax.swing.JTextArea(); jLabel5 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(255, 255, 153)); btn_upload.setText("Upload"); btn_upload.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_uploadActionPerformed(evt); } }); btn_ok.setText("OK"); btn_ok.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_okActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Upload jawaban"); jLabel2.setText("Pilihan Materi"); cb_pilih.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Enkapsulasi", "Abstract Class", "Interface", "Polymorphism" })); jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel9.setText("STUDI KASUS"); cb_kembali.setText("Kembali"); cb_kembali.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cb_kembaliActionPerformed(evt); } }); tbl_stukas.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tbl_stukasMouseClicked(evt); } }); jScrollPane2.setViewportView(tbl_stukas); ta_stukas.setColumns(20); ta_stukas.setRows(5); jScrollPane3.setViewportView(ta_stukas); jLabel1.setText("Kerjakan studi kasus pada text area ini "); ta_jawaban.setColumns(20); ta_jawaban.setRows(5); jScrollPane1.setViewportView(ta_jawaban); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("Soal "); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(51, 51, 51) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(btn_upload, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(cb_kembali, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(jScrollPane2))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(304, 304, 304) .addComponent(jLabel9)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(210, 210, 210) .addComponent(jLabel2) .addGap(18, 18, 18) .addComponent(cb_pilih, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(btn_ok))) .addContainerGap(45, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addGap(41, 41, 41) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(cb_pilih, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btn_ok)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE) .addComponent(jScrollPane1)) .addGap(18, 18, 18) .addComponent(btn_upload) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE) .addComponent(cb_kembali) .addGap(27, 27, 27)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void cb_kembaliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_kembaliActionPerformed // TODO add your handling code here: Beranda n = new Beranda(); n.setVisible(true); this.setVisible(false); }//GEN-LAST:event_cb_kembaliActionPerformed private void tbl_stukasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_stukasMouseClicked try { int row = tbl_stukas.rowAtPoint(evt.getPoint()); String bab = tbl_stukas.getValueAt(row, 0).toString(); String kasus = tbl_stukas.getValueAt(row, 1).toString(); ta_stukas.setText(String.valueOf(kasus)); } catch(Exception e){ } }//GEN-LAST:event_tbl_stukasMouseClicked private void btn_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_okActionPerformed String mtr = (String)cb_pilih.getSelectedItem(); if(mtr=="Enkapsulasi"){ Object[]baris = {"Bab", "Kasus"}; tabmode = new DefaultTableModel(null, baris); tbl_stukas.setModel(tabmode); try{ hasil = stukas.tampilData1(); while(hasil.next()){ stukas.setBab(hasil.getString("Bab")); stukas.setKasus(hasil.getString("Kasus")); Object[] data = {stukas.getBab(), stukas.getKasus()}; tabmode.addRow(data); } } catch(Exception e){ } } else if(mtr=="Abstract Class"){ Object[]baris = {"Bab", "Kasus"}; tabmode = new DefaultTableModel(null, baris); tbl_stukas.setModel(tabmode); try{ hasil = stukas.tampilData2(); while(hasil.next()){ stukas.setBab(hasil.getString("Bab")); stukas.setKasus(hasil.getString("Kasus")); Object[] data = {stukas.getBab(), stukas.getKasus()}; tabmode.addRow(data); } } catch(Exception e){ } } else { System.out.println("Error"); } }//GEN-LAST:event_btn_okActionPerformed public void reset_text(){ ta_jawaban.setText(""); } private void btn_uploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_uploadActionPerformed if(ta_jawaban.getText().trim().equals("")){ JOptionPane.showMessageDialog(null, "Maaf, nomor 5 Password belum diisi!"); ta_jawaban.requestFocus(); }else { String jawaban = ""; try { jwb.setJwb1(ta_jawaban.getText()); jwb.simpanData(jwb.getJwb()); JOptionPane.showMessageDialog(null, "Data berhasil disimpan" , "Informasi", JOptionPane.INFORMATION_MESSAGE); reset_text(); }catch(Exception e){ JOptionPane.showMessageDialog(null, "Data gagal disimpan","Informasi", JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_btn_uploadActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Stukas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Stukas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Stukas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Stukas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Stukas().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_ok; private javax.swing.JButton btn_upload; private javax.swing.JButton cb_kembali; private javax.swing.JComboBox cb_pilih; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JTextArea ta_jawaban; private javax.swing.JTextArea ta_stukas; private javax.swing.JTable tbl_stukas; // End of variables declaration//GEN-END:variables }
C#
UTF-8
813
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BiblioCat.Data { public class Series { [Key] public int SeriesId { get; set; } [Required] [DisplayName("Name of Series")] public string SeriesName { get; set; } [DisplayName("Series Description")] public string SeriesDescription { get; set; } [DisplayName("Authors in the Series")] public virtual List<SeriesAuthor> AuthorsInSeries { get; set; } = new List<SeriesAuthor>(); [DisplayName("Books in the Series")] public virtual List<SeriesBook> BooksInSeries { get; set; } = new List<SeriesBook>(); } }
Markdown
UTF-8
5,494
3.03125
3
[]
no_license
What is Thunder? Thunder is an open-source and easy to use Java Networking Framework for Java 1.8 and higher Thunder uses TCP for guranteed data transfer Thunder is thread safe and supports Compression of Packets. --------- Content: - [Understanding the Basics](#basics) - [ThunderServer](#thunderserver) - [ThunderClient](#thunderclient) - [Using a ThunderListener](#thunderlistener) - [Creating and Sending Packets](#packets) - [Handling Packets](#packethandling) - [Response System](#response-system) --------- ## Basics: The ThunderServer and the ThunderClient are based on the ThunderConnection The ThunderConnection has its own unique Session to identify it. You can get it by using ThunderConnection#getSession() --------- ## ThunderServer: You can create a ThunderServer as the following. The Server is used to handle all Connections (ThunderClients). ```Java ThunderServer thunderServer = Thunder.createServer(); thunderServer.start(1401).perform(); ``` --------- ## ThunderClient: The ThunderClient connects to the ThunderServer and transfers data from one connection to another. ```Java ThunderClient thunderClient = Thunder.createClient(); thunderClient.connect("127.0.0.1", 1401).perform(); ``` --------- ## ThunderListener: The ThunderListener implements three methods to listen for events. The Listener can be add to a ThunderConnection (so either ThunderClient or ThunderServer) ```Java thunderClient.addSessionListener(new ThunderListener() { @Override public void handleConnect(ThunderSession session) { System.out.println("[Client] Connected to ThunderServer (" + System.currentTimeMillis() + ")"); } @Override public void handleHandshake(PacketHandshake handshake) { System.out.println("[Client] Received HandShake from ThunderServer! (" + System.currentTimeMillis() + ")"); } @Override public void handlePacketSend(Packet packet) { System.out.println("[Client] Sending " + packet.getClass().getSimpleName() + "... (" + System.currentTimeMillis() + ")"); } @Override public void handlePacketReceive(Packet packet) { System.out.println("[Client] Received " + packet.getClass().getSimpleName() + "! (" + System.currentTimeMillis() + ")"); } @Override public void handleDisconnect(ThunderSession session) { System.out.println(thunderClient.toString()); } }); ``` --------- ## Packets: Packets are the objects that contain the data which is getting transferred between ThunderConnections. Packet.class is abstract and contains two default methods. Packet#write(PacketBuffer) and Packet#read(PacketBuffer). Every Packet has its own UUID, a protocolVersion, a protocolId, and other values. An example Packet could look like the following: ```Java @Getter @AllArgsConstructor public class SamplePacket extends Packet { private String name; private int age; @Override public void write(PacketBuffer buf) { buf.writeString(name); buf.writeInt(age); } @Override public void read(PacketBuffer buf) { name = buf.readString(); age = buf.readInt(); } } ``` The attributes inside of a Packet must be read and written from or into the PacketBuffer. A Packet can be send through a ThunderConnection. ```Java SamplePacket samplePacket = new SamplePacket("Name", 32); thunderConnection.sendPacket(samplePacket); ``` --------- ## PacketHandling: When receiving Packets from a different ThunderConnection you can handle the received Packet with the integrated PacketAdapter and register a PacketHandler to handle the Packet. ```Java thunderConnection.addPacketHandler(new PacketHandler() { @Override public void handle(ThunderPacket packet) { //Check if packet is SamplePacket if (packet instanceof SamplePacket) { SamplePacket samplePacket = (SamplePacket) packet; System.out.println(samplePacket.getAge()); System.out.println(samplePacket.getName()); System.out.println(samplePacket.getProcessingTime() + "ms"); //The time the packet took System.out.println(samplePacket.toString()); //Information on the Packet } } }); ``` --------- ## Response System: The PacketSystem takes advantage of a Response-based System. You can await for a Response when sending a Packet. You can respond to a Packet with a ResponseStatus and/or a Message. An example could look like this: (Waiting for the Response with Consumer) ```Java thunderConnection.sendPacket(new SamplePacket("Luca", 16), new Consumer<Response>() { @Override public void accept(Response response) { System.out.println(response.getStatus() + " - " + response.getMessage() + " [" + response.getProcessingTime() + "ms]"); } }); ``` (Waiting for the Response without Consumer) ```Java SamplePacket samplePacket = new SamplePacket("Name", 16); Response response = thunderConnection.transferToResponse(samplePacket); System.out.println(response.getStatus() + " - " + response.getMessage()); ``` (Responding to the Packet) ```Java thunderConnection.addPacketHandler(new PacketHandler() { @Override public void handle(ThunderPacket packet) { //Check if packet is SamplePacket if (packet instanceof SamplePacket) { packet.respond(ResponseStatus.SUCCESS, "Test Message"); } } }); ```
Python
UTF-8
2,474
2.828125
3
[]
no_license
''' Description: This script is used to install an angleReader node based on selection. The first selected item will be used as base and the second as driver. Arguments: rotateAxis(optional = [1,0,0]) - The axis that will be read by the angleReader. frontAxis(optional = [0,1,0]) - The front axis that will be used by the angleReader. Output: Tuple (angleReaderTransform, angleReaderShape) Authors: Marin Petrov www.scroll-lock.eu ''' # imports import maya.cmds as mc # load plugin if not mc.pluginInfo('angleReader', q=True, loaded=True): mc.loadPlugin('angleReader') def installAngleReader(name, rotateAxis=[1,0,0], frontAxis=[0,1,0]): sel = mc.ls(sl=True) if len(sel) != 2: raise RuntimeError, 'Please select 2 transforms as base and driver in order to install angleReader' base, driver = sel if not name: raise RuntimeError, 'No name specified' else: baseName = '%s%sBaseGrp' %(base,name) driverName = '%s%sDriverGrp' %(driver,name) readerName = '%s%sReader' %(driver,name) shapeName = '%s%sReaderShape' %(driver,name) # create the angleReader node readerShape = mc.createNode('angleReader', n=shapeName) reader = mc.listRelatives(readerShape, p=True) mc.rename(reader, readerName) print reader # create two transforms that will be used as input for the reader's matrices baseGrp = mc.createNode('transform', n=baseName) driverGrp = mc.createNode('transform', n=driverName) # snap the reader to the driver's position and parent it to the base driverPos = mc.xform(driver, m=True, ws=True, q=True) mc.xform(reader, m=driverPos) mc.parent(reader, base) # snap the groups to the driver's position mc.xform(baseGrp, m=driverPos) mc.parent(baseGrp, base) mc.xform(driverGrp, m=driverPos) mc.parent(driverGrp, driver) # connect the base and driver to the angleReader's matrix attributes mc.connectAttr('%s.worldMatrix[0]'%baseGrp, '%s.baseMatrix'%readerShape) mc.connectAttr('%s.worldMatrix[0]'%driverGrp, '%s.driverMatrix'%readerShape) # set the rotate and front axis for axis, value in zip(['X', 'Y', 'Z'], rotateAxis): mc.setAttr('%s.rotateAxis%s' %(readerShape, axis), value) for axis, value in zip(['X', 'Y', 'Z'], frontAxis): mc.setAttr('%s.frontAxis%s' %(readerShape, axis), value) return (reader, readerShape)
Java
UTF-8
2,562
2.34375
2
[]
no_license
package test.restservices; import java.io.IOException; import test.restservices.ResultMessage; import java.io.InputStream; import java.nio.charset.Charset; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonUtil { public static <Lead> Lead readObject(String jsonData, Class<Lead> clazz) { Lead res = null; try { res = new ObjectMapper().readValue(jsonData, clazz); } catch (IOException e) { throw new RuntimeException(e); } return res; } public static <Lead> Lead readObject(InputStream is, Class<Lead> clazz) { Lead res = null; try { res = new ObjectMapper().readValue(is, clazz); } catch (IOException e) { throw new RuntimeException(e); } return res; } public static String toJson(Object res) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); prepareMapperForOutput(mapper); return mapper.writeValueAsString(res); } private static void prepareMapperForOutput(ObjectMapper mapper) { mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public static ResponseEntity<String> toJsonResponse(HttpStatus httpStatus, Object res) { String json; try { json = toJson(res); } catch (JsonProcessingException e) { // LOG.error("Exception happen during convert object " + res + " to // json.", e); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } HttpHeaders headers = new HttpHeaders(); MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8")); headers.setContentType(mediaType); return new ResponseEntity<>(json, headers, httpStatus); } public static ResponseEntity<String> toJsonResponse(Object res) { return toJsonResponse(HttpStatus.OK, res); } public static ResponseEntity<String> toJsonResponse(HttpStatus httpStatus, ResultMessage resultMessage) { String json; try { json = toJson(resultMessage); } catch (JsonProcessingException e) { return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } HttpHeaders headers = new HttpHeaders(); MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8")); headers.setContentType(mediaType); return new ResponseEntity<>(json, headers, httpStatus); } }
C++
UTF-8
687
2.6875
3
[ "MIT" ]
permissive
#include "file/file.h" #include "util.h" #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> File::File(const std::string &path, bool readonly) { SYSCALL(fd_ = open(path.c_str(), readonly ? O_RDONLY : O_RDWR | O_CREAT, S_IRWXU)); SYSCALL(len_ = lseek(fd_, 0, SEEK_END)); SYSCALL(lseek(fd_, 0, SEEK_SET)); SYSCALL_F(addr_ = (char *)mmap(nullptr, len_, readonly ? PROT_READ : PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0), nullptr); } File::~File() { if (fd_ == -1) return; SYSCALL(munmap(addr_, len_)); close(fd_); }
PHP
UTF-8
981
2.84375
3
[ "MIT" ]
permissive
<?php namespace App\Api; use GuzzleHttp\Client; class AlphaVantage { private static $key; function __construct() { self::$key = env('ALPHAVANTAGE_KEY'); } public function daily($symbol, $dataType = 'csv', $outputSize = 'compact') { try { $client = new Client(); $uri = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' . $symbol . '&outputsize=' . $outputSize . '&datatype=' . $dataType . '&apikey=' . self::getKey(); $result = $client->get($uri); if ($dataType === "json") { return $result->getBody()->getContents(); } elseif ($dataType === "csv") { return $result->getBody()->getContents(); } else { return false; } } catch (\Exception $e) { return false; } } private static function getKey() { return self::$key; } } ?>
C++
UTF-8
4,497
2.640625
3
[]
no_license
/* Fireplace Starter (ESP8266) ESP8266 module that sends a remote control signal to start a fireplace Created 31 August 2018 By Ivan Sy Modified 6 September 2018 By Ivan Sy https://github.com/isyca/esp8266-fireplace-starter */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <RCSwitch.h> RCSwitch txSwitch = RCSwitch(); ESP8266WebServer webServer(80); const char* ssid = "SSID"; const char* password = "password"; const char* hostnameStr = "fireplace"; const int transmitPin = 0; const int externalLED = 2; const int pulseLength = 360; int lightStatusInt = 0; int heatStatusInt = 0; void turnFirePlaceON () { txSwitch.setRepeatTransmit(2); txSwitch.send("000001110011010111000101"); txSwitch.setRepeatTransmit(1); txSwitch.send("000001110011010111"); } void turnFirePlaceOFF () { txSwitch.setRepeatTransmit(3); txSwitch.send("000001110011010100110101"); txSwitch.setRepeatTransmit(1); txSwitch.send("00000"); } void handleRoot() { webServer.send(200, "application/json", "{\"result\": 0, \"msglevel\": \"ERROR\", \"msg\": \"Access ROOT nothing here\"}"); } void handleNotFound() { String message = "File Not Found = "; message += " URI: ["; message += webServer.uri(); message += "] Method: ["; message += (webServer.method() == HTTP_GET) ? "GET" : "POST"; message += "] Arguments: ["; message += webServer.args(); message += "]"; for (uint8_t i = 0; i < webServer.args(); i++) { message += "(" + webServer.argName(i) + ": " + webServer.arg(i) + ")"; } webServer.send(404, "application/json", "{\"result\": 0, \"msglevel\": \"ERROR\", \"msg\": \"" + message + "\"}"); } void blinkExternalLED(int count, int remainHigh) //count = 5 means approx 1 second delay { while (count > 0) { digitalWrite(externalLED, LOW); delay(100); digitalWrite(externalLED, HIGH); count = count -1; } if (remainHigh = 1) { digitalWrite(externalLED, HIGH); } else { digitalWrite(externalLED, LOW); } } void setup(void) { pinMode(externalLED, OUTPUT); WiFi.hostname(hostnameStr); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); txSwitch.enableTransmit(transmitPin); txSwitch.setPulseLength(pulseLength); while (WiFi.status() != WL_CONNECTED) { blinkExternalLED(25,0); // ~5 seconds delay } webServer.on("/", handleRoot); webServer.on("/on", []() { blinkExternalLED(2,1); turnFirePlaceON(); lightStatusInt = 1; webServer.send(200, "application/json", "{\"result\": 1, \"msglevel\": \"INFO\", \"msg\": \"Fireplace on\"}"); }); webServer.on("/off", []() { blinkExternalLED(2,1); turnFirePlaceOFF(); lightStatusInt = 0; heatStatusInt = 0; webServer.send(200, "application/json", "{\"result\": 1, \"msglevel\": \"INFO\", \"msg\": \"Fireplace off\"}"); }); webServer.on("/heaton", []() { // off, turn on, then turn on again blinkExternalLED(2,1); if (lightStatusInt = 1) { turnFirePlaceON(); heatStatusInt = 1; webServer.send(200, "application/json", "{\"result\": 1, \"msglevel\": \"INFO\", \"msg\": \"Fireplace Heat on\"}"); } else { if (heatStatusInt = 1) { turnFirePlaceOFF(); delay(500); } turnFirePlaceON(); delay(300); turnFirePlaceON(); heatStatusInt = 1; lightStatusInt = 1; webServer.send(200, "application/json", "{\"result\": 1, \"msglevel\": \"INFO\", \"msg\": \"Fireplace Heat on\"}"); } }); webServer.on("/heatoff", []() { // completely turn it off (same as /off) blinkExternalLED(2,1); turnFirePlaceOFF(); lightStatusInt = 0; heatStatusInt = 0; webServer.send(200, "application/json", "{\"result\": 1, \"msglevel\": \"INFO\", \"msg\": \"Fireplace Heat off\"}"); }); webServer.on("/status", []() { String statusStr = String("{\"light\": " + String(lightStatusInt) + ", \"heat\":" + String(heatStatusInt) + "}"); webServer.send(200, "application/json", statusStr); }); webServer.on("/homebridge-lightstatus", []() { webServer.send(200, "text/plain", String(lightStatusInt)); }); webServer.on("/homebridge-heatstatus", []() { webServer.send(200, "text/plain", String(heatStatusInt)); }); webServer.onNotFound(handleNotFound); webServer.begin(); MDNS.begin(hostnameStr); } void loop(void) { digitalWrite(externalLED, HIGH); webServer.handleClient(); }
Java
UTF-8
1,565
2.21875
2
[]
no_license
package com.mmj.user.manager.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.math.BigDecimal; import java.util.List; /** * @description: 会员优惠券 * @auther: KK * @date: 2019/7/11 */ @Data @ApiModel(value = "会员优惠券", description = "会员优惠券") public class MemberCouponDto { @ApiModelProperty(value = "是否会员日 true是 false否") private Boolean memberDay; @ApiModelProperty(value = "会员日可领的总共金额,单位:元") private BigDecimal totalCouponMoney; @ApiModelProperty(value = "距离下个会员日的毫秒数,前端需根据此值转换成距离下个会员日还有XX天XX小时XX分XX秒,倒计时结束后需要重新调用当前接口拉取最新数据,展示可领取多少,以及领取的按钮") private Long nextMemberDayIntervalMilliseconds; @ApiModelProperty(value = "优惠券信息") private List<CouponStat> couponInfoList; @Data @ApiModel(value = "用户优惠券信息") public static class CouponStat { @ApiModelProperty(value = "是否已领取,true:是;false:否") private Boolean hasCollected; @ApiModelProperty(value = "已领取的百分比") private String percent; @ApiModelProperty(value = "已领取的文字描述") private String percentStr; @ApiModelProperty(value = "优惠券信息") private CouponInfoDataDto couponInfo; } }
Markdown
UTF-8
3,896
3.1875
3
[ "Apache-2.0" ]
permissive
# InterviewTricks # Decided to store various types of exercises that fall under the following categories: 1. Trick questions that my friends tell me about. 2. Common algorithms, linkedlist,queue, tree, trie/suffix trees, sorts, searches 3. Numerical algorithms that commonly pop up as Trick interview questions 4. JDK8 Lambda examples 5. Many examples are documented and illustrated from the seminal , yet old , book "Concurrency In Practice". I have tried add JDK8 lambda expressions to the examples wherever possible. 6. Numerical Summing Trick Questions: Number pairs in a set that sum up to some n; Subset Sum Problem; etc etc CONTRIBUTE! CONTRIBUTE! Feel free to offer pull requests. If I like your request I will add it to my repository noting your contribution. I'll pay special attention to any Dynamic programming examples or any experimental Trie algorithms you might know about. ## NOTE: items marked with a ++ have been implemented but not transferred to the git repo yet. ## I will try to keep of list of what I have put here thus far: 1. find all pairs in an array that sum up to some input number. 2. fibanacci 3. factorial 4. various types of sorts and searches. 5. find all triplets in an array that sum up to some input number. 6. find the n largest elements at anypoint in time of an infinite flowing stream of elements. Approach O(log n) time complexity. 7. various ways to reverse a string other than the obvious way,i.e. in O(n/2) time complexity. 8. Look up a number in a list and return all repeated instances of that number. Attempt to approach O(logn) time complexity. 9. Create a home grown version of a simple linked list. 10. Implement both a stack and a queue using the home grown linked list in (9). 11. Implement both a stack and a queue using Java's linked list. 12. Implement a simple binary tree. 13. Implement the following tree traversals: inorder , preorder , postorder, breadthfirst depthfirst. 14. Use the visitor pattern to process the nodes in the traversals of ( 13 ). 15. Implement a binary search 16. Implement a quick sort algorithm 17. Bubble Sort 18. Merge Sort 19. Selection sort ++ 20. Experimental external merge sort ++ 21. anagram finder 22. palandrom finder 23. reverse string method in O(n/2) time complexity; includes recursive example O(n) complexity 24. remove duplicates from a sorted array: 1.Iterative , 2. Inplace , 3. Recursive 25. Linked list: insertAtHead, insertAtEnd, insertAtMiddle, insertSorted algorithms 26. Linked list: deleteNode algorithms 27. Find 2 elements that are maximum distance apart int array. (Test used at Amazon) 28. Find the missing number in an integer array. 29. Simulation: RestService call logging successful logins to database without waiting for response from DB 30. Various examples from "Mastering Lambdas, Java Programming in a Multicore World" 31. Simple Matrix Dot Multiplication example ( TODO -- multi-threaded approach to Matrix Multiplication ) 32. Simple Generic Trie Tree Implementation. Feel Free to contribute. 33. SUBSET SUM PROBLEM: Simple Dynamic Programming Implementation. 34. Find all pairs in a SORTED array that add up to some number. 35. MaxHeapify, heap sort , extract max 36. Examples of latches, CyclicBarrier, CountDown , Exchanger ## started adding a collection of examples of Design Patterns implemented in Java. thus far: 1. visitor pattern 2. factory method pattern 3. singleton pattern 4. strategy pattern 5. decorator pattern 6. command pattern 7. builder pattern 7. proxy pattern ## Misc Thread Related Exercises fully documented( will add soon ) 1. various chapters from Concurrency In Practice by Brian Goetz are examined in detail. 2. Added some jkd8 lambda features to some of the Concurrency In Practice examples. 3. Created an Experiment Concurrent Sorting Class. It uses Callbles, Queues, etc to sort large input. # and so on and so on.
JavaScript
UTF-8
2,510
2.640625
3
[]
no_license
const mysql = require('../database/mysql-libs') let mongo = require('./../database/mongo-libs'); /** * @function <b> signup </b> <br> * Service function for registering a new user * @param name email password lat long dob phoneNumber * @return {Object} result object from sql */ const signup = async (name, email, password, lat, long, dob, phoneNumber) => { let query = `insert into user (name,email,password,date_of_birth,current_latitude,current_longitude,phone_number) values (?,?,?,?,?,?,?)`; try { let result = await mysql.mysqlQuery(query, [name, email, password, dob, lat, long, phoneNumber]); return (result); } catch (err) { throw err; } } /** * @function <b> login </b> <br> * Service function for logging in a existing User * @param name id * @return {Object} result object from sql contains password (if successfull) */ const login = async (id) => { let query = `select password from user where user_id = ?`; try { let result = await mysql.mysqlQuery(query, [id]) if(!result){ throw new Error('No matching element found'); }else{ return result } } catch (err) { throw err } } /** * @function <b> createBooking </b> <br> * Service function for creating a booking for logged in User * @param name id * @return {Object} result object from sql contains password (if successfull) */ const createBooking = async(id,pickupLat,pickupLong,dropLat,dropLong)=>{ let query = `insert into bookings (user_id,pickup_latitude,pickup_longitude,drop_latitude,drop_longitude) values (?,?,?,?,?)` try { let result = await mysql.mysqlQuery(query,[id,pickupLat,pickupLong,dropLat,dropLong]) mongo.insertDataInMongo("created",{ booking_id:result.insertId, user_id:id, date : new Date() }) return result; } catch (err) { throw err } } const bookingHistory = async(userId)=>{ let query = `SELECT user.name AS 'USER NAME' ,user.user_id,driver.driver_id,driver.name AS 'Driver Name' ,bookings.booking_id FROM user inner JOIN bookings ON user.user_id = bookings.user_id INNER JOIN driver on bookings.driver_id = driver.driver_id where bookings.status = 2 AND user.user_id= ?;` try { let result = await mysql.mysqlQuery(query, [userId]) if(!result){ throw new Error('No matching element found'); }else{ return result } } catch (err) { throw err } } module.exports = { signup, login, createBooking, bookingHistory }
Python
UTF-8
1,073
3.71875
4
[]
no_license
# Abir Taheer # IntroCS pd1 # HW26 -- 000 000 111, v10 # 2019-03-18 def bondify(name: str) -> str: """ :param name: The name of the person :return: The name, bondified >>> bondify("Abir Taheer") 'Taheer, Abir Taheer' >>> bondify("banana man") 'man, banana man' >>> bondify("coolio") 'coolio, coolio' """ loc = name.find(" ") return name[loc + 1:] + ", " + name def replace(s: str, q: str, r: str) -> str: """ :param s: The original string :param q: The string to match in the original string :param r: The string to replace the match with :return: The new string with the replacement in place >>> replace("hello from the other side", "other", "banana") 'hello from the banana side' >>> replace("Winter is coming", "Winter", "Spring") 'Spring is coming' >>> replace("Dolphins run this planet", "dolphins", "mice") 'Dolphins run this planet' """ loc = s.find(q) if loc == -1: return s beginning = s[:loc] end = s[loc + len(q):] return beginning + r + end
Markdown
UTF-8
1,207
3.109375
3
[]
no_license
# FCP-Codes This is my final course project codes. It's a project that I have done in my undergraduate Electrical Engineering degree, where I classify face expressions using machine learning. -frames: This notebook processes videos in a given directory. First it extract the frames of the video (29.97 frames per second) then it creates 2 folders, called FramesSemLandmark and FramesComLandmark. In the first one it saves the raw frames. In the second one it saves the frames with the 67 landmakrs (points of interest) in the face. After processing the video, it gets all the landmarks positions in the face, saving them in a csv file in the order (x1,y1,x2,y2,...) where (x1,y1) represent the landmarks coordenate in the first frame. After this step, it calculates the mean and the variance of all the landmarks, and label them from 1 to 22 according with the expressions itself, saving it in the FinalData.csv. -Training: This notebook processes the DinalData.csv. It creates some classifier (SVM with linear kernel) and after that it trains this classifier and test it in the test set created in the train_test_split function with 30% of the data in the test set. More classifiers will be added later.
Java
UTF-8
401
2.90625
3
[]
no_license
package org.okarmus.game.utils.comparator; import java.util.Comparator; import org.okarmus.game.model.card.Card; public class CardComparator implements Comparator<Card>{ @Override public int compare(Card c1, Card c2) { int colorCompare = c1.getColor().getPriority() - c2.getColor().getPriority(); if (colorCompare != 0) {return colorCompare;} return c1.getValue() - c2.getValue(); } }
C++
UHC
9,397
3
3
[]
no_license
#include <iostream> #include <fstream> #include <ctime> using namespace std; #include "Header.h" #include "Func.h" int Player::plnum = 1; // static ܺ ʱȭ int Player::turn = 1; // static ܺ ʱȭ extern int shopbalance = 1; // Ͽ ָ ֵ ϴ int main() { int n, num, c; string name; srand((unsigned int)time(NULL)); cout << " ӿ ȯմϴ.\n"; cout << "=============================================================\n"; cout << "̸ Է ּ : "; cin >> name; User user(name); User* puser = &user; // ü do { cout << "=============================================================\n"; cout << "1. 2. 3. 4.\n"; cout << "\n :"; cin >> n; if (n == 1) { do { cout << "ϴ ÷̾ Է ּ(ִ 7) : "; cin >> num; } while (num > 7); cout << "=============================================================\n"; Com* com = new Com[num]; // ü 迭 for (int i = 0; i < num; i++) com[i] = Com(i); // ڿ Է¹ ŭ ǻ ÷̾ ü Player::plnum += num; int* tmp = new int[Player::plnum]; // Ȯ ϴ 迭 for (int k = 0; k < Player::plnum; k++) { tmp[k] = 1; // ù ° 迭 1 ʱȭ } do { cout << Player::turn << "° ۵Ǿϴ. ( ÷̾ : " << Player::plnum << ")\n"; cout << "1. 2. 3. \n"; cout << " : "; cin >> c; if (c == 1) // { if (user.unit[0].name == "") { cout << " ϴ.\n"; } else { UnitData e; // ü for (int t = 0; t < num; t++) // ǻ ÷̾ { if (com[t].printstatus() != 0) com[t].buy(e); } if (user.printstatus() == 0) // Ǿ matchnum ٱ ڷ ʵ { user.setmatchnum(10); } else user.setmatchnum(0); int h = Player::plnum - 1; int* p = new int[h]; // ǻ ÷̾ ŭ 迭 ( ) Matchnum(p, h); // 迭 p 1~÷̾ ڸ ְ int m = 0; for (int o = 0; o < num; o++) // ǻ ÷̾ ÷ ϸ ο { if (com[o].printstatus() != 0) { com[o].setmatchnum(p[m]); m++; } } cout << "=============================================================\n"; cout << " Ī \n"; cout << "\n"; matchingresult(user, com, num); // Ī ǥϴ Լ ȣ cout << "=============================================================\n"; // ÷̾ VS ǻ ÷̾ int j = find(com); if (battle(user, com[j]) == 0) // ڰ й { user.setlife(2, com[j].unitsum(1)); com[j].setmoney(1, user.unitsum(2)); cout << " Ʈ : " << user.printlife() << "\n"; if (user.printlife() <= 0) { user.out(); goto ending; } } else // ڰ ¸ { com[j].setlife(2, user.unitsum(1)); user.setmoney(1, com[j].unitsum(2)); cout << " Ʈ : " << com[j].printlife() << "\n"; if (com[j].printlife() <= 0) { com[j].out(); cout << com[j].printname() << "Ż!\n"; Player::plnum--; if (Player::plnum == 1) goto ending; } } // ǻ ÷̾ VS ǻ ÷̾ if (h+1 != 2) { int k = Player::plnum - 2; int* u = new int[k]; commatch(u, com, num); // ǻ ÷̾ matchnum if (Player::plnum % 2 == 0) // ǻ ÷̾ Ȧ (ü ÷̾ ¦ ) { for (int i = 0; i < k; i += 2) { int t = u[i], y = u[i + 1]; if (combattle(com[t], com[y]) == 1) // տ ġ ǻ ÷̾ ¸ { com[y].setlife(2, com[t].unitsum(1)); com[t].setmoney(1, com[y].unitsum(2)); if (com[y].printlife() <= 0) { com[y].out(); cout << com[y].printname() << "Ż!\n"; Player::plnum--; } } else // ڿ ġ ǻ ÷̾ ¸ { com[t].setlife(2, com[y].unitsum(1)); com[y].setmoney(1, com[t].unitsum(2)); if (com[t].printlife() <= 0) { com[t].out(); cout << com[t].printname() << "Ż!\n"; Player::plnum--; } } } } else // ǻ ÷̾ ¦ (ü ÷̾ Ȧ) { if (k == 1) // ü ÷̾ 3̸ 迭 u[1] ǹǷ ÷̾ ٸ ó { int t = u[k - 1], y = 1; for (int r = 0; r < num; r++) { if (com[r].printmatchnum() == 1) // matchnum ÷̾ ã ⸦ Ī { y = r; break; } } if (combattle(com[t], com[y]) == 1) // տ ġ ǻ ÷̾ ¸ { com[t].setmoney(1, com[y].unitsum(2)); if (com[y].printlife() <= 0) { com[y].out(); cout << com[y].printname() << "Ż!\n"; Player::plnum--; } } else { com[t].setlife(2, com[y].unitsum(1)); if (com[t].printlife() <= 0) { com[t].out(); cout << com[t].printname() << "Ż!\n"; Player::plnum--; } } } else { for (int i = 0; i < k - 1; i += 2) { int t = u[i], y = u[i + 1]; if (combattle(com[t], com[y]) == 1) // տ ġ ǻ ÷̾ ¸ { com[y].setlife(2, com[t].unitsum(1)); com[t].setmoney(1, com[y].unitsum(2)); if (com[y].printlife() <= 0) { com[y].out(); cout << com[y].printname() << "Ż!\n"; Player::plnum--; } } else // ڿ ġ ǻ ÷̾ ¸ { com[t].setlife(2, com[y].unitsum(1)); com[y].setmoney(1, com[y].unitsum(2)); if (com[t].printlife() <= 0) { com[t].out(); cout << com[t].printname() << "Ż!\n"; Player::plnum--; } } } int t = u[k - 1], y = u[k - 2]; // ÷̾ ε ÷̾ if (combattle(com[t], com[y]) == 1) // տ ġ ǻ ÷̾ ¸ { com[t].setmoney(1, com[y].unitsum(2)); } else { com[t].setlife(2, com[y].unitsum(1)); if (com[t].printlife() <= 0) { com[t].out(); cout << com[t].printname() << "Ż!\n"; Player::plnum--; } } } } } rankinit(puser, com, num); ranking(puser, com, num); battleresult(user, com, tmp, num); cout << "=============================================================\n"; Player::turn++; delete[]p; } } else if (c == 2) // { user.buy(UnitShop(user)); // ϰ UnitData Լ ҷ ϵ(ڰ ) user.buy() } else if (c == 3) // ( ٲٱ, Ǹ, <-> ȯ) { MyTeamInfo(puser); } } while (Player::plnum != 1); // ÷̾ 1 ݺ ending: cout << Player::turn << " "; if (user.printstatus() == 1) { cout << user.printname() << "() Ͽϴ. մϴ!\n"; } else { cout << "Żϼ̽ϴ.\n"; } delete[] com; // Ҵ ǻ ÷̾ 迭 ݳ delete[] tmp; cout << " \n"; } if (n == 2) { manual(); // ؽƮ ̳ʸ } if (n == 3) { printdatabase(); // ϴ Լ ȣ } } while (n != 4); }
JavaScript
UTF-8
1,926
3.203125
3
[]
no_license
console.log("================================"); console.log("Welcome to Your Sandbox Console."); console.log("================================"); console.log("Click on http://jquery.com to head to the docs"); // Q: How do you make a DOM element a jQuery object? // A: Target it with a css selector and then just wrap it in cash, homie. // Example: $("#title") // Q: How do you create a NEW jQuery object you can later append to the DOM? // A: Provide the opening tag of the type of element you want to create and then wrap it in cash // Example: var newDiv = $("<div>"); //1. $("h1").text("The Fart Store"); //2. $("h1").addClass("classy"); //more specific //$(#title).addClass("classy"); //3. Change the h1's font size to 4ems $("h1").css({ "font-size": "4em" }); //4. Target that first paragraph tag and change it's HTML content to "We've got fun AND games - Axel Rose" $("p").first().text("We've got fun AND games - Axel Rose") //.eq() is better than .first //5. Change the h2's text from "Sandbox Features:" to "Manifesto" $("h2").text("Manifesto") var $h2 = $("h2").text("Manifesto"); //6. Remove the entire unordered list of features from the DOM $("ul").remove(); //7. Beneath the 'Manifesto' h2, append a paragraph that reads "No judgement." (Look into the .after() method) $("h2").after('<p>No Judgement</p>'); //8. Create a button element with text "Sample The Product" and an id of "sample-button". Append it to the DOM's <body> element var $newButton = $("<button>"); $newButton.text("Sample the Product"); $newButton.attr({ id: "sample-button", role: "funzies" }); var $body = $("body"); $("body").append($newButton); function emitFart() { var $newDiv = $("<div>"); $newDiv.addClass("product"); $newDiv.css("display", "none"); $body.append($newDiv); setTimeout(function() { $newDiv.fadeIn(); }, 1500); setTimeout(function() { $newDiv.fadeOut('slow'); }, 5000); }
Java
UTF-8
376
2.5625
3
[ "MIT" ]
permissive
package PackageUsers; import java.io.Serializable; /** * Interface do User */ public interface IUser extends Comparable<IUser>, Serializable{ public String getUserID(); public String getName(); public IUser clone(); /** * Calcula o hash value do User * @return hash value do User */ @Override public int hashCode(); }
Python
UTF-8
4,717
3.109375
3
[ "MIT" ]
permissive
# !/usr/bin/env python # coding: utf-8 """ Converts a tree structure in to a valid JSON. This module works with both Python 2 and 3. """ __version__ = '0.1' version = __version__ import logging import nltk import json from nltk.chunk.regexp import * LOG = logging.getLogger("treetojson") def set_debug(debug=True, filename='dicttoxml.log'): if debug: import datetime print('Debug mode is on. Events are logged at: %s' % (filename)) logging.basicConfig(filename=filename, level=logging.INFO) LOG.info('\nLogging session starts: %s' % ( str(datetime.datetime.today())) ) else: logging.basicConfig(level=logging.WARNING) print('Debug mode is off.') def __depict_tree(data=None, words=None, label=None, grammar=None): """Converts the provided list into a tree structure Arguments: - data contains a list which should look like, [('I', 'NN'), ('am', 'NN'), ('a', 'NN'), ('good', 'VB'), ('boy', 'NN')] - words contains a split sentence, a sentence can be splitted and sent as an argument, ['I', 'am', 'a', 'good', 'boy'] - label contains the specific label of the words given. ['NN', 'NN', 'NN', 'NN', 'VB'] - grammar is optional, it accepts NLTK regexp grammar. """ LOG.info('Inside __depict_tree()') if (words is None or label is None) and data is None: raise ValueError("Words and labels or data containing list should be provided.") if words and label: if len(words) != len(label): raise ValueError("Lengths of words and labels should be equal") if words is None and label is None and data: sentence = data else: sentence = [] for index in xrange(len(words)): sentence.append((words[index], label[index])) if grammar is None: parser = RegexpParser(''' ''') else: parser = RegexpParser(grammar) return parser.parse(sentence) def __create_inner_json_subtree(inner_json_value): LOG.info('Inside __create_inner_json_subtree') inner_json = "[" for index in xrange(len(inner_json_value)): if index == len(inner_json_value) - 1: inner_json += "{\"" + inner_json_value[index][1] + "\":\"" + inner_json_value[index][0] + "\"}" else: inner_json += "{\"" + inner_json_value[index][1] + "\":\"" + inner_json_value[index][0] + "\"}," inner_json += "]" return inner_json def __create_inner_json(tree, index, inner_json_value): LOG.info('Inside __create_inner_json') if index == len(tree) + 1: inner_json = "{\"" + inner_json_value[1] + "\":\"" + inner_json_value[0] + "\"}" else: inner_json = "{\"" + inner_json_value[1] + "\":\"" + inner_json_value[0] + "\"}," return inner_json def __create_outer_json(tree, subtree, index, inner_json): LOG.info('Inside __create_outer_json') if index == len(tree) + 1: outer_json = "{\"" + subtree.label() + "\":" + inner_json + "}" else: outer_json = "{\"" + subtree.label() + "\":" + inner_json + "}," return outer_json def __traverse_tree(tree): LOG.info('Inside __traverse_tree') json_value = "" index = 1 for subtree in tree: index += 1 if type(subtree) == nltk.tree.Tree: if subtree.height() > 2: if index == len(tree) + 1: outer_json = "{\"" + subtree.label() + "\": [" + __traverse_tree(subtree) + "]}" else: outer_json = "{\"" + subtree.label() + "\": [" + __traverse_tree(subtree) + "]}," else: inner_json_value = json.loads(json.dumps(subtree, ensure_ascii=False)) inner_json = __create_inner_json_subtree(inner_json_value) outer_json = __create_outer_json(tree, subtree, index, inner_json) else: inner_json_value = json.loads(json.dumps(subtree, ensure_ascii=False)) outer_json = __create_inner_json(tree, index, inner_json_value) json_value += outer_json return json_value def get_json(data=None, words=None, label=None, grammar=None): """Provides a JSON output for a given list Arguments: - data contains a list which should look like, [('I', 'NN'), ('am', 'NN'), ('a', 'NN'), ('good', 'VB'), ('boy', 'NN')] - grammar is optional, it accepts NLTK regexp grammar. """ LOG.info('Inside get_json()') tree = __depict_tree(data=data, words=words, label=label, grammar=grammar) json_value = __traverse_tree(tree) return json.loads("{\"SENTENCE\":[" + json_value + "]}")
C++
UTF-8
455
3.25
3
[]
no_license
#include <cstdlib> #include <iostream> #include <cmath> using namespace std; int main(int argc, char** argv) { double R, a, perumetr, square; cout<<"Введіть радіус описаного кола навколо 17-кутника: "; cin>>R; a=2*R*sin(3.14/17); perumetr=17*a; cout<<"Периметр = "<<perumetr<<endl; square=(17/2)*pow(R, 2)*sin(2*3.14/17); cout<<"Площа = "<<square; return 0; }
JavaScript
UTF-8
265
3.703125
4
[]
no_license
let nthNumber = 10; const sum_of_multiples = function(nthNumber){ let sum = 0; for(let index=1; index < nthNumber; index++){ if(index % 3 == 0 || index % 5 == 0){ sum = sum + index; } } return sum; } console.log(sum_of_multiples(nthNumber));
Python
UTF-8
1,275
3.65625
4
[]
no_license
class BinaryNode: def __init__(self, e: chr): self.element = e self.left = None self.right = None def read_preorder(r: BinaryNode): global index if index < l - 1: if s[index + 1] == '#': if index < l - 2: if s[index + 2] == '#': index += 2 return else: r.right = BinaryNode(s[index + 2]) index += 2 read_preorder(r.right) else: r.left = BinaryNode(s[index + 1]) index += 1 read_preorder(r.left) if index < l - 1: if s[index + 1] == '#': index += 1 return else: r.right = BinaryNode(s[index + 1]) index += 1 read_preorder(r.right) return def inorder_traversal(r: BinaryNode): global inorder if r.left is not None: inorder_traversal(r.left) inorder += r.element + ' ' if r.right is not None: inorder_traversal(r.right) s = input() l = len(s) index = 0 root = BinaryNode(s[0]) read_preorder(root) inorder = '' inorder_traversal(root) print(inorder, end='')
JavaScript
UTF-8
506
3.8125
4
[]
no_license
function talk (sound) { console.log(this) console.log(this.sound) } let animal ={ talk } let cat = { sound: 'Meow' } let dog ={ sound: 'Woofering' } let prarieDog = { howl: function(){ console.log(this.sound.toUpperCase()) } } // cat.talk() Object.setPrototypeOf(cat, animal) Object.setPrototypeOf(dog, animal) cat.talk() dog.talk() animal.talk=function(){ console.log('A am an animal that says ' + this.sound + '.') } Object.setPrototypeOf(prarieDog, dog) prarieDog.howl() cat.talk()
JavaScript
UTF-8
733
2.5625
3
[]
no_license
const { assert } = require('chai'); const { urlsForUser } = require('../helpers.js'); const urlDatabase = { "lksr5j": { longURL: 'http://www.facebook.com', userID: 'userRandomID' } }; describe('urlsForUser', function() { it('should return user specific URLs', function() { const userURLs = urlsForUser('userRandomID', urlDatabase); const expectedOutput = "lksr5j"; const firstKey = Object.keys(userURLs)[0]; assert.equal(expectedOutput, firstKey); }); it('should return undfined with an invalid userID', function() { const userURLs = urlsForUser('', urlDatabase); const expectedOutput = undefined; const firstKey = Object.keys(userURLs)[0]; assert.equal(expectedOutput, firstKey); }); });
PHP
UTF-8
729
2.578125
3
[]
no_license
<?php //process client request (via URL) include ("function.php"); header("Content-Type:application/json"); if (!empty($_GET['name'])) { $name=$_GET['name']; $price=get_price($name); if(empty($price)){ //book not found deliver_response(200,"book not found", NULL); } else{ //respond book price deliver_response(200,"book found",$price); } } else{ //throw invalid request deliver_response(400, "Invalid Requst",NULL); } function deliver_response($status,$status_message, $data){ header("HTTP/1.1 $status $status_message $data"); $response['status']=$status; $response['status_message']=$status_message; $response['data']=$data; $json_response=json_encode($response); echo $json_response; } ?>
Java
UTF-8
665
3
3
[]
no_license
package lists.model; import java.util.ArrayList; import javax.swing.JOptionPane; public class ArrayListController { private ArrayList<String> firstWords; public ArrayListController() //default constructor { firstWords = new ArrayList<String>(); } public void start() { firstWords.add("asdfjkl;sadjkfjl"); firstWords.add("babababbabnadadaabbab"); firstWords.add("( ͡° ͜ʖ ͡°)"); showList(); } private void showList() { for(int spot =0; spot < firstWords.size();spot++) JOptionPane.showMessageDialog(null, firstWords.get(spot)+ "is at spot#" + spot); JOptionPane.showMessageDialog(null, "( ͡° ͜ʖ ͡°) hey lenny!"); } }
JavaScript
UTF-8
1,368
3.3125
3
[]
no_license
function mostrar() { var letra,num,par=0,impar=0,respuesta,cero=0,pos=0,neg=0,prom=0; while(respuesta!="no"){ letra=prompt("Ingrese una letra"); console.log(letra); num=parseInt(prompt("Ingrese un numero entre -100 y 100: ")) while(isNaN(num) || num<-100 || num>100){ num=parseInt(prompt("Error! Ingrese un numero entre -100 y 100")); } console.log(num); if(num%2==0){ par++ }else{ if(num%2!=0){ impar++ } } if(num>0){ prom++ pos=pos+num }else{ if(num<0){ neg=neg+num }else{ cero++ } } respuesta=prompt("¿Ingresar mas datos? (si/no)") while(respuesta!="si" && respuesta!="no"){ respuesta=prompt("Error! Desea ingresar mas datos? (si/no)") } } document.write("Cantidad de numeros pares: "+par+"<br>Cantidad de numeros impares: "+impar+"<br>Cantidad de ceros: "+cero+"<br>Promedio de positivos: "+pos/prom+"<br>Suma de negativos: "+neg); }
C
UTF-8
17,833
3.28125
3
[]
no_license
/** * \file fonctionGrille.c * \brief Contient toutes les fonctions utiles à gestion la grille de jeu * \author Asmae Bouhandi * \version 1 * \date 01 avril 2020 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include <ctype.h> #include "../lib/commun.h" #include "../lib/fonctionGrille.h" #define NORD 0 #define OUEST 1 #define EST 2 #define SUD 3 // #define NORDOUEST 4 // #define NORDEST 5 // #define SUDOUEST 6 // #define SUDEST 7 //int N = 8 ; /** * \fn void initGrille(char matrice[N_TEST][N_TEST]) * \brief Remplit une matrice du caractère avec le caractère '.' * \param char matrice[N_TEST][N_TEST] * \return rien */ void initGrille(char matrice[N_TEST][N_TEST]){ int i, j ; for(i=0; i<N_TEST; i++) { for(j=0; j<N_TEST; j++) { matrice[i][j] = '.' ; } } } /** * \fn void affGrille(char matrice[N_TEST][N_TEST]) * \brief Affiche la matrice passé en paramètre. * \param char matrice[N_TEST][N_TEST] * \return rien */ void affGrille(char matrice[N_TEST][N_TEST]){ int i, j ; for(i=0; i<N_TEST; i++) { for(j=0; j<N_TEST; j++) { printf(" %c ", matrice[i][j]) ; } printf("\n"); } } /** * \fn int nombreAleatoire(int limMax) * \brief Renvoie un nombre entre 0 et limMax-1 * \param int limMax * \return Valeur entière entre 0 et limMas-1 */ int nombreAleatoire(int limMax){ return (rand() % limMax); } /** * \fn void voidToChar(char matrice[N_TEST][N_TEST]) * \brief Remplace chaque caractère '.' d'une matrice de caractère par une lettre minuscule aléatoire * \param char matrice[N_TEST][N_TEST] * \return rien */ void voidToChar(char matrice[N_TEST][N_TEST]) { //printf("--> RemplirCaseMatVide <--\n"); int i, j ; srand((unsigned)time(NULL)); for(i=0 ; i<N_TEST ; i++) { for(j=0 ; j<N_TEST ; j++) { if(matrice[i][j] == '.') { matrice[i][j] = 'A'+rand()%26; } } } } /** * \fn int tirerMot(char * nomFichier, char * motTire) * \brief affecte à un pointeur sur char un mot du fichier * nomFichier * \param char * nomFichier, char * motTire * \return 1 si un problème survient, 0 sinon */ int TirerMot(char *nomFichier, char *motTire){ FILE * fichier = NULL ; int nbrMots = 0, numMot = 0, charLu ; int indiceMot ; fichier = fopen(nomFichier, "r") ; /*Vérifie si le fichier est ouvrable*/ if (fichier == NULL){ printf("Problème à l'ouverture du fichier\n"); return 1; } /* Comptage du nombre de mot dans le fichier, Stocké dans nbrMots */ do{ charLu = fgetc(fichier); if (charLu == '\n') { nbrMots++; } } while(charLu != EOF); //printf("Il y a %i mots dans la bibliothèque\n", nbrMots); numMot = nombreAleatoire(nbrMots); indiceMot=numMot; rewind(fichier); while (numMot > 0){ charLu = fgetc(fichier); if (charLu == '\n'){ numMot--; } } fgets(motTire, 100, fichier); //printf("Le mot numéro %i est %s", indiceMot+1, motTire); fclose(fichier); return indiceMot; } /** * \fn int RechercheTableau(int *tab, int n) * \brief Recherche l'entier n dans le tableau tab * \param int *tab, int n * \return 0 ou 1 */ int RechercheTableau(int *tab, int n) { int N = 30 ; for(int i = 0 ; i < N ; i ++) { if (tab[i] == n) { return 1 ; } } return 0 ; } /** * \fn void ajoutListe(mot_tire liste_mot[N_TEST+1], char *mot) * \brief ajoute à la liste un mot * \param mot_tire liste_mot[N_TEST+1], char *mot * \return rien */ void ajoutListe(mot_tire liste_mot[N_TEST+1], char *mot) { int i = 0 ; while(liste_mot[i].mot == "\0") { i++ ; } strcpy(liste_mot[i].mot, mot) ; } /** * \fn void upper_string(char *s) * \brief Fait passer un chaine de caractère de minuscule vers majuscule * \param char *s * \return rien */ void upper_string(char *s) { int c = 0; while (s[c] != '\0') { if (s[c] >= 'a' && s[c] <= 'z') { s[c] = s[c] - 32; } c++; } } /** * \fn void PlacerMot(char matrix[N_TEST][N_TEST]) * \brief place un mot dans la grille * \param char matrix[N_TEST][N_TEST] * \return rien */ void PlacerMot(char matrix[N_TEST][N_TEST], char *themefile, mot_tire liste_mot[N_TEST+1]) { //printf("--> PlacerMot <--\n"); srand(time(NULL)) ; int k = 0 ; int a = 0 ; //int essai = 0 ; int compteur = 0 ; int random_i, random_j, random_choix = 0 ; char word[50] ;//="fjlskdjfldslqfj"; int lenght = 0 ; int deja_utilises[30] = {0} ; //affGrille(matrix) ; while(compteur < N_TEST) { tirer_mot: //printf("Word n°%d\n", compteur) ; do{ a = TirerMot(themefile, word); lenght = strlen(word)-1; }while((lenght>N_TEST) || RechercheTableau(deja_utilises, a)); // if(RechercheTableau(deja_utilises, N, a)) // { // printf("Ce mot est déjà utilisé!\n"); // } //printf("Random numbers\n"); random_i = rand() % N_TEST; random_j = rand() % N_TEST; random_choix = (rand() % 4); //random_choix = 3 ; switch(random_choix){ // case NORDOUEST: // while(random_i-lenght<0||random_j-lenght<0) // { // random_i = rand() % N; // random_j = rand() % N; // } // printf("NORDOUEST (%i - %i)!\n", random_i, random_j); // while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) // { // matrix[random_i][random_j]= word[k] ; // random_i-- ; // random_j-- ; // k++ ; // compteur++; // } // break; // case NORDEST: // while(random_i+lenght<N||random_j-lenght>0){ // random_i = rand() % N; // random_j = rand() % N; // } // printf("NORDEST (%i - %i)!\n", random_i, random_j); // while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) // { // matrix[random_i][random_j]= word[k] ; // random_i++ ; // random_j-- ; // k ++ ; // compteur++; // } // break; // case SUDOUEST: // while(random_i-lenght<0||random_j+lenght>N) // { // random_i = rand() % N; // random_j = rand() % N; // } // printf("SUDOUEST (%i - %i)!\n", random_i, random_j); // while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) // { // matrix[random_i][random_j]= word[k] ; // random_i-- ; // random_j++ ; // k ++ ; // compteur++; // } // break; // case SUDEST: // while(random_i+lenght>N || random_j+lenght>N) // { // random_i = rand() % N; // random_j = rand() % N; // } // printf("SUDEST (%i - %i)!\n", random_i, random_j); // while(k<lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) // { // matrix[random_i][random_j]= word[k] ; // random_i++ ; // random_j++ ; // k ++ ; // compteur++; // } // break; case NORD: //printf("NORD\n"); k = 0 ; while(random_i-lenght+1<0) { random_i = rand() % N_TEST; //printf("nord %i %i\n", random_i, random_j); } int i = random_i ; while(k < lenght) { if (matrix[i][random_j] == '.') { //printf("NORD (%i - %i)!\n", i, random_j); //printf("on avance !\n"); } else if (matrix[i][random_j] == toupper(word[k])) { //printf("NORD (%i - %i)!\n", i, random_j); //printf("on avance !\n"); } else { //printf("NORD (%i - %i)!\n", i, random_j); //printf("ça marche pas !\n"); goto tirer_mot ; } i -- ; k ++ ; } //printf("NORD (%i - %i)!\n", random_i, random_j); k = 0 ; liste_mot[compteur].x1 = random_i ; liste_mot[compteur].y1 = random_j ; while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) { //printf("word[%i] = %c\n", k, word[k]); if(isalpha(word[k])) { matrix[random_i][random_j]= toupper(word[k]) ; random_i-- ; } k ++ ; } //printf("compteur : %i | nord : %s\n", compteur, word); upper_string(word) ; strcpy(liste_mot[compteur].mot, word); liste_mot[compteur].x2 = random_i ; liste_mot[compteur].y2 = random_j ; //ajoutListe(liste_mot,word) ; compteur++; deja_utilises[compteur] = a ; break; case OUEST: //printf("OUEST\n"); k = 0 ; while(random_j-lenght<0) { //random_j = rand() % N_TEST; random_j++; //printf("ouest %i - %i\n", random_i, random_j); } int j = random_j ; while(k < lenght) { if (matrix[random_i][j] == '.') { //printf("OUEST (%i - %i)!\n", random_i, j); //printf("on avance !\n"); } else if (matrix[random_i][j] == toupper(word[k])) { //printf("OUEST (%i - %i)!\n", random_i, j); //printf("on avance !\n"); } else { //printf("OUEST (%i - %i)!\n", random_i, j); //printf("ça marche pas !\n"); goto tirer_mot ; } j -- ; k ++ ; } //printf("OUEST (%i - %i)!\n", random_i, random_j); k = 0 ; liste_mot[compteur].x1 = random_i ; liste_mot[compteur].y1 = random_j ; while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == word[k])) { if(isalpha(word[k])) { matrix[random_i][random_j]= toupper(word[k]) ; //printf("Dans OUEST\n"); //printf("word[%i] = %c\n", k, word[k]); //affGrille(matrix) ; //printf("\n"); random_j-- ; } k++ ; } //printf("compteur : %i | ouest : %s\n", compteur, word); upper_string(word) ; strcpy(liste_mot[compteur].mot, word); liste_mot[compteur].x2 = random_i ; liste_mot[compteur].y2 = random_j ; //ajoutListe(liste_mot,word) ; compteur++; deja_utilises[compteur] = a ; break; case EST: //printf("EST\n"); k = 0 ; while(random_j+lenght>N_TEST) { random_j = rand() % N_TEST; } j = random_j ; while(k < lenght) { if (matrix[random_i][j] == '.') { //printf("EST (%i - %i)!\n", random_i, j); //printf("on avance !\n"); } else if (matrix[random_i][j] == toupper(word[k])) { //printf("EST (%i - %i)!\n", random_i, j); //printf("on avance !\n"); } else { //printf("EST (%i - %i)!\n", random_i, j); //printf("ça marche pas !\n"); goto tirer_mot ; } j ++ ; k ++ ; } //printf("EST (%i - %i)!\n", random_i, random_j); k = 0 ; liste_mot[compteur].x1 = random_i ; liste_mot[compteur].y1 = random_j ; while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == toupper(word[k]))) { //printf("word[%i] = %c\n", k, word[k]); if(isalpha(word[k])) { matrix[random_i][random_j]= toupper(word[k]) ; random_j++ ; } k ++ ; } //printf("compteur : %i | est : %s\n", compteur, word); upper_string(word) ; strcpy(liste_mot[compteur].mot, word); liste_mot[compteur].x2 = random_i ; liste_mot[compteur].y2 = random_j ; //ajoutListe(liste_mot,word) ; compteur++; deja_utilises[compteur] = a ; break; case SUD: //printf("SUD\n"); k = 0 ; while(random_i+lenght>N_TEST) { random_i = rand() % N_TEST; } i = random_i ; while(k < lenght) { if (matrix[i][random_j]=='.') { //printf("SUD (%i - %i)!\n", i, random_j); //printf("on avance !\n"); } else if (matrix[i][random_j] == toupper(word[k])) { //printf("SUD (%i - %i)!\n", i, random_j); //printf("on avance !\n"); } else { //printf("SUD (%i - %i)!\n", i, random_j); //printf("ça marche pas !\n"); goto tirer_mot ; } i ++ ; k ++ ; } //printf("SUD (%i - %i)!\n", random_i, random_j); k = 0 ; liste_mot[compteur].x1 = random_i ; liste_mot[compteur].y1 = random_j ; while(k < lenght && (matrix[random_i][random_j]=='.' || matrix[random_i][random_j] == toupper(word[k]))) { //printf("word[%i] = %c\n", k, word[k]); if(isalpha(word[k])) { matrix[random_i][random_j]= toupper(word[k]) ; random_i++ ; } k ++ ; } //printf("compteur : %i | sud : %s\n", compteur, word); upper_string(word) ; strcpy(liste_mot[compteur].mot, word); liste_mot[compteur].x2 = random_i ; liste_mot[compteur].y2 = random_j ; //ajoutListe(liste_mot, word) ; compteur++; deja_utilises[compteur] = a ; break; default: break; } } // affGrille(matrix) ; }
Java
UTF-8
31,448
1.835938
2
[]
no_license
package com.android.settings.wifi.cmcc; import android.app.AlarmManager; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.ActionListener; import android.os.PowerManager; import android.os.SystemClock; import android.os.SystemProperties; import android.provider.Settings.Global; import android.provider.Settings.System; import android.util.Log; import android.view.View; import android.widget.CheckBox; import com.android.settings.MLog; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; public class SwitchToWifiUtils { private static volatile SwitchToWifiUtils mInstance; private Context mApplicationContext; private DisconnectedSSID mDisconnectedSSID; private int mHighestPriorityNetworkId = -1; private long mIgnoreTime; private MobileNework mMobileNework; private ScanAlarm mScanAlarm; private ScanEvent mScanEvent; private StateSaver mStateSaver; private ArrayList<ISwitchToWifi> mSwitchList; private UserDisconnectEvent mUserDisconnectEvent; private WifiConnection mWifiConnection; private WifiToWifi mWifiToWifi; private WifiWrapper mWifiWrapper; private interface ISwitchToWifi { boolean switchToWifi(); } private class AutoSwitch implements ISwitchToWifi { private AutoSwitch() { } public boolean switchToWifi() { return SwitchToWifiUtils.this.mWifiWrapper.canSwitchToWifi(true); } } public static class Config { public static boolean isCMCC() { return "CMCC".equalsIgnoreCase(SystemProperties.get("ro.config.operators", "")); } public static int getSwitchToWifiType(Context context) { return System.getInt(context.getContentResolver(), "wifi_connect_type", 0); } public static boolean shouldNotShowDialog(Context context) { if (1 != System.getInt(context.getContentResolver(), "not_show_wifi_to_wifi_pop", 0)) { return false; } Log.d("WifiUtils", "do not show wifi to wifi pop"); return true; } } private class DisconnectedSSID { private DisconnectedSSID() { } public void onWifiDisconnected() { SwitchToWifiUtils.this.mStateSaver.saveLong("ssid_disconnect_time", System.currentTimeMillis()); } public void onWifiConnected(String ssid) { SwitchToWifiUtils.this.mStateSaver.saveString("last_ssid", ssid); SwitchToWifiUtils.this.mStateSaver.saveLong("ssid_disconnect_time", 0); } public String getRecentDisconnectedSSID() { if (isRecentDisconnected()) { return SwitchToWifiUtils.this.mStateSaver.queryString("last_ssid", null); } return null; } public void setRecentDisconnectedSSID(String ssid) { SwitchToWifiUtils.this.mStateSaver.saveString("last_ssid", ssid); } private boolean isRecentDisconnected() { if (System.currentTimeMillis() - SwitchToWifiUtils.this.mStateSaver.queryLong("ssid_disconnect_time", 0) < 10000) { return true; } return false; } } private interface OnPromptResultListener { void onPromptResult(boolean z, boolean z2); } private class ManualSwitch implements ISwitchToWifi, OnPromptResultListener { private ManualSwitch() { } public boolean switchToWifi() { if (!isPromptAllowed()) { MLog.v("WifiUtils", "Manual prompt is not allowed!"); return false; } else if (Config.shouldNotShowDialog(SwitchToWifiUtils.this.mApplicationContext) || !SwitchToWifiUtils.this.mWifiWrapper.canSwitchToWifi(false)) { return false; } else { PromptDialog.show(SwitchToWifiUtils.this.mApplicationContext, SwitchToWifiUtils.this.mApplicationContext.getString(2131627527), this); return true; } } public void onPromptResult(boolean positive, boolean checked) { System.putInt(SwitchToWifiUtils.this.mApplicationContext.getContentResolver(), "not_show_wifi_to_wifi_pop", checked ? 1 : 0); if (positive) { Intent intent = new Intent("android.settings.WIFI_SETTINGS"); intent.setFlags(268435456); SwitchToWifiUtils.this.mApplicationContext.startActivity(intent); } else { SwitchToWifiUtils.this.mMobileNework.onCancelSwitchToWifi(); } updatePromptTime(3600000); } private boolean isPromptAllowed() { long now = System.currentTimeMillis(); long nextPromptTime = SwitchToWifiUtils.this.mStateSaver.queryLong("next_manual_prompt_time", 0); MLog.v("WifiUtils", "now = " + now + ", nextPromptTime = " + nextPromptTime); return now >= nextPromptTime; } private void updatePromptTime(long nextPromptInterval) { SwitchToWifiUtils.this.mStateSaver.saveLong("next_manual_prompt_time", System.currentTimeMillis() + nextPromptInterval); } } private class MobileNework { private AlarmManager mAlarmManager; private PendingIntent mPendingIntent; public MobileNework() { this.mAlarmManager = (AlarmManager) SwitchToWifiUtils.this.mApplicationContext.getSystemService("alarm"); Intent intent = new Intent("com.android.settings.action.ALARM_SWITCH_TO_MOBILE_NETWORK"); intent.setPackage("com.android.settings"); this.mPendingIntent = PendingIntent.getBroadcast(SwitchToWifiUtils.this.mApplicationContext, 0, intent, 0); } public void setAlarm(long delayMillis) { this.mAlarmManager.setExact(0, System.currentTimeMillis() + delayMillis, this.mPendingIntent); } public void cancelAlarm() { this.mAlarmManager.cancel(this.mPendingIntent); } private void setSwitchFlag(boolean flag) { SwitchToWifiUtils.this.mStateSaver.saveBoolean("needSwitchToMoblie", flag); } private boolean getSwitchFlag() { return SwitchToWifiUtils.this.mStateSaver.queryBoolean("needSwitchToMoblie", false).booleanValue(); } public void onWifiConnectionChanged(boolean isWifiConnectingOrConnected) { if (isWifiConnectingOrConnected) { setSwitchFlag(false); cancelAlarm(); switchToMobileNetwork(false); } else if (SwitchToWifiUtils.this.mWifiWrapper.isWifiEnabled()) { SwitchToWifiUtils.this.mWifiWrapper.startScan(); setSwitchFlag(true); if (Config.getSwitchToWifiType(SwitchToWifiUtils.this.mApplicationContext) == 0) { onWifiDisconnected(); } } else { cancelAlarm(); switchToMobileNetwork(true); } } public void onChooseWifiFirst() { MLog.v("WifiUtils", "onChooseWifiFirst()"); checkSwitchToMobileNetworkDelayed(20000); } public void onWifiConnecting() { MLog.v("WifiUtils", "onWifiConnecting()"); checkSwitchToMobileNetworkDelayed(10000); } public void onWifiConnected() { MLog.v("WifiUtils", "onWifiConnected()"); checkSwitchToMobileNetworkDelayed(0); } public void onWifiDisconnected() { MLog.v("WifiUtils", "onWifiDisconnected()"); checkSwitchToMobileNetworkDelayed(5000); } private void onCancelSwitchToWifi() { MLog.v("WifiUtils", "onCancelSwitchToWifi()"); checkSwitchToMobileNetworkDelayed(0); } private void checkSwitchToMobileNetworkDelayed(long delayMillis) { cancelAlarm(); if (getSwitchFlag()) { setAlarm(delayMillis); } } private void checkSwitchToMobileNetwork() { if (getSwitchFlag()) { switchToMobileNetwork(true); setSwitchFlag(false); } } private void switchToMobileNetwork(boolean switchToNetwork) { MLog.i("WifiUtils", "switch to mobile network: " + switchToNetwork); Intent intent = new Intent("android.intent.action.SWITCH_TO_MOBILE_NETWORK"); intent.putExtra("switch_state", switchToNetwork); SwitchToWifiUtils.this.mApplicationContext.sendBroadcast(intent, "huawei.android.permission.HW_SIGNATURE_OR_SYSTEM"); } } private class NotificationSwitch implements ISwitchToWifi, OnPromptResultListener { private NotificationSwitch() { } public boolean switchToWifi() { if (!isPromptAllowed()) { MLog.v("WifiUtils", "Query prompt is not allowed!"); return false; } else if (Config.shouldNotShowDialog(SwitchToWifiUtils.this.mApplicationContext) || !SwitchToWifiUtils.this.mWifiWrapper.canSwitchToWifi(false)) { return false; } else { String msg = createDialogMessage(); if (msg == null || msg.length() == 0) { return false; } PromptDialog.show(SwitchToWifiUtils.this.mApplicationContext, msg, this); return true; } } private String createDialogMessage() { String ssid = SwitchToWifiUtils.this.mWifiWrapper.getHighestPriorityApSsid(); MLog.i("WifiUtils", "highest priority ap ssid: " + ssid); if (ssid == null) { return null; } String message; if (((ConnectivityManager) SwitchToWifiUtils.this.mApplicationContext.getSystemService("connectivity")).getMobileDataEnabled()) { message = SwitchToWifiUtils.this.mApplicationContext.getString(2131627526, new Object[]{ssid}); } else { message = SwitchToWifiUtils.this.mApplicationContext.getString(2131627528, new Object[]{ssid}); } return message; } public void onPromptResult(boolean positive, boolean checked) { System.putInt(SwitchToWifiUtils.this.mApplicationContext.getContentResolver(), "not_show_wifi_to_wifi_pop", checked ? 1 : 0); if (positive) { trySwitchToWifi(); return; } updatePromptTime(3600000); SwitchToWifiUtils.this.mMobileNework.onCancelSwitchToWifi(); } private boolean isPromptAllowed() { long now = System.currentTimeMillis(); long nextPromptTime = SwitchToWifiUtils.this.mStateSaver.queryLong("next_query_prompt_time", 0); MLog.v("WifiUtils", "now = " + now + ", nextPromptTime = " + nextPromptTime); return now >= nextPromptTime; } private void trySwitchToWifi() { if (SwitchToWifiUtils.this.mWifiWrapper.canSwitchToWifi(false)) { SwitchToWifiUtils.this.onUserConnectEvent(); SwitchToWifiUtils.this.mWifiWrapper.switchToWifi(); } } private void updatePromptTime(long nextPromptInterval) { SwitchToWifiUtils.this.mStateSaver.saveLong("next_query_prompt_time", System.currentTimeMillis() + nextPromptInterval); } } private static class PromptDialog { private static boolean mIsShowing = false; private static boolean mPromptResult = false; private PromptDialog() { } public static void show(Context context, String message, final OnPromptResultListener listener) { if (!mIsShowing) { OnPromptResultListener promptResultListener = listener; mPromptResult = false; Builder builder = new Builder(context, 33947691); View view = View.inflate(builder.getContext(), 2130969286, null); builder.setView(view); final CheckBox cb = (CheckBox) view.findViewById(2131887597); builder.setMessage(message).setTitle(2131627350).setCancelable(false).setPositiveButton(2131625656, new OnClickListener() { public void onClick(DialogInterface dialog, int id) { PromptDialog.mPromptResult = true; } }).setNegativeButton(2131625657, null).setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface arg0) { listener.onPromptResult(PromptDialog.mPromptResult, cb.isChecked()); PromptDialog.mIsShowing = false; } }); Dialog dialog = builder.create(); dialog.getWindow().setType(2003); dialog.show(); mIsShowing = true; } } } private static class ScanAlarm { private AlarmManager mAlarmManager; private PendingIntent mPendingIntent; private PowerManager mPowerManager; private long mSupplicantScanIntervalMs; public ScanAlarm(Context context) { this.mAlarmManager = (AlarmManager) context.getSystemService("alarm"); this.mPowerManager = (PowerManager) context.getSystemService("power"); Intent intent = new Intent("com.android.settings.action.START_SCAN_WIFI"); intent.setPackage("com.android.settings"); this.mPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 268435456); int defaultScanInterval = context.getResources().getInteger(17694766); this.mSupplicantScanIntervalMs = Global.getLong(context.getContentResolver(), "wifi_supplicant_scan_interval_ms", (long) defaultScanInterval); MLog.i("WifiUtils", "Supplicant scan interval: " + this.mSupplicantScanIntervalMs + ", default scan interval: " + defaultScanInterval); } public void setAlarm() { MLog.v("WifiUtils", "set wifi scan alarm!"); this.mAlarmManager.set(3, SystemClock.elapsedRealtime() + (this.mPowerManager.isScreenOn() ? this.mSupplicantScanIntervalMs : 300000), this.mPendingIntent); } } private class ScanEvent { public ScanEvent() { SwitchToWifiUtils.this.mIgnoreTime = SwitchToWifiUtils.this.mStateSaver.queryLong("ignore_scan_event_time", 0); } public void onWifiConnecting() { setIgnoreScanEventTime(10000); } public void onWifiConnected() { setIgnoreScanEventTime(0); } public void onWifiDisconnected() { setIgnoreScanEventTime(10000); } public void onChooseWifiFirst() { setIgnoreScanEventTime(30000); } private void setIgnoreScanEventTime(long interval) { SwitchToWifiUtils.this.mIgnoreTime = System.currentTimeMillis() + interval; SwitchToWifiUtils.this.mStateSaver.saveLong("ignore_scan_event_time", SwitchToWifiUtils.this.mIgnoreTime); } private boolean shouldIgnoreScanEvent() { return System.currentTimeMillis() < SwitchToWifiUtils.this.mIgnoreTime; } } private static class Security { private Security() { } public static boolean isSameSecurity(WifiConfiguration config, ScanResult result) { boolean z = false; if (config == null || result == null) { return false; } if (getSecurity(config) == getSecurity(result)) { z = true; } return z; } private static int getSecurity(WifiConfiguration config) { if (config.allowedKeyManagement.get(1)) { return 2; } if (config.allowedKeyManagement.get(2) || config.allowedKeyManagement.get(3)) { return 3; } return config.wepKeys[0] != null ? 1 : 0; } private static int getSecurity(ScanResult result) { if (result.capabilities.contains("WEP")) { return 1; } if (result.capabilities.contains("PSK")) { return 2; } if (result.capabilities.contains("EAP")) { return 3; } return 0; } } private class StateSaver { private Editor mEditor = this.mSharedPreferences.edit(); private SharedPreferences mSharedPreferences; public StateSaver(Context context) { this.mSharedPreferences = context.getSharedPreferences("wifi_switch_pref", 0); } public void saveLong(String key, long value) { MLog.d("WifiUtils", "save state: key = " + key + ", value = " + value); this.mEditor.putLong(key, value); this.mEditor.apply(); } public long queryLong(String key, long defaultValue) { return this.mSharedPreferences.getLong(key, defaultValue); } public void saveString(String key, String value) { MLog.d("WifiUtils", "save state: key = " + key + ", value = " + value); this.mEditor.putString(key, value); this.mEditor.apply(); } public String queryString(String key, String defaultValue) { return this.mSharedPreferences.getString(key, defaultValue); } public void saveBoolean(String key, boolean value) { this.mEditor.putBoolean(key, value); this.mEditor.apply(); } public Boolean queryBoolean(String key, boolean defaultValue) { return Boolean.valueOf(this.mSharedPreferences.getBoolean(key, defaultValue)); } } private class UserDisconnectEvent { private long mIgnoreDisconnectTime; public UserDisconnectEvent() { this.mIgnoreDisconnectTime = SwitchToWifiUtils.this.mStateSaver.queryLong("ignore_user_disconnect_time", 0); } public void onUserDisconnect() { setIgnoreTime(5000); } public void onWifiConnected() { setIgnoreTime(0); } private void setIgnoreTime(long interval) { this.mIgnoreDisconnectTime = System.currentTimeMillis() + interval; SwitchToWifiUtils.this.mStateSaver.saveLong("ignore_user_disconnect_time", this.mIgnoreDisconnectTime); } private boolean isUserDisconnectWifi() { return System.currentTimeMillis() < this.mIgnoreDisconnectTime; } } private final class WifiConnection { private AtomicBoolean mConnected = new AtomicBoolean(false); public WifiConnection(boolean isConnected) { update(isConnected); } public boolean update(boolean isConnected) { if (isConnected() == isConnected) { return false; } this.mConnected.set(isConnected); return true; } private boolean isConnected() { return this.mConnected.get(); } } private class WifiToWifi implements ISwitchToWifi, OnPromptResultListener { private WifiToWifi() { } public boolean switchToWifi() { if (Config.shouldNotShowDialog(SwitchToWifiUtils.this.mApplicationContext) || Config.getSwitchToWifiType(SwitchToWifiUtils.this.mApplicationContext) == 0 || SwitchToWifiUtils.this.mUserDisconnectEvent.isUserDisconnectWifi() || !SwitchToWifiUtils.this.mWifiWrapper.canSwitchToWifi(false)) { return false; } PromptDialog.show(SwitchToWifiUtils.this.mApplicationContext, SwitchToWifiUtils.this.mApplicationContext.getString(2131627529), this); SwitchToWifiUtils.this.mScanEvent.onChooseWifiFirst(); SwitchToWifiUtils.this.mMobileNework.onChooseWifiFirst(); return true; } public void onPromptResult(boolean positive, boolean checked) { System.putInt(SwitchToWifiUtils.this.mApplicationContext.getContentResolver(), "not_show_wifi_to_wifi_pop", checked ? 1 : 0); if (positive) { Intent intent = new Intent("android.settings.WIFI_SETTINGS"); intent.setFlags(268435456); SwitchToWifiUtils.this.mApplicationContext.startActivity(intent); SwitchToWifiUtils.this.mScanEvent.onChooseWifiFirst(); SwitchToWifiUtils.this.mMobileNework.onChooseWifiFirst(); return; } SwitchToWifiUtils.this.mMobileNework.onCancelSwitchToWifi(); } } private class WifiWrapper { private ActionListener mConnectListener = new ActionListener() { public void onSuccess() { } public void onFailure(int reason) { } }; private WifiManager mWifiManager; public WifiWrapper() { this.mWifiManager = (WifiManager) SwitchToWifiUtils.this.mApplicationContext.getSystemService("wifi"); } public boolean isWifiEnabled() { return this.mWifiManager.isWifiEnabled(); } public boolean startScan() { return this.mWifiManager.startScan(); } public boolean canSwitchToWifi(boolean includeRecentDisconnectedSSID) { boolean z; if (!this.mWifiManager.isWifiEnabled() || isWiFiConnected()) { z = false; } else { z = isWifiApAvailable(includeRecentDisconnectedSSID); } MLog.v("WifiUtils", "Can switch to wifi:" + z); return z; } public void switchToWifi() { if (SwitchToWifiUtils.this.mHighestPriorityNetworkId != -1) { this.mWifiManager.connect(SwitchToWifiUtils.this.mHighestPriorityNetworkId, this.mConnectListener); SwitchToWifiUtils.this.mHighestPriorityNetworkId = -1; } } public String getConnectedSSID() { WifiInfo info = this.mWifiManager.getConnectionInfo(); if (info != null) { return info.getSSID(); } return null; } public String getHighestPriorityApSsid() { String recentDisconnectSSID = WifiInfo.removeDoubleQuotes(SwitchToWifiUtils.this.mDisconnectedSSID.getRecentDisconnectedSSID()); List<WifiConfiguration> networks = this.mWifiManager.getConfiguredNetworks(); List<ScanResult> scanResults = this.mWifiManager.getScanResults(); String highestPriorityNetworkSSID = null; int highestPriority = -1; if (!(networks == null || scanResults == null)) { for (WifiConfiguration network : networks) { for (ScanResult scanresult : scanResults) { if (network.SSID != null && scanresult.SSID != null && network.SSID.equals("\"" + scanresult.SSID + "\"") && Security.isSameSecurity(network, scanresult) && !scanresult.SSID.equals(recentDisconnectSSID) && network.priority > highestPriority) { highestPriority = network.priority; highestPriorityNetworkSSID = network.SSID; SwitchToWifiUtils.this.mHighestPriorityNetworkId = network.networkId; } } } } return highestPriorityNetworkSSID; } public boolean isWifiApAvailable(boolean includeRecentDisconnectedSSID) { String recentDisconnectSSID = WifiInfo.removeDoubleQuotes(SwitchToWifiUtils.this.mDisconnectedSSID.getRecentDisconnectedSSID()); List<WifiConfiguration> configs = this.mWifiManager.getConfiguredNetworks(); List<ScanResult> results = this.mWifiManager.getScanResults(); if (!(results == null || configs == null)) { for (ScanResult result : results) { if (!(result.SSID == null || result.SSID.length() == 0 || result.capabilities.contains("[IBSS]"))) { for (WifiConfiguration conf : configs) { if (conf.SSID != null && result.SSID.equals(WifiInfo.removeDoubleQuotes(conf.SSID)) && Security.isSameSecurity(conf, result)) { if (includeRecentDisconnectedSSID || !result.SSID.equals(recentDisconnectSSID)) { MLog.v("WifiUtils", "isWifiAvailable() return true :" + result.SSID); return true; } MLog.v("WifiUtils", "Recent disconnected ssid is ignored: " + recentDisconnectSSID); } } continue; } } } MLog.v("WifiUtils", "isWifiAvailable() return false"); return false; } private boolean isWiFiConnected() { NetworkInfo info = ((ConnectivityManager) SwitchToWifiUtils.this.mApplicationContext.getSystemService("connectivity")).getNetworkInfo(1); if (info != null) { MLog.v("WifiUtils", "wifi NetworkInfo: " + info.toString()); return info.isConnectedOrConnecting(); } MLog.v("WifiUtils", "No wifi connection info"); return false; } } private SwitchToWifiUtils(Context context) { this.mApplicationContext = context.getApplicationContext(); this.mWifiWrapper = new WifiWrapper(); this.mStateSaver = new StateSaver(this.mApplicationContext); this.mScanAlarm = new ScanAlarm(this.mApplicationContext); this.mMobileNework = new MobileNework(); this.mUserDisconnectEvent = new UserDisconnectEvent(); this.mScanEvent = new ScanEvent(); this.mDisconnectedSSID = new DisconnectedSSID(); if (this.mWifiWrapper.isWiFiConnected()) { this.mWifiConnection = new WifiConnection(true); this.mDisconnectedSSID.setRecentDisconnectedSSID(this.mWifiWrapper.getConnectedSSID()); } else { this.mWifiConnection = new WifiConnection(false); } this.mSwitchList = new ArrayList(); this.mSwitchList.add(0, new AutoSwitch()); this.mSwitchList.add(1, new ManualSwitch()); this.mSwitchList.add(2, new NotificationSwitch()); this.mWifiToWifi = new WifiToWifi(); } public static SwitchToWifiUtils getInstance(Context context) { if (mInstance == null) { mInstance = new SwitchToWifiUtils(context); } return mInstance; } public void onUserConnectEvent() { this.mScanEvent.onWifiConnecting(); this.mMobileNework.onWifiConnecting(); this.mUserDisconnectEvent.onUserDisconnect(); System.putInt(this.mApplicationContext.getContentResolver(), "wifi_ap_manual_connect", 1); Log.d("WifiUtils", "onUserConnectEvent manual connect"); } public void onUserDisconnectEvent() { this.mUserDisconnectEvent.onUserDisconnect(); } public void onUserForgetEvent() { this.mUserDisconnectEvent.onUserDisconnect(); } public void onWifiStateChanged(Intent intent) { switch (intent.getIntExtra("wifi_state", 0)) { case 0: case 1: this.mDisconnectedSSID.setRecentDisconnectedSSID(null); return; default: return; } } public void onWifiNetworkStateChanged(NetworkInfo info) { if (info == null) { MLog.e("WifiUtils", "NetworkInfo is null!"); return; } if (this.mWifiConnection.update(info.isConnected())) { State state = info.getState(); if (state == State.DISCONNECTED) { MLog.i("WifiUtils", "Wifi is disconnected!"); this.mDisconnectedSSID.onWifiDisconnected(); this.mWifiToWifi.switchToWifi(); } else if (state == State.CONNECTED) { String ssid = this.mWifiWrapper.getConnectedSSID(); MLog.i("WifiUtils", ssid + " is connected!"); this.mDisconnectedSSID.onWifiConnected(ssid); this.mUserDisconnectEvent.onWifiConnected(); this.mScanEvent.onWifiConnected(); this.mMobileNework.onWifiConnected(); } } } public void onScanFinished() { if (Config.getSwitchToWifiType(this.mApplicationContext) != 0) { this.mScanAlarm.setAlarm(); } if (!this.mScanEvent.shouldIgnoreScanEvent()) { if (!this.mWifiConnection.isConnected() || this.mWifiConnection.isConnected() == this.mWifiWrapper.isWiFiConnected()) { boolean result = ((ISwitchToWifi) this.mSwitchList.get(Config.getSwitchToWifiType(this.mApplicationContext))).switchToWifi(); MLog.i("WifiUtils", "switch type:" + Config.getSwitchToWifiType(this.mApplicationContext) + " result:" + result); if (!(result || this.mWifiWrapper.isWiFiConnected())) { this.mMobileNework.onCancelSwitchToWifi(); } return; } MLog.i("WifiUtils", "Wifi state is changing, ignore scan result!"); } } public void startScan() { this.mWifiWrapper.startScan(); } public void handleSwitchToMoblie() { this.mMobileNework.checkSwitchToMobileNetwork(); } public void onWifiConnectionChanged(boolean isConnectingOrConnected) { this.mMobileNework.onWifiConnectionChanged(isConnectingOrConnected); } public void updateSupplicantState(SupplicantState state) { if (!this.mWifiConnection.isConnected()) { if ((state != null && SupplicantState.isHandshakeState(state)) || SupplicantState.DISCONNECTED.equals(state)) { if (SupplicantState.DISCONNECTED.equals(state)) { this.mScanEvent.onWifiDisconnected(); this.mMobileNework.onWifiDisconnected(); return; } this.mScanEvent.onWifiConnecting(); this.mMobileNework.onWifiConnecting(); } } } }
Python
UTF-8
465
3.34375
3
[]
no_license
from turtle import * speed(0) bgcolor("Black") color("White") pensize(5) def hex(side): for count in range(2): forward(side) left(120) def rotation(): n = 0 colormode(255) c = 0 pencolor(c,c,c) for count in range(500): if c != 255: c += 255.0/120 pencolor(c,c,c) hex(n) n += 4 left(2) penup() goto(0,0) pendown() rotation() hideturtle() done()
Markdown
UTF-8
1,105
2.6875
3
[]
no_license
#不要使用retainCount ###主要内容 1. NSObject协议中定义了下面的方法,用于查询对象当前的保留计数: - (NSUInteger)retainCount ; 2. ARC中这个方法这个方法已经被废弃,如果在ARC中调用,编译器就会报错,这和在ARC中调用`retain`,`release`,`autorelease`方法时情况一样 3. 它返回的保留计数只是某个给定时间点上的值,该方法并未考虑到系统会杀害后吧自动释放池清空,因而不会讲后续的释放操作作为返回值里减去,这样的话,此值就未必能真实反映实际的引用计数,因此不要用retainCount作为循环判断的条件 4. retainCount可能永远不返回0,因为有时系统会优化对象的释放行为,在引用计数还是1的时候就把它回收啦.只有在系统不打算这么优化时,计数值才会递减至0 ###重点总结 * 对象的保留计数看似有用,实则不然,因为任何给定时间点上,`绝对保留计数`都无法反映对象生命期的全貌 * 引入ARC之后,retainCount方法就正式废止啦,在ARC下调用该方法会导致编译器报错
Java
UTF-8
1,678
3.796875
4
[]
no_license
Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL. Note: You may only use constant extra space. Recursive approach is fine, implicit stack space does not count as extra space for this problem. You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children). Example: Given the following perfect binary tree, 1 / \ 2 3 / \ / \ 4 5 6 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL Iterative solution (0 ms) : public class Solution { public void connect(TreeLinkNode root) { if (root == null) return; TreeLinkNode pre = root; TreeLinkNode cur = null; while(pre.left != null) { cur = pre; while(cur != null) { cur.left.next = cur.right; if(cur.next != null) cur.right.next = cur.next.left; cur = cur.next; } pre = pre.left; } } } Recursive Solution (0 ms) : public class Solution { public void connect(TreeLinkNode root) { if(root == null) return; if(root.left == null && root.right == null) return; if(root.left != null && root.right != null) root.left.next = root.right; if(root.next != null) root.right.next = root.next.left; connect(root.left); connect(root.right); } }
JavaScript
UTF-8
3,855
2.546875
3
[]
no_license
// Slider options var mySwiper = new Swiper(".swiper-container", { // Optional parameters direction: "vertical", loop: true, // If we need pagination pagination: { el: ".swiper-pagination", }, // Navigation arrows navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, // And if we need scrollbar scrollbar: { el: ".swiper-scrollbar", }, }); // Input flag options var input = document.querySelector("#phone"); window.intlTelInput(input, { // whether or not to allow the dropdown allowDropdown: true, // if there is just a dial code in the input: remove it on blur autoHideDialCode: true, // add a placeholder in the input with an example number for the selected country autoPlaceholder: "polite", // modify the parentClass customContainer: "", // modify the auto placeholder customPlaceholder: null, // append menu to specified element dropdownContainer: null, // don't display these countries excludeCountries: [], // format the input value during initialisation and on setNumber formatOnDisplay: true, // geoIp lookup function geoIpLookup: null, // inject a hidden input with this name, and on submit, populate it with the result of getNumber hiddenInput: "", // initial country initialCountry: "", // localized country names e.g. { 'de': 'Deutschland' } localizedCountries: null, // don't insert international dial codes nationalMode: true, // display only these countries onlyCountries: [], // number type to use for placeholders placeholderNumberType: "MOBILE", // the countries at the top of the list. defaults to united states and united kingdom preferredCountries: ["ru", "gb"], // display the country dial code next to the selected flag so it's not part of the typed number separateDialCode: true, // specify the path to the libphonenumber script to enable validation/formatting utilsScript: "", }); // Modal document.querySelector("#call").addEventListener("click", function () { document.querySelector(".modal").style.display = "flex"; document.body.style.overflow = "hidden"; }); document.querySelector(".close").addEventListener("click", function () { document.querySelector(".modal").style.display = "none"; document.body.style.overflow = "visible"; }); // modalInput var input = document.querySelector("#modal-phone"); window.intlTelInput(input, { // whether or not to allow the dropdown allowDropdown: true, // if there is just a dial code in the input: remove it on blur autoHideDialCode: true, // add a placeholder in the input with an example number for the selected country autoPlaceholder: "polite", // modify the parentClass customContainer: "", // modify the auto placeholder customPlaceholder: null, // append menu to specified element dropdownContainer: null, // don't display these countries excludeCountries: [], // format the input value during initialisation and on setNumber formatOnDisplay: true, // geoIp lookup function geoIpLookup: null, // inject a hidden input with this name, and on submit, populate it with the result of getNumber hiddenInput: "", // initial country initialCountry: "", // localized country names e.g. { 'de': 'Deutschland' } localizedCountries: null, // don't insert international dial codes nationalMode: true, // display only these countries onlyCountries: [], // number type to use for placeholders placeholderNumberType: "MOBILE", // the countries at the top of the list. defaults to united states and united kingdom preferredCountries: ["ru", "gb"], // display the country dial code next to the selected flag so it's not part of the typed number separateDialCode: true, // specify the path to the libphonenumber script to enable validation/formatting utilsScript: "", });
Java
UTF-8
3,374
2.703125
3
[]
no_license
package com.itextpdf.highlevel.notused.appendix; import com.itextpdf.io.font.constants.StandardFonts; import com.itextpdf.kernel.colors.ColorConstants; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.kernel.pdf.canvas.PdfCanvasConstants; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.Paragraph; import com.itextpdf.layout.property.Property; import java.io.File; import java.io.IOException; /** * @author Bruno Lowagie (iText Software) */ public class DocumentFontMethods { public static final String DEST = "results/appendix/document_font_methods.pdf"; public static void main(String args[]) throws IOException { File file = new File(DEST); file.getParentFile().mkdirs(); new DocumentFontMethods().createPdf(DEST); } public void createPdf(String dest) throws IOException { // Initialize PDF document PdfDocument pdf = new PdfDocument(new PdfWriter(dest)); // Initialize document Document document = new Document(pdf); Paragraph p; p = new Paragraph("Testing font methods"); document.add(p); PdfFont font = PdfFontFactory.createFont(StandardFonts.TIMES_ROMAN); document.setFont(font); p = new Paragraph("Testing font methods: changed font"); document.add(p); document.setFontSize(18); p = new Paragraph("Testing font methods: changed font size"); document.add(p); document.setFontColor(ColorConstants.BLUE); p = new Paragraph("Testing font methods: changed color"); document.add(p); document.setBold(); p = new Paragraph("Testing font methods: to bold"); document.add(p); document.setItalic(); p = new Paragraph("Testing font methods: to italic"); document.add(p); document.setProperty(Property.BOLD_SIMULATION, false); document.setProperty(Property.ITALIC_SIMULATION, false); document.setProperty(Property.FONT_COLOR, null); p = new Paragraph("Testing font methods: resetting style and color"); document.add(p); document.setLineThrough(); p = new Paragraph("Testing font methods: line through (default)"); document.add(p); document.setProperty(Property.UNDERLINE, null); document.setUnderline(); p = new Paragraph("Testing font methods: underline (default)"); document.add(p); document.setProperty(Property.UNDERLINE, null); document.setUnderline(2, 4); document.setUnderline(ColorConstants.BLUE, 5, 0.1f, 2, -0.5f, PdfCanvasConstants.LineCapStyle.ROUND); p = new Paragraph("Testing font methods: underline (custom)"); document.add(p); document.setProperty(Property.UNDERLINE, null); document.setTextRenderingMode(PdfCanvasConstants.TextRenderingMode.STROKE); p = new Paragraph("Testing font methods: change text rendering mode"); document.add(p); document.setStrokeWidth(0.1f); document.setStrokeColor(ColorConstants.BLUE); p = new Paragraph("Testing font methods: change stroke width and color"); document.add(p); //Close document document.close(); } }
Java
UTF-8
1,481
2.171875
2
[]
no_license
package bg.infosys.interns.bmanagement.ws.test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import javax.transaction.Transactional; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.*; import org.mockito.junit.MockitoJUnitRunner; import bg.infosys.interns.bmanagement.core.dao.EmployeeDAO; import bg.infosys.interns.bmanagement.ws.controllers.EmployeeController; import bg.infosys.interns.bmanagement.ws.dto.EmployeeDTO; import bg.infosys.interns.bmanagement.ws.dto.mapper.EmployeeMapper; import bg.infosys.interns.bmanagement.ws.service.EmployeeService; @RunWith(MockitoJUnitRunner.class) public class EmployeeControllerTest { private static final Integer EMPLOYEE_ID = 1; private static final String EMPLOYEE_NAME = "George"; @Mock private EmployeeDAO dao; @Mock private EmployeeMapper mapper; @InjectMocks private EmployeeService service; private EmployeeDTO dto; @Before public void setUp() { dto=new EmployeeDTO(); dto.setId(EMPLOYEE_ID); dto.setName(EMPLOYEE_NAME); } @Test public void testGetById() { when(service.findById(Mockito.anyInt())).thenReturn(dto); assertEquals(service.findById(EMPLOYEE_ID),dto); } @Test public void findAll() { List<EmployeeDTO>employees=Arrays.asList(dto); when(service.findAll()).thenReturn(employees); assertEquals(service.findAll(),employees); } }
Markdown
UTF-8
715
3.109375
3
[]
no_license
# GhostTweeter **Periodically tweets out a random link to one of your Ghost blog post.** Tweets are sent in the following format: ``` <post title>: <url> #<tag1> #<tag2> ``` Converts every tag into a hashtag (as long as characters are not >140) *You must edit this code and enter in your own account authentication (see below).* Getting your authentication: 1. Go to https://apps.twitter.com/app/new and create a new app 2. Once created, copy and paste your API key and secret (will be under "Keys and Access Tokens") 3. Create an access token, copy and paste those as well This Python code requires [tweepy](https://github.com/tweepy/tweepy) and [feedparser](https://github.com/kurtmckee/feedparser) to run.
C++
UTF-8
2,383
2.703125
3
[]
no_license
#include "light.h" #include "program.h" #include "camera.h" bool Light::Create(const Name& name) { m_name = name; #ifdef _DEBUG m_debug_model = m_engine->Factory()->Create<Model>(Model::GetClassName()); m_debug_model->m_name = "model"; m_debug_model->m_engine = m_engine; m_debug_model->m_scene = m_scene; m_debug_model->m_transform.scale = glm::vec3(0.15f, 0.15f, 0.15f); m_debug_model->m_mesh = m_engine->Resources()->Get<Mesh>("meshes/debug_cube.obj"); m_debug_model->m_mesh->m_material = m_engine->Resources()->Get<Material>("debug_material"); m_debug_model->m_shader = m_engine->Resources()->Get<Program>("debug_shader"); #endif // _DEBUG return true; } void Light::Update() { } void Light::Draw(GLenum primitiveType) { #ifdef _DEBUG m_debug_model->m_transform.translation = m_transform.translation; m_debug_model->m_transform.rotation = m_transform.rotation; m_debug_model->m_mesh->m_material->diffuse = diffuse; m_debug_model->Draw(primitiveType); #endif // _DEBUG } void Light::SetShader(class Program* shader) { SetShader("light", shader); } void Light::SetShader(const std::string& light_name, Program* shader) { ASSERT(shader); shader->Use(); shader->SetUniform(light_name + ".ambient", ambient); shader->SetUniform(light_name + ".diffuse", diffuse); shader->SetUniform(light_name + ".specular", specular); shader->SetUniform(light_name + ".type", type); shader->SetUniform(light_name + ".cutoff", glm::radians(cutoff)); shader->SetUniform(light_name + ".exponent", exponent); std::vector<Camera*> cameras = m_scene->Get<Camera>(); ASSERT(!cameras.empty()); glm::mat4 light_view_matrix = cameras[0]->m_view_matrix * m_transform.GetMatrix(); shader->SetUniform(light_name + ".position", light_view_matrix[3]); shader->SetUniform(light_name + ".direction", glm::mat3(light_view_matrix) * glm::vec3(0.0f, 0.0f, 1.0f)); } void Light::Edit() { Actor::Edit(); ImGui::Separator(); ImGui::Text(("Type: %s", Light::GetClassName())); ImGui::ColorEdit3("Ambient", glm::value_ptr(ambient)); ImGui::ColorEdit3("Diffuse", glm::value_ptr(diffuse)); ImGui::ColorEdit3("Specular", glm::value_ptr(specular)); ImGui::SliderFloat("Cutoff", &cutoff, 0.0f, 90.0f); ImGui::SliderFloat("Exponent", &exponent, 0.0f, 128.0f); const char* types[] = { "Point", "Direction", "Spot" }; ImGui::Combo("Type", (int*)&type, types, IM_ARRAYSIZE(types)); }
C++
UTF-8
4,039
3.203125
3
[]
no_license
#include <cfloat> #include <iostream> #include <thread> #include <vector> #include <chrono> #include <mutex> #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> typedef size_t ID; class IAccount { private: std::mutex m_lock; public: virtual void Deposit( float amount ) = 0; virtual void Withdraw( float amount ) = 0; virtual float Balance() const = 0; std::mutex& Lock() { return m_lock; } }; template <size_t MAX_PER_TRANSACTION = 1000, size_t MIN_PER_TRANSACTION = 0> class CashAccount : public IAccount { private: const ID m_id; volatile float m_balance = 0.0f; public: CashAccount( const ID id ) throw() : m_id( id ) { } void ChangeAmount( float amount, bool fDeposit ) { // check the limits per transaction if (amount <= MIN_PER_TRANSACTION || amount > MAX_PER_TRANSACTION) { return; } std::unique_lock<std::mutex> lock(Lock()); // check the total limits if (fDeposit && m_balance + amount > FLT_MAX) return; // Withdrawing amount *= -1; if (!fDeposit && m_balance + amount < 0.0f) return; m_balance += amount; } void Deposit( float amount ) override { ChangeAmount(amount, /*fDeposit*/ true); } virtual void Withdraw( float amount ) override { ChangeAmount(amount, /*fDeposit*/ false); } virtual float Balance() const override { return m_balance; } void Reset() { m_balance = 0; } }; class AccountManager { private: std::vector<IAccount> m_vecAccount; public: static AccountManager& Instance() { static AccountManager instance; return instance; } void Transfer(const ID from, const ID to, float amount) { IAccount *fromAccount, *toAccount; fromAccount = toAccount = nullptr; if (m_vecAccount.size() < from || m_vecAccount.size() < to) // account don't exist return; fromAccount = &m_vecAccount.at(from); toAccount = &m_vecAccount.at(to); // TODO: wrap into trans // don't actually take the locks yet std::unique_lock<std::mutex> lock1(fromAccount->Lock(), std::defer_lock); std::unique_lock<std::mutex> lock2(toAccount->Lock(), std::defer_lock); // lock both unique_locks without deadlock std::lock(lock1, lock2); fromAccount->Withdraw(amount); toAccount->Deposit(amount); toAccount = fromAccount = nullptr; } ID AddCashAccount() { // TODO: Check for mem pressure std::mutex mutex; std::unique_lock<std::mutex> lock(mutex); auto id = m_vecAccount.size(); m_vecAccount.push_back(CashAccount<>(id)); return id; } void Deposit(ID accountId, float amount) { if (m_vecAccount.size() < accountId) // account doesn't exist return; m_vecAccount.at(accountId).Deposit(amount); } void Withdraw(ID accountId, float amount) { if (m_vecAccount.size() < accountId) // account doesn't exist return; m_vecAccount.at(accountId).Withdraw(amount); } }; auto main() -> void { std::cout << "C++ version " << __cplusplus << std::endl; ID id = 0; CashAccount<> account( id ); auto manager = AccountManager::Instance(); auto account1 = manager.AddCashAccount(); auto account2 = manager.AddCashAccount(); manager.Transfer(account1, account2, 100); auto functor = [&account]() -> void { account.Deposit( 1 ); }; auto functor2 = [ &account ]() -> void { account.Withdraw( 0.1f ); }; for( ;; ) { std::vector<std::thread> v; for( size_t i = 1; i <= 2000; ++i ) { /*v.push_back( i % 2 != 0 ? std::thread( functor ) : std::thread( functor2 ) );*/ auto t = std::thread(functor); auto t2 = std::thread(functor2); t.join(); t2.join(); } for( auto& th : v ) th.join(); std::cout << "ID " << id << " balance is " << account.Balance() << std::endl; account.Reset(); } }
Python
UTF-8
14,697
2.96875
3
[ "MIT" ]
permissive
"""Library for interfaces into DataJoint pipelines.""" import datajoint as dj import datetime import numpy as np DAY = 24 * 60 * 60 DEFAULT_FETCH_LIMIT = 1000 # Stop gap measure to deal with super large tables class DJConnector(): """ Primary connector that communicates with a DataJoint database server. """ @staticmethod def attempt_login(database_address: str, username: str, password: str): """ Attempts to authenticate against database with given username and address :param database_address: Address of database :type database_address: str :param username: Username of user :type username: str :param password: Password of user :type password: str :return: Dictionary with keys: result(True|False), and error (if applicable) :rtype: dict """ dj.config['database.host'] = database_address dj.config['database.user'] = username dj.config['database.password'] = password # Attempt to connect return true if successful, false is failed try: dj.conn(reset=True) return dict(result=True) except Exception as e: return dict(result=False, error=e) @staticmethod def list_schemas(jwt_payload: dict): """ List all schemas under the database :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :return: List of schemas names in alphabetical order excluding information_schema :rtype: list """ DJConnector.set_datajoint_config(jwt_payload) # Attempt to connect return true if successful, false is failed return [row[0] for row in dj.conn().query(""" SELECT SCHEMA_NAME FROM information_schema.schemata WHERE SCHEMA_NAME != "information_schema" ORDER BY SCHEMA_NAME """)] @staticmethod def list_tables(jwt_payload: dict, schema_name: str): """ List all tables and their type give a schema :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :return: Contains a key for a each table type and it corressponding table names :rtype: dict """ DJConnector.set_datajoint_config(jwt_payload) # Get list of tables names\ tables_name = dj.schema(schema_name).list_tables() # Dict to store list of table name for each type tables_dict_list = dict(manual_tables=[], lookup_tables=[], computed_tables=[], imported_tables=[], part_tables=[]) # Loop through each table name to figure out what type it is and add them to # tables_dict_list for table_name in tables_name: table_type = dj.diagram._get_tier( '`' + schema_name + '`.`' + table_name + '`').__name__ print(table_name, table_type, flush=True) if table_type == 'Manual': tables_dict_list['manual_tables'].append(dj.utils.to_camel_case(table_name)) elif table_type == 'Lookup': tables_dict_list['lookup_tables'].append(dj.utils.to_camel_case(table_name)) elif table_type == 'Computed': tables_dict_list['computed_tables'].append(dj.utils.to_camel_case(table_name)) elif table_type == 'Imported': tables_dict_list['imported_tables'].append(dj.utils.to_camel_case(table_name)) elif table_type == 'Part': table_name_parts = table_name.split('__') tables_dict_list['part_tables'].append(DJConnector.snake_to_camel_case( table_name_parts[-2]) + '.' + DJConnector.snake_to_camel_case( table_name_parts[-1])) else: print(table_name + ' is of unknown table type') return tables_dict_list @staticmethod def fetch_tuples(jwt_payload: dict, schema_name: str, table_name: str): """ Get records as tuples from table :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :return: List of tuples in dict form :rtype: list """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) # Get the table object refernece table = getattr(schema_virtual_module, table_name) # Fetch tuples without blobs as dict to be used to create a # list of tuples for returning non_blobs_rows = table.fetch(*table.heading.non_blobs, as_dict=True, limit=DEFAULT_FETCH_LIMIT) # Buffer list to be return rows = [] # Looped through each tuple and deal with TEMPORAL types and replacing # blobs with ==BLOB== for json encoding for non_blobs_row in non_blobs_rows: # Buffer object to store the attributes row = [] # Loop through each attributes, append to the tuple_to_return with specific # modification based on data type for attribute_name, attribute_info in table.heading.attributes.items(): if not attribute_info.is_blob: if non_blobs_row[attribute_name] is None: # If it is none then just append None row.append(None) elif attribute_info.type == 'date': # Date attribute type covert to epoch time row.append((non_blobs_row[attribute_name] - datetime.date(1970, 1, 1)).days * DAY) elif attribute_info.type == 'time': # Time attirbute, return total seconds row.append(non_blobs_row[attribute_name].total_seconds()) elif attribute_info.type in ('datetime', 'timestamp'): # Datetime or timestamp, use timestamp to covert to epoch time row.append(non_blobs_row[attribute_name].timestamp()) elif attribute_info.type[0:7] == 'decimal': # Covert decimal to string row.append(str(non_blobs_row[attribute_name])) else: # Normal attribute, just return value with .item to deal with numpy # types if isinstance(non_blobs_row[attribute_name], np.generic): row.append(np.asscalar(non_blobs_row[attribute_name])) else: row.append(non_blobs_row[attribute_name]) else: # Attribute is blob type thus fill it in string instead row.append('=BLOB=') # Add the row list to tuples rows.append(row) return rows @staticmethod def get_table_attributes(jwt_payload: dict, schema_name: str, table_name: str): """ Method to get primary and secondary attributes of a table :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :return: Dict of primary, secondary attributes and with metadata: attribute_name, type, nullable, default, autoincrement. :rtype: dict """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) table_attributes = dict(primary_attributes=[], secondary_attributes=[]) for attribute_name, attribute_info in getattr(schema_virtual_module, table_name).heading.attributes.items(): if attribute_info.in_key: table_attributes['primary_attributes'].append(( attribute_name, attribute_info.type, attribute_info.nullable, attribute_info.default, attribute_info.autoincrement )) else: table_attributes['secondary_attributes'].append(( attribute_name, attribute_info.type, attribute_info.nullable, attribute_info.default, attribute_info.autoincrement )) return table_attributes @staticmethod def get_table_definition(jwt_payload: dict, schema_name: str, table_name: str): """ Get the table definition :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :return: definition of the table :rtype: str """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) return getattr(schema_virtual_module, table_name).describe() @staticmethod def insert_tuple(jwt_payload: dict, schema_name: str, table_name: str, tuple_to_insert: dict): """ Insert record as tuple into table :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :param tuple_to_insert: Record to be inserted :type tuple_to_insert: dict """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) getattr(schema_virtual_module, table_name).insert1(tuple_to_insert) @staticmethod def update_tuple(jwt_payload: dict, schema_name: str, table_name: str, tuple_to_update: dict): """ Update record as tuple into table :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :param tuple_to_update: Record to be updated :type tuple_to_update: dict """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) getattr(schema_virtual_module, table_name).update1(tuple_to_update) @staticmethod def delete_tuple(jwt_payload: dict, schema_name: str, table_name: str, tuple_to_restrict_by: dict): """ Delete a specific record based on the restriction given (Can only delete 1 at a time) :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict :param schema_name: Name of schema to list all tables from :type schema_name: str :param table_name: Table name under the given schema; must be in camel case :type table_name: str :param tuple_to_restrict_by: Record to restrict the table by to delete :type tuple_to_restrict_by: dict """ DJConnector.set_datajoint_config(jwt_payload) schema_virtual_module = dj.create_virtual_module(schema_name, schema_name) # Get all the table attributes and create a set table_attributes = set(getattr(schema_virtual_module, table_name).heading.primary_key + getattr(schema_virtual_module, table_name).heading.secondary_attributes) # Check to see if the restriction has at least one matching attribute, if not raise an # error if len(table_attributes & tuple_to_restrict_by.keys()) == 0: raise Exception('Restriction is invalid: None of the attributes match') # Compute restriction tuple_to_delete = getattr(schema_virtual_module, table_name) & tuple_to_restrict_by # Check if there is only 1 tuple to delete otherwise raise error if len(tuple_to_delete) > 1: raise Exception("""Cannot delete more than 1 tuple at a time. Please update the restriction accordingly""") elif len(tuple_to_delete) == 0: raise Exception('Nothing to delete') # All check pass thus proceed to delete tuple_to_delete.delete_quick() @staticmethod def set_datajoint_config(jwt_payload: dict): """ Method to set credentials for database :param jwt_payload: Dictionary containing databaseAddress, username and password strings :type jwt_payload: dict """ dj.config['database.host'] = jwt_payload['databaseAddress'] dj.config['database.user'] = jwt_payload['username'] dj.config['database.password'] = jwt_payload['password'] dj.conn(reset=True) @staticmethod def snake_to_camel_case(string: str): """ Helper method for converting snake to camel case :param string: String in snake format to convert to camel case :type string: str :return: String formated in CamelCase notation :rtype: str """ return ''.join(string_component.title() for string_component in string.split('_'))
Markdown
UTF-8
3,091
3.21875
3
[]
no_license
# Frontend Mentor - Stats preview card component solution This is a solution to the [Stats preview card component challenge on Frontend Mentor](https://www.frontendmentor.io/challenges/stats-preview-card-component-8JqbgoU62). Frontend Mentor challenges help you improve your coding skills by building realistic projects. ## Table of contents - [Frontend Mentor - Stats preview card component solution](#frontend-mentor---stats-preview-card-component-solution) - [Table of contents](#table-of-contents) - [Overview](#overview) - [The challenge](#the-challenge) - [Screenshot](#screenshot) - [Links](#links) - [My process](#my-process) - [Built with](#built-with) - [What I learned](#what-i-learned) - [Useful resources](#useful-resources) - [Author](#author) ## Overview ### The challenge Users should be able to: - View the optimal layout depending on their device's screen size ### Screenshot ![Mobile View](/screenshots/mobile-screenshot.png) ![Desktop View](/screenshots/desktop-screenshot.png) ### Links - Solution URL: [Solution URL](https://www.frontendmentor.io/challenges/stats-preview-card-component-8JqbgoU62/hub/stats-preview-card-component-zs7x4zJoO) - Live Site URL: [Live Site Demo](https://ckharrison.github.io/stats-preview-card-component/) ## My process I used this challenge to help solidify my knowledge of responsive design using CSS Grid and Flexbox. I started out creating the mobile design first and then went ahead and implemented the desktop design via a media query. ### Built with - Semantic HTML5 markup - CSS custom properties - Flexbox - CSS Grid - Mobile-first workflow ### What I learned The most challenging part about this design was adding a tint/colored overlay to the hero image. This is the first time I have done something like this via CSS. Normally I would have just added in the tint via photoshop, but I decided to take the time to learn how to do this via CSS only. I was able to accomplish this by adding in a div container over the hero image, and using the wrapping div's :after pseudo property to add in the overlay tint. ``` .hero::after { content: ''; display: block; position: absolute; height: 100%; width: 100%; background: var(--violet-accent-image); opacity: .5; top: 0; left: 0; } ``` I also learned how to add responsive images depending on the viewport's screensize using the srcset image attribute. I've never done that before so this was a fun new thing to learn. ### Useful resources - [Ideabase - Adding Image overlay tint](https://ideabasekent.com/wiki/adding-image-overlay-tint-using-css) - I was able to use this article as a resource on how to tint an image. I found it incredibly helpful. - [CSS Tips and Tricks - Guide to Responsive Images](https://css-tricks.com/a-guide-to-the-responsive-images-syntax-in-html/#using-srcset) - This was a useful article that helped me with responsive images. ## Author - Website - [CKHarrison](https://github.com/CKHarrison) - Frontend Mentor - [@yourusername](https://www.frontendmentor.io/profile/ckharrison)
Java
UTF-8
2,202
1.90625
2
[]
no_license
package github.com.junhyoung.killingtime; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.media.Image; import android.preference.DialogPreference; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void Popup_Producer(View view){ Toast toast=Toast.makeText(getApplicationContext(),"조장 정찬형",Toast.LENGTH_LONG); ImageView imageView=new ImageView(getApplicationContext()); imageView.setImageResource(R.drawable.jch); toast.setView(imageView); toast.setGravity(Gravity.CENTER,50,50); toast.setMargin(1000, 1000); toast.show(); } public void Start(View v){ Intent myintent = new Intent(getApplicationContext(),SelectModeActivity.class); startActivity(myintent); } public void Recorder(View v){ Intent myintent = new Intent(getApplicationContext(),RecordActivity.class); startActivity(myintent); } public void Help(View v) { Context mContext = getApplicationContext(); LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.activity_helper, (ViewGroup) findViewById(R.id.popup)); AlertDialog.Builder aDialog = new AlertDialog.Builder(this); aDialog.setTitle("도움말"); aDialog.setView(layout); aDialog.setNegativeButton("돌아가기", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); AlertDialog ad = aDialog.create(); ad.show(); } }
Markdown
UTF-8
2,908
3.125
3
[ "MIT" ]
permissive
# &lt;dev-log /&gt; A server with which I keep a development log. Anything from what's tripped me up, blocked me, or simply something I've learned. The UI side of it is... let's go with functional. ## An API and a web server. It's built with [Hapi] and attempted to be done in a RESTful way. The same urls can be called with an `Accept: application/json` header for API functionality, and without for normal website functionality (no need for all that `/api/logs` or `/logs.json` business). The following endpoints are currently available: | Endpoint | Method | Details | |---------------------|-----------|---------------------------------------------------------------------------| | `/` | | Just a landing page with the added ability to post a new log entry. | | `/log` | PUT/POST | Add a new log entry by sending a `msg` parameter | | `/log/{id}` | PATCH/POST| Edit/update the given log entry. | | `/log/{id}` | DELETE | Delete the given log entry. | | `/log/{id}/delete` | POST | Another delete because browsers suck and don't support the DELETE method. | | `/logs` | GET | Retrieve a list of all the current logs. | | `/search?q={query}` | POST | Search the logs for `{query}` | ### Alfred The very reason I wanted this to be an API as well is so that I could have an Alfred workflow that let me quickly log these entries. I do this with the following simple cURL request: ``` curl -X PUT -H "Content-Type: application/json" -d "{ 'msg': '{query}' }" 127.0.0.1:1236/log ``` ## Setting up shop 1. Clone/download the repo. 2. Run `npm install`. 3. Make a copy of `config.js.example` and rename it to `config.js`. 4. Tweak the settings in `config.js` to suit your needs (most notably `dbUrl`). 5. Fire up the server with `npm start`. 6. Open <http://localhost:1236/> to start adding logs. ### What about Mongo DB? You need to either roll your own, or I find that a free [mlabs] account is more than enough for the very occasional log/lookup/search/whatever. ## Current state of things At this stage, I'm still learning [Hapi], and [Mongo] properly so everything is still very much subject to change. On the off chance anyone actually sees this in its current state... I apologize :P ## The UI As mentioned above... the UI is serviceable. Below is a screenshot of what it looks like (using the awesome [redacted font][redacted]): --- ![Screenshot of dev-log UI](screenshot.png) --- [Hapi]: http://hapijs.com [mlabs]: http://mlabs.com [Mongo]: https://mongodb.com [redacted]: https://github.com/christiannaths/Redacted-Font
C#
UTF-8
1,478
3.125
3
[]
no_license
using System; using System.Diagnostics; using System.Text; using System.Threading.Tasks; namespace CSharpTestingConsole { class Program { static void Main(string[] args) { bool useHiddenWindow = true; Console.WriteLine("Hit a key when you're ready!"); Console.ReadKey(); Console.WriteLine(string.Format("Executing dotnet new --list --type project")); Process process = new Process(); process.EnableRaisingEvents = true; process.StartInfo.FileName = "dotnet"; process.StartInfo.Arguments = "new --list --type project"; process.StartInfo.CreateNoWindow = useHiddenWindow; if (useHiddenWindow) { process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); } try { process.Start(); if (useHiddenWindow) { process.BeginOutputReadLine(); } process.WaitForExit(); } catch (Exception e) { Console.WriteLine("exception: {0}", e); } Console.WriteLine("Bye!"); } } }
Java
UTF-8
938
3.109375
3
[]
no_license
package model; import java.util.ArrayList; import java.util.List; import interfaces.Observer; import interfaces.Subject; public class EmailTopic implements Subject { public List<Observer> observers; private String message; public EmailTopic() { this.observers = new ArrayList<>(); } @Override public void register(Observer observer) { if (observer == null) { throw new NullPointerException("Null Observer"); } if (!observers.contains(observer)) { observers.add(observer); } } @Override public void unRegister(Observer observer) { observers.remove(observer); } @Override public void notifyObserver() { for (Observer observer : observers) { observer.update(); } } @Override public Object getUpdate(Observer observer) { return this.message; } public void postMessage(String msg) { System.out.println("Message is posted " + msg); this.message = msg; notifyObserver(); } }
Java
UTF-8
7,907
2.53125
3
[]
no_license
package edu.elon.cs.gamealarm.MiniGame2; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Point; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.Display; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.WindowManager; import java.util.Random; import edu.elon.cs.gamealarm.R; /** * Copyright JohnAnge Kernodle and Zack Layne */ public class GameLoopView extends SurfaceView implements SurfaceHolder.Callback { MediaPlayer player; private GameLoopThread thread; private SurfaceHolder surfaceHolder; private Context context; //locations private float ballX, ballY; private float spotX, spotY; private float spotX2, spotY2; private float spotX3, spotY3; private Point size; public GameLoopView(Context context, AttributeSet attrs) { super(context, attrs); // remember the context for finding resources this.context = context; // want to know when the surface changes surfaceHolder = getHolder(); surfaceHolder.addCallback(this); // game loop thread thread = new GameLoopThread(); // figure out the screen width WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); size = new Point(); display.getSize(size); Random r = new Random(); spotX = r.nextInt(size.x - 100)+50; spotY = r.nextInt((size.y/3)-100)+50; spotX2 = r.nextInt(size.x-100)+50; spotY2 = r.nextInt((size.y/3)-100)+50+(size.y/3); spotX3 = r.nextInt(size.x-100)+50; spotY3 = r.nextInt((size.y/3)-100)+50+(2*size.y/3); ballX = spotX; ballY = spotY; } // SurfaceHolder.Callback methods: @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { // thread exists, but is in terminated state if (thread.getState() == Thread.State.TERMINATED) { thread = new GameLoopThread(); } // start the game loop thread.setIsRunning(true); thread.start(); } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { boolean retry = true; thread.setIsRunning(false); while (retry) { try { thread.join(); retry = false; } catch (InterruptedException e) { } } } // Game Loop Thread private class GameLoopThread extends Thread { private boolean isRunning = false; private long lastTime; // the bird sprite private Ball ball; //the spot sprite private Spot spot; private Spot spot2; private Spot spot3; private int greenSquareAmount = 0; private int hasSpot1 = 0; private int hasSpot2 = 0; private int hasSpot3 = 0; private Bitmap bgBitmap; // frames per second calculation private int frames; private long nextUpdate; public GameLoopThread() { ball = new Ball(context); spot = new Spot(context); spot2 = new Spot(context); spot3 = new Spot(context); } public void setIsRunning(boolean isRunning) { this.isRunning = isRunning; } // the main loop @Override public void run() { player = MediaPlayer.create(context, R.raw.alarmnoise); player.start(); lastTime = System.currentTimeMillis(); while (isRunning) { // grab hold of the canvas Canvas canvas = surfaceHolder.lockCanvas(); if (canvas == null) { // trouble -- exit nicely isRunning = false; continue; } synchronized (surfaceHolder) { // compute how much time since last time around long now = System.currentTimeMillis(); double elapsed = (now - lastTime) / 1000.0; lastTime = now; float screenX = size.x; float screenY = size.y; //top if (ballY<=(screenX+40)-screenX){ ballY = 45; } else{ ballY += RollerBallActivity.accelY*3; } //left side if (ballX<=(screenY+40)-screenY){ ballX=45; }else{ ballX += RollerBallActivity.accelX*3; } //bottom if (ballY>size.y-40){ ballY = size.y-45; } else{ ballY += RollerBallActivity.accelY*3; } //right side if (ballX>size.x-40){ ballX=size.x-45; } else{ ballX += RollerBallActivity.accelX*3; } if ((Math.abs(ball.x-spotX)<20&&Math.abs(ball.y-spotY)<50)&& hasSpot1 == 0){ spot.changeImage(context); greenSquareAmount++; hasSpot1 = 1; } if ((Math.abs(ball.x-spotX2)<20&&Math.abs(ball.y-spotY2)<50)&& hasSpot2 == 0){ spot2.changeImage(context); greenSquareAmount++; hasSpot2 = 1; } if ((Math.abs(ball.x-spotX3)<20&&Math.abs(ball.y-spotY3)<50)&& hasSpot3 == 0){ spot3.changeImage(context); greenSquareAmount++; hasSpot3 = 1; } if (greenSquareAmount>2) { player.stop(); ((Activity) context).finish(); System.out.println("complete"); } // update/draw doUpdate(elapsed); doDraw(canvas); } // release the canvas if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas); } } } // an approximate frames per second calculation private void updateFPS(long now) { float fps = 0.0f; ++frames; float overtime = now - nextUpdate; if (overtime > 0) { fps = frames / (1 + overtime/1000.0f); frames = 0; nextUpdate = System.currentTimeMillis() + 1000; System.out.println("FPS: " + (int) fps); } } /* THE GAME */ // move all objects in the game private void doUpdate(double elapsed) { ball.doUpdate(elapsed, ballX, ballY); spot.doUpdate(elapsed, spotX, spotY); spot2.doUpdate(elapsed, spotX2, spotY2); spot3.doUpdate(elapsed, spotX3, spotY3); } // draw all objects in the game private void doDraw(Canvas canvas) { // draw the background canvas.drawColor(Color.WHITE); spot.doDraw(canvas); spot2.doDraw(canvas); spot3.doDraw(canvas); ball.doDraw(canvas); } } }
TypeScript
UTF-8
105
2.546875
3
[]
no_license
export interface IAuthentication<L, O> { loginWithGoogle(): Promise<L>; signOut(): Promise<O>; }
Python
UTF-8
4,242
3.09375
3
[ "MIT" ]
permissive
### assignment 4-1 ### import numpy as np import pandas as pd import scipy.io import scipy ## 1.1 visual ## all_data = scipy.io.loadmat("d:/data/ex04/ex4data1.mat") X = all_data['X'] # shape (5000, 400) y = all_data['y'] # shape (5000, 1) w_set = scipy.io.loadmat("d:/data/ex04/ex4weights.mat") W1 = w_set['Theta1'].T # shape (401, 25) W2 = w_set['Theta2'].T # shape (26, 10) ## 1.2 model representation ## ## 1.3 feedforward and cost function # parameter # classes = 10 def one_hot(y): one_hot = np.zeros((len(y), classes), dtype=np.int32) for i in range(len(y)): one_hot[i, y[i]-1] = 1 return one_hot y = one_hot(y) def logits(X, W): return np.matmul(X, W) def sigmoid(z): return 1. / (1 + np.exp(-z)) def layer(X, W): X = np.insert(X, 0, 1, axis=1) # bias 추가 return np.insert(sigmoid(logits(X, W)), 0, 1, axis=1) def hypothesis(X, W): return sigmoid(logits(X, W)) def cost(X, y, hypothesis, ld=0): m = len(X) hypo = hypothesis cost_sum = 0 for i in range(m): cost_k = 0 for k in range(classes): error = -(y[i][k] * np.log(hypo[i][k])) - ((1 - y[i][k]) * np.log(1 - (hypo[i][k]))) cost_k += error cost_sum += cost_k / m return cost_sum hypo = hypothesis(layer(X, W1), W2) err = cost(X, y, hypo) # 0.287629165 ## 1.4 Regularized cost function ## def reg_cost(X, y, hypothesis, ld=1): m = len(X) hypo = hypothesis cost_sum = 0 for i in range(m): cost_k = 0 for k in range(classes): error = -(y[i][k] * np.log(hypo[i][k])) - ((1 - y[i][k]) * np.log(1 - (hypo[i][k]))) cost_k += error cost_sum += cost_k / m total_reg = 0. total_reg += np.sum(np.square(W1)) + np.sum(np.square(W2)) #element-wise multiplication total_reg *= float(ld)/(2*m) total_reg += cost_sum return total_reg err_reg = reg_cost(X, y, hypo) # 0.384487796 ### 2 backpropagation ### ## 2.1 Sigmoid gradient ## def sigmoidGradient(z): ## sigmoid 미분 ## return sigmoid(z)*(1 - sigmoid(z)) #test = sigmoidGradient([0], [1]) # 0.25 ## 2.2 Random init ## def random_init(): ## W init (-> random uniform) epsilon_init = 0.12 W_init = [np.random.uniform(low=-epsilon_init, high=epsilon_init, size=W1.shape), np.random.uniform(low=-epsilon_init, high=epsilon_init, size=W2.shape)] return W_init W_init = random_init() ## 2.3 Backpropagation ## def backpropagation(W, X, y, ld=0): W1 = W[0] W2 = W[1] m = len(X) ## frontpropagation ## a1 = np.insert(X, 0, 1, axis=1) z2 = logits(a1, W1) a2 = np.insert(sigmoid(z2), 0, 1, axis=1) z3 = logits(a2, W2) hypothesis = sigmoid(z3) # delta matrix # --> cost Delta2 = np.zeros_like(W2) Delta1 = np.zeros_like(W1) # cost # for i in range(m): delta3 = hypothesis[[i]] - y[[i]] # 편미분 (partial J / partial a3) * (partial a3 / partial z3) Delta2 += np.dot(a2[[i]].T, delta3) # (1,26).T *(1,10) # partial z3 / partial w2 완성 # 편미분 (partialJ(2) / partial a2) * (partial a2 / partial z2) # delta2 = np.matmul(delta3, W2.T[:,1:]) * sigmoidGradient(z2)[i] # (1,10) (10, 26) Delta1 += np.dot(a1[[i]].T, delta2) # Delta2 *= 1/m Delta1 *= 1/m # reg Delta1[:,1:] = Delta1[:,1:] + (float(ld)/m) * W1[:,1:] Delta2[:,1:] = Delta2[:,1:] + (float(ld)/m) * W2[:,1:] return [Delta1, Delta2] back = backpropagation(W_init, X, y, ld=0.) ## 2.4 gradient checking ## hypo = hypothesis(layer(X, W1), W2) err = cost(X, y, hypo) # 0.287629165 ## 2.5 Regularized NN ## ## 2.6 run/learn/predict ## def gradientDescent(W, X, y, ld=0.): W1 = W[0] W2 = W[1] for i in range(100): hypo = hypothesis(layer(X, W1), W2) cost_val = reg_cost(X, y, hypo, ld=0.001) Delta = backpropagation(W, X, y, ld=0.001) W1 -= Delta[0] W2 -= Delta[1] if i % 10 == 0: print(cost_val) return hypo, [W1, W2] y_hat, err = gradientDescent(W_init, X, y, ld=0.001) predict = np.equal(np.argmax(y_hat, axis=1), np.argmax(y, axis=1)) acc = len(y[predict]) / len(y) print(acc)
Python
UTF-8
3,431
2.921875
3
[ "MIT" ]
permissive
import asyncio from collections import namedtuple from vk import VK import json PoolRequest = namedtuple('PoolRequest', ['method', 'params', 'result']) class RequestResult(object): """ Результат запроса из пула """ __slots__ = ('_result', 'ready', '_error') def __init__(self): self._result = None self.ready = False self._error = False @property def error(self): """Ошибка, либо `False`, если запрос прошёл успешно.""" return self._error @error.setter def error(self, value): self._error = value self.ready = True @property def result(self): """Результат запроса, если он прошёл успешно.""" if not self.ready: raise RuntimeError('Result is not available in `with` context') if self._error: raise Exception( self._error, 'Got error while executing request: [{}] {}'.format( self.error['error_code'], self.error['error_msg'] ) ) return self._result @result.setter def result(self, result): self._result = result self.ready = True @property def ok(self): """`True`, если результат запроса не содержит ошибок, иначе `False`""" return self.ready and not self._error class VKRequestsPool: def __init__(self, vk: VK): self.vk = vk self.pool = [] self.running = False async def wait_for_run(self): while self.running: await asyncio.sleep(1) async def __aenter__(self): await self.wait_for_run() return self async def __aexit__(self, *args): await self.execute() async def index_execute(self, code, index): return await self.vk._api_request("execute", True, {"code": code}, True, False), index def method(self, method, params): if not self.running: result = RequestResult() req = PoolRequest(method, params, result) self.pool.append(req) return result async def execute_iter(self): await self.wait_for_run() self.running = True tasks = [] for i in range(0, len(self.pool), 25): requests = ','.join( f'API.{req.method}({json.dumps(req.params)})' for req in self.pool[i:i+25] ) code = f'return [{requests}];' tasks.append(self.index_execute(code, i)) for res in asyncio.as_completed(tasks): res, index = await res response = res['response'] response_errors = iter(res.get("execute_errors", [])) for x, current_response in enumerate(response): cur_index = index + x current_result = self.pool[cur_index].result if current_response is not False: current_result.result = current_response else: current_result.error = next(response_errors) yield cur_index, current_result self.pool = [] self.running = False async def execute(self): async for _, _ in self.execute_iter(): ...
Markdown
UTF-8
13,875
2.84375
3
[]
no_license
--- layout: post title: Quagga and GNS3 --- * TOC {:toc} # Introduction I've been meaning to play with [Quagga](http://www.quagga.net/) for sometime. One of the administrators of the Quagga Project is an old friend of mine - I've had many debates with him over IRC, Facebook and Twitter over the years. Yet despite my interest in the networking field, I've not spent any time actually working with Quagga. This tutorial presupposes some basic knowledge of Cisco networking, Linux, GNS3, and Virtualbox. This means that in order to follow this tutorial you will need the following on your machine. By the end of the tutorial you will have configured OSPF and BGP (IPv4 only) and established full connectivity between three hosts. * [GNS3](http://www.gns3.net). Additionally, you will need a Cisco IOS image to use with GNS3 for the Cisco elements. * [VirtualBox](http://www.virtualbox.org). * An [Ubuntu Server](http://www.ubuntu.com/) base install. For this example, I'm using Ubuntu 16.04.1 LTS. ## Versions 1. 18th Feb 2017 - First draft published online. # Create the Quagga Server I have a very basic (and by basic I mean default install, no services at all) Ubuntu installation in my VirtualBox environment. I use this to help clone Ubuntu setups. This VirtualBox VM is setup so by default it has access to the internet through the single network interface. The first step is to clone this server in VirtualBox - copying the images. This is done by selecting the Ubuntu Base image, right clicking on the entry and selecting clone. On the first page you need to define the name of the VirtualBox server (this is important, so hold onto that information for later): ![Clone1]({{ site.baseurl }}/img/quagga-tutorial/clone1.png) I typically go for Full Clone, but you can go for Linked Clone if you know what you're doing: ![Clone2]({{ site.baseurl }}/img/quagga-tutorial/clone2.png) Once that's complete, boot up the VM. Log into the VM and then run the command sudo apt-get install quagga And you now have Quagga installed on the machine. The next step is to halt the quagga server, and then change the network configuration. If you right click on the server, select Settings and go to Network you will see that Adapter1 is enabled, and attached to NAT. If you select Adapter2 you will see it's not attached to anything. ![Adapter1 before]({{ site.baseurl }}/img/quagga-tutorial/quagga-network-before-1.png) ![Adapter2 before]({{ site.baseurl }}/img/quagga-tutorial/quagga-network-before-2.png) Before we move on, we need to detach the first adapter as by unchecking the Enable Network Adapter box (Alternatively, you can set this to Generic Driver if you want, but GNS3 will do that for you anyway in the next stage). Finally, we need to add the server to GNS3. In GNS3, go GNS3->Preferences->VirtualBox VMs and select New. A Dropdown list of all the VMs in Virtualbox will be shown and you can select the instance you've installed Quagga on. ![Add VM to GNS]({{ site.baseurl }}/img/quagga-tutorial/addtogns1.png) However, this typically adds the VM with a single interface - you need multiple interfaces for the lab set so select the VM, then click Edit and on the Network screen, increase the number of Adapters to 4. ![Increase Adapter Counter Screenshot]({{ site.baseurl }}/img/quagga-tutorial/addtogns2.png) # GNS3 Topology / IP Allocation. Before we go on, the next step is to layout the topology for this lab. As we're trying to cover both OSPF and BGP, we will set up three Cisco routers as well as the Quagga router: ![Network Topology]({{ site.baseurl }}/img/quagga-tutorial/topology.png) In the diagram above, the Quagga router is the Grey router. R1, R2 and R3 are all Cisco routers. IP Allocations are as follows: <table> <tr> <th>Subnet</th> <th>Hosts</th> </tr> <tr><td>192.168.1.0/24</td><td>Host 1 to R1</td></tr> <tr><td>192.168.2.0/24</td><td>Host 2 to R2</td></tr> <tr><td>192.168.3.0/25</td><td>Used for Loopbacks on R1 and R2</td> </tr> <tr><td>192.168.3.128/30</td><td>R1 to Quagga router</td></tr> <tr><td>192.168.3.132/30</td><td>R2 to Quagga router</td></tr> <tr><td>172.16.1.0/24</td><td>BGP Peering LAN between Quagga and R3</td></tr> <tr><td>172.16.2.0/24</td><td>Host 3 to R3</td></tr> <tr><td>172.16.3.3/32</td><td>Loopback on R3</td></tr> </table> R1, R2 and Quagga are all in AS65001 and will use OSPF for dynamic routing accross the PtP links. The routes in AS65001 can all be summarised under 192.168.0.0/22 and this summary route will be used in BGP peering between Quagga and R3. The routes with AS65002 will be advertised to the Quagga router, which will then redistribute those routes into the IGP to deliver full connectivity. We won't go into details on how to setup the Ubuntu Hosts and I'm simply supplying the Cisco Router configurations ([R1]({{ site.baseurl }}/files/quagga-tutorial/r1.conf), [R2]({{ site.baseurl }}/files/quagga-tutorial/r2.conf), and [R3]({{ site.baseurl }}/files/quagga-tutorial/r3.conf)) Within GNS3, I set things up so that Ethernet1 on the Quagga device connects to R1, Ethernet2 to R2 and Ethernet3 to R3. Note though that as Ubuntu 16 uses systemd, the interfaces aren't eth1, eth2 and eth3. # Configuring Quagga Quagga is not a single server on a Linux box, but actually consists of several seperate daemons, each running a particular routing protocol. By default, none of the daemons are configured to run so the first thing we need to do is turn on the specific daemons we require. Using your preferred editor of choice (vim, emacs, pico) edit /etc/quagga/daemons to read as follows zebra=yes bgpd=yes ospfd=yes ospf6d=no ripd=no ripngd=no isisd=no babeld=no Then change into /etc/quagga and do the following: sudo touch zebra.conf bgpd.conf ospfd.conf sudo chown quagga.quaggavty zebra.conf bgpd.conf ospfd.conf Then restart the quagga service sudo /etc/init.d/quagga restart Finally, you need to enable ip forwarding in the Linux kernel: sysctl -w net.ipv4.ip_forward=1 If this has all been done correctly, it should then be possible to connect and manage the quagga instances using vtysh. This moves you from the UNIX command line into a more Cisco IOS style of environment. However, there is one last niggle. For some reason, the vtysh interface defaults to using less as its pager of choice. You will find it annoying hitting q all the time so I suggest changing the pager to use more. You can do this from the command line by executing the following: VTYSH_PAGER=more;export VTYSH_PAGER Then enter the quagga configuration mode - you may need to run this as sudo. vtysh This environment is a little like Cisco, but not completely. Entering configuration mode is done in the same way you would on a Cisco device ## OSPF Configuration interface enp0s8 description ethernet1 ip address 192.168.3.130/30 ! interface enp0s9 description ethernet2 ip address 192.168.3.134/30 ! router ospf network 192.168.0.0/22 area 0.0.0.0 The use of enp0s8 and enp0s9 is a feature of systemd and the fact we're using Ubuntu 16 - if you're using an earlier version, the interface names will be different. You can then save the configuration in a similar way to a Cisco IOS device: ubuntu# wr Building Configuration... Configuration saved to /etc/quagga/zebra.conf Configuration saved to /etc/quagga/ospfd.conf Configuration saved to /etc/quagga/bgpd.conf [OK] You can now verify OSPF adjacencies are up in the vtysh environment: ubuntu# sh ip ospf neighbor Neighbor ID Pri State Dead Time Address Interface RXmtL RqstL DBsmL 192.168.3.1 1 Full/DR 30.647s 192.168.3.129 enp0s8:192.168.3.130 0 0 0 192.168.3.2 1 Full/DR 37.764s 192.168.3.133 enp0s9:192.168.3.134 0 0 0 ubuntu# show ip route Codes: K - kernel route, C - connected, S - static, R - RIP, O - OSPF, I - IS-IS, B - BGP, P - PIM, A - Babel, > - selected route, * - FIB route C>* 127.0.0.0/8 is directly connected, lo O>* 192.168.1.0/24 [110/11] via 192.168.3.129, enp0s8, 00:08:17 O>* 192.168.2.0/24 [110/11] via 192.168.3.133, enp0s9, 00:08:21 O>* 192.168.3.1/32 [110/11] via 192.168.3.129, enp0s8, 00:08:17 O>* 192.168.3.2/32 [110/11] via 192.168.3.133, enp0s9, 00:08:21 O 192.168.3.128/30 [110/10] is directly connected, enp0s8, 00:08:21 C>* 192.168.3.128/30 is directly connected, enp0s8 O 192.168.3.132/30 [110/10] is directly connected, enp0s9, 00:08:26 C>* 192.168.3.132/30 is directly connected, enp0s9 ## BGP Configuration There are two parts to the BGP configuration - again, this is quite similar to the Cisco style, though there are a couple of differences. interface enp0s10 description ethernet3 - BGP Peering ip address 172.16.1.1/24 router bgp 65001 bgp router-id 192.168.3.134 network 192.168.0.0/22 neighbor 172.16.1.3 remote-as 65002 ! router ospf redistribute bgp ! ip route 192.168.0.0/22 Null0 BGP show commands are very similar: buntu# show ip bgp sum BGP router identifier 192.168.3.134, local AS number 65001 RIB entries 5, using 560 bytes of memory Peers 1, using 4568 bytes of memory Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down State/PfxRcd 172.16.1.3 4 65002 10 10 0 0 0 00:06:06 2 Total number of neighbors 1 ubuntu# show ip bgp BGP table version is 0, local router ID is 192.168.3.134 Status codes: s suppressed, d damped, h history, * valid, > best, = multipath, i internal, r RIB-failure, S Stale, R Removed Origin codes: i - IGP, e - EGP, ? - incomplete Network Next Hop Metric LocPrf Weight Path *> 172.16.2.0/24 172.16.1.3 0 0 65002 i *> 172.16.3.3/32 172.16.1.3 0 0 65002 i *> 192.168.0.0/22 0.0.0.0 0 32768 i Total number of prefixes 3 ubuntu# show ip bgp nei 172.16.1.3 routes BGP table version is 0, local router ID is 192.168.3.134 Status codes: s suppressed, d damped, h history, * valid, > best, = multipath, i internal, r RIB-failure, S Stale, R Removed Origin codes: i - IGP, e - EGP, ? - incomplete Network Next Hop Metric LocPrf Weight Path *> 172.16.2.0/24 172.16.1.3 0 0 65002 i *> 172.16.3.3/32 172.16.1.3 0 0 65002 i Total number of prefixes 2 ubuntu# show ip bgp nei 172.16.1.3 BGP neighbor is 172.16.1.3, remote AS 65002, local AS 65001, external link BGP version 4, remote router ID 172.16.3.3 BGP state = Established, up for 00:06:38 Last read 00:00:45, hold time is 180, keepalive interval is 60 seconds Neighbor capabilities: 4 Byte AS: advertised Route refresh: advertised and received(old & new) Address family IPv4 Unicast: advertised and received Graceful Restart Capabilty: advertised Message statistics: Inq depth is 0 Outq depth is 0 Sent Rcvd Opens: 1 1 Notifications: 0 0 Updates: 1 1 Keepalives: 8 8 Route Refresh: 0 0 Capability: 0 0 Total: 10 10 Minimum time between advertisement runs is 30 seconds For address family: IPv4 Unicast Community attribute sent to this neighbor(both) 2 accepted prefixes Connections established 1; dropped 0 Last reset never Local host: 172.16.1.1, Local port: 53632 Foreign host: 172.16.1.3, Foreign port: 179 Nexthop: 172.16.1.1 Nexthop global: fe80::a00:27ff:fe11:9481 Nexthop local: :: BGP connection: non shared network Read thread: on Write thread: off And finally we can see that host3 can reach host1 and host2: thomas@ubuntu:~$ ping -c 5 192.168.1.10 PING 192.168.1.10 (192.168.1.10) 56(84) bytes of data. 64 bytes from 192.168.1.10: icmp_seq=1 ttl=61 time=79.2 ms 64 bytes from 192.168.1.10: icmp_seq=2 ttl=61 time=67.3 ms 64 bytes from 192.168.1.10: icmp_seq=3 ttl=61 time=77.6 ms 64 bytes from 192.168.1.10: icmp_seq=4 ttl=61 time=74.6 ms 64 bytes from 192.168.1.10: icmp_seq=5 ttl=61 time=80.1 ms --- 192.168.1.10 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4007ms rtt min/avg/max/mdev = 67.353/75.798/80.153/4.638 ms thomas@ubuntu:~$ ping -c 5 192.168.2.10 PING 192.168.2.10 (192.168.2.10) 56(84) bytes of data. 64 bytes from 192.168.2.10: icmp_seq=1 ttl=61 time=35.2 ms 64 bytes from 192.168.2.10: icmp_seq=2 ttl=61 time=43.2 ms 64 bytes from 192.168.2.10: icmp_seq=3 ttl=61 time=72.3 ms 64 bytes from 192.168.2.10: icmp_seq=4 ttl=61 time=106 ms 64 bytes from 192.168.2.10: icmp_seq=5 ttl=61 time=78.3 ms --- 192.168.2.10 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4006ms rtt min/avg/max/mdev = 35.266/67.233/106.897/25.761 ms thomas@ubuntu:~$ traceroute 192.168.1.10 traceroute to 192.168.1.10 (192.168.1.10), 30 hops max, 60 byte packets 1 172.16.2.1 (172.16.2.1) 9.355 ms 9.164 ms 8.881 ms 2 172.16.1.1 (172.16.1.1) 20.742 ms 33.116 ms 32.974 ms 3 192.168.3.129 (192.168.3.129) 32.824 ms 43.471 ms 54.863 ms 4 192.168.1.10 (192.168.1.10) 65.912 ms 76.476 ms 87.405 ms So we now have a fully connected network using Quagga where BGP and OSPF is required to enable the connectivity between all the devices. # Conclusions Hopefully that was useful for some of you. If you have any feedback, please email me at thomasb@gmail.com - I'd love to hear from you. ## Useful Resources * [GNS File]({{ site.baseurl }}/files/quagga-tutorial/quagga-lab.gns3)
C++
UTF-8
976
3.125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: int numUniqueEmails(vector<string>& emails) { unordered_set<string> us; for (string email : emails) { string normalized; bool local = true; for (int i = 0, length = email.length(); i < length; ++i) { if (local) { while (email[i] == '.') ++i; if (email[i] == '+') { while (email[i] != '@') ++i; } } if (email[i] == '@') { local = false; } normalized += email[i]; } us.insert(normalized); } return us.size(); } }; int main() { vector<string> emails { "test.email+alex@leetcode.com", "test.e.mail+bob.cathy@leetcode.com", "testemail+david@lee.tcode.com", }; int ret = Solution().numUniqueEmails(emails); cout << ret << endl; }
Java
UTF-8
379
1.585938
2
[ "Apache-2.0" ]
permissive
package com.atguigu.gmall.ums.dao; import com.atguigu.gmall.ums.entity.MemberLoginLogEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 会员登录记录 * * @author canjian * @email * @date 2021-12-25 14:10:10 */ @Mapper public interface MemberLoginLogDao extends BaseMapper<MemberLoginLogEntity> { }
C#
UTF-8
1,313
3.234375
3
[]
no_license
/* * Link: https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/submissions/ * Author: Dung Nguyen Tien (Chris) */ public class Solution { public int CountComponents(int n, int[][] edges) { if (edges.Length == 0 || edges[0].Length == 0) return n; var map = CreateMap(n, edges); var visited = new HashSet<int>(); var count = 0; for (var i = 0; i < n; i++) { if (!visited.Contains(i)) { visited.Add(i); dfs(map, visited, i); count++; } } return count; } public void dfs(List<IList<int>> map, HashSet<int> visited, int x) { foreach(var node in map[x]) { if (!visited.Contains(node)) { visited.Add(node); dfs(map, visited, node); } } } public List<IList<int>> CreateMap(int n, int[][] edges) { var map = new List<IList<int>>(); for (var i = 0; i < n; i ++) { map.Add(new List<int>()); } foreach(var edge in edges) { map[edge[0]].Add(edge[1]); map[edge[1]].Add(edge[0]); } return map; } }
Java
UTF-8
264
1.882813
2
[]
no_license
package samplePackage1; import samplePackage2.sP2_class2; public class sP1_class1 extends sP2_class2{ public static void main(String[] args) { // TODO Auto-generated method stub sP2_class2 ob = new sP2_class2(); ob.display(); } }
Markdown
UTF-8
1,744
2.921875
3
[ "MIT" ]
permissive
# 《全栈之巅》学习笔记-登陆接口 ## 1. 在login.vue中增加接口请求 ``` methods:{ async login(){ const res=await this.$http.post('login',this.model) localStorage.token=res.data.token this.$router.push('/') this.$message({ type:'success', message:'登陆成功' }) } ``` ## 2. 去index.js中增加接口 ``` app.post('/admin/api/login', async (req, res) => { const { username, password } = req.body const user = await AdminUser.findOne({username}).select('+password') assert(user,422,'用户不存在') const isValid=require('bcrypt').compareSync(password,user.password) assert(isValid,422,'密码错误') const token=jwt.sign({id:user._id},app.get('secret')) res.send({token}) }) ``` ## 3. 全局捕获错误 * http-request拦截器 ``` http.interceptors.request.use(function (config) { // Do something before request is sent if (localStorage.token) { //请求头,格式为:Bearer+空格+token,服务端会提取这个请求的token config.headers.Authorization = 'Bearer ' + localStorage.token } return config; }, function (error) { // Do something with request error return Promise.reject(error); }); ``` * http-response加上拦截器 ``` http.interceptors.response.use(res=>{ return res },err => { if(err.response.data.message){ Vue.prototype.$message({ type:'error', message:err.response.data.message }) if(err.response.status === 401){ router.push('/login') //有任何错误,服务端会限制它跳回登录页 } } return Promise.reject(err) }) ```
JavaScript
UTF-8
1,134
2.59375
3
[ "MIT", "BSD-3-Clause" ]
permissive
require(['jquery', 'ejs'], function ($, EJS) { var photographerId = $('#photographer').data('photographer').id; var trStr = '<tr><td><%= items.join("</td><td>") %></td></tr>'; var template = new EJS({ text: trStr }); $('.coupon .form-inline').on('click', '.btn-exchange', function () { var $exchangeBtn = $(this); var $input = $exchangeBtn.siblings().find('input'); var code = $input.val(); if (code.trim() === '') { $input.focus(); return ; } $.post('/coupon/accessile', { id: photographerId, exchangeCode: code }) .done(function (result) { console.log(result); var data; if (result.retCode == 200 ) { data = result.data; data.length > 0 && $('.' + $exchangeBtn.data('targetClass')).append(template.render({items: data})); } else { alert('添加兑换券失败:' + result.retDesc + ',请刷新重试!'); } }) .fail(function (jqXHR, textStatus) { alert('添加兑换券失败: ' + textStatus + ',请刷新重试!'); }); }); });
Java
UTF-8
727
2.5
2
[]
no_license
package de.fiduciagad.ase.postagecharge; import static de.fiduciagad.ase.postagecharge.DefinitionBuilder.definitionOfType; import static de.fiduciagad.ase.postagecharge.Range.RangeBuilder.from; import static de.fiduciagad.ase.postagecharge.Type.LETTER; public final class Definitions { private Definitions() { super(); } public static final Definition STANDARD_LETTER = definitionOfType(LETTER) .length(from(14).to(23.5)).width(from(9).to(12.5)) .height(from(0).to(0.5)).gramm(from(0).to(20)).build(); public static final Definition KOMPAKT_LETTER = definitionOfType(LETTER) .length(from(10).to(23.5)).width(from(7).to(12.5)) .height(from(0).to(1)).gramm(from(0).to(50)).build(); }
Ruby
UTF-8
88
3.140625
3
[]
no_license
class Piece def initialize(x, y, color) @x = x @y = y @color = color end end
C#
UTF-8
957
2.59375
3
[]
no_license
using Questionnaires.QL.AST.Types; using System.Diagnostics; using System.Windows.Controls; namespace Questionnaires.UI.Widgets { public class CheckBoxWidget : QuestionWidget { private CheckBox CheckBox; public CheckBoxWidget() : base(new CheckBox()) { Debug.Assert(Control.GetType() == typeof(CheckBox)); CheckBox = Control as CheckBox; CheckBox.Checked += (sender, args) => OnInputChanged(new BooleanType(CheckBox.IsChecked.Value)); CheckBox.Unchecked += (sender, args) => OnInputChanged(new BooleanType(CheckBox.IsChecked.Value)); } public override void SetQuestionValue(IType value) { Debug.Assert(value.GetType() == typeof(BooleanType)); SetQuestionValue((dynamic)value); } public void SetQuestionValue(BooleanType value) { CheckBox.IsChecked = value.GetValue(); } } }
Java
UTF-8
1,086
1.960938
2
[]
no_license
package com.lizc.app.network.http.datasource; import com.lizc.app.network.http.config.LizcHttpConfig; import com.lizc.app.network.http.datasource.base.INewContentDataSource; import com.lizc.app.network.http.request.GetHomeRecommendsRequest; import com.lizc.app.network.http.service.ApiService; import com.lizc.app.network.model.NewContent; import com.njcool.lzccommon.network.http.basis.BaseRemoteDataSource; import com.njcool.lzccommon.network.http.basis.callback.RequestCallback; import com.njcool.lzccommon.network.viewmodel.base.BaseViewModel; /** * 作者:leavesC * 时间:2019/1/30 0:49 * 描述: */ public class NewsContentDataSource extends BaseRemoteDataSource implements INewContentDataSource { public NewsContentDataSource(BaseViewModel baseViewModel) { super(baseViewModel); } @Override public void getNewContent(GetHomeRecommendsRequest getHomeRecommendsRequest, RequestCallback<NewContent> callback) { execute(getService(ApiService.class, LizcHttpConfig.BASE_URL).getNewContents(getHomeRecommendsRequest), callback); } }
Shell
UTF-8
1,144
2.6875
3
[]
no_license
GREEN='\033[1;32m' NC='\033[0m' WORKER1_IP="172.16.0.2" WORKER2_IP="172.16.0.3" MASTER_IP="172.16.0.1" MASTER_MGMT_IP="172.30.0.51" WORKER1_MGMT_IP="172.30.0.52" WORKER2_MGMT_IP="172.30.0.53" CLEAR_IPTABLES="sudo iptables -t nat -F && sudo iptables -F && sudo iptables -X" eval $CLEAR_IPTABLES ssh -i ~/.ssh/worker1 oscar@$WORKER1_MGMT_IP "eval $CLEAR_IPTABLES" ssh -i ~/.ssh/worker2 oscar@$WORKER2_MGMT_IP "eval $CLEAR_IPTABLES" # CHANGE_OVSDB_PORT="sudo sed -i \'/set ovsdb-server \"\$DB_FILE\"/a \\ set \\\"\$\@\\\" --remote=ptcp:6650\' /usr/local/share/openvswitch/scripts/ovs-ctl && \ # sudo /usr/local/share/openvswitch/scripts/ovs-ctl restart" # eval $CHANGE_OVSDB_PORT # ssh -i ~/.ssh/worker1 oscar@$WORKER1_MGMT_IP "eval $CHANGE_OVSDB_PORT" # ssh -i ~/.ssh/worker2 oscar@$WORKER2_MGMT_IP "eval $CHANGE_OVSDB_PORT" sudo rm -rf /root/.kube/config sudo mkdir -p /root/.kube sudo cp $HOME/.kube/config /root/.kube/config printf "\nRemember to copy kube config to /root/.kube/config on all minion(worker) nodes:\n\n" printf "${GREEN}\tsudo rm -rf /root/.kube \tsudo mkdir -p /root/.kube \tsudo cp -r $HOME/.kube /root${NC}\n\n"
Java
UTF-8
8,513
1.773438
2
[]
no_license
package uk.ee.framework.elements.sections.shop; import java.util.concurrent.TimeUnit; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import ru.yandex.qatools.htmlelements.element.Select; import ru.yandex.qatools.htmlelements.element.TextInput; import uk.ee.framework.business_objects.dao.customer.Customer; import uk.ee.framework.elements.common.Button; import uk.ee.framework.elements.common.CheckBox; import uk.ee.framework.elements.common.Link; import uk.ee.framework.elements.common.TextBlock; import uk.ee.framework.elements.webdriver_aware.CustomHtmlElement; import uk.ee.framework.utils.Waiter; /** * Created by Syamphaneendra Kalluri on 06/06/2016 * Modified by prabhu_S on 07/13/2016 * This class represents the selenium version of the Personal Details section. * */ public class PersonalDetails extends CustomHtmlElement { @FindBy(css = "input#email") TextInput email; @FindBy(css = "select#title") Select title; @FindBy(css = "input#firstName") TextInput firstName; @FindBy(css = "input#initials") TextInput initial; @FindBy(css = "input#lastName") TextInput lastName; @FindBy(css = "input#contactNumber") TextInput contactNumber; @FindBy(css = "input#alternativeNumber") TextInput alternativeNumber; @FindBy(css = "select#dob_day") Select dob_day; @FindBy(css = "select#dob_month") Select dob_month; @FindBy(css = "select#dob_year") Select dob_year; @FindBy(css = "input#useDeliveryAddress") CheckBox useDeliveryAddress; @FindBy(css = "input#lookup_postcode_currentAddress") TextInput postcode; @FindBy(css = "a#link_lookup_postcode_currentAddress") Link findAddress; @FindBy(css = "input#companyName_currentAddress") TextInput companyName; @FindBy(css = "input#building_currentAddress") TextInput building; @FindBy(css = "input#street1_currentAddress") TextInput address1; @FindBy(css = "input#town_currentAddress") TextInput townName; @FindBy(css = "input#postCode_currentAddress") TextInput postCodeCurrentAddress; @FindBy(css = "select#currentAddressMonth") Select currentAddressMonth; @FindBy(css = "select#currentAddressYear") Select currentAddressYear; @FindBy(id = "employmentType") Select employmentType; @FindBy(css = "select#startMonthOfEmployment") Select startMonthOfEmployment; @FindBy(css = "select#startYearOfEmployment") Select startYearOfEmployment; @FindBy(css = "select#startMonthOfBank") Select startMonthOfBank; @FindBy(css = "select#startYearOfBank") Select startYearOfBank; @FindBy(css="select#addressList_currentAddress_select") Select addressList; @FindBy(css = "input.checkout-cta") Button nextStep; /*SB customer*/ @FindBy(css="input#businessCompanyName") WebElement businessCompanyName; @FindBy(xpath="//input[@id='tradingName']") WebElement tradingName; @FindBy(css = "input#buildingNumber_deliveryAddress") WebElement houseNumber; @FindBy(css = "input#county_deliveryAddress") TextInput country; @FindBy(css = "input#buildingNumber_currentAddress") WebElement sbHouseNumber; @FindBy(css = "input#county_currentAddress") TextInput sbCountry; @FindBy(css = "span.ee-form-message.ee-form-message--active") TextBlock errorMsg; /** * @param customerObj */ private void proceedBasicPersonalDetails(final Customer customerObj) { email.sendKeys(customerObj.getEmail()); title.selectByValue(customerObj.getTitle()); initial.sendKeys(customerObj.getInitial()); firstName.sendKeys(customerObj.getFirstName()); lastName.sendKeys(customerObj.getLastName()); contactNumber.sendKeys(customerObj.getContactNumber()); alternativeNumber.sendKeys(customerObj.getAlternativeNumber()); dob_day.selectByValue(customerObj.getDob_day()); dob_month.selectByValue(customerObj.getDob_month()); dob_year.selectByValue(customerObj.getDob_year()); } /** * @param customerObj */ public void proceedPersonalDetails(final Customer customerObj) { proceedBasicPersonalDetails(customerObj); if ("true".equalsIgnoreCase(customerObj.getUseDeliveryAddress())) { useDeliveryAddress.set(Boolean.TRUE); } else { useDeliveryAddress.set(Boolean.FALSE); } /* * postcode.sendKeys(customerObj.getPostcode()); * companyName.sendKeys(customerObj.getCompanyName()); * building.sendKeys(customerObj.getBuilding()); * address1.sendKeys(customerObj.getAddress1()); * townName.sendKeys(customerObj.getTownName()); * postCodeCurrentAddress.sendKeys(customerObj.getPostCodeCurrentAddress * ()); */ currentAddressMonth.selectByValue(customerObj.getCurrentAddressMonth()); currentAddressYear.selectByValue(customerObj.getCurrentAddressYear()); employmentType.selectByValue(customerObj.getEmploymentType()); startMonthOfEmployment.selectByValue(customerObj.getStartMonthOfEmployment()); startYearOfEmployment.selectByValue(customerObj.getStartYearOfEmployment()); startMonthOfBank.selectByValue(customerObj.getStartMonthOfBank()); startYearOfBank.selectByValue(customerObj.getStartYearOfBank()); nextStep.click(); } /** * @param customerObj */ public void proceedPaygPersonalDetails(final Customer customerObj) { proceedBasicPersonalDetails(customerObj); if ("true".equalsIgnoreCase(customerObj.getUseDeliveryAddress())) { useDeliveryAddress.set(Boolean.TRUE); } else { useDeliveryAddress.set(Boolean.FALSE); } nextStep.click(); } /** * @param customerObj */ public void proceedSIMOPaygPersonalDetails(final Customer customerObj) { proceedBasicPersonalDetails(customerObj); selectPersonalAddress(customerObj.getPostcode()); // Setting SIMO address /*postcode.sendKeys(customerObj.getPostcode()); findAddress.click(); addressList.selectByValue("2");*/ nextStep.click(); } /** * @param customerObj */ public void proceedSIMOPersonalDetails(final Customer customerObj) { proceedBasicPersonalDetails(customerObj); //setting SIMO address postcode.sendKeys(customerObj.getPostcode()); findAddress.click(); currentAddressMonth.selectByValue(customerObj.getCurrentAddressMonth()); currentAddressYear.selectByValue(customerObj.getCurrentAddressYear()); employmentType.selectByValue(customerObj.getEmploymentType()); startMonthOfEmployment.selectByValue(customerObj.getStartMonthOfEmployment()); startYearOfEmployment.selectByValue(customerObj.getStartYearOfEmployment()); startMonthOfBank.selectByValue(customerObj.getStartMonthOfBank()); startYearOfBank.selectByValue(customerObj.getStartYearOfBank()); addressList.selectByIndex(1); nextStep.click(); } public void proceedSBSoleTraderDetails(String postCode, final Customer customerObj) { businessCompanyName.sendKeys("Everything"); tradingName.sendKeys("Everywhere"); proceedBasicPersonalDetails(customerObj); selectSBAddress(customerObj.getPostcode()); currentAddressMonth.selectByValue(customerObj.getCurrentAddressMonth()); currentAddressYear.selectByValue(customerObj.getCurrentAddressYear()); employmentType.selectByValue(customerObj.getEmploymentType()); startMonthOfEmployment.selectByValue(customerObj.getStartMonthOfEmployment()); startYearOfEmployment.selectByValue(customerObj.getStartYearOfEmployment()); startMonthOfBank.selectByValue(customerObj.getStartMonthOfBank()); startYearOfBank.selectByValue(customerObj.getStartYearOfBank()); nextStep.click(); } public void selectPersonalAddress(final String postCode) { try { postcode.sendKeys(postCode); findAddress.click(); if (houseNumber.isDisplayed()) { houseNumber.sendKeys("2"); address1.sendKeys("Marsh Layne"); townName.sendKeys("Leeds"); country.sendKeys("UK"); } else { addressList.selectByIndex(2); } } catch (NoSuchElementException e) { addressList.selectByIndex(2); } } public void selectSBAddress(final String postCode) { try { postcode.sendKeys(postCode); findAddress.click(); System.out.println("errorMsg.isDisplayed()" + errorMsg.isDisplayed()); webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); System.out.println("houseNumber.isDisplayed()" + houseNumber.isDisplayed()); if (sbHouseNumber.isDisplayed()) { sbHouseNumber.sendKeys("2"); address1.sendKeys("Marsh Layne"); townName.sendKeys("Leeds"); sbCountry.sendKeys("UK"); } else { addressList.selectByIndex(2); } } catch (NoSuchElementException e) { addressList.selectByIndex(2); } } public void continueToNext() { nextStep.click(); } }
Markdown
UTF-8
866
2.6875
3
[]
no_license
# JAVA ALGORITHM 6 ### 문제 수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일 때 걷는다면 1초 후에 X-1 또는 X+1로 이동하게 된다. 순간이동을 하는 경우에는 1초 후에 2*X의 위치로 이동하게 된다. 수빈이와 동생의 위치가 주어졌을 때, 수빈이가 동생을 찾을 수 있는 가장 빠른 시간이 몇 초 후인지 구하는 프로그램을 작성하시오. ### 입력 첫 번째 줄에 수빈이가 있는 위치 N과 동생이 있는 위치 K가 주어진다. ### 출력 수빈이가 동생을 찾는 가장 빠른 시간을 출력한다. # Code `````java ````` # 풀이 ## Info ### 분석 ### func1
Java
UTF-8
1,966
2.765625
3
[]
no_license
package nl.jellow.wimalert.util; import android.util.Log; import android.util.Pair; import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import nl.jellow.wimalert.App; /** * Created by Jelle on 12-11-2016. */ public class Aes { public static final int BYTE_LENGTH = 16; public static final int BIT_LENGTH = BYTE_LENGTH * 8; private static final String TAG = App.TAG; private static final String ALGORITHM = "AES/CBC/NoPadding"; public static byte[] getKeyFromPassword(final String password) { // Get the SHA-256 hash of the password // Use the first 16 bytes as the key final byte[] key = new byte[BYTE_LENGTH]; final MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-256"); final byte[] hash = digest.digest(password.getBytes("UTF-8")); System.arraycopy(hash, 0, key, 0, BYTE_LENGTH); } catch (final Exception e) { Log.e(TAG, "Couldn't generate key from password", e); } return key; } private static byte[] padd(final byte[] input) { if (input.length % BYTE_LENGTH == 0) { return input; } final byte[] output = new byte[(input.length + BYTE_LENGTH - 1) / BYTE_LENGTH * BYTE_LENGTH]; Arrays.fill(output, (byte)0); System.arraycopy(input, 0, output, 0, input.length); return output; } public static Pair<byte[], byte[]> encrypt(final String message, final byte[] key) { try { final SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); final Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, keySpec); final byte[] iv = c.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); final byte[] encrypted = c.doFinal(padd(message.getBytes("UTF-8"))); return new Pair<>(iv, encrypted); } catch (final Exception e) { Log.e(TAG, "Couldn't encrypt message", e); } return new Pair<>(new byte[0], new byte[0]); } }