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
Rust
UTF-8
1,397
2.90625
3
[]
no_license
use std::prelude::v1::*; use std::boxed::FnBox; use client::ClientObj; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum KeyAction { MoveLeft(u8), MoveRight(u8), MoveUp(u8), MoveDown(u8), Select, Cancel, SetHotbar(i8), ToggleDebugPanel, } impl KeyAction { pub fn from_code(code: u8) -> Option<KeyAction> { use self::KeyAction::*; match code { 0 => Some(MoveLeft(1)), 1 => Some(MoveRight(1)), 2 => Some(MoveUp(1)), 3 => Some(MoveDown(1)), 10 => Some(MoveLeft(10)), 11 => Some(MoveRight(10)), 12 => Some(MoveUp(10)), 13 => Some(MoveDown(10)), 20 => Some(Select), 21 => Some(Cancel), 31 ... 39 => Some(SetHotbar(code as i8 - 31)), 114 => Some(ToggleDebugPanel), _ => None, } } } pub enum EventStatus { Unhandled, Handled, //UseDefault, // TODO: would like to use `&mut Client`, but don't want to thread <GL> all around Action(Box<FnBox(&mut ClientObj)>), } impl EventStatus { pub fn action<F: FnOnce(&mut ClientObj)+'static>(f: F) -> EventStatus { EventStatus::Action(box f) } pub fn is_handled(&self) -> bool { match *self { EventStatus::Unhandled => false, _ => true, } } }
PHP
UTF-8
747
2.796875
3
[ "MIT" ]
permissive
<?php namespace bot\object; /** * Contains information about why a request was unsuccessfull. * * @method bool hasMigrateToChatId() * @method bool hasRetryAfter() * @method int getMigrateToChatId($default = null) * @method int getRetryAfter($default = null) * * @author Mehdi Khodayari <mehdi.khodayari.khoram@gmail.com> * @since 2.0.1 * * Class ResponseParameters * @package bot\object * @link https://core.telegram.org/bots/api#responseparameters */ class ResponseParameters extends Object { /** * Every object have relations with other object, * in this method we introduce all object we have relations. * * @return array of objects */ protected function relations() { return []; } }
C++
UTF-8
274
2.90625
3
[]
no_license
#pragma once #include<list> using std::list; struct FPNode { FPNode() { item_name = -1; parent = nullptr; count = 0; } FPNode(int name, FPNode* p) { item_name = name; parent = p; count = 1; } int item_name; int count; list<FPNode*> childs; FPNode* parent; };
Swift
UTF-8
787
3.109375
3
[]
no_license
// // StringExtension.swift // MyTVShows // // Created by Juan Jose Elias Navarro on 30/08/21. // import UIKit extension String { func height(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) return ceil(boundingBox.height) } func width(height: CGFloat, font: UIFont) -> CGFloat{ let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) return ceil(boundingBox.width) } }
JavaScript
UTF-8
2,388
2.703125
3
[ "MIT" ]
permissive
// Generated by github.com/steida/coffee2closure 0.0.14 /** @fileoverview Watch clicking on anchors elements. It uses Polymer PointerEvents to enable fast click on touch devices. Note, this trick does not work on iOS also sometimes we need zoom. https://plus.google.com/u/0/+RickByers/posts/ej7nsuoaaDa @see TODO */ goog.provide('este.labs.events.AnchorClickHandler'); goog.require('este.Base'); goog.require('este.thirdParty.pointerEvents'); /** @param {Element=} element @constructor @extends {este.Base} */ este.labs.events.AnchorClickHandler = function(element) { this.element = element != null ? element : document.documentElement; este.labs.events.AnchorClickHandler.superClass_.constructor.call(this); este.thirdParty.pointerEvents.install(); this.registerEvents(); } goog.inherits(este.labs.events.AnchorClickHandler, este.Base); /** @type {Element} @protected */ este.labs.events.AnchorClickHandler.prototype.element = null; /** @protected */ este.labs.events.AnchorClickHandler.prototype.registerEvents = function() { this.on(this.element, goog.events.EventType.CLICK, this.onElementClick); if (!este.thirdParty.pointerEvents.isSupported()) { return; } return this.on(this.element, goog.events.EventType.POINTERUP, this.onElementPointerUp); }; /** @param {goog.events.BrowserEvent} e @protected */ este.labs.events.AnchorClickHandler.prototype.onElementClick = function(e) { var anchor; anchor = this.tryGetClickableAnchor(e.target); if (!anchor) { return; } e.preventDefault(); if (este.thirdParty.pointerEvents.isSupported()) { return; } return this.dispatchClick(anchor); }; /** @param {goog.events.BrowserEvent} e @protected */ este.labs.events.AnchorClickHandler.prototype.onElementPointerUp = function(e) { var anchor; anchor = this.tryGetClickableAnchor(e.target); if (!anchor) { return; } return this.dispatchClick(anchor); }; /** @param {Node} node @return {Element} @protected */ este.labs.events.AnchorClickHandler.prototype.tryGetClickableAnchor = function(node) { return goog.dom.getAncestorByTagNameAndClass(node, goog.dom.TagName.A); }; /** @param {Element} anchor @protected */ este.labs.events.AnchorClickHandler.prototype.dispatchClick = function(anchor) { return this.dispatchEvent({ type: goog.events.EventType.CLICK, target: anchor }); };
Java
UTF-8
2,537
2.4375
2
[]
no_license
package com.osu.cse.apps.mobile.woof; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class FamilyMainFragment extends Fragment implements View.OnClickListener { private static final String TAG = "FamilyMainFragment"; private Button mFamiliesButton; private Button mInvitationsButton; private Button mCreateNewFamilyButton; public static FamilyMainFragment newInstance() { return new FamilyMainFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate() called"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.i(TAG, "onCreateView() called"); View v = inflater.inflate(R.layout.fragment_family_main, container, false); mFamiliesButton = v.findViewById(R.id.families_button); mFamiliesButton.setOnClickListener(this); mInvitationsButton = v.findViewById(R.id.invitations_button); mInvitationsButton.setOnClickListener(this); mCreateNewFamilyButton = v.findViewById(R.id.create_new_family_button); mCreateNewFamilyButton.setOnClickListener(this); enableButtons(true); return v; } public void onClick(View v) { enableButtons(false); Intent intent; switch(v.getId()) { case R.id.families_button: intent = FamilySelectionActivity.newIntent(getActivity()); startActivity(intent); break; case R.id.invitations_button: intent = FamilyInvitationsActivity.newIntent(getActivity()); startActivity(intent); break; case R.id. create_new_family_button: intent = CreateNewFamilyActivity.newIntent(getActivity()); startActivity(intent); break; } } @Override public void onResume(){ Log.d(TAG, "Called onResume()"); super.onResume(); enableButtons(true); } private void enableButtons(Boolean enable){ mCreateNewFamilyButton.setEnabled(enable); mInvitationsButton.setEnabled(enable); mFamiliesButton.setEnabled(enable); } }
Java
UTF-8
4,887
2.984375
3
[]
no_license
/** * */ package ru.fizteh.fivt.students.nikitaAntonov.utils; import java.util.ArrayList; import java.util.TreeMap; /** * Дешёвая въетнамская подделка под getopt (ну надо же как-то выживать в этом * жестоком мире без getopt`а) * * @author Антонов Никита */ public class OptionParser { private TreeMap<Character, Option> options; protected boolean canWorkWithoutParams = false; public ArrayList<String> freedomOpts; public OptionParser(String optstring) { if (optstring == null) { throw new NullPointerException(); } options = new TreeMap<>(); freedomOpts = new ArrayList<>(); int toSkip = 0; for (int i = 0, e = optstring.length(); i < e; ++i) { char c = optstring.charAt(i); if (toSkip > 0) { --toSkip; continue; } if (!Character.isLetterOrDigit(c)) { throw new OptstringException("Incorrect symbol '" + c + "' in optstring\n(position: " + i + ")"); } if (options.containsKey(c)) { throw new OptstringException("the symbol '" + c + "' appeared twice"); } char next = (i + 1 < e) ? optstring.charAt(i + 1) : 0; char next2 = (i + 2 < e) ? optstring.charAt(i + 2) : 0; Option.NeedValue q = Option.NeedValue.NO; if (next == ':') { if (next2 == ':') { toSkip = 2; q = Option.NeedValue.OPTIONAL; } else { toSkip = 1; q = Option.NeedValue.NECESSARY; } } options.put(c, new Option(q)); } } public void parse(String args[]) throws IncorrectArgsException { boolean skipNext = false; for (int i = 0, end = args.length; i < end; ++i) { if (skipNext) { skipNext = false; continue; } String opt = args[i]; String nextOpt = ((i + 1 < end) ? args[i + 1] : null); if (isOptions(args[i])) { skipNext = parseOption(opt.substring(1), nextOpt); } else { freedomOpts.add(opt); } } } private boolean parseOption(String opt, String next) throws IncorrectArgsException { boolean nextOptWasUsed = false; for (int i = 0, e = opt.length(); i < e; ++i) { char c = opt.charAt(i); Option o = options.get(c); if (o == null) { throw new IncorrectArgsException("Incorrect argument " + c); } if (o.qualifier == Option.NeedValue.NO || (o.qualifier == Option.NeedValue.OPTIONAL && (i + 1 != e || next == null || isOptions(next)))) { o.value = null; o.isSet = true; } else if (o.qualifier != Option.NeedValue.NO && i + 1 == e && next != null && !isOptions(next)) { o.value = next; o.isSet = true; nextOptWasUsed = true; } else { throw new IncorrectArgsException( "Incorrect usage of parameter " + c); } } return nextOptWasUsed; } public boolean has(char c) { Option o = options.get(c); if (o == null) { return false; } return o.isSet; } public boolean hasArgument(char c) { Option o = options.get(c); if (o == null) { return false; } return o.value != null; } public String valueOf(char c) { Option o = options.get(c); if (o == null) { return null; } return o.value; } static boolean isOptions(String opt) { return opt.matches("^-\\w+$"); } static class Option { public String value = null; public boolean isSet = false; public NeedValue qualifier; enum NeedValue { NO, OPTIONAL, NECESSARY }; public Option(NeedValue q) { qualifier = q; } } public static class OptstringException extends RuntimeException { private static final long serialVersionUID = -8414609923100637823L; public OptstringException(String message) { super(message); } } public static class IncorrectArgsException extends Exception { private static final long serialVersionUID = 5392124941354868981L; public IncorrectArgsException(String message) { super(message); } } }
Python
UTF-8
1,009
3.59375
4
[]
no_license
import collections from typing import List class Solution: def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]: results = [] window = collections.deque() current_max = float('-inf') for i, v in enumerate(nums): window.append(v) if i < k - 1: continue print(i, v) # 새로 추가된 값이 기존 최대값보다 큰 경우 교체 if current_max == float('-inf'): current_max = max(window) elif v > current_max: current_max = v results.append(current_max) print(window) # 최대값이 윈도우에서 빠지면 초기화 if current_max == window.popleft(): current_max = float('-inf') print(window) return results nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3 sol = Solution() chk = sol.maxSlidingWindow(nums, k) print(chk)
JavaScript
UTF-8
2,197
3.375
3
[]
no_license
var Personaje = /** @class */ (function () { function Personaje(nombre) { this.ki = 100; this.semillas = 100; this.nombre = ""; this.mana = 30; this.sayayin = 25; this.ataques = 10; this.nombre = nombre; } Personaje.prototype.ataque = function (jugadorObjetivo) { jugadorObjetivo.vida -= this.ataques; this.status(jugadorObjetivo); }; Personaje.prototype.curar = function (jugadorObjetivo) { if (this.ki >= 100) { console.log('No se puede usar esta habilidad'); } else { jugadorObjetivo.vida += 20; this.semillas -= 20; } this.status(jugadorObjetivo); }; Personaje.prototype.habilidadn = function (jugadorObjetivo) { if (this.semillas >= 30) { jugadorObjetivo.vida -= 45; this.semillas -= this.mana; } else { console.log('No hay chakra suficiente'); } this.status(jugadorObjetivo); }; Personaje.prototype.habilidad = function (jugadorObjetivo) { if (this.semillas >= 25) { jugadorObjetivo.vida -= 40; this.semillas -= this.sayayin; } else { console.log('No hay chakra suficiente'); } this.status(jugadorObjetivo); }; Personaje.prototype.revivir = function (jugadorObjetivo) { if (this.ki <= 0) { jugadorObjetivo.vida += 30; } else { console.log('No se puede usar esta habilidad'); } this.status(jugadorObjetivo); }; Personaje.prototype.recuperarChakra = function (jugadorObjetivo) { if (this.semillas >= 100) { console.log('No se puede usar esta habilidad'); } else { jugadorObjetivo.chakra += 20; } this.status(jugadorObjetivo); }; Personaje.prototype.status = function (jugadorObjetivo) { console.log(jugadorObjetivo); console.log(this); }; return Personaje; }()); var naruto = new Personaje('naruto'); var sasuke = new Personaje('sasuke'); console.log(naruto); console.log(sasuke);
Ruby
UTF-8
358
2.78125
3
[]
no_license
class Statement def view(log) print_header log.history.each do |arr| arr.each do |item| if item.class == Time print item.strftime("%c"), "\t" else print item, "\t\t" end end print "\n" end end private def print_header puts "Date\t\t\t\t Amount\t\t Balance\n" end end
Java
UTF-8
617
2.921875
3
[]
no_license
package com.wzh.crocodile.ex00_ready.thread.th01_test1; /** * @Description: 直接调用火箭发射倒计时(非多线程) * @Author: 吴智慧 * @Date: 2019/11/16 14:39 */ public class MainThread { public static void main(String[] args) { LiftOff launch = new LiftOff(); // 当从Runnable导出一个类时,必须实现run()方法,但是这个方法并无特殊之处(不会产生任何内在地线程能力) // 要实现线程行为,必须显示地将一个任务附着于线程上 // 此错火箭倒计时,不创建新线程 launch.run(); } }
C++
UTF-8
1,063
2.59375
3
[]
no_license
#ifndef CONSTANTS_H #define CONSTANTS_H namespace ACTORS { int const MENEL = 0; int const STAFF = 1; int const MANAGEMENT = 2; } namespace MENEL { int const TIMESTAMP = 10; int const DRUNK = 11; int const NOT_DRUNK = 12; int const STATE = 13; int const OUT = 14; } namespace MANAGEMENT { int const LAST_MENEL_IN = 20; int const OPEN_EXHIBITION = 21; int const END_OF_EXHIBITION = 22; } namespace STAFF { int const HELP = 30; int const TIMESTAMP = 31; int const STATUS_CHANGE = 32; //TAGTYPE int const LEAVING_FOR = 61; //MESSAGE_TYPE int const REQUESTING_ADDITIONAL = 62; //czekam na dodatkowych int const CONSENSUS = 63; int const ACCEPTED = 64; int const NORMAL = 65; int const CONTACT = 66; int const PENDING = 67; int const WHITE = 70; int const GREEN = 71; int const BLACK = 72; int const RED = 73; int const FORCE = 74; } namespace CONSTANT { int const NOT_PARTICIPATING = -100; int const NOT_IMPORTANT = -101; } #endif // CONSTANTS_H
Java
UTF-8
3,799
3.40625
3
[]
no_license
package pl.jakd.TramSim; import java.awt.geom.Point2D; import java.util.*; /** * klasa reprezentująca przystanek w symulacji * * @author jacek */ public class TramStop { private String name; // nazwa private Point2D.Double point; // pozycja na planszy private LinkedList<Passenger> passengers; // pasażerowie na przystanku private LinkedList<Tram> timtabl; // rozkład jazdy private StopWatcher watcher; // "zarządca" przystanku private LinkedList<Route> routes; // gdzie można dojechać z tego przystanku /** * tworzy nową instancję przystanku * * @param name * nazwa przystanku * @param p * położenie na mapie */ public TramStop(String name, Point2D.Double p) { this.name = name; this.point = p; watcher = new StopWatcher(this); passengers = new LinkedList<Passenger>(); timtabl = new LinkedList<Tram>(); } /** * ustala trasy przystanku, tj. trasy z danego przystanku do innych * sąsiadujących * * @param routes */ public void setRoutes(LinkedList<Route> routes) { this.routes = routes; } /** * tramwaj ogłasza za pomocą tej metody, że właśnie podjechał na przystanek * * @param t * tramwaj, który podjechał */ public void arrived(Tram t) { watcher.arrived(t); } /** * tramwaj ogłasza odjazd * * @param t * tramwaj, który ogłasza odjazd */ public void leave(Tram t) { watcher.leave(t); } /** * zwraca trasy danego przystanku, czyli gdzie można z niego dojechać * * @return trasy danego przystanku */ public LinkedList<Route> getRoutes() { return routes; } /** * zwraca położenie przystanku * * @return położenie przystanku */ public Point2D.Double getPoint() { return point; } /** * ustala rozkład jazdy, czyli tramwaj, który przejeżdża przez dany * przystanek * * @param t */ public void setTimeTable(LinkedList<Tram> t) { this.timtabl = t; } /** * dodaje tramwaj do rozkładu * * @param t * tramwaj który dodajemy do przystanku */ public void addTram(Tram t) { timtabl.add(t); } /** * zwraca zarządcę przystanku * * @return zarządca przystanku */ public StopWatcher getWatcher() { return watcher; } /** * dodaje pasażera do przystanku * * @param p * nowy oczekujący pasażer */ public void addPassenger(Passenger p) { watcher.addPassenger(p); // passengers.add(p); } /** * zwraca nazwę przystanku * * @return nazwa przystanku */ public String getName() { return name; } /** * zwraca rozkład jazdy przystanku * * @return rozkład jazdy przystanku */ public LinkedList<Tram> getTimeTable() { return timtabl; } /** * zwraca listę pasażerów oczekujących na przystanku * * @return lista pasażerów oczekujących na przystanku */ public LinkedList<Passenger> getPassengers() { return passengers; } /** * zwraca trasę prowadzącą z tego przystanku do przystanku docelowego. * jeżeli przystanek dest nie jest sąsiadem tego przystanku, czyli nie * istnieje bezpośrednia trasa do niego, wówczas zwraca null * * @param dest * przystanek do którego chcemy dojechać * @return trasa do przystanku dest z this, lub null, jeżeli nie znaleziono */ public Route getRoute(TramStop dest) { Route tmp = new Route(this, dest, null); for (Route r : routes) { if (tmp.equals(r)) return r; } return null; // nie powinno wystąpić } @Override public boolean equals(Object o) { if (o instanceof TramStop) if (((TramStop) o).name.equals(this.name)) return true; if (o instanceof String) if (o.equals(name)) return true; return false; } @Override public String toString() { return name; } }
Markdown
UTF-8
2,690
2.59375
3
[]
no_license
--- title: Patatesli Kabak Spaghetti | Potato Zucchini Spaghetti date: 2020-05-16 cover: kabak.jpeg tags: [glutensiz, vegan] --- *(6-7 Kişilik)* **Malzemeler:** - 4 haşlanmış patates - 2 domates - 1 soğan - 1 kabak - 2 havuç - 2 salatalık turşusu - 2 çorba kaşığı maydanoz - 2 çorba kaşığı dereotu - 3 çorba kaşığı zeytinyağı - Yarım limon suyu - 1 tatlı kaşığı sumak veya kırmızı biber - Tuz **Hazırlanışı:** - Tencereye 2 çorba kaşığı zeytinyağı koyup, üzerine ince doğranmış soğanları ekleyip biraz pişiriyoruz. - Kabukları soyulmuş küp küp doğranmış domates katıp tencerenin kapağını kapatıp orta ısıdaki ocakta suyunu çekene kadar pişiriyoruz. - Ardından haşlanmış ve rendelenmiş patates ekliyoruz. - Küçük doğranmış salatalık turşusunu, tuz ve biberi ilave ederek 1 dakika daha karıştırıyoruz ve ardından ocağı kapatıyoruz. - Soğumaya bırakıyoruz. - Soğuduktan sonra üzerine maydanoz ve dereotunu ekleyip karıştırıyoruz. Karışımımızı servis tabağına alıyoruz. *Başka bir tabakta ise:* - Kabak ve havucumuzu şekillendiriyoruz. Ben özel bir aparat ile kullandım. Ancak siz kabak ve havucu jülyen kesebilir veya rendeleyebilirsiniz. - Üzerine limon suyu, tuz ve 1 kaşık zeytinyağını katarak karıştırıyoruz. - Önceden servis tabağına aldığımız patatesli karışımımızın üzerine kabak ve havuç karışımımızı ekliyoruz. Afiyet olsun:) Süre: 30 dakikada hazır. <p> <iframe width="640" height="385" src="//www.youtube.com/embed/dOIg3_Qfe8o" frameborder="0" allowfullscreen> </iframe> </p> ———————————————————————————————————————————————— ## Potato Zucchini Spaghetti *(6-7 person)* **Ingredients:** - 4 boiled and grated potatoes - 2 tomatoes - 1 onion - 2 pickles - 1 zucchini - 2 carrots - 2 tablespoons parsley - 2 tablespoons dill - 3 tablespoons olive oil - Half lemon juice - 1 dessert spoon aleppo chilli pepper, or sumac - Salt **Directions:** - Place the olive oil in a medium pot over medium-low heat. Stir in onion and cook gently. - Mix in grated tomatoes and cover the pot and simmer it. - Add boiled/ grated potatoes and pickles. - Season with salt and chili pepper. Mix it 1 minute. - Remove from heat and let it get cold under room temperature. Pour into a medium bowl. *In a separate bowl:* - Grate/julienne carrot and zucchini. - Add lemon juice, salt and 1 tablespoon olive oil and mix it. - Pour into a potatoes mixture. Ready to serve. Bon Appétit:) Time: Ready in 30 minutes
Python
UTF-8
773
3.375
3
[]
no_license
# Read a video stream from camera (frame by frame) import cv2 # Capture the device from which you want to read images cap = cv2.VideoCapture(0) # 0 means default webcam while True : ret, frame = cap.read() # ret is true if image is captured properly if not ret: break gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow("Video Frame1", gray_frame) # cv2.imshow("Video Frame2", frame) #Wait for user input - enter q to stop the loop key_pressed = cv2.waitKey(1) & 0xFF #cv2.waitKey gives 32bit int #0xFF is 8bit ones #& gives last bits -> convert 32bits to 8bits since ascii values : 0-255(8bit) if key_pressed == ord('q') : break cap.release() # release device cv2.destroyAllWindows()
PHP
UTF-8
1,332
2.875
3
[ "MIT" ]
permissive
<?php namespace Ikimea\Kong\Api; use Ikimea\Kong\Client; use Ikimea\Kong\Message\ResponseMediator; abstract class AbstractApi { /** * @var Client */ protected $client; /** * @param Client $client */ public function __construct(Client $client) { $this->client = $client; } /** * @param $path * @param array $requestHeaders * @return array|string */ public function get($path, array $requestHeaders = array()) { $response = $this->client->getHttpClient()->get( $path, $requestHeaders ); return ResponseMediator::getContent($response); } /** * @param $path * @param $body * @param array $requestHeaders * @return array|string */ public function post($path, $body, array $requestHeaders = array()) { $response = $this->client->getHttpClient()->post( $path, $body, $requestHeaders ); return ResponseMediator::getContent($response); } /** * @param $response * @return bool */ public function exist($response): bool { if (isset($response['message']) && 'Not found' == $response['message']) { return false; } return true; } }
Java
UTF-8
759
1.757813
2
[ "BSD-3-Clause" ]
permissive
package elf.acceptance.test.oms.placement.common.status; import fit.ColumnFixture; import fitlibrary.DoFixture; public class PlacementStatusFixture extends DoFixture { private CreatePlacementAndCancelPlacmentFixture createPlacementAndCancelPlacment = new CreatePlacementAndCancelPlacmentFixture(); private ReceiveFillFixture receiveFill = new ReceiveFillFixture(); private CheckCreateFillResponseFixture checkCreateFillResponse = new CheckCreateFillResponseFixture(); public ColumnFixture createPlacementAndCancelPlacment() { return createPlacementAndCancelPlacment; } public ColumnFixture receiveFill() { return receiveFill; } public ColumnFixture checkCreateFillResponse() { return checkCreateFillResponse; } }
JavaScript
UTF-8
1,316
2.828125
3
[]
no_license
import RecorridoParametrico from "../recorrido_parametrico.js"; class Recta extends RecorridoParametrico { constructor(largo, cantRepeticionesTextura = 1) { super(); this.largo = largo; this.sentido = 'x'; this.cantRepeticionesTextura = cantRepeticionesTextura; } getPosicion(u) { if (!this.sentido) return [this.largo * u, 0, 0]; switch(this.sentido) { case 'x': return [this.largo * u, 0, 0]; case 'y': return [0, this.largo * u, 0]; case 'z': return [0, 0, this.largo * u]; default: return [this.largo * u, 0, 0]; } } getTangente(u) { switch(this.sentido) { case 'x': return [1, 0, 0]; case 'y': return [0, 1, 0]; case 'z': return [0, 0, 1]; default: return [1, 0, 0]; } } getNormal(u) { switch(this.sentido) { case 'x': return [0, 1, 0]; case 'y': return [0, 0, 1]; case 'z': return [1, 0, 0]; default: return [0, 1, 0]; } } getBinormal(u) { switch(this.sentido) { case 'x': return [0, 0, 1]; case 'y': return [1, 0, 0]; case 'z': return [0, 1, 0]; default: return [0, 0, 1]; } } getLongitudRecorrido() { return this.largo; } getCoordenadaTextura(u) { return u * this.cantRepeticionesTextura; } } export default Recta;
JavaScript
UTF-8
199
3.25
3
[]
no_license
//UC1 const IS_ABSENT = 0 let empCheck = Math.floor(Math.random() * 10 % 2; if (empCheck == IS_ABSENT) { console.log("Employee is Absent"); return; } else { console.log("Emoloyee is PRESENT"); }
Java
UTF-8
375
3
3
[]
no_license
package chapter03.exercise08; import java.util.Random; public class Long16And8 { public static void main(String[] args) { long n1 = 0x2f; //Шестнадцатиричное System.out.println("l1: " + Long.toBinaryString(n1)); long n2 = 0177; //Восьмиричное System.out.println("l2: " + Long.toBinaryString(n2)); } }
SQL
UTF-8
618
3.421875
3
[]
no_license
DELIMITER $$ CREATE FUNCTION `getRating`( `b` varchar(255)) RETURNS DECIMAL(12,4) DETERMINISTIC READS SQL DATA BEGIN DECLARE c double; DECLARE a double default 1; set a = (select total_star from restaurant where Place_idPlace =(select Place_idPlace from restaurant where Place_idPlace = (select idPlace from place where placeName = b))); set c = (select count(id) from review where Place_idPlace = (select Place_idPlace from restaurant where Place_idPlace = (select idPlace from place where placeName = b))); RETURN a/c; END$$ DELIMITER ; drop function getRating; select getRating('blaze pizza') AS `Avg_Rating`;
Java
UTF-8
3,311
1.765625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2016 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.syndesis.connector.dropbox; import java.util.Locale; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.component.extension.verifier.DefaultComponentVerifierExtension; import org.apache.camel.component.extension.verifier.ResultBuilder; import org.apache.camel.component.extension.verifier.ResultErrorBuilder; import org.apache.camel.component.extension.verifier.ResultErrorHelper; import com.dropbox.core.DbxException; import com.dropbox.core.DbxRequestConfig; import com.dropbox.core.v2.DbxClientV2; import io.syndesis.connector.support.util.ConnectorOptions; public class DropBoxVerifierExtension extends DefaultComponentVerifierExtension { public static final String ACCESS_TOKEN = "accessToken"; public static final String CLIENT_IDENTIFIER = "clientIdentifier"; protected DropBoxVerifierExtension(String defaultScheme, CamelContext context) { super(defaultScheme, context); } // ********************************* // Parameters validation // @Override protected Result verifyParameters(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS) .error(ResultErrorHelper.requiresOption(ACCESS_TOKEN, parameters)) .error(ResultErrorHelper.requiresOption(CLIENT_IDENTIFIER, parameters)); return builder.build(); } // ********************************* // Connectivity validation // ********************************* @Override protected Result verifyConnectivity(Map<String, Object> parameters) { return ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY) .error(parameters, DropBoxVerifierExtension::verifyCredentials).build(); } private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) { String token = ConnectorOptions.extractOption(parameters, ACCESS_TOKEN); String clientId = ConnectorOptions.extractOption(parameters, CLIENT_IDENTIFIER); try { // Create Dropbox client DbxRequestConfig config = new DbxRequestConfig(clientId, Locale.getDefault().toString()); DbxClientV2 client = new DbxClientV2(config, token); client.users().getCurrentAccount(); } catch (DbxException e) { builder.error(ResultErrorBuilder .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, "Invalid client identifier and/or access token") .parameterKey(ACCESS_TOKEN).parameterKey(CLIENT_IDENTIFIER).build()); } } }
C++
UTF-8
565
3.015625
3
[]
no_license
// Problem //Sum of Square Differences #include<iostream> #include<vector> #include <cmath> #include <bitset> #include <iterator> #include <time.h> #include <math.h> #define log(x) std::cout << #x"=" << x << std::endl int main() { int limit = 100; int sum_of_squares = 0; int square_of_sum = 0; for(int i = 1; i <=limit; i++){ sum_of_squares = sum_of_squares + ( i * i ); square_of_sum = square_of_sum + i; } int finalt = (square_of_sum * square_of_sum) - sum_of_squares; log(finalt); getchar(); return 0; }
JavaScript
UTF-8
5,194
2.828125
3
[ "MIT" ]
permissive
// Script to collect themepark wait times. // include the Themeparks library var Themeparks = require("themeparks"); // initialise caching (see https://github.com/BryanDonovan/node-cache-manager) // var cacheManager = require('cache-manager'); // Themeparks.Settings.Cache = cacheManager.caching({ // store: require('cache-manager-fs-binary'), // options: { // reviveBuffers: false, // binaryAsStream: true, // ttl: 60 * 60, // maxsize: 1000 * 1000 * 1000, // path: 'diskcache', // preventfill: false // } // }); // list all the parks supported by the library // for (var park in Themeparks.Parks) { // console.log("* " + new Themeparks.Parks[park]().Name + " (DisneyAPI." + park + ")"); // } // * California Adventure - Disneyland Resort (DisneyAPI.DisneylandResortCaliforniaAdventure) // * Magic Kingdom - Disneyland Resort (DisneyAPI.DisneylandResortMagicKingdom) // * Universal Studios Hollywood (DisneyAPI.UniversalStudiosHollywood) var Disneyland = new Themeparks.Parks.DisneylandResortMagicKingdom(); var DisneyCA = new Themeparks.Parks.DisneylandResortCaliforniaAdventure(); var universalStudiosHollywood = new Themeparks.Parks.UniversalStudiosHollywood(); // print csv header console.log("park, ride_name, wait_time, status, date-time, fast_pass"); //Disneyland.GetWaitTimes().then(function(rides) { // printParkInfo("Disneyland", rides); // print each wait time // for (var i=0, ride; ride=rides[i++];) { // console.log(ride.name + ": " + ride.waitTime + " minutes wait"); // console.log(JSON.stringify(ride, null, 2)); // } // }, console.error); // Example from themparks github // Access wait times by Promise // const CheckWaitTimes = () => { // Disneyland.GetWaitTimes().then((rideTimes) => { // rideTimes.forEach((ride) => { // console.log(`${ride.name}: ${ride.waitTime} minutes wait (${ride.status})`); // }); // }).catch((error) => { // console.error(error); // }); // }; // CheckWaitTimes(); // change inspired by example from themparks github // access wait times by Promise // const CheckDisneylandWaitTimes = () => { // Disneyland.GetWaitTimes().then((rideTimes) => { // printParkInfo("Disneyland", rideTimes); // }).catch((error) => { // console.error(error); // }); // }; // CheckDisneylandWaitTimes(); // // access wait times by Promise // DisneyCA.GetWaitTimes().then(function(rides) { // printParkInfo("California Adventure", rides); // }, console.error); // universalStudiosHollywood.GetWaitTimes().then(function(rides) { // printParkInfo("Universal Studios Hollywood", rides); // }, console.error); function printParkInfo(parkName, waitTimeArray) { // console.log("============================="); // console.log("wait times: " + waitTimeArray.length); var currentdate = new Date(); // console.log(currentdate); // console.log(waitTimeArray) // uncomment this line to see the JSON reponses; for testing printWaitTimesCSV(parkName, waitTimeArray, currentdate); // console.log(JSON.stringify(DisneylandWaitTimes, null, 2)); } function printWaitTimesCSV(parkName, waitTimeArray, dateTime) { for (var index in waitTimeArray) { if (waitTimeArray.hasOwnProperty(index)) { var ride = waitTimeArray[index]; // escaping quotes in ride names to be "" instead of single "'s. Ruby csv importer requires that instead of \". See: // [Ruby CSV parsing string with escaped quotes - Stack Overflow](https://stackoverflow.com/questions/14534522/ruby-csv-parsing-string-with-escaped-quotes) console.log("\"" + parkName + "\",\"" + ride.name.replace(/\"/g,'\""') + "\",\"" + ride.waitTime + "\",\"" + ride.status + "\",\"" + dateTime + "\",\"" + ride.fastPass.toString() + "\""); } } } // New style of calling // Access wait times by Promise const CheckDisneylandTimes = () => { Disneyland.GetWaitTimes().then((rides) => { printParkInfo("Disneyland", rides); }).catch((error) => { console.error(error); }); }; CheckDisneylandTimes(); // Access wait times by Promise const CheckDisneyCATimes = () => { DisneyCA.GetWaitTimes().then((rides) => { printParkInfo("California Adventure", rides); }).catch((error) => { console.error(error); }); }; CheckDisneyCATimes(); // Access wait times by Promise const CheckUniversalStudiosHollywoodTimes = () => { universalStudiosHollywood.GetWaitTimes().then((rides) => { printParkInfo("Universal Studios Hollywood", rides); }).catch((error) => { console.error(error); }); }; CheckUniversalStudiosHollywoodTimes(); // ---- // // access wait times by Promise // Disneyland.GetWaitTimes().then(function(rides) { // printParkInfo("Disneyland", rides); // // print each wait time // // for(var i=0, ride; ride=rides[i++];) { // // console.log(ride.name + ": " + ride.waitTime + " minutes wait"); // // } // }, console.error); // // access wait times by Promise // DisneyCA.GetWaitTimes().then(function(rides) { // printParkInfo("California Adventure", rides); // }, console.error); // universalStudiosHollywood.GetWaitTimes().then(function(rides) { // printParkInfo("Universal Studios Hollywood", rides); // }, console.error);
Markdown
UTF-8
40,506
2.859375
3
[ "Apache-2.0" ]
permissive
--- layout: post title: "LIME: Machine Learning Model Interpretability with LIME" excerpt: "Predict employee churn with H2O machine learning and LIME. Use LIME (local Interpretable Model-agnostic Explanations) for model explanation in data science for business." author: "Brad Boehmke" date: 2018-06-25 04:45:01 categories: [Business] tags: [R-Project, R, R-Bloggers, DS4B, LIME, Churn, Human Resources, Employee Turnover, Employee Attrition, h2o, caret, lime, vip, pdp, Learn-Machine-Learning] image: /assets/2018-06-25-lime/employee-attrition-target-employees.png --- Data science tools are getting better and better, which is improving the predictive performance of machine learning models in business. With new, high-performance tools like, [___H2O___](https://www.h2o.ai/) for automated machine learning and [___Keras___](https://tensorflow.rstudio.com/keras/) for deep learning, the performance of models are increasing tremendously. __There's one catch: Complex models are unexplainable... that is until LIME came along!__ [___LIME___](https://cran.r-project.org/package=lime), which stands for Local Interpretable Model-agnostic Explanations, has opened the doors to black-box (complex, high-performance, but unexplainable) models in business applications! __Explanations are MORE CRITICAL to the business than PERFORMANCE.__ Think about it. What good is a high performance model that predicts employee attrition if we can't tell what features are causing people to quit? We need explanations to improve business decision making. Not just performance. >_Explanations are __MORE CRITICAL__ to the business than __PERFORMANCE__. Think about it. What good is a high performance model that predicts employee attrition if we can't tell what features are causing people to quit? We need explanations to improve business decision making. Not just performance._ In this Machine Learning Tutorial, [Brad Boehmke](https://www.linkedin.com/in/brad-boehmke-ph-d-9b0a257/), Director of Data Science at [84.51&deg;](https://www.linkedin.com/company/84-51/), shows us how to use LIME for machine learning interpretability on a __Human Resources Employee Turnover Problem__, specifically showing the value of developing interpretablity visualizations. He shows us options for ___Global Importance___ and compares it to LIME for ___Local Importance___. We use machine learning R packages `h2o`, `caret`, and `ranger` in the tutorial, showcasing how to use `lime` for local explanations. Let's get started! ## Articles In The Model Interpretability Series __Articles related to machine learning and black-box model interpretability__: * __LIME__: [LIME and H2O: Using Machine Learning With LIME To Understand Employee Churn](http://www.business-science.io/business/2018/06/25/lime-local-feature-interpretation.html) * __DALEX__: [DALEX and H2O: Machine Learning Model Interpretability and Feature Explanation](http://www.business-science.io/business/2018/07/23/dalex-feature-interpretation.html) * __IML__: [IML and H2O: Machine Learning Model Interpetability and Feature Explanation](http://www.business-science.io/business/2018/08/13/iml-model-interpretability.html) __Awesome Data Science Tutorials with LIME for black-box model explanation in business__: * __Credit Default Risk__: [Kaggle Competition in 30 Minutes: Predict Home Credit Default Risk With R](http://www.business-science.io/business/2018/08/07/kaggle-competition-home-credit-default-risk.html) * __Human Resources Employee Turnover__:[HR Analytics: Using Machine Learning To Predict Employee Turnover](http://www.business-science.io/business/2017/09/18/hr_employee_attrition.html) * __Customer Churn__:[Customer Analytics: Using Deep Learning With Keras To Predict Customer Churn](http://www.business-science.io/business/2017/11/28/customer_churn_analysis_keras.html) * __Sales Product Backorders__: [Sales Analytics: How To Use Machine Learning To Predict And Optimize Product Backorders](http://www.business-science.io/business/2017/10/16/sales_backorder_prediction.html) <!-- CTA Small --> <!-- <br> <hr> <h2 class="text-center">Learn Data Science For Business</h2> [Business Science University](https://university.business-science.io/) is an educational platform that teaches how to apply data science to business. Our current offering includes of a fully integrated, project-based, 3-course `R-Track` designed to take you from ___data science foundations___ to ___machine learning-powered production web apps___. [See our Curriculum below](#curriculum). <p class="text-center" style="font-size:30px;"> <a href="https://university.business-science.io/"><strong>Join Business Science University Today</strong></a> </p> <hr> <br> --> <!-- End CTA --> ## LIME: A Secret Weapon For ROI-Driven Data Science <a class="anchor" id="secret-weapon"></a> > Introduction by Matt Dancho, Founder of Business Science ___Business success___ is dependent on the ability for managers, process stakeholders, and key decision makers to make the right decisions often using data to understand what's going on. This is where machine learning can help. Machine learning can analyze vast amounts of data, creating highly predictive models that tell managers key information such as how likely someone is likely to leave an organization. However, machine learning alone is not enough. Business leaders require explanations so they can determine adjustments that will improve results. These explanations require a different tool: ___LIME___. Let's find out why __LIME is truly a secret weapon for ROI-driven data science__! __In the HR Employee Attrition example discussed in this article, the machine learning model predicts the probability of someone leaving the company.__ This probability is then converted to a prediction of either leave or stay through a process called ___Binary Classification___. However, this doesn't solve the main objective, which is to make better decisions. It only tells us if someone is a high flight risk (i.e. has high attrition probability). ![Employee Attrition: Machine Learning Predicts Which Employees Are Likely To Leave](/assets/2018-06-25-lime/employee-attrition.png) <p class="text-center date">Employee Attrition: Machine Learning Predicts Which Employees Are Likely To Leave</p> __How do we change decision making and therefore improve? It comes down to levers and probability__. Machine learning tells us which employees are highest risk and therefore ___high probability___. We can hone in on these individuals, but we need a different tool to understand why an individual is leaving. This is where LIME comes into play. LIME uncovers the ___levers___ or features we can control to make business improvements. <img src="/assets/2018-06-25-lime/employee-attrition-lime-result.png" alt="LIME: Uncovering Levers We Can Control" style="width:50%;"> <p class="text-center date">LIME: Uncovers Levers or Features We Can Control</p> In our HR Employee Attrition Example, LIME detects "Over Time" (lever) as a key feature that _supports_ employee turnover. We can _control_ the "Over Time" feature by implementing a "limited-overtime" or "no-overtime" policy. ![Employee Attrition: Targeting Employees With Over Time](/assets/2018-06-25-lime/employee-attrition-target-employees.png) <p class="text-center date">Analyzing A Policy Change: Targeting Employees With Over Time</p> Toggling the "OverTime" feature to "No" enables calculating an expected value or benefit of reducing overtime by implementing a new OT policy. For the individual employee, a expected savings results. When applied to the entire organization, this process of _adjusting levers_ can result in impactful policy changes that __save the organization millions per year and generate ROI__. ![Employee Attrition: Adjusting Levers](/assets/2018-06-25-lime/employee-attrition-expected-savings.png) <p class="text-center date">Adjusting The Over Time Results In Expected Savings</p> #### Interested in Learning LIME While Solving A Real-World Churn Problem? If you want to solve this real-world employee churn problem developing models with __H2O Automated Machine Learning__, using __LIME For Black-Box ML Model Explanation__, and __analyzing the impact of a policy change through optimization and sensitivity analysis__, get started today with [Data Science For Business (DS4B 201 / HR 201)](https://university.business-science.io/p/hr201-using-machine-learning-h2o-lime-to-predict-employee-turnover/?coupon_code=DS4B15). You'll learn ___ROI-Driven Data Science___, implementing the tools (H2O + LIME) and our data science framework ([BSPF](/bspf.html)) under my guidance (Matt Dancho, Instructor and Founder of Business Science) in our new, self-paced course part of the [Business Science University](https://university.business-science.io/) virtual data science workshop. <span data-sumome-listbuilder-embed-id="1e13d987ad901ab4571b6d92bb2ab8a2230c397b886c1fd49eba5392ed5c88cb"></span> ## Learning Trajectory Now that we have a flavor for what LIME does, let's get on with learning how to use it! In this machine learning tutorial, you will learn: * [Global Interpretation: How to perform global intepretation with `vip` and `pdp` and how global differs from local with LIME](#global-interp) * [Local Interpretation: How To Perform Local Interpretation with `lime` using models developed with `h2o`, `caret`, and `ranger`](#local-interp) * [Visualizing LIME Results: Using `plot_features()` and `plot_explanations()`](#viz) * [Tuning LIME: Improving explanation accuracy](#tuning-lime) * [Integrating Models: Working with unsupported models to get LIME integration](#model-integration) In fact, one of the coolest things you'll learn is how to create a visualization that compares multiple H2O modeling algorithms that examine employee attrition. This is akin to getting different perspectives for how each of the models view the problem: * Random Forest (RF) * Generalized Linear Regression (GLM) * Gradient Boosted Machine (GBM). ![LIME Multiple Models](/assets/2018-06-25-lime/lime-multiple-models.png) <p class="text-center date">Comparing LIME results of different H2O modeling algorithms</p> ## About The Author This ___MACHINE LEARNING TUTORIAL___ comes from [Brad Boehmke](https://www.linkedin.com/in/brad-boehmke-ph-d-9b0a257/), Director of Data Science at [84.51&deg;](https://www.linkedin.com/company/84-51/), where he and his team develops algorithmic processes, solutions, and tools that enable 84.51&deg; and its analysts to efficiently extract insights from data and provide solution alternatives to decision-makers. Brad is not only a talented data scientist, he's an adjunct professor at the University of Cincinnati, Wake Forest, and Air Force Institute of Technology. Most importantly, he's an [active contributor](https://github.com/bradleyboehmke) to the __Data Science Community__ and he enjoys giving back via advanced machine learning education available at the [UC Business Analytics R Programming Guide](http://uc-r.github.io/)! ## Machine Learning Tutorial: Visualizing Machine Learning Models with LIME > By Brad Boehmke, Director of Data Science at 84.51&deg; Machine learning (ML) models are often considered "black boxes" due to their complex inner-workings. More advanced ML models such as random forests, gradient boosting machines (GBM), artificial neural networks (ANN), among others are typically more accurate for predicting nonlinear, faint, or rare phenomena. Unfortunately, more accuracy often comes at the expense of interpretability, and interpretability is crucial for business adoption, model documentation, regulatory oversight, and human acceptance and trust. Luckily, several advancements have been made to aid in interpreting ML models. Moreover, it’s often important to understand the ML model that you’ve trained on a global scale, and also to zoom into local regions of your data or your predictions and derive local explanations. ___Global interpretations___ help us understand the inputs and their entire modeled relationship with the prediction target, but global interpretations can be highly approximate in some cases. ___Local interpretations___ help us understand model predictions for a single row of data or a group of similar rows. This post demonstrates how to use the `lime` package to perform local interpretations of ML models. This will not focus on the theoretical and mathematical underpinnings but, rather, on the practical application of using `lime`. [^lime_paper] ## Libraries This tutorial leverages the following packages. {% highlight r %} # required packages # install vip from github repo: devtools::install_github("koalaverse/vip") library(lime) # ML local interpretation library(vip) # ML global interpretation library(pdp) # ML global interpretation library(ggplot2) # visualization pkg leveraged by above packages library(caret) # ML model building library(h2o) # ML model building # other useful packages library(tidyverse) # Use tibble, dplyr library(rsample) # Get HR Data via rsample::attrition library(gridExtra) # Plot multiple lime plots on one graph # initialize h2o h2o.init() {% endhighlight %} {% highlight text %} ## Connection successful! ## ## R is connected to the H2O cluster: ## H2O cluster uptime: 3 minutes 17 seconds ## H2O cluster timezone: America/New_York ## H2O data parsing timezone: UTC ## H2O cluster version: 3.19.0.4208 ## H2O cluster version age: 4 months and 6 days !!! ## H2O cluster name: H2O_started_from_R_mdancho_zbl980 ## H2O cluster total nodes: 1 ## H2O cluster total memory: 3.50 GB ## H2O cluster total cores: 4 ## H2O cluster allowed cores: 4 ## H2O cluster healthy: TRUE ## H2O Connection ip: localhost ## H2O Connection port: 54321 ## H2O Connection proxy: NA ## H2O Internal Security: FALSE ## H2O API Extensions: Algos, AutoML, Core V3, Core V4 ## R Version: R version 3.4.4 (2018-03-15) {% endhighlight %} {% highlight r %} h2o.no_progress() {% endhighlight %} To demonstrate model visualization techniques we'll use the employee attrition data that has been included in the `rsample` package. This demonstrates a binary classification problem ("Yes" vs. "No") but the same process that you'll observe can be used for a regression problem. Note: I force ordered factors to be unordered as `h2o` does not support ordered categorical variables. For this exemplar I retain most of the observations in the training data sets and retain 5 observations in the `local_obs` set. These 5 observations are going to be treated as new observations that we wish to understand ___why___ the particular predicted response was made. {% highlight r %} # create data sets df <- rsample::attrition %>% mutate_if(is.ordered, factor, ordered = FALSE) %>% mutate(Attrition = factor(Attrition, levels = c("Yes", "No"))) index <- 1:5 train_obs <- df[-index, ] local_obs <- df[index, ] # create h2o objects for modeling y <- "Attrition" x <- setdiff(names(train_obs), y) train_obs.h2o <- as.h2o(train_obs) local_obs.h2o <- as.h2o(local_obs) {% endhighlight %} We will explore how to visualize a few of the more popular machine learning algorithms and packages in R. For brevity I train default models and do not emphasize hyperparameter tuning. The following produces: * Random forest model using `ranger` via the `caret` package * Random forest model using `h2o` * Elastic net model using `h2o` * GBM model using `h2o` * Random forest model using `ranger` directly {% highlight r %} # Create Random Forest model with ranger via caret fit.caret <- train( Attrition ~ ., data = train_obs, method = 'ranger', trControl = trainControl(method = "cv", number = 5, classProbs = TRUE), tuneLength = 1, importance = 'impurity' ) # create h2o models h2o_rf <- h2o.randomForest(x, y, training_frame = train_obs.h2o) h2o_glm <- h2o.glm(x, y, training_frame = train_obs.h2o, family = "binomial") h2o_gbm <- h2o.gbm(x, y, training_frame = train_obs.h2o) # ranger model --> model type not built in to LIME fit.ranger <- ranger::ranger( Attrition ~ ., data = train_obs, importance = 'impurity', probability = TRUE ) {% endhighlight %} ## Global Interpretation <a class="anchor" id="global-interp"></a> The most common ways of obtaining global interpretation is through: * variable importance measures * partial dependence plots Variable importance quantifies the global contribution of each input variable to the predictions of a machine learning model. Variable importance measures rarely give insight into the average direction that a variable affects a response function. They simply state the magnitude of a variable’s relationship with the response as compared to other variables used in the model. For example, the `ranger` random forest model identified monthly income, overtime, and age as the top 3 variables impacting the objective function. {% highlight r %} vip(fit.ranger) + ggtitle("ranger: RF") {% endhighlight %} ![plot of chunk unnamed-chunk-4](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-4-1.png) After the most globally relevant variables have been identified, the next step is to attempt to understand how the response variable changes based on these variables. For this we can use partial dependence plots (PDPs) and individual conditional expectation (ICE) curves. These techniques plot the change in the predicted value as specified feature(s) vary over their marginal distribution. Consequently, we can gain some local understanding how the reponse variable changes across the distribution of a particular variable but this still only provides a global understanding of this relationships across all observed data. For example, if we plot the PDP of the monthly income variable we see that the probability of an employee attriting decreases, on average, as their monthly income approaches \$5,000 and then remains relatively flat. {% highlight r %} # built-in PDP support in H2O h2o.partialPlot(h2o_rf, data = train_obs.h2o, cols = "MonthlyIncome") {% endhighlight %} ![plot of chunk unnamed-chunk-5](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-5-1.png) {% highlight text %} ## PartialDependence: Partial Dependence Plot of model DRF_model_R_1529928665020_106 on column 'MonthlyIncome' ## MonthlyIncome mean_response stddev_response ## 1 1009.000000 0.229433 0.229043 ## 2 2008.473684 0.216096 0.234960 ## 3 3007.947368 0.167686 0.234022 ## 4 4007.421053 0.161024 0.231287 ## 5 5006.894737 0.157775 0.231151 ## 6 6006.368421 0.156628 0.231455 ## 7 7005.842105 0.157734 0.230267 ## 8 8005.315789 0.160137 0.229286 ## 9 9004.789474 0.164437 0.229305 ## 10 10004.263158 0.169652 0.227902 ## 11 11003.736842 0.165502 0.226240 ## 12 12003.210526 0.165297 0.225529 ## 13 13002.684211 0.165051 0.225335 ## 14 14002.157895 0.165051 0.225335 ## 15 15001.631579 0.164983 0.225316 ## 16 16001.105263 0.165051 0.225019 ## 17 17000.578947 0.165556 0.224890 ## 18 18000.052632 0.165556 0.224890 ## 19 18999.526316 0.166498 0.224726 ## 20 19999.000000 0.182348 0.219882 {% endhighlight %} We can gain further insight by using centered ICE curves which can help draw out further details. For example, the following ICE curves show a similar trend line as the PDP above but by centering we identify the decrease as monthly income approaches &#36;5,000 followed by an increase in probability of attriting once an employee's monthly income approaches \$20,000. Futhermore, we see some turbulence in the flatlined region between &#36;5-&#36;20K) which means there appears to be certain salary regions where the probability of attriting changes. {% highlight r %} fit.ranger %>% pdp::partial(pred.var = "MonthlyIncome", grid.resolution = 25, ice = TRUE) %>% autoplot(rug = TRUE, train = train_obs, alpha = 0.1, center = TRUE) {% endhighlight %} ![plot of chunk unnamed-chunk-6](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-6-1.png) These visualizations help us to understand our model from a global perspective: identifying the variables with the largest overall impact and the typical influence of a feature on the response variable across all observations. However, what these do not help us understand is given a new observation, what were the most ___influential variables that determined the predicted outcome___. Say we obtain information on an employee that makes about &#36;10,000 per month and we need to assess their probabilty of leaving the firm. Although monthly income is the most important variable in our model, it may not be the most influential variable driving this employee to leave. To retain the employee, leadership needs to understand what variables are most influential for that specific employee. This is where `lime` can help. ## Local Interpretation <a class="anchor" id="local-interp"></a> Local Interpretable Model-agnostic Explanations (__LIME__) is a visualization technique that helps explain individual predictions. As the name implies, it is model agnostic so it can be applied to any supervised regression or classification model. Behind the workings of LIME lies the assumption that ___every complex model is linear on a local scale___ and asserting that it is possible to fit a simple model around a single observation that will mimic how the global model behaves at that locality. The simple model can then be used to explain the predictions of the more complex model locally. The generalized algorithm LIME applies is: 1. Given an observation, ___permute___ it to create replicated feature data with slight value modifications. 2. Compute ___similarity distance measure___ between original observation and permuted observations. 3. Apply selected machine learning model to ___predict outcomes___ of permuted data. 4. ___Select m number of features___ to best describe predicted outcomes. 5. ___Fit a simple model___ to the permuted data, explaining the complex model outcome with *m* features from the permuted data weighted by its similarity to the original observation . 6. Use the resulting ___feature weights to explain local behavior___. Each of these steps will be discussed in further detail as we proceed. ### lime::lime The application of the LIME algorithm via the `lime` package is split into two operations: `lime::lime()` and `lime::explain()`. The `lime::lime()` function creates an "explainer" object, which is just a list that contains the machine learning model and the feature distributions for the training data. The feature distributions that it contains includes distribution statistics for each categorical variable level and each continuous variable split into *n* bins (default is 4 bins). These feature attributes will be used to permute data. The following creates our `lime::lime()` object and I change the number to bin our continuous variables into to 5. {% highlight r %} explainer_caret <- lime::lime(train_obs, fit.caret, n_bins = 5) class(explainer_caret) {% endhighlight %} {% highlight text %} ## [1] "data_frame_explainer" "explainer" ## [3] "list" {% endhighlight %} {% highlight r %} summary(explainer_caret) {% endhighlight %} {% highlight text %} ## Length Class Mode ## model 24 train list ## bin_continuous 1 -none- logical ## n_bins 1 -none- numeric ## quantile_bins 1 -none- logical ## use_density 1 -none- logical ## feature_type 31 -none- character ## bin_cuts 31 -none- list ## feature_distribution 31 -none- list {% endhighlight %} ### lime::explain Once we created our `lime` objects, we can now perform the generalized LIME algorithm using the `lime::explain()` function. This function has several options, each providing flexibility in how we perform the generalized algorithm mentioned above. * `x`: Contains the one or more single observations you want to create local explanations for. In our case, this includes the 5 observations that I included in the `local_obs` data frame. _Relates to algorithm step 1_. * `explainer`: takes the explainer object created by `lime::lime()`, which will be used to create permuted data. Permutations are sampled from the variable distributions created by the `lime::lime()` explainer object. _Relates to algorithm step 1_. * `n_permutations`: The number of permutations to create for each observation in `x` (default is 5,000 for tabular data). _Relates to algorithm step 1_. * `dist_fun`: The distance function to use. The default is Gower's distance but can also use euclidean, manhattan, or any other distance function allowed by `?dist()`. To compute similarity distance of permuted observations, categorical features will be recoded based on whether or not they are equal to the actual observation. If continuous features are binned (the default) these features will be recoded based on whether they are in the same bin as the observation. Using the recoded data the distance to the original observation is then calculated based on a user-chosen distance measure. _Relates to algorithm step 2_. * `kernel_width`: To convert the distance measure to a similarity value, an exponential kernel of a user defined width (defaults to 0.75 times the square root of the number of features) is used. Smaller values restrict the size of the local region. _Relates to algorithm step 2_. * `n_features`: The number of features to best describe predicted outcomes. _Relates to algorithm step 4_. * `feature_select`: To select the best *n* features, `lime` can use forward selection, ridge regression, lasso, or a tree to select the features. In this example I apply a ridge regression model and select the *m* features with highest absolute weights. _Relates to algorithm step 4_. For classification models we also have two additional features we care about and one of these two arguments must be given: * `labels`: Which label do we want to explain? In this example, I want to explain the probability of an observation to attrit ("Yes"). * `n_labels`: The number of labels to explain. With this data I could select `n_labels = 2` to explain the probability of "Yes" and "No" responses. {% highlight r %} explanation_caret <- lime::explain( x = local_obs, explainer = explainer_caret, n_permutations = 5000, dist_fun = "gower", kernel_width = .75, n_features = 5, feature_select = "highest_weights", labels = "Yes" ) {% endhighlight %} The `explain()` function above first creates permutations, then calculates similarities, followed by selecting the *m* features. Lastly, `explain()` will then fit a model (_algorithm steps 5 & 6_). `lime` applies a ridge regression model with the weighted permuted observations as the simple model. [[^glmnet]] If the model is a regressor, the simple model will predict the output of the complex model directly. If the complex model is a classifier, the simple model will predict the probability of the chosen class(es). The `explain()` output is a data frame containing different information on the simple model predictions. Most importantly, for each observation in `local_obs` it contains the simple model fit (`model_r2`) and the weighted importance (`feature_weight`) for each important feature (`feature_desc`) that best describes the local relationship. {% highlight r %} tibble::glimpse(explanation_caret) {% endhighlight %} {% highlight text %} ## Observations: 25 ## Variables: 13 ## $ model_type <chr> "classification", "classification", "cla... ## $ case <chr> "1", "1", "1", "1", "1", "2", "2", "2", ... ## $ label <chr> "Yes", "Yes", "Yes", "Yes", "Yes", "Yes"... ## $ label_prob <dbl> 0.216, 0.216, 0.216, 0.216, 0.216, 0.070... ## $ model_r2 <dbl> 0.5517840, 0.5517840, 0.5517840, 0.55178... ## $ model_intercept <dbl> 0.1498396, 0.1498396, 0.1498396, 0.14983... ## $ model_prediction <dbl> 0.3233514, 0.3233514, 0.3233514, 0.32335... ## $ feature <chr> "OverTime", "MaritalStatus", "BusinessTr... ## $ feature_value <fct> Yes, Single, Travel_Rarely, Sales, Very_... ## $ feature_weight <dbl> 0.14996805, 0.05656074, -0.03929651, 0.0... ## $ feature_desc <chr> "OverTime = Yes", "MaritalStatus = Singl... ## $ data <list> [[41, Yes, Travel_Rarely, 1102, Sales, ... ## $ prediction <list> [[0.216, 0.784], [0.216, 0.784], [0.216... {% endhighlight %} ### Visualizing results <a class="anchor" id="viz"></a> However the simplest approach to interpret the results is to visualize them. There are several plotting functions provided by `lime` but for tabular data we are only concerned with two. The most important of which is `plot_features()`. This will create a visualization containing an individual plot for each observation (case 1, 2, ..., n) in our `local_obs` data frame. Since we specified `labels = "Yes"` in the `explain()` function, it will provide the probability of each observation attriting. And since we specified `n_features = 10` it will plot the 10 most influential variables that best explain the linear model in that observations local region and whether the variable is causes an increase in the probability (supports) or a decrease in the probability (contradicts). It also provides us with the model fit for each model ("Explanation Fit: XX"), which allows us to see how well that model explains the local region. Consequently, we can infer that case 3 has the highest liklihood of attriting out of the 5 observations and the 3 variables that appear to be influencing this high probability include working overtime, being single, and working as a lab tech. {% highlight r %} plot_features(explanation_caret) {% endhighlight %} ![plot of chunk unnamed-chunk-10](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-10-1.png) The other plot we can create is a __heatmap__ showing how the different variables selected across all the observations influence each case. We use the `plot_explanations()` function. This plot becomes useful if you are trying to find common features that influence all observations or if you are performing this analysis across many observations which makes `plot_features()` difficult to discern. {% highlight r %} plot_explanations(explanation_caret) {% endhighlight %} ![plot of chunk unnamed-chunk-11](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-11-1.png) ### Tuning LIME <a class="anchor" id="tuning-lime"></a> As you saw in the above `plot_features()` plot, the output provides the model fit. In this case the best simple model fit for the given local regions was _R^2 = 0.59_ for case 3. Considering there are several knobs we can turn when performing the LIME algorithm, we can treat these as tuning parameters to try find the best fit model for the local region. This helps to maximize the amount of trust we can have in the local region explanation. As an example, the following changes the distance function to use the manhattan distance algorithm, we increase the kernel width substantially to create a larger local region, and we change our feature selection approach to a LARS lasso model. The result is a fairly substantial increase in our explanation fits. {% highlight r %} # tune LIME algorithm explanation_caret <- lime::explain( x = local_obs, explainer = explainer_caret, n_permutations = 5000, dist_fun = "manhattan", kernel_width = 3, n_features = 5, feature_select = "lasso_path", labels = "Yes" ) plot_features(explanation_caret) {% endhighlight %} ![plot of chunk unnamed-chunk-13](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-13-1.png) ### Supported vs Non-support models <a class="anchor" id="model-integration"></a> Currently, `lime` supports supervised models produced in `caret`, `mlr`, `xgboost`, `h2o`, `keras`, and `MASS::lda`. Consequently, any supervised models created with these packages will function just fine with `lime`. {% highlight r %} explainer_h2o_rf <- lime(train_obs, h2o_rf, n_bins = 5) explainer_h2o_glm <- lime(train_obs, h2o_glm, n_bins = 5) explainer_h2o_gbm <- lime(train_obs, h2o_gbm, n_bins = 5) explanation_rf <- lime::explain(local_obs, explainer_h2o_rf, n_features = 5, labels = "Yes", kernel_width = .1, feature_select = "highest_weights") explanation_glm <- lime::explain(local_obs, explainer_h2o_glm, n_features = 5, labels = "Yes", kernel_width = .1, feature_select = "highest_weights") explanation_gbm <- lime::explain(local_obs, explainer_h2o_gbm, n_features = 5, labels = "Yes", kernel_width = .1, feature_select = "highest_weights") p1 <- plot_features(explanation_rf, ncol = 1) + ggtitle("rf") p2 <- plot_features(explanation_glm, ncol = 1) + ggtitle("glm") p3 <- plot_features(explanation_gbm, ncol = 1) + ggtitle("gbm") gridExtra::grid.arrange(p1, p2, p3, nrow = 1) {% endhighlight %} ![plot of chunk unnamed-chunk-14](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-14-1.png) However, any models that do not have built in support will produce an error. For example, the model we created directly with `ranger` is not supported and produces an error. {% highlight r %} explainer_ranger <- lime(train, fit.ranger, n_bins = 5) {% endhighlight %} {% highlight text %} ## Error in UseMethod("lime", x): no applicable method for 'lime' applied to an object of class "function" {% endhighlight %} We can work with this pretty easily by building two functions that make `lime` compatible with an unsupported package. First, we need to create a `model_type()` function that specifies what type of model this unsupported package is using. `model_type()` is a `lime` specific function, we just need to create a `ranger` specific method. We do this by taking the class name for our `ranger` object and creating the `model_type.ranger` method and simply return the type of model ("classification" for this example). {% highlight r %} # get the model class class(fit.ranger) {% endhighlight %} {% highlight text %} ## [1] "ranger" {% endhighlight %} {% highlight r %} # need to create custom model_type function model_type.ranger <- function(x, ...) { # Function tells lime() what model type we are dealing with # 'classification', 'regression', 'survival', 'clustering', 'multilabel', etc return("classification") } model_type(fit.ranger) {% endhighlight %} {% highlight text %} ## [1] "classification" {% endhighlight %} We then need to create a `predict_model()` method for ranger as well. The output for this function should be a data frame. For a regression problem it should produce a single column data frame with the predicted response and for a classification problem it should create a column containing the probabilities for each categorical class (binary "Yes" "No" in this example). {% highlight r %} # need to create custom predict_model function predict_model.ranger <- function(x, newdata, ...) { # Function performs prediction and returns data frame with Response pred <- predict(x, newdata) return(as.data.frame(pred$predictions)) } predict_model(fit.ranger, newdata = local_obs) {% endhighlight %} {% highlight text %} ## Yes No ## 1 0.2915452 0.7084548 ## 2 0.0701619 0.9298381 ## 3 0.4406563 0.5593437 ## 4 0.3465294 0.6534706 ## 5 0.2525397 0.7474603 {% endhighlight %} Now that we have those methods developed and in our global environment we can run our `lime` functions and produce our outputs.[^dynamic] {% highlight r %} explainer_ranger <- lime(train_obs, fit.ranger, n_bins = 5) explanation_ranger <- lime::explain(local_obs, explainer_ranger, n_features = 5, n_labels = 2, kernel_width = .1) plot_features(explanation_ranger, ncol = 2) + ggtitle("ranger") {% endhighlight %} ![plot of chunk unnamed-chunk-18](/figure/source/2018-06-25-lime-local-feature-interpretation/unnamed-chunk-18-1.png) ## Learning More At [Business Science](http://www.business-science.io/), we've been using the `lime` package with clients to help explain our machine learning models - ___It's been our secret weapon___. Our primary use cases are with `h2o` and `keras`, both of which are supported in `lime`. In fact, we actually built the `h2o` integration to gain the beneifts of LIME with stacked ensembles, deep learning, and other black-box algorithms. We've used it with clients to help them detect which employees should be considered for executive promotion. We've even provided previous real-world business problem / machine learning tutorials: * [HR Analytics: Using Machine Learning To Predict Employee Turnover](http://www.business-science.io/business/2017/09/18/hr_employee_attrition.html) * [Customer Analytics: Using Deep Learning With Keras To Predict Customer Churn](http://www.business-science.io/business/2017/11/28/customer_churn_analysis_keras.html) * [Sales Analytics: How To Use Machine Learning To Predict And Optimize Product Backorders](http://www.business-science.io/business/2017/10/16/sales_backorder_prediction.html) In fact, those that want to learn `lime` while solving a real world data science problem can get started today with our new course: [Data Science For Business (DS4B 201)](https://university.business-science.io/) <span data-sumome-listbuilder-embed-id="1e13d987ad901ab4571b6d92bb2ab8a2230c397b886c1fd49eba5392ed5c88cb"></span> ## Resources LIME provides a great, model-agnostic approach to assessing local interpretation of predictions. To learn more I would start with the following resources: * __Original paper:__ Marco Tulio Ribeiro, Sameer Singh, and Carlos Guestrin. 2016. “Why Should I Trust You?”: Explaining the Predictions of Any Classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD ’16). ACM, New York, NY, USA, 1135-1144. DOI: https://doi.org/10.1145/2939672.2939778 * __KDD2016 presentation:__ [Marco Ribeiro presents the original paper](https://www.youtube.com/watch?v=KP7-JtFMLo4) * __lime vignette:__ [Understanding lime](https://cran.r-project.org/web/packages/lime/vignettes/Understanding_lime.html) * __London AI & Deep Learning Meetup Presentation:__ [Interpretable Machine Learning Using LIME Framework](https://www.youtube.com/watch?v=CY3t11vuuOM) ## Footnotes [^lime_paper]: To this end, you are encouraged to read through the [article](https://arxiv.org/abs/1602.04938) that introduced the lime framework as well as the additional resources linked to from the original [Python repository](https://github.com/marcotcr/lime). [^glmnet]: If you've never applied a weighted ridge regression model you can see some details on its application in the [`glmnet` vignette](https://web.stanford.edu/~hastie/glmnet/glmnet_alpha.html) [^dynamic]: If you are curious as to why simply creating the `model_type.ranger` and `predict_model.ranger` methods and hosting them in your global environment causes the `lime` functions to work then I suggest you read [chapter 6 of Advanced R](http://adv-r.had.co.nz/Functions.html).
JavaScript
UTF-8
12,379
2.625
3
[]
no_license
/**************************************************************************** Copyright (c) 2018 Timofey Borisov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ /* Usage: dynamic: let v = { some_value = 10 } utils.bind.val.dynamic = v; utils.bind.defineDynamic(); utils.bind.parseDom(document.getElementById("your_element")); //All %v some_value% in element will be replaced with value of this variable //It's better to use next function if you want to parse big element (Like full <body>): utils.bind.parseBindableChilds(document.getElementById("your_element")) //It will only parse childs with "bindable" class static: */ (function(){ let local = weakDeclaration("utils.bind"); //=== //Properties and variables local.val = { static:null, dynamic:null, currency:null } local.properties = { animateValues : true, //Allow smooth animation for valuse animationInterval : 0.1, //Speed of animation animationStrength : 0.2, replaceDollarSign : true, //Parse all signs as link activeCurrencyCode : "USD", emitEvents : true, //Emit change events for values saveOriginHTML : true //Save origin html text if you want to dynamic language changes } //=== //Actual interface local.parseBindableChilds = function(dom){ var linkDoms = dom.getElementsByClassName("bindable"); for(var l in linkDoms){ if(typeof linkDoms[l].innerHTML == "string") local.parseDom(linkDoms[l]); } } local.parseDom = function(dom){ var toParse = dom._origin_innerHTML||dom.innerHTML; if(dom.classList.contains("fast-bind")) toParse = "%c " + toParse + "%"; var text = local.parsePresetsText(toParse); if(local.properties.saveOriginHTML) dom._origin_innerHTML = toParse; dom.innerHTML = text.text; if(text.values.length) local.initUpdateText(dom, text); } //=== //Lot of helpers var processValuesChange = function(key, data){ //smooth value changing if(local.val.dynamic.hasOwnProperty(key+"_animated")){ var animation = function(){ local.val.dynamic[key+"_animated"] = Math.lerp(local.val.dynamic[key+"_animated"], local.val.dynamic[key], local.properties.animationStrength); //check fast and than check fine if(Math.round(local.val.dynamic[key+"_animated"]) == Math.round(local.val.dynamic[key]) && Math.abs(local.val.dynamic[key+"_animated"].toFixed(2)) == Math.abs(local.val.dynamic[key].toFixed(2))){ local.val.dynamic[key+"_animated"] = local.val.dynamic[key]; local.val.dynamic["_"+key+"_animated"].holdupTimer = null; clearInterval(local.val.dynamic["_"+key+"_animated"].intervalID) } } if(!local.properties.animateValues) local.val.dynamic[key+"_animated"] = local.val.dynamic[key]; else if(!local.val.dynamic["_"+key+"_animated"].holdupTimer){ //holdupTimer disabled for now local.val.dynamic["_"+key+"_animated"].holdupTimer = setTimeout( function(){ local.val.dynamic["_"+key+"_animated"].intervalID = setInterval(animation, local.properties.animationInterval); }, 100); } } } var defconst = function(key){ Object.defineProperty(local.val.dynamic, key, { get: function() { return local.val.dynamic['_' + key].val; }, set: function(v) { if(v == undefined){ console.error("value for " + key + " is undefined"); return; } else if(typeof v == "string"){ //possible it's float var parsed = parseFloat(v); if(!isNaN(parsed)) v = parsed; } else if(isNaN(v)){ console.warn(key + " was ", v, " and it's incorrect"); return; } var _key = '_'+ key; //event var els = local.val.dynamic[_key].elements var oldvalue = local.val.dynamic[_key].val; var evkeys = {oldvalue: oldvalue, newvalue: v, elements:els, key:key}; local.val.dynamic[_key].val = v; processValuesChange(key, evkeys); if(local.properties.emitEvent) utils.events.emit("gamevalchanged", evkeys); //sent personal events for(var i in els){ var el = els[i]; var prop = el._raw_innerHTML; if(!prop) continue; var str = local.subtituteValsInText(prop); if(!el.classList.contains("bindable_static")) el.innerHTML = str; if(local.val.dynamic[_key].eventListeners){ var detail = evkeys; detail.string = str; detail.settings = prop.values; var evt = new CustomEvent('gamevalchanged', {detail: detail}); el.dispatchEvent(evt); } } } }); }; //game values //getset for game values. Will send events and change strings local.defineDynamic = function(){ for(var k in local.val.dynamic) { if(k[0] == '_') continue; local.initGetterPropForValue(k); } }; local.clearElements = function(){ for(var k in local.val.dynamic) { if(k[0] != '_') continue; local.val.dynamic[k].elements = []; } }; local.initGetterPropForValue = function(value){ if(value[0] == '_') return; //create new buffer local.val.dynamic['_' +value] = {}; local.val.dynamic['_' +value].elements = []; local.val.dynamic['_' +value].val = local.val.dynamic[value]; local.val.dynamic['_' +value].onchange = []; local.val.dynamic['_' +value].eventListeners = false; //init setget for original defconst(value); }; //======= //Lang //======= local.parsePresetsText = function(rawtext){ var origintext = rawtext; var text = { text:"", values:[], //value = {settings, variable, format, origin_format} }; //var rawtext = rowtext.match(/\%.*?\%/g); rawtext = rawtext.split('%'); for(var i = 0;i < rawtext.length;i++){ var newvalue = { //settings : null, format : null, value : null, variable_name : null, origin_format : null, modifiers : null } if(rawtext[i][0] == 'c'){ //means constant var prop = rawtext[i].split(' ')[1]; if(local.val.static.hasOwnProperty(prop)){ text.text += '%s'; newvalue.format = "%s"; newvalue.value = genPointer("static", prop); newvalue.origin_format = prop; } else{ text.text += prop; console.warn("Can't find lang constant: " + prop); } } else if(rawtext[i][0] == 'v'){ //means value var rawTextSplit = rawtext[i].split(' '); var prop = rawTextSplit[1]; newvalue.origin_format = rawtext[i]; if(local.val.dynamic.hasOwnProperty(prop)){ text.text += '%s'; var settings = processPointerModificators(rawTextSplit.slice(2), prop); prop = settings.prop; newvalue.variable_name = prop; newvalue.value = genPointer("dynamic", prop, settings.fraclength); //pointer newvalue.modifiers = settings.modifiers; if(typeof(local.val.dynamic[prop]) == "string"){ newvalue.format = "%s"; } else{ var format = '%'; //padding - value like //%'*4d //where // '* is padding symbol // 4 minimum string length if(settings.minIlength){ format += "\'" + settings.fillSymbol; format += (1 + settings.minIlength + (settings.fraclength ? settings.fraclength : 0)).toString(); } if(settings.fraclength != null) format += "." + settings.fraclength; format += "f"; newvalue.format = format; } } else{ text.text += prop; console.warn("Can't find value constant: " + prop); } } else text.text += rawtext[i]; if(newvalue.format) text.values.push(newvalue); } if(!text.text.length) text.text = origintext; return text; } local.subtituteValsInText = function(rawtext){ var formated = []; for(var i in rawtext.values){ var v = rawtext.values[i]; var rawval = v.value(); if(v.modifiers && v.modifiers.includes("abs")){ rawval = Math.abs(rawval); } formated.push(sprintf(v.format, rawval)); } var newtext = vsprintf(rawtext.text, formated); if(local.properties.replaceDollarSign && local.val.currency && local.val.currency.hasOwnProperty(local.properties.activeCurrencyCode)) newtext = newtext.replaceAll('$', local.val.currency[local.properties.activeCurrencyCode].symbol_native); return newtext; } local.initUpdateText = function(inner, text){ inner._raw_innerHTML = text; inner.innerHTML = local.subtituteValsInText(text) for(var k in text.values) if(text.values[k].variable_name ){ if(!local.val.dynamic['_' + text.values[k].variable_name]){ console.log("Can't find val for:", '_' + text.values[k].variable_name); continue; } local.val.dynamic['_' + text.values[k].variable_name].elements.push(inner); } } var genPointer = function(where, what, roundAt){ return function(){ var v = local.val[where][what]; //avoid -0 if(roundAt != undefined && !isNaN(roundAt) && typeof v != "string"){ if(parseFloat(v.toFixed(roundAt)) == 0) v = Math.abs(v); } return v; } } //parsePresetsText helpers: /** * @brief finds value in local.val val and returns * @Param ref string starting with '&' character and variable name exist in local.val.dynamic * @Returns local.val.dynamic[ref.substr(1)] or ref */ var refToVal = function(ref){ var val = ref; if(ref && ref[0] == "*") val = local.val.dynamic[ref.substr(1)]; if(val == undefined){ console.warn("Can't find value pointer: " + ref); return null; } return val; } var irefToVal = function(ref){ return parseInt(refToVal(ref)); } //Works directly with local.val.dynamic var processPointerModificators = function(modifiers, prop){ var settings = { prop : prop, modifiers : null, fraclength : null, //float rounding modifier maxIlength : null, minIlength : null, fillSymbol : ' ' } if(!modifiers.length) return settings; settings.modifiers = modifiers; for(var i in modifiers){ var str = modifiers[i]; if(str == "a" || str == "animated"){ if(!local.val.dynamic.hasOwnProperty(prop+"_animated")){ local.val.dynamic[prop+"_animated"] = local.val.dynamic[prop]; local.initGetterPropForValue(prop+"_animated"); } settings.prop = prop+"_animated"; } if(str.startsWith("f(") || str.startsWith("fixed(")){ //input will like /* f('*[2:8].5) where: '* fillSymbol (padding symbol) [2:8] max and min length .5 fraclength */ var expr = str.split('(')[1].slice(0, -1); var values = expr.split('.'); {//fractional part var frac = irefToVal(values[1]); if(!isNaN(frac)) settings.fraclength = frac; } {//padding symbol if(values[0][0] == "\'"){ settings.fillSymbol = values[0][1]; values[0] = values[0].substr(2); } } {//padding length and max length if(values[0].length){ var arrinteg = values[0].split(':'); var min = irefToVal(arrinteg[0].substr(1)); var max = irefToVal(arrinteg[1].slice(0, -1)); //we have to decrease one symbol if there's no frac part var dec = settings.fraclength ? 0 : 1; if(!isNaN(min)) settings.minIlength = min - dec; if(!isNaN(max)) settings.maxIlength = max - dec; } } } if(str == "ev" || str == "event") local.val.dynamic['_'+settings.prop].eventListeners = true; } return settings; } String.prototype.replaceAll = function(search, replacement) { var target = this; return target.split(search).join(replacement); }; }());
Python
UTF-8
2,962
3.171875
3
[]
no_license
########## input file "logistic_and_svm_data.txt" has changed with space. import math import numpy as np from chart import Chart from readfile import Readfile FILE_NAME = "data/logistic_and_svm_data.txt" SMALL_NUMBER = 0.000000000000001 ################################################## ITERATION_NUMBER = 15000 ALPHA = 0.0009 INPUT_NUMBER = 2 WEIGHT = [-4.0, 1.0, 1.0] LAMBDA = 0.00001 # W0 + W1*X1 + W2*X2 ################################################## def sigmoid(x): return 1.0/(1.0+np.exp(-x)) def hypothesis(weight, x, j): result = 0.0 result += weight[0] for i in range(INPUT_NUMBER): result += (weight[i+1] * x[j][i]) return sigmoid(result) def summation(y, x, weight, hasX, m, k=-1): # hasX for W1. loss = 0.0 for i in range(m): hw = hypothesis(weight, x, i) error = (hw - y[i]) if hasX: error = error * x[i][k] loss += error return loss def l2_norm(weights): result = [] for i in weights: result.append(i - (LAMBDA * i)) return result def gradient_descent(x, y, weight, m): new_weight = [] const = float(ALPHA)/float(m) new_weight.append(weight[0] - (const * summation(y, x, weight, False, m))) for i in range(INPUT_NUMBER): new_weight.append(weight[i+1] - (const * summation(y, x, weight, True, m, i))) new_weight = l2_norm(new_weight) # l2-norm return new_weight def cost_function(x, y, weight, m): # cost function cost = 0.0 for i in range(m): cost1 = (-1) * y[i] * math.log(hypothesis(weight, x, i)) if hypothesis(weight, x, i) != 1: # for math error domain -> log(0) is not defined. cost2 = (1-y[i]) * math.log(1-hypothesis(weight, x, i)) else: cost2 = (1-y[i]) * math.log(SMALL_NUMBER) cost += (cost1 - cost2) constant = float(1) / float(m) cost *= constant print "Cost function is:", cost def logistic_regression(x, y, m, weight): for i in range(ITERATION_NUMBER): weight = gradient_descent(x, y, weight, m) cost_function(x, y, weight, m) return weight def seperate_data(x, y, output, m): isSickX = [] # 1 isSickY = [] # 1 notSickX = [] notSickY = [] for i in range(m): if output[i] == 0: notSickX.append(x[i]) notSickY.append(y[i]) else: isSickX.append(x[i]) isSickY.append(y[i]) return isSickX, isSickY, notSickX, notSickY if __name__ == '__main__': readFile = Readfile(FILE_NAME) x = readFile.readDataCol(1) y = readFile.readDataCol(2) output = readFile.readDataCol(3) isSickX, isSickY, notSickX, notSickY = seperate_data(x, y, output, len(output)) input = readFile.readDataLines() weight = logistic_regression(input, output, len(input), WEIGHT) chart = Chart() chart.draw_classification_line(weight, notSickX, notSickY, isSickX, isSickY, input)
Shell
UTF-8
290
2.71875
3
[]
no_license
#!/usr/bin/env bash SSH_KEY=$1 BUNDLE_NAME=$2 VERSION=${3-`cat ./VERSION`} BUNDLE_FILE="$BUNDLE_NAME-bundle-$VERSION.zip" BUNDLE_PATH='/var/www/api.openrouteservice.org/html/api-plugins/' scp -i $SSH_KEY $BUNDLE_FILE ubuntu@api.openrouteservice.org:~/ ssh -i $SSH_KEY ubuntu@api.openrouteservice.org "sudo mv ~/$BUNDLE_FILE $BUNDLE_PATH"
JavaScript
UTF-8
2,464
2.6875
3
[]
no_license
(function($){ $.fn.customInput = function (settings) { options = $.extend({}, $.fn.customInput.defaults, settings); $.each($(this), function (i, item) { item = $(item); if (item.attr('type') == 'checkbox' || item.attr('type') == 'radio') { item.hide(); idInput = item.attr('id'); label = $("label[for='"+ idInput +"']"); label.css('padding-left', options.paddingLeft) .css('margin', '0 0 0 5px'); changeImage(item, options); if (item.attr('type') == 'radio') { if ($.browser.msie) { label.click(function () { var item = $('input[type="radio"]#' + $(this).attr('for')); item.attr('checked', 'checked'); inputName = item.attr('name'); $.each($('input[name="'+ inputName +'"]'), function (i, radio) { changeImage($(radio), options); }); }); } else { item.click(function () { inputName = $(this).attr('name'); $.each($('input[name="'+ inputName +'"]'), function (i, radio) { changeImage($(radio), options); }); }); } } else { if ($.browser.msie) { label.click(function () { var item = $('input[type="checkbox"]#' + $(this).attr('for')); if (item.attr('checked')) { item.removeAttr('checked'); } else { item.attr('checked', 'checked'); } changeImage(item, options); }); } else { item.click(function () { changeImage($(this), options); }); } } } }); }; function changeImage(item, options) { idInput = item.attr('id'); label = $("label[for='"+ idInput +"']"); var imageOn = ""; var imageOf = ""; switch (item.attr('type')) { case 'radio' : imageOn = options.imageRadioOn; imageOff = options.imageRadioOff; break; case 'checkbox': imageOn = options.imageCheckboxOn; imageOff = options.imageCheckboxOff; break; } if (item.attr('checked')) { label.css('background', "url('"+ imageOn +"') no-repeat"); } else { label.css('background', "url('"+ imageOff +"') no-repeat"); } }; function changeImagesRadio() { }; $.fn.customInput.defaults = { imageCheckboxOn: 'images/checkbox_on.png', imageCheckboxOff: 'images/checkbox_off.png', imageRadioOn: 'images/checkbox_on.png', imageRadioOff: 'images/checkbox_off.png', paddingLeft: '22px', debug: false }; })(jQuery);
C#
UTF-8
2,423
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Sokoban.Core.Tests { [TestFixture] internal class MovementTests { [Test] public void BasicTest() { const string step0 = @"#### #-@# #--# ####"; const string step1 = @"#### #@-# #--# ####"; const string step2 = @"#### #--# #@-# ####"; const string step3 = @"#### #--# #-@# ####"; var level = new LevelCreator().Create(step0); TestStep(level, level.TryMoveLeft, step1); TestStep(level, level.TryMoveDown, step2); TestStep(level, level.TryMoveRight, step3); TestStep(level, level.TryMoveUp, step0); } [Test] public void WallsShouldBeImpassable() { const string levelData = @"### #@# ###"; NoMovement(levelData); } [Test] public void CratesShouldBeImpassable() { const string levelData = @"##### #-$-# #$@$# #-$-# #####"; NoMovement(levelData); } [Test] public void CratesShouldBeMovable() { const string step0 = @"-###- -#-#- ##$## #-$@# #####"; const string step1 = @"-###- -#-#- ##$## #$@-# #####"; const string step2 = @"-###- -#$#- ##@## #$--# #####"; var level = new LevelCreator().Create(step0); TestStep(level, level.TryMoveLeft, step1); TestStep(level, level.TryMoveUp, step2); } [Test] public void LevelBordersShouldBeImpassable() { const string input = "@"; var level = new LevelCreator().Create(input); Assert.AreEqual(1, level.Width); Assert.AreEqual(1, level.Height); var moved = level.TryMoveLeft() || level.TryMoveDown() || level.TryMoveRight() || level.TryMoveUp(); Assert.IsFalse(moved); } private static void NoMovement(string levelData) { var level = new LevelCreator().Create(levelData); TestStep(level, level.TryMoveLeft, levelData, Assert.IsFalse); TestStep(level, level.TryMoveDown, levelData, Assert.IsFalse); TestStep(level, level.TryMoveRight, levelData, Assert.IsFalse); TestStep(level, level.TryMoveUp, levelData, Assert.IsFalse); } private static void TestStep(Level level, Func<bool> stepFunc, string stepResult, Action<bool> assert = null) { assert = assert ?? Assert.IsTrue; var moved = stepFunc(); assert(moved); Assert.AreEqual(stepResult, level.ToString()); } } }
SQL
UTF-8
339
3.359375
3
[]
no_license
CREATE TABLE [ticket].[TicketType] ( [Id] INT IDENTITY (1, 1) NOT NULL, [EventId] INT NOT NULL, [Price] MONEY NOT NULL, CONSTRAINT [PK_ButtonCode] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_ButtonCode_SaleEvent] FOREIGN KEY ([EventId]) REFERENCES [ticket].[SaleEvent] ([Id]) ON DELETE CASCADE );
Python
UTF-8
900
3.4375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Jul 12 16:13:46 2014 @author: shunxu """ # -*- coding: utf-8 -*- """ Created on Sat Jul 26 11:20:43 2014 @author: shunxu """ import math num_range_low = 0 num_range_high = 100 real_num = 0 remain_guess_times = 0 print int(math.ceil(math.log(4,2))) remain_guess_times = int(math.ceil(math.log(num_range_high - num_range_low + 1, 2))) print remain_guess_times print("-----------math functions-------------") #数学函数 #取顶 print(math.ceil(2.3)) #取底 print(math.floor(2.3)) #取绝对值 print(math.fabs(-1)) #阶乘 print(math.factorial(3)) #求直角三角形斜边长 print(math.hypot(3,4)) #求x的y次方 print(math.pow(2,3)) #求x的开平方 print(math.sqrt(4)) #截断,只取整数部分 print(math.trunc(2.3)) #判断是否NaN(not a number) print(math.isnan(2.3333))
Java
UTF-8
969
2.375
2
[ "MIT" ]
permissive
package com.github.twitch4j.graphql.command; import com.apollographql.apollo.ApolloCall; import com.apollographql.apollo.ApolloClient; import com.github.twitch4j.graphql.internal.FetchActivePredictionsQuery; import lombok.NonNull; public class CommandFetchActivePredictions extends BaseCommand<FetchActivePredictionsQuery.Data> { private final String channelId; /** * Constructor * * @param apolloClient Apollo Client * @param channelId The id of the channel to fetch active predictions of */ public CommandFetchActivePredictions(@NonNull ApolloClient apolloClient, @NonNull String channelId) { super(apolloClient); this.channelId = channelId; } @Override protected ApolloCall<FetchActivePredictionsQuery.Data> getGraphQLCall() { return apolloClient.query( FetchActivePredictionsQuery.builder() .channelId(channelId) .build() ); } }
Markdown
UTF-8
3,634
3
3
[]
no_license
# 图解Http ### 分层 TCP/IP协议族按层次分别分为4层:应用层,传输层,网络层和数据链路层. 应用层:TCP/IP协议族内预存了各类通用的应用服务.比如FTP,DNS,HTTP 传输层:TCP,UDP 网络层:网络层用来处理网络上流动的数据包.数据包是网络传输的最小数据单位 链路层:用来处理链接网络的硬件部分. ![Image](/DiagramHttp/_001.jpg) ### 三次握手,四次挥手 ![Image](/DiagramHttp/_002.jpg) ![Image](/DiagramHttp/_003.jpg) ![Image](/DiagramHttp/_004.jpg) 三次握手目的是为了确认这是一个有效的连接,为了防止已经失效的请求到服务器而产生错误. 四次挥手的目的是因为TCP是全双工模式,也就是它们必须相互断开通道连接. ### URI与URL URI就是某个协议方案表示的资源的的定位标识符,例如HTTP协议,ftp,flie,ContentProvider等.URI是个纯粹的句法结构,用于指定标识Web资源的字符串的各个不同部分。URL是URI的一个特例,它包含了定位Web资源的足够信息.URI 是统一资源标识符,而 URL 是统一资源定位符。因此,笼统地说,每个 URL 都是 URI,但不一定每个 URI 都是 URL。这是因为 URI 还包括一个子类,即统一资源名称 (URN),它命名资源但不指定如何定位资源。 ### HTTP方法 方法名|描述 ---|--- GET|获取资源,用来请求访问已经被URI识别的资源. POST|传输实体主体. PUT|传输文件 HEAD|获取报文首部,与GET区别是不返回报文主体部分 DELETE|删除文件,因为没有经过验证,一般不用 OPTIONS|询问支持的方法 TRACE|追踪路径 CONNECT|要求用隧道协议连接代理 ### 状态码 状态码|类别|原因短语 ---|---|--- 1XX|Informational(信息性状态码)|接受的请求正在处理 2XX|Success(成功性状态码)|请求正常处理完毕 3XX|Redirection(重定向状态码)|需要进行夫家操作以完成请求 4XX|Client Error(客户端错误状态码)|服务器无法处理请求 5XX|Server Error(服务器错误状态码)|服务器处理请求出错 类别|结果 ---|--- 200|OK 201|No Content(没有内容更新) 206|Partial Content(范围请求) 301|Moved Permanently(永久性重定向) 302|Found(临时性重定向,询问是否要访问另外一个URI) 303|See Other(明确表示需要访问另一个URI) 304|Not Modified(服务器资源未改变,可直接使用客户端未过期缓存) 307|Temporay Redirect(临时重定向,与302类似) 400|Bad Request(请求语法错误) 401|Unauthorized(需要HTTP认证) 403|Forbidden(无权访问) 404|Not Found(访问URI不存在) 500|Internal Server Error(服务器内部错误) 503|Server Unavailable(服务器繁忙) ### HTTP首部 ![Image](/DiagramHttp/_005.jpg) ![Image](/DiagramHttp/_006.jpg) ![Image](/DiagramHttp/_007.jpg) ![Image](/DiagramHttp/_008.jpg) ### HTTPS HTTP+加密+认证+完整性保护=HTTPS,HTTP加上加密处理和认证以及完整性保护后即是HTTPS. HTTPS是身披SSL外壳的HTTP,HTTPS本身并不是一种新的协议,只是HTTP通信接口部分用SSL和TLS协议代替而已. 通常,HTTP直接和TCP通信.当使用SSL时,则演变成先和SSL通信,再由SSL和TCP通信了. ![Image](/DiagramHttp/_009.jpg) HTTPS采用共享密钥加密和公开密钥加密亮着并用的混合加密机制.若密钥能够事业线安全交互,那就使用共享密钥, 否则就考虑使用公开密钥的方式.但公开公密钥的速度要比共享密钥加密速度要慢. 因为公开密钥有可能是已经是被替换掉了,所以必须先嵌入由数字证书认证机构颁发的公开密钥,再进行加密.
Java
UTF-8
3,618
1.976563
2
[]
no_license
package com.rwq.testnetty; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import com.rwq.testnetty.bean.Message; import com.rwq.testnetty.conn.ImConnProvide; import com.rwq.testnetty.event.ChatBaseEvent; import com.rwq.testnetty.event.ChatTransDataEvent; import com.rwq.testnetty.event.MessageQoSEvent; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements ChatBaseEvent, ChatTransDataEvent, MessageQoSEvent { private final String TAG = getClass().getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "发起连接", Snackbar.LENGTH_LONG).show(); ImConnProvide.getInstance().connect(); } }); ImConnProvide.getInstance().init("106.13.25.41", 5280, this, this, this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { super.onDestroy(); ImConnProvide.getInstance().disconnect(); ImConnProvide.getInstance().release(); } @Override public void onLoginMessage(int dwErrorCode) { Log.i(TAG, "onLoginMessage:" + dwErrorCode); Message.IMMessage.Builder builder = Message.IMMessage.newBuilder(); Message.IMAuthMessage authMessage = Message.IMAuthMessage.newBuilder() .setMsgId(System.currentTimeMillis() + "") .setSource("ANDROID") .setToken("eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTA1NjQzMjksInVzZXJfbmFtZSI6ImFkbWluIiwiYXV0aG9yaXRpZXMiOlsiU1lTVEVNIiwiVVNFUiIsIkFETUlOIl0sImp0aSI6IjRiYjU2MTJjLTE0ZGUtNDY5Zi05MzRmLThmZTFiNmVjNTkxNyIsImNsaWVudF9pZCI6ImFwcGNsaWVudCIsInNjb3BlIjpbIm9wZW5pZCJdfQ.LV5V7uUKrIWkQmztIQdXSNWPQqS9vHRoIf7WYDhbJDqMmJ_86ybR9hSX1VhDTJy2w_0KKiar8wCslssrlQWqEVWJyUeRBPsIs7PsX8sx8L2bDWBYn4DruPLrvaDVfjhtEvPcu6wMGOM8OpnmzwWEt4kmZ_8PzPHETqkoR2D0jnHjmYZLYCdQQ7Nm0FNpQuvM6wkN3ide-nwGBnrajj03q98_Pz0QF9ay9MFdORQrfMrwShVUDe2PV_gI8mfgthI3Jk_M4poSI25_dRorTR037UK7CxQlcRmzKI84eGsMpUebDVAM2bZP1cZW0_a4ELVmrN6s7rgCs5LoEGqlT0OSBg") .setUserId("20201332044000001").build(); Message.IMMessage imMessage = builder.setDataType(Message.IMMessage.DataType.IMAuthMessage).setAuthMessage(authMessage).build(); ImConnProvide.getInstance().getChannel().writeAndFlush(imMessage); } @Override public void onLinkCloseMessage(int dwErrorCode) { Log.i(TAG, "onLinkCloseMessage:" + dwErrorCode); } @Override public void onTransBuffer(String fingerPrintOfProtocal, String userid, String dataContent, int typeu) { } @Override public void onErrorResponse(int errorCode, String errorMsg) { } @Override public void messagesLost(ArrayList<?> lostMessages) { } @Override public void messagesBeReceived(String theFingerPrint) { } }
C#
UTF-8
1,735
3.015625
3
[ "MIT" ]
permissive
using System; namespace BodeAbp.Queue.Protocols { [Serializable] public class QueueKey : IComparable<QueueKey>, IComparable { public string Topic { get; set; } public int QueueId { get; set; } public QueueKey() { } public QueueKey(string topic, int queueId) { Topic = topic; QueueId = queueId; } public static bool operator ==(QueueKey left, QueueKey right) { return IsEqual(left, right); } public static bool operator !=(QueueKey left, QueueKey right) { return !IsEqual(left, right); } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) { return false; } var other = (QueueKey)obj; return Topic == other.Topic && QueueId == other.QueueId; } public override int GetHashCode() { return (Topic + QueueId.ToString()).GetHashCode(); } public override string ToString() { return string.Format("{0}@{1}", Topic, QueueId); } private static bool IsEqual(QueueKey left, QueueKey right) { if (ReferenceEquals(left, null) ^ ReferenceEquals(right, null)) { return false; } return ReferenceEquals(left, null) || left.Equals(right); } public int CompareTo(QueueKey other) { return ToString().CompareTo(other.ToString()); } public int CompareTo(object obj) { return ToString().CompareTo(obj.ToString()); } } }
Java
UTF-8
1,148
3.578125
4
[]
no_license
class Solution { public int lengthOfLongestSubstring(String s) { int n = s.length(); int ans = 0, left=0, right=0; Set<Character> set = new HashSet(); while(left<n && right<n){ if(!set.contains(s.charAt(right))){ set.add(s.charAt(right)); right++; ans = Math.max(ans, right-left); } else{ set.remove(s.charAt(left++)); } } return ans; } } class Solution { public int lengthOfLongestSubstring(String s) { if(s==null || s.length()==0) return 0; int start = 0; int end = 0; int maxLength = 1; int length = s.length(); Set<Character> set = new HashSet(); while(start<length && end<length){ char ch = s.charAt(end); if(!set.contains(ch)){ set.add(ch); end++; maxLength = Math.max(maxLength, set.size()); } else{ set.remove(s.charAt(start++)); } } return maxLength; } }
Go
UTF-8
1,361
3.84375
4
[]
no_license
package main import ( "log" "sync" "time" ) type Processor struct { queue chan int workers sync.WaitGroup shutdown chan struct{} } func (p *Processor) Run(count int) { p.shutdown = make(chan struct{}) for i := 0; i < count; i++ { p.workers.Add(1) go p.worker(i) } } func (p *Processor) Stop() { close(p.shutdown) p.workers.Wait() } func (p *Processor) Submit(i int) { p.queue <- i } func (p *Processor) worker(id int) { defer p.workers.Done() for { select { case item := <-p.queue: log.Printf("%3d: (%d) WORKING", item, id) if item%2 == 0 { time.Sleep(time.Second * 3) } else { time.Sleep(time.Second * 5) } log.Printf("%3d: (%d) WORKED", item, id) case <-p.shutdown: log.Printf("Shutdown %d", id) return } } } func main() { processor := &Processor{ queue: make(chan int, 1), workers: sync.WaitGroup{}, } processor.Run(4) // start with 4 workers go func() { var i = 0 for { if i < 100 { log.Printf("%3d: ADDING", i) processor.Submit(i) log.Printf("%3d: ADDED", i) } if i == 10 { processor.Stop() // waits until existing workers have completed processor.Run(2) // restart with only 2 workers } if i == 15 { processor.Stop() processor.Run(20) // restart with 20 workers } i++ } }() forever := make(chan struct{}) <-forever }
Java
UTF-8
917
3.609375
4
[]
no_license
import java.util.HashMap; import java.util.Map; public class LongestPalindrome { //Case sensitive, s max length = 1010 //Runtime: 6 ms //Memory usage: 37.4 MB public int longestPalindrome(String s) { if (s.length() == 0) return 0; Map<Character, Integer> occur = new HashMap<>(); //Build occurrence map for (int i = 0; i < s.length(); i++) { occur.put(s.charAt(i), occur.getOrDefault(s.charAt(i), 0) + 1); } boolean hasOdd = false; int maxLength = 0; int count; for (Map.Entry<Character, Integer> entry: occur.entrySet()) { count = entry.getValue(); if (!hasOdd && count % 2 == 1) hasOdd = true; if (count >= 2) { maxLength += (count % 2 == 1) ? (count - 1) : count; } } if (hasOdd) maxLength++; return maxLength; } }
Markdown
UTF-8
2,847
3.5
4
[]
no_license
#【区块链】一张大表还是一本大书 这两天,又读了一遍王建硕的这篇文章——《[互联网是一张网,Web3 是一张表(一张大大的表)](https://mp.weixin.qq.com/s/KMminDvloww_rZQ4qrkdfQ)》。 「怎样用最简单的话来介绍区块链这个概念」,单单是这一个想法,就把我迷住了。自己回头重新翻看了一下自己还没写完的《什么是区块链》系列,果然还是太复杂了! 我同意王建硕的意见,「用 “下一代互联网” 来解释 Web3 」确实是偷懒!Web3和Web的关系,真的就好像雷锋与雷峰塔一样。于是他说: > Web3 是全球一张表(大大的表格),以及基于这个表的应用。 > > 有人用互联网的技术,解释资产怎么从一个人手里转移到另一个人手里面,听众会误以为资产跟一封电子邮件一样从一个地方发送到了另外一个地方。 > > 其实,并没有传输过程,就是大家用了一张表记账,这张大大的 Excel 表格有一栏叫做 “钱”,一栏叫做 “主人”。在这张大表里面一笔钱的 “主人” 从张三改成李四,就完成了资产的转移。并没有什么东西顺着网线网线从张三的电脑(或钱包)里面转移到了李四手里。 这么说确实挺简单的,他还将这句话用简单的单词写成了了英文: > Blockchain == a very big table shared by everyone in the world 并通过了Randall 的1000个词检测。但我细想了一下,却发现这里用 Table这个词,悄悄隐藏了一个重大概念。Table本意是桌子,可是这里指的却是表格,甚至是Excel这样的电子表格,其中所记录的内容,还隐藏了「钱」、「主人」这类财经领域的概念。 而且,这句英文里,还有一个重要的概念没能表达,那就是,这表里的记录可不能随便更改。 我试着重新梳理了一下概念,觉得换用「书」这个词更好。不论书还是Book,都是更为基本,且没有太多歧义的概念。毕竟,连记账都是叫做Bookkeeping嘛。所以,我的定义是这样的: > 区块链是一本非常巨大的书。一本用来保存你和他人最重要东西的书。这世界上的每一个人都可以分享这边书,并且相信这本书上的内容。 > > Blockchain == A very very big book. It keeps the most important things for you and others. Every one in the world could share it and trust it. 好吧,这句英文,经过了[Randa ll 的 1000 个词表检查](https://xkcd.com/simplewriter/) ,也通过了https://hemingwayapp.com/ 的Readability Grade 1 ;) 还有一个需要优化的部分——这本书是电子的、虚拟的,这个概念要怎么用1000个单词解释清楚呢?找时间,还是把我那《什么是区块链系列》先写完吧。
Java
UTF-8
683
2.234375
2
[]
no_license
package com.torlus.jnl.entities; import com.torlus.jnl.Entity; import com.torlus.jnl.Signal; import com.torlus.jnl.SignalType; public class Ab8016a extends Entity { @Override public String getBaseName() { return "ab8016a"; } @Override public boolean requireSysclk() { return true; } public Ab8016a() { for (int i = 0; i < 16; i++) { Signal s = new Signal("z", SignalType.BUS); s.bit = i; ios.add(s); } ios.add(new Signal("cen", SignalType.IN)); ios.add(new Signal("rw", SignalType.IN)); // ios.add(new Signal("clk", SignalType.IN)); for (int i = 0; i < 8; i++) { Signal s = new Signal("a", SignalType.IN); s.bit = i; ios.add(s); } } }
JavaScript
UTF-8
2,750
3.109375
3
[]
no_license
import { elements } from './base'; // read the html element information of the selected course export const getProductInfo = (product) => { // console.log(course); const productInfo = { image: product.querySelector('img').src, price: product.querySelector('h5').textContent, id: product.querySelector('button').getAttribute('data-id') } //console.log(productInfo); // Insert into Cart addInfoCart (productInfo); totalPrice(); } // total price calculate function function totalPrice() { const total = []; const items = document.querySelectorAll('.item-info'); items.forEach(function (item) { total.push(parseFloat(item.textContent)); }); // console.log(total); const totalPrice = total.reduce(function (total, item) { total += item; return total; }, 0); // console.log('total '+ totalPrice); document.querySelector('#total-price').textContent = totalPrice; } const templateBuild = function(product) { // build template const row = document.createElement('tr'); row.innerHTML = ` <li> <span class="item"> <span class="item-left"> <img src="${product.image}" width="100" height="150"/> <span class="item-info"> <span>${product.price}</span> </span> </span> <span class="item-right"> <button class="btn btn-xs btn-danger pull-right" data-id ="${product.id}">x</button> </span> </span> </li> `; // add into shoping cart elements.shopingCartContent.appendChild(row); } const addInfoCart = (product) => { // templateBuild(product); saveIntoStorage(product); } function saveIntoStorage(product) { let products = getProductsFromStorage(); products.push(product); localStorage.setItem('products', JSON.stringify(products)); } // get the content from storage function getProductsFromStorage() { let products; if (localStorage.getItem('products') === null) { products = []; } else { products = JSON.parse(localStorage.getItem('products')); } return products; } // load products data from local storage export function getFromLocalStorage() { let productsLS = getProductsFromStorage(); productsLS.forEach( function (product) { templateBuild(product); }); } // remove from localstorage export function removeProductLocalStorage (id) { let productsLS = getProductsFromStorage(); productsLS.forEach(function (productLS, index) { if (productLS.id === id) { productsLS.splice(index, 1) } }); //console.log(productsLS); localStorage.setItem('products', JSON.stringify(productsLS)); }
Java
UTF-8
2,054
2.0625
2
[]
no_license
package controllers; import java.io.IOException; import java.util.List; import com.wrapper.spotify.exceptions.SpotifyWebApiException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import constants.Constants; import domain.AggregatePlaylist; import domain.SimplePlaylist; import services.PlaylistService; @RestController @RequestMapping("playlists") public class PlaylistController { @Autowired private PlaylistService _playlistService; @GetMapping(value = "/spotify/{page}") public List<SimplePlaylist> getPlaylists(@PathVariable("page") int page, @RequestHeader(Constants.ACCESS_HEADER) String accessToken) throws IOException, SpotifyWebApiException { return _playlistService.getUserPlaylists(accessToken, page); } @PostMapping(value = "/info/{playlistId}") public void generatePlaylistInfo(@PathVariable("playlistId") String playlistId, @RequestHeader(Constants.ACCESS_HEADER) String accessToken) throws InterruptedException, IOException, SpotifyWebApiException { _playlistService.generatePlaylistInfo(accessToken, playlistId); } @GetMapping(value = "/info/{playlistId}") public AggregatePlaylist getPlaylistInfo(@PathVariable("playlistId") String playlistId) { return _playlistService.getPlaylistInfo(playlistId); } @GetMapping(value = "/existing") public List<SimplePlaylist> getExistingPlaylists(@RequestHeader(Constants.ACCESS_HEADER) String accessToken) throws InterruptedException, IOException, SpotifyWebApiException { return _playlistService.getExistingPlaylists(accessToken); } }
TypeScript
UTF-8
816
2.71875
3
[]
no_license
import Game from "managers/Game"; import Upgrade from "upgrades/Upgrade"; import { ALLOW_PLAYER_TO_MOVE_INDEPENDENTLY_UPGRADE_COST, UpgradeKey, UpgradeType } from "constants/UpgradeConstants"; const BUTTON_UI_ID = 'buyPlayerMoveIndependently'; const TOOLTIP_TEXT = 'Players can have one bot moving at the same time as they manually move.'; export class PlayerMoveIndependentlyUpgrade extends Upgrade { constructor(game: Game, upgradeKey: UpgradeKey, upgradeLevel: number = 0) { super(game, UpgradeType.MOVEMENT, BUTTON_UI_ID, TOOLTIP_TEXT, upgradeKey, upgradeLevel, true); } public updateUiProperties(): void { this.setUiText(`Player Can Move Independently: ${this.getPrettyPrintCost()} pts`); } public getCost(): number { return ALLOW_PLAYER_TO_MOVE_INDEPENDENTLY_UPGRADE_COST; } }
Python
UTF-8
6,979
2.78125
3
[]
no_license
from typing import List import asyncpg class Repo: """Db layer""" def __init__(self, conn: asyncpg.pool.PoolConnectionProxy) -> None: self.conn = conn async def add_user(self, tg_id: int, username: str) -> None: """Добавляет пользователя в базу данных""" await self.conn.execute( "INSERT INTO users(tg_id, username) VALUES ($1, $2) ON CONFLICT (tg_id) DO NOTHING", tg_id, username ) return async def users_list(self) -> List[asyncpg.Record]: """Возвращает список всех пользователей бота""" users = [ row for row in await self.conn.fetch( "SELECT * FROM users", ) ] return users async def admins_list(self) -> List[int]: """Возвращает список всех админов бота""" admins = [ row[0] for row in await self.conn.fetch( """ SELECT tg_id FROM users WHERE role = 'admin'; """, ) ] return admins async def mark_user_as_inactive(self, tg_id: int) -> None: """Меняет статус активности пользователя""" await self.conn.execute( """ UPDATE users SET is_active = FALSE WHERE tg_id = $1; """, tg_id ) async def change_user_role(self, username: str, role: str) -> None: """Изменяет роль пользователя.""" update = await self.conn.execute( """ UPDATE users SET role = $2 WHERE username = $1; """, username, role, ) return update async def get_subscribers(self, service_name: str) -> List[int]: """Получение всех подписчиков Список tg_id активных пользователей бота, у которых есть подписка(и) """ users = [ row[0] for row in await self.conn.fetch( """ SELECT u.tg_id FROM users u JOIN subscriptions subs ON u.id = subs.user_id JOIN services s ON subs.service_id = s.id WHERE service_name = $1 AND u.is_active = true; """, service_name ) ] return users async def get_user_subscriptions(self, tg_id: int) -> List[asyncpg.Record]: """Подписки пользователя""" subscriptions = [ row for row in await self.conn.fetch( """ SELECT s.id, s.service_name FROM services s JOIN subscriptions subs ON s.id = subs.service_id WHERE subs.user_id = ( SELECT id FROM users WHERE tg_id = $1 ); """, tg_id ) ] return subscriptions async def add_subcription(self, tg_id: int, service_id: int) -> None: """Добавление подписки Добавляет пользователя в список рассылки по определенному сервису. """ await self.conn.execute( """ INSERT INTO subscriptions(user_id, service_id) VALUES ( (SELECT id FROM users WHERE tg_id = $1), $2 ) ON CONFLICT (user_id, service_id) DO NOTHING """, tg_id, service_id ) async def delete_subscription(self, tg_id: int, service_id: int) -> None: """Удаление подписки Удаляет пользователя из списка рассылки по определенному сервису. """ await self.conn.execute( """ DELETE FROM subscriptions as s WHERE user_id = (SELECT id FROM users WHERE tg_id = $1) AND service_id = $2; """, tg_id, service_id ) async def get_available_services_to_subscribe(self, tg_id: int) -> List[asyncpg.Record]: """Доступные сервисы для подписки В список не включены те сервисы, на которые пользователь уже подписан """ services = [ row for row in await self.conn.fetch( """ SELECT id, service_name FROM services WHERE services.id NOT IN ( SELECT service_id FROM subscriptions WHERE user_id = ( SELECT id FROM users WHERE tg_id = $1 ) ); """, tg_id, ) ] return services async def increase_interactions_counter(self, command: str) -> None: """Счетчик Обновляет счетчик вызова команд по названию команды. """ await self.conn.execute( """ UPDATE interactions_count SET cnt = cnt + 1 WHERE command = $1 """, command ) return async def get_service_names(self) -> List[str]: """Получает имена всех доступных сервисов""" names = [ row[0] for row in await self.conn.fetch( "SELECT service_name FROM services;" ) ] return names async def get_interactions_stats(self): """Статистика использования команд.""" stats = [ row for row in await self.conn.fetch( """SELECT * FROM interactions_count""", ) ] return stats async def get_services_stats(self): """Статистика по каждому сервису Название сервиса — количество подписчиков """ stats = [ row for row in await self.conn.fetch( """ SELECT s.service_name as service_name, COUNT(subs.user_id) as subscribers FROM services s JOIN subscriptions subs ON s.id = subs.service_id GROUP BY service_name ORDER BY subscribers DESC """, ) ] return stats
SQL
UTF-8
923
3.671875
4
[]
no_license
--insert insert into author values(1,'박경리','토지작가'); --insert2 (컬럼 지정) 순서 몰라도 사용 가능 insert into author (no,name) values(2,'이훈'); insert into author (name,no) values('공자',3); --insert3 insert into book values (1,'토지',null,1); insert into book (no,title,author_no) values (2,'칼의노래',2); --insert4 (Subquery) insert into book (select 3, '논어',null,3 from dual); --update update book set title = '토지3판', rate = 5, author_no=3 where no=1; commit; rollback; select * from author; select * from book; --update2 update book set rate = 5 where author_no =(select no from author where name = '이훈'); --delete delete from book where no = 3; --delete2 delete from book where author_no = (select no from author where name = '이훈'); --pseudo column (테이블 내 없는 컬럼 출력) select user from book;
Java
UTF-8
1,158
3.390625
3
[]
no_license
/** * projectName:Java开发实战经典 * fileName:StaticCodeDemo.java * packageName:com.java.development.five.codeblock * date:2018年9月17日上午10:13:09 * copyright(c) 2017-2020 xxx公司 */ package com.java.development.five.codeblock; /** * @title: StaticCodeDemo.java * @package com.java.development.five.codeblock * @description: TODO * @author: zxsn * @date: 2018年9月17日 上午10:13:09 * @version: V1.0 */ class StaticCode { { System.out.println("1、构造快。"); } static { System.out.println("0、静态地代码块。"); } public StaticCode() { System.out.println("2、构造方法。"); } } public class StaticCodeDemo { static { System.out.println("在主方法所在类中定义的代码块。"); } /** *@title main *@description: TODO *@author: zxsn *@date: 2018年9月17日 上午10:13:09 *@param args *@throws */ public static void main(String[] args) { new StaticCode(); new StaticCode(); new StaticCode(); } }
Java
UTF-8
2,267
2.40625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package filters; import businesslogic.UserService; import domainmodel.User; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author 727334 */ @WebFilter(filterName = "AdminFilter", servletNames = {"UserServlet"}) public class AdminFilter implements Filter { private FilterConfig filterConfig = null; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // this code executes before the servlet // ... // ensure user is authenticated HttpSession session = ((HttpServletRequest)request).getSession(); UserService us = new UserService(); String username =(String) session.getAttribute("username"); User user = new User(); try { user = us.get(username); } catch (Exception ex) { Logger.getLogger(AdminFilter.class.getName()).log(Level.SEVERE, null, ex); } if (session.getAttribute("username") != null && user.getRole().getRoleID() == 1) { chain.doFilter(request, response); } else { // get out of here! ((HttpServletResponse)response).sendRedirect("home"); } // this code executes after the servlet // ... } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } }
Java
WINDOWS-1250
615
3.671875
4
[]
no_license
package A5_Eingabe; import java.util.Scanner; public class EingabeKonsole { public static void main(String[] args) { //Eingabe Scanner s = new Scanner(System.in); System.out.print("Ihr alter: "); int alter = s.nextInt(); System.out.print("Ihre Gre in cm: "); double groesse = s.nextDouble(); System.out.print("Ihr Name: "); String name = s.next(); //Ausgabe System.out.println("-------------------------------"); System.out.println("Sie sind "+alter+" Jahre alt"); System.out.println("und "+groesse+"cm gro"); System.out.println("Ihr Name lautet: "+name); } }
Java
UTF-8
7,690
1.890625
2
[]
no_license
package com.harmazing.ifttt; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.ByteString; import com.harmazing.cache.ActiveCommandQueue; import com.harmazing.entity.AirCondition; import com.harmazing.entity.Gateway; import com.harmazing.entity.ZigbeeOO; import com.harmazing.ifttt.CommandUtil.Scope; import com.harmazing.protobuf.CommandProtos; import com.harmazing.protobuf.CommandProtos.AirConditionerControl.CommandType; import com.harmazing.protobuf.DeviceProtos.DeviceSpecific; import com.harmazing.protobuf.DeviceProtos.DeviceSpecific.DeviceType; import com.harmazing.server.ActiveChannelGroup; import com.harmazing.service.DeviceService; import com.harmazing.util.MessageUtil; import com.harmazing.util.ProtobufUtil; import com.harmazing.util.QueueUtil; public class IftttAction { public final static Logger LOGGER = LoggerFactory.getLogger(IftttAction.class); private final static String channel = "ifttt_channel"; private ActiveCommandQueue activeQueue = null; DeviceService dev_srv = null; ///////////////////////////////////////////////////// public IftttAction(DeviceService srv, ActiveCommandQueue queue ){ dev_srv = srv; activeQueue = queue; } ///////////////////////////////////////////////////// public void execute(String act) throws Exception{ JSONObject obj = new JSONObject(act); JSONArray array = obj.getJSONArray("action"); for(int i=0; i<array.length(); ++i){ JSONObject action = (JSONObject)array.get(i); int dev_type = (int)action.get("type"); if(dev_type == DeviceSpecific.DeviceType.INNOLINKS_AC_VALUE ){ executeAC(action); }else if(dev_type == DeviceSpecific.DeviceType.INNOLINKS_AC_POWER_SOCKET_VALUE){ executeIR(action); }else if(dev_type == DeviceSpecific.DeviceType.ZIGBEE_OO_VALUE){ executeOO(action); } } } /////////////////////////////////////////////////////// private void executeAC(JSONObject obj){ String op = (String)obj.get("op"); String var = (String)obj.get("var"); int val = Integer.parseInt((String)obj.get("val")); String mac = (String)obj.get("mac"); AirCondition ac = dev_srv.getAcByAcMac(mac); /* long current_time = System.currentTimeMillis(); long update_time = this.convertTimeStr2Long(ac.getUpdate_time()); if( (current_time - update_time) < regulation_interval) return; */ if( ac == null || (ac.getOperStatus() == 0)|| (ac.getOnOff() == 0)) { LOGGER.info("IftttThread.executeAC: AC("+mac+") is OFFLINE, do nothing."); return; } Gateway gw = dev_srv.getGWByGwId(ac.getGw_id()); if( gw.getOperStatus() == 0) { LOGGER.info("IftttThread.executeAC: GW("+mac+") is OFFLINE, do nothing."); return; } String gw_mac = gw.getMac(); String ac_mac = ac.getMac(); DeviceType dev_type = DeviceType.INNOLINKS_AC; publish("COMMAND", "", gw_mac, ac_mac, var, String.valueOf(val)); //execution(var, val, channel, gw_mac, ac_mac, dev_type,"", val); } /////////////////////////////////////////////////////// private void executeIR(JSONObject obj){ String modsig = ""; int rcu_id = 1000; String ac_mac = (String)obj.get("mac"); String var = (String)obj.get("var"); int val = Integer.parseInt((String)obj.get("val")); AirCondition ac = dev_srv.getAcByAcMac(ac_mac); if( ac == null || (ac.getOperStatus() == 0) || (ac.getOnOff() == 0)) { LOGGER.info("IftttThread.executeAC: AC("+ac_mac+") is OFFLINE, do nothing."); return; } Gateway gw = dev_srv.getGWByGwId(ac.getGw_id()); String gw_mac = gw.getMac(); if( gw.getOperStatus() == 0) { LOGGER.info("IftttThread.executeAC: GW("+gw_mac+") is OFFLINE, do nothing."); return; } rcu_id = ac.getRcuId(); int mode = ac.getMode(); int acTemp = ac.getAcTemp(); int udSwing = ac.getUpDownSwing(); int lrSwing = ac.getLeftRightSwing(); int speed = ac.getSpeed(); int onOff = ac.getOnOff(); if(var.equals("mode")){ mode = val; }else if(var.equals("acTemp")){ acTemp = val; }else if(var.equals("onOff")){ onOff = val; }else if(var.equals("speed")){ speed = val; }else if(var.equals("upDownSwing")){ udSwing = val; } modsig += mode; if(acTemp < 10) modsig += "0"; modsig += acTemp; modsig += udSwing; modsig += lrSwing; modsig += speed; modsig += onOff; publish(CommandUtil.IrControlCommandType.IR_TX_CODE, "IRCONTROL", gw_mac, ac_mac, "modsig", ""+rcu_id+"&"+modsig); /* JSONObject ac_code_obj = MessageUtil.getAcCodesById(String.valueOf(rcu_id), modsig); if(ac_code_obj == null || (int)ac_code_obj.get("status") == 1){ LOGGER.warn("IfTTT.executeIR: Could not find matchaced AC codes with modsig(" + modsig + "), do nothing."); return; } String str_main = (String)ac_code_obj.get("main"); JSONArray llength = ac_code_obj.getJSONArray("length"); String length = MessageUtil.convertJSONArray2String(llength); ByteString main = null; if( str_main != null && !(str_main.toString().equals(""))){ main = ProtobufUtil.covertMain2SBytetring( str_main); } CommandProtos.IrControl.CommandType cmd_type = CommandProtos.IrControl.CommandType.IR_TX_CODE; int seq_num = ActiveChannelGroup.sendIrControlMessage(channel, gw_mac, ac_mac, cmd_type, main, length); QueueUtil.addIrControlCmd2Queue(activeQueue, seq_num, channel, ac_mac, modsig); */ } /////////////////////////////////////////////////////// private void executeOO(JSONObject obj){ String op = (String)obj.get("op"); String var = (String)obj.get("var"); int val = Integer.parseInt((String)obj.get("val")); String mac = (String)obj.get("mac"); ZigbeeOO oo = dev_srv.getZiebeeOOByMac(mac); Gateway gw = dev_srv.getGWByGwId(oo.getGw_id()); String gw_mac = gw.getMac(); String ac_mac = oo.getMac(); DeviceType dev_type = DeviceType.ZIGBEE_OO; //execution(var, val, channel, gw_mac, ac_mac, dev_type,"", val); publish("COMMAND", "", gw_mac, ac_mac, var, String.valueOf(val)); } ////////////////////////////////////////////////////// private void execution(String var, int val, String channel, String gw_mac, String dev_mac, DeviceType dev_type, String str_param, Integer int_param){ CommandType cmd_type = CommandType.ON; if( var.equals("onOff")){ if( val == 0){ cmd_type = CommandType.OFF; }else if( val == 1){ cmd_type = CommandType.ON; } }else if( var.equals("acTemp")){ cmd_type = CommandType.TEMP_SET; }else if( var.equals("speed")){ cmd_type = CommandType.FAN_SET; } int seq_num = ActiveChannelGroup.sendCommandMessageByDeviceId(channel, gw_mac, dev_mac, dev_type, cmd_type, str_param, int_param); QueueUtil.addDeviceControlCmd2Queue( activeQueue, seq_num, channel, dev_mac, dev_type, cmd_type, int_param); } //////////////////////////////////////////////////////// private void publish( String cmd_type, String msg_type, String gw_mac, String dev_mac, String var, String value){ try{ Map<String, String> command = null; if(msg_type.equals("IRCONTROL")){ command =CommandUtil.buildIrControlMessageMap(gw_mac, dev_mac, cmd_type, value); }else if( msg_type.equals("COMMAND")){ command =CommandUtil.buildCommandMessageMap( Scope.DEVICE, gw_mac, dev_mac, cmd_type, var, Integer.parseInt(value)); } int onStatus = CommandUtil.syncSendMessage(command); if( onStatus == 0){ LOGGER.debug("Regulation and adjustment succesfully."); }else{ LOGGER.debug("Regulation and adjustment failed."); } }catch(Exception e){ e.printStackTrace(); } } }
Markdown
UTF-8
10,001
3.09375
3
[]
no_license
--- description: 阅读libevent源码过程中的一些记录 --- # Libevent - Source Code \(3\) ## 配置event\_base 相关文件: ```c event.h event-internal.h event.c ``` 初始化出一个`event_base`有有两种方法,`event_base_new()`和`event_base_new_with_config()` 先看`event_base_new()`: ```c // event.c struct event_base * event_base_new(void) { struct event_base *base = NULL; struct event_config *cfg = event_config_new(); if (cfg) { base = event_base_new_with_config(cfg); event_config_free(cfg); } return base; } ``` 实际上是new除了一个默认的config然后调`event_base_new_with_config()`,看看`event_config_new()`里面主要是初始化了一个`event_config` ```c // event-internal.h /** Internal structure: describes the configuration we want for an event_base * that we're about to allocate. */ struct event_config { TAILQ_HEAD(event_configq, event_config_entry) entries; int n_cpus_hint; enum event_method_feature require_features; enum event_base_config_flag flags; };c ``` 向`entries`里面添加`avoid_method`: ```c // event.c int event_config_avoid_method(struct event_config *cfg, const char *method) { struct event_config_entry *entry = mm_malloc(sizeof(*entry)); // 申请一块内存 if (entry == NULL) return (-1); if ((entry->avoid_method = mm_strdup(method)) == NULL) { // 把屏蔽的method复制进去 mm_free(entry); return (-1); } TAILQ_INSERT_TAIL(&cfg->entries, entry, next); // 插入到cfg->entries里 return (0); } ``` 能够看出这个配置的作用是避免使用指定的多路IO复用函数 > 查看Libevent源码包里的文件,可以发现有诸如epoll.c、select.c、poll.c、devpoll.c、kqueue.c这些文件。打开这些文件就可以发现在文件内容的前面都会定义一个struct eventop类型变量。该结构体的第一个成员必然是一个字符串。这个字符串就描述了对应的多路IO复用函数的名称。所以是可以通过名称来禁用某种多路IO复用函数的。 设置`n_cpus_hint`,来方便libevent作为参考用核。这只是一个提示,实际libevent使用的核可能比这个多或者少 ```c int event_config_set_num_cpus_hint(struct event_config *cfg, int cpus); ``` 设置`require_features`,配置需要的功能,用或传进去 ```c int event_config_require_features(struct event_config *cfg, int features); //event.h文件 enum event_method_feature { //支持边沿触发 EV_FEATURE_ET = 0x01, //添加、删除、或者确定哪个事件激活这些动作的时间复杂度都为O(1) //select、poll是不能满足这个特征的.epoll则满足 EV_FEATURE_O1 = 0x02, //支持任意的文件描述符,而不能仅仅支持套接字 EV_FEATURE_FDS = 0x04 }; ``` 设置flags,配置需要的,用或传进去 ```c int event_config_set_flag(struct event_config *cfg, int flag); enum event_base_config_flag { //不要为event_base分配锁。设置这个选项可以为event_base节省一点加锁和解锁的时间,但是当多个线程访问event_base会变得不安全 EVENT_BASE_FLAG_NOLOCK = 0x01, //选择多路IO复用函数时,不检测EVENT_*环境变量。使用这个标志要考虑清楚:因为这会使得用户更难调试程序与Libevent之间的交互 EVENT_BASE_FLAG_IGNORE_ENV = 0x02, //仅用于Windows。这使得Libevent在启动时就启用任何必需的IOCP分发逻辑,而不是按需启用。如果设置了这个宏,那么evconn_listener_new和bufferevent_socket_new函数的内部将使用IOCP EVENT_BASE_FLAG_STARTUP_IOCP = 0x04, //在执行event_base_loop的时候没有cache时间。该函数的while循环会经常取系统时间,如果cache时间,那么就取cache的。如果没有的话,就只能通过系统提供的函数来获取系统时间。这将更耗时 EVENT_BASE_FLAG_NO_CACHE_TIME = 0x08, //告知Libevent,如果决定使用epoll这个多路IO复用函数,可以安全地使用更快的基于changelist 的多路IO复用函数:epoll-changelist多路IO复用可以在多路IO复用函数调用之间,同样的fd 多次修改其状态的情况下,避免不必要的系统调用。但是如果传递任何使用dup()或者其变体克隆的fd给Libevent,epoll-changelist多路IO复用函数会触发一个内核bug,导致不正确的结果。在不使用epoll这个多路IO复用函数的情况下,这个标志是没有效果的。也可以通过设置EVENT_EPOLL_USE_CHANGELIST 环境变量来打开epoll-changelist选项 EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10 }; ``` ## 跨平台Reactor接口 ```c struct event_base { /** Function pointers and other data to describe this event_base's * backend. */ const struct eventop *evsel; /** Pointer to backend-specific data. */ void *evbase; ... } /** Structure to define the backend of a given event_base. */ struct eventop { /** The name of this backend. */ const char *name; /** Function to set up an event_base to use this backend. It should * create a new structure holding whatever information is needed to * run the backend, and return it. The returned pointer will get * stored by event_init into the event_base.evbase field. On failure, * this function should return NULL. */ void *(*init)(struct event_base *); /** Enable reading/writing on a given fd or signal. 'events' will be * the events that we're trying to enable: one or more of EV_READ, * EV_WRITE, EV_SIGNAL, and EV_ET. 'old' will be those events that * were enabled on this fd previously. 'fdinfo' will be a structure * associated with the fd by the evmap; its size is defined by the * fdinfo field below. It will be set to 0 the first time the fd is * added. The function should return 0 on success and -1 on error. */ int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo); /** As "add", except 'events' contains the events we mean to disable. */ int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo); /** Function to implement the core of an event loop. It must see which added events are ready, and cause event_active to be called for each active event (usually via event_io_active or such). It should return 0 on success and -1 on error. */ int (*dispatch)(struct event_base *, struct timeval *); /** Function to clean up and free our data from the event_base. */ void (*dealloc)(struct event_base *); /** Flag: set if we need to reinitialize the event base after we fork. */ int need_reinit; /** Bit-array of supported event_method_features that this backend can * provide. */ enum event_method_feature features; /** Length of the extra information we should record for each fd that has one or more active events. This information is recorded as part of the evmap entry for each fd, and passed as an argument to the add and del functions above. */ size_t fdinfo_len; }; ``` 可以看出这里跟前面的log, lock等一样,定义了一个`eventop`存放所有对`event`的操作的函数指针,在每个函数的文件里面会有针对这些函数的实现,如`epoll, select`等。然后每个`event_base`根据创建的时候传入的`config`选择具体要用哪个`eventop`。 看一下这部分是如何实现的: 在`event_base_new_with_config`里面有对`eventop`的选择 ```c // event.c struct event_base * event_base_new_with_config(const struct event_config *cfg) { ... for (i = 0; eventops[i] && !base->evbase; i++) { if (cfg != NULL) { /* determine if this backend should be avoided */ if (event_config_is_avoided_method(cfg, eventops[i]->name)) // 用FOREACH遍历cfg->entries看这个方法是不是被屏蔽掉了 continue; if ((eventops[i]->features & cfg->require_features) != cfg->require_features) // 看这个方法是否满足用户需要的feature continue; } /* also obey the environment variables */ if (should_check_environment && event_is_method_disabled(eventops[i]->name)) // 看环境变量有没有屏蔽某个方法 continue; base->evsel = eventops[i]; // 确定了方法之后把它放进event_base里 base->evbase = base->evsel->init(base); } ... } ``` `eventops`是怎么来的呢,基本是判断系统里有没有某个方法,然后加进一个数组里。把效率高的放在前面优先用 ```c #ifdef _EVENT_HAVE_EVENT_PORTS extern const struct eventop evportops; #endif #ifdef _EVENT_HAVE_SELECT extern const struct eventop selectops; #endif #ifdef _EVENT_HAVE_POLL extern const struct eventop pollops; #endif #ifdef _EVENT_HAVE_EPOLL extern const struct eventop epollops; #endif #ifdef _EVENT_HAVE_WORKING_KQUEUE extern const struct eventop kqops; #endif #ifdef _EVENT_HAVE_DEVPOLL extern const struct eventop devpollops; #endif #ifdef WIN32 extern const struct eventop win32ops; #endif /* Array of backends in order of preference. */ static const struct eventop *eventops[] = { #ifdef _EVENT_HAVE_EVENT_PORTS &evportops, #endif #ifdef _EVENT_HAVE_WORKING_KQUEUE &kqops, #endif #ifdef _EVENT_HAVE_EPOLL &epollops, #endif #ifdef _EVENT_HAVE_DEVPOLL &devpollops, #endif #ifdef _EVENT_HAVE_POLL &pollops, #endif #ifdef _EVENT_HAVE_SELECT &selectops, #endif #ifdef WIN32 &win32ops, #endif NULL }; ``` ## 参考资料 [https://blog.csdn.net/luotuo44/category\_9262895.html](https://blog.csdn.net/luotuo44/category_9262895.html) [http://www.wangafu.net/~nickm/libevent-book/Ref2\_eventbase.html](http://www.wangafu.net/~nickm/libevent-book/Ref2_eventbase.html)
Markdown
UTF-8
1,490
3.203125
3
[]
no_license
# noobannotator This is a Rich Text Editor (based on DraftJs) that allows user to add comments and emoji's into articles. ![alt text](https://github.com/raymond-ong/noobannotator/blob/master/screenshots/screenshot_default.png?raw=true) ## Features 1. Add Comments and Emoji's into rich text editor * Hover over the comments (right hand side) or the commented keywords to highlight the corresponding keyword or comment 2. Save the document to the browser's local storage, so that it can be loaded next time ## How to use 1. Start editing document 2. To add comments, highlight some text, then click "Comment" button 2.1. To change the comment color, type in any CSS color like "blue" or "#00f" or "#0000ff" 3. To delete a comment, click the Red X button inside the comment dialog's top right hand corner. 4. To Save the document to the browser's local storage, stype in a file name into the editable dropdown control on the top right corner of the window, then select "Create <filename>" 4.1. Existing saved documents can also be deleted by clicking the "Delete" button in the droddown menu. ### Demo Page: https://raymond-ong.github.io/noobannotator/ * Best viewed in Desktop browser * Although it would still work in mobile browsers, it's not as intuitive (e.g. selecting text) ### TODO's - [X] Better placement of the comments (currently just stacking the comments - [ ] Better mobile browser support - [ ] Add in more Rich Text Box features (e.g. Colors, Highlighting, Images)
Java
UTF-8
13,408
1.875
2
[]
no_license
package com.example.john.mobicare_uganda.views; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CalendarView; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.example.john.mobicare_uganda.R; import com.example.john.mobicare_uganda.dbsyncing.Appointment_Reciever; import com.example.john.mobicare_uganda.dbsyncing.Appoitments; import com.github.sundeepk.compactcalendarview.CompactCalendarView; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.LinkedList; import java.util.List; import connectivity.Get_CurrentDateTime; import server_connections.Doctor_Operations; import users.Dialog_Message; import users.User_Details; /** * Created by john on 11/2/17. */ public class Scheduler_1 extends AppCompatActivity { String date_,time1,time2; private TextView selected_date,selected_time,time_from,time_to,date_text,selected_day; private DatePicker datePicker; private TimePicker timePicker; private ImageView imageView; int doctor_id,category_id; AlarmManager alarmManager; private PendingIntent pendingIntent; private Context context = this; private Button submit_btn; int flag1 = 1; int flag2 = 1; @RequiresApi(api = Build.VERSION_CODES.O) @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scheduler_1); selected_date = (TextView) findViewById(R.id.select_date); selected_day = (TextView) findViewById(R.id.select_day); selected_time = (TextView) findViewById(R.id.select_t); date_text = (TextView) findViewById(R.id.date_text); time_from = (TextView) findViewById(R.id.text_time_from); time_to = (TextView) findViewById(R.id.text_time_to); imageView = (ImageView) findViewById(R.id.imageView); timePicker = (TimePicker) findViewById(R.id.tp_timepicker) ; datePicker = (DatePicker) findViewById(R.id.simpleDatePicker); submit_btn = (Button) findViewById(R.id.submit_btn); date_ = getIntent().getStringExtra("date"); time1 = getIntent().getStringExtra("time1"); time2 = getIntent().getStringExtra("time2"); doctor_id = Integer.parseInt(getIntent().getStringExtra("doctor_id")); category_id = Integer.parseInt(getIntent().getStringExtra("category_id")); date_text.setText(date_); time_from.setText(time1); time_to.setText(time2); selected_time.setText(time1); try { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm"); Date date = null; date = sdf.parse(time1); Calendar c = Calendar.getInstance(); c.setTime(date); timePicker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(c.get(Calendar.MINUTE)); timePicker.setIs24HourView(false); int today = Get_CurrentDateTime.getCurrentDay(); int day_s = Get_CurrentDateTime.getDate_By(date_); selected_day.setText(date_); if (today == day_s){ selected_date.setText(new Get_CurrentDateTime().getCurrentDate()); }else if (today < day_s || today > day_s ){ int diff = day_s - today; String dt = new Get_CurrentDateTime().getCurrentDate(); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cl = Calendar.getInstance(); cl.setTime(sf.parse(dt)); cl.add(Calendar.DATE, diff+7); // number of days to add dt = sf.format(cl.getTime()); // dt is now the new date selected_date.setText(dt); } final String [] splits1 = time1.split(":"); final String [] splits2 = time2.split(":"); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker timePicker, int hrs, int min) { selected_time.setText(hrs+":"+min); String sel_time = hrs+":"+min; if (hrs >= Integer.parseInt(splits1[0]) && hrs <= Integer.parseInt(splits2[0]) ){ sel_time = hrs+":"+min; if (flag2 == 1){ imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.single_tick)); submit_btn.setEnabled(true); } flag1 = 1; }else { sel_time ="("+sel_time+ ")\nOut of Range!"; imageView.setImageDrawable(context.getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel)); submit_btn.setEnabled(false); flag1 = 1; } selected_time.setText(sel_time); } }); submit_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String time_selected = selected_time.getText().toString().trim(); String date_selected = selected_date.getText().toString().trim(); showDialog(date_selected, time_selected); } }); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } setMin(); }catch (Exception e){ e.printStackTrace(); } setDate(); try{ }catch (Exception e){ e.printStackTrace(); } } @RequiresApi(api = Build.VERSION_CODES.O) public void setDate(){ try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; date = sdf.parse(new Get_CurrentDateTime().getCurrentDate()); Calendar c = Calendar.getInstance(); c.setTime(date); datePicker.setMinDate(c.getTimeInMillis()); datePicker.init(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) { // Log.d("Date", "Year=" + year + " Month=" + (month + 1) + " day=" + dayOfMonth); SimpleDateFormat simpledateformat = new SimpleDateFormat("EEEE"); Date date = new Date(year, month, dayOfMonth-1); String dayOfWeek = simpledateformat.format(date); selected_day.setText(dayOfWeek); String select = year+"-"+month+"-"+dayOfMonth; if (dayOfWeek.equals(date_)){ selected_date.setText(select); if (flag1 == 1){ imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.single_tick)); submit_btn.setEnabled(true); } flag2 = 1; }else { selected_date.setText("("+select+")\nOut of Range!"); imageView.setImageDrawable(context.getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel)); submit_btn.setEnabled(false); flag2 = 0; } } }); c.add(Calendar.DATE,30); datePicker.setMaxDate(c.getTimeInMillis()); }catch (Exception e){ e.printStackTrace(); } } public static String getCurrentDay(){ String daysArray[] = {"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"}; Calendar calendar = Calendar.getInstance(); int day = calendar.get(Calendar.DAY_OF_WEEK); return daysArray[day]; } public void setMin(){ try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; date = sdf.parse(new Get_CurrentDateTime().getCurrentDate()); Calendar c = Calendar.getInstance(); c.setTime(date); //datePicker.setMinDate(c.getTimeInMillis()); }catch (Exception e){ e.printStackTrace(); } } public void showDialog(final String date, final String ss){ // final int block_id = new Block_Operations(context).seletedID(number); final AlertDialog.Builder dialog = new AlertDialog.Builder(context); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE ); //LayoutInflater inflater = context.getLayoutInflater(); View view = inflater.inflate(R.layout.appoint_dialog, null); dialog.setView(view); Button ok_btn = (Button) view.findViewById(R.id.ok_btn); Button cancel = (Button) view.findViewById(R.id.cancel_btn); final EditText editText = (EditText) view.findViewById(R.id.block_text); TextView textView = (TextView) view.findViewById(R.id.msg_txt); TextView selected_day = (TextView) view.findViewById(R.id.day_selected); TextView selected_date = (TextView) view.findViewById(R.id.date_selected); TextView selected_time = (TextView) view.findViewById(R.id.time_selected); selected_day.setText(date_); selected_date.setText(date); selected_time.setText(ss); textView.setText("Are you sure you want to schedule appointments to "+new Doctor_Operations(context).getNames(doctor_id)+"?"); final AlertDialog alert = dialog.create(); try { alert.show(); }catch (Exception e){ e.printStackTrace(); } ok_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String body = editText.getText().toString().trim(); if (!body.equals("")){ String phone = new User_Details(context).getContact(); ProgressDialog progressDialog = new ProgressDialog(context); progressDialog.setMessage("please wait.."); new Appoitments(context).send(date,ss,date_,String.valueOf(doctor_id),String.valueOf(category_id),phone,body,1,progressDialog); //Toast.makeText(context,message,Toast.LENGTH_SHORT).show(); try{ String[] splits = date.split("-"); String[] splits2 = ss.split(":"); alert.dismiss(); //finish(); }catch (Exception e){ e.printStackTrace(); } } } }); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { alert.dismiss(); } }); } private void setAlarm(int year, int month, int day, int hour, int minute){ try { Calendar c = Calendar.getInstance(); c.set(year, month, day); c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.MINUTE, minute); alarmManager = (AlarmManager)context. getSystemService(ALARM_SERVICE); Intent myIntent = new Intent(context, Appointment_Reciever.class); pendingIntent = PendingIntent.getBroadcast(context, 192837, myIntent, 0); alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent); }catch (Exception e){ Log.e("Alarm Error: ","Error occured: "+e); } } private void cancelAlarm() { if (alarmManager != null) { alarmManager.cancel(pendingIntent); } } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle arrow click here if (item.getItemId() == android.R.id.home) { //Intent intent = new Intent(context, Welcome_Activity.class); //startActivity(intent); finish(); // close this activity and return to preview activity (if there is any) } return super.onOptionsItemSelected(item); } }
C++
UTF-8
1,655
3.046875
3
[]
no_license
#include "PlaneStatistic.h" #include "Plane.h" #include <iostream> PlaneStatistic::PlaneStatistic() { statistic = new std::map<std::string, PlaneInfo*>; } PlaneStatistic::~PlaneStatistic() { } bool PlaneStatistic::addToStatistic(const Plane& plane) { std::string planeModel = plane.GetModel(); if (statistic->find(planeModel) != statistic->end()) { (*statistic)[planeModel]->operator++(); return true; } PlaneInfo* info = new PlaneInfo(planeModel); statistic->insert(std::pair<std::string, PlaneInfo*>(planeModel, info)); return false; } void PlaneStatistic::fixAccident(const std::string& model, int survCount, int flyCount) { (*statistic)[model]->planeCrash(survCount, flyCount); } void PlaneStatistic::showFull() { int i = 0; for (const auto& kv : *statistic) { std::cout << "-------------------------" << std::endl; std::cout << "Plane: " << kv.first << " (summary " <<kv.second->getAccidentsCount() << " accidents)" << std::endl; if (kv.second->getAccidentsCount() > 0) { std::cout << "ACCIDENT LIST:" << std::endl; for (size_t i = 0; i < kv.second->getAccidentsCount(); ++i) { std::cout << "Date of accident: " << asctime((*kv.second->getAccidents())[i]->time); std::cout << "Flights before the accident: " << (*kv.second->getAccidents())[i]->flyCount << std::endl; if ((*kv.second->getAccidents())[i]->survCount > 0) std::cout << "Peoples survived: " << (*kv.second->getAccidents())[i]->survCount << std::endl << std::endl; else std::cout << "No one survived..." << std::endl << std::endl; } } else std::cout << "There were no accidents" << std::endl; } }
Swift
UTF-8
1,364
2.546875
3
[]
no_license
import UIKit class LigandHeaderCollectionView: UICollectionReusableView, Reusable { //---------------------------------------------------------------------------- // MARK: - Properties //---------------------------------------------------------------------------- /******************** Outlet ********************/ @IBOutlet weak var sectionTitleLabel: UILabel! @IBOutlet weak var sectionImageView: UIImageView! /******************** Parameters ********************/ var sectionName: String? { didSet { setupLabel() } } var sectionImage: UIImage? { didSet { setupImage() } } //---------------------------------------------------------------------------- // MARK: - View Life Cycle //---------------------------------------------------------------------------- override func awakeFromNib() { super.awakeFromNib() setup() } private func setup() { setupView() setupLabel() setupImage() } private func setupView() { backgroundColor = .secondarySystemBackground } private func setupImage() { sectionImageView.tintColor = .secondaryLabel sectionImageView.image = sectionImage sectionImageView.isHidden = sectionImage == nil ? true : false } private func setupLabel() { sectionTitleLabel.text = sectionName sectionTitleLabel.textColor = .secondaryLabel } }
C#
UTF-8
1,547
3.734375
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class RandomClass { // This generates Pseudo random values // Do not create multiple instances of random in close time private static readonly Random random = new Random(); //Inclusive of left and right private int GetRandom(int min, int max) { return min + (int)random.Next() * (max - min + 1); } public void Shuffle(int[] a) { for (int i = 0; i < a.Length; i++) { int k = random.Next(0, i); int temp = a[i]; a[i] = a[k]; a[k] = temp; } } public void GenerateRandomSetOfMelements(int[] input, int m) { int[] output = new int[m]; for (int i = 0; i < m; i++) { output[i] = input[i]; } for (int i = m; i < input.Length; i++) { int k = random.Next(0, i); if (k < m) { output[k] = input[i]; } } PrintArray(output); } private void PrintArray(int[] a) { for (int i = 0; i < a.Length; i++) { Console.Write(a[i] + " "); } Console.ReadLine(); } } }
Shell
UTF-8
722
2.75
3
[]
no_license
#!/usr/bin/env expect set timeout 120 spawn fabmanager create-admin --app superset set username "{{superset.admin.username}}" set first_name "{{superset.admin.first_name}}" set last_name "{{superset.admin.last_name}}" set email "{{superset.admin.email}}" set password "{{superset.admin.password}}" expect { "Username \\\[admin\\\]:" { send "$username\n";} } sleep 2 expect { "User first name \\\[admin\\\]:" { send "$first_name\n";} } sleep 2 expect { "User last name \\\[user\\\]:" { send "$last_name\n";} } sleep 2 expect { "Email \\\[admin@fab.org\\\]:" { send "$email\n";} } sleep 2 expect { "Password" { send "$password\n";} } sleep 2 expect { "Repeat for confirmation:" { send "$password\n"; } } expect eof
Python
UTF-8
624
4.1875
4
[]
no_license
# Author : Rayaan Fakier FKRRAY001 # Date : 05 - 05 - 2014 # question1.py def recursive_palindrome(string): '''Python program to check whether a string is a palindrome''' # Base Case - stop when 1 letter left if string == "": return "Palindrome!" # Recursive case - prints not palindrome else: if string[0] == string[-1]: return recursive_palindrome(string[1:-1]) else: return "Not a palindrome!" if __name__ == '__main__': string = input("Enter a string:\n") #recursive_palindrome(string) print(recursive_palindrome(string))
Python
UTF-8
3,914
3.203125
3
[]
no_license
import unittest import sys sys.path.append(".") #from puissance4_objet import connect4 from connect4 import Board, Game class Test_board(unittest.TestCase): def test_verif_ligne(self): N = [[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 5., 5., 5.], [5., 5., 5., 1., 1., 1., 5.], [5., 1., 5., 5., 1., 1., 5.]] board = Board(N) result = board.verif_ligne() self.assertEqual(result, True) def test_verif_colonne(self): Z = [[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.]] board1 = Board(Z) result1 = board1.verif_colonne() self.assertEqual(result1,True) def test_verif_diag(self): Y = [[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0.], [0., 0., 1., 1., 0., 0., 0.], [0., 1., 1., 5., 0., 0., 0.], [1., 1., 1., 5., 1., 1., 0.]] board2 = Board(Y) result2 = board2.verif_diagonale() self.assertEqual(result2, True) '''test fonctionnel: test: user case : cas gagnant input: 1 matrice entree + 1 matrice sortie 2 joueurs Boucle : - Etape 1: joueur 1 - Etape 2: vérifier que le joueur 2 prend la main - Etape 3: Joueur 2 : joue - Etape 4: Vérifier que la case (colonne/ ligne) est disponible - Etape 5: vérifier que la bonne case a été jouée - Etape 6: redonner la main au joueur 2 - Etape 7: reverifier la boucle précédente - Etape 8 : redonner la main au joueur 3 - Etape 9 : reverifier la boucle précédente - Etape 10 : verifier les positions (diagonales / alignements) pas de force 4 ''' class Test_jeton(unittest.TestCase): def placer_jeton(self,M,col): pos = col matrice_pleine = 0 for i in range(5,-1, -1) : if(M[i][pos]==0) : M[i][pos]=1 break ## controle d'insertion if(i==0 and M[i][pos]!=0): print("La colonne est pleine !!") columns=[] for j in range(7) : if (M[0][j]==0) : columns.append(j) if(len(columns)>0) : print("les colonnes possibles : ", columns) else : print("Matrice pleine ! fin du jeu :) ") matrice_pleine=1 return(M) def test_placer_jeton(self): X = [[1., 5., 5., 1., 1., 1., 5.], [5., 5., 1., 5., 1., 1., 1.], [5., 1., 1., 5., 5., 5., 1.], [1., 1., 5., 1., 1., 5., 5.], [5., 1., 5., 5., 1., 1., 5.], [1., 5., 5., 1., 5., 5., 1.]] M = [[1., 5., 5., 1., 1., 1., 5.], [5., 5., 1., 5., 1., 1., 1.], [5., 1., 1., 5., 5., 5., 1.], [1., 1., 5., 1., 1., 5., 5.], [5., 1., 5., 5., 1., 1., 5.], [1., 5., 5., 1., 5., 5., 1.]] col = 3 result3 = self.placer_jeton(X,col) #print(result3) self.assertEqual(result3, M) def test_placer_jeton1(self): X1 = [[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.]] M1 = [[0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0., 0.]] col = 3 result4 = self.placer_jeton(X1,col) self.assertEqual(result4, M1) if __name__ == '__main__': unittest.main()
Java
UTF-8
664
2.6875
3
[]
no_license
package com.cts.cd.ui; import java.util.Set; import java.util.TreeSet; import com.cts.cd.model.Person; public class App06 { public static void main(String [] args) { Set<Person> persons = new TreeSet<>(); persons.add(new Person("srinivas", 53)); persons.add(new Person("asish", 23)); persons.add(new Person("meghana", 23)); persons.add(new Person("meghana", 23)); persons.add(new Person("vinutha", 22)); persons.add(new Person("sri lekha", 21)); persons.add(new Person("divya", 25)); persons.add(new Person("divya", 21)); for(Person person : persons) { System.out.println(person); } System.out.println("---------------------"); } }
Java
UTF-8
1,839
3.203125
3
[]
no_license
package com.huuuxi.jdk.concurrent; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentSkipListMap; /** * * @author wyliujiangbin * ConcurrentMap 增加了桶segment机制,每个桶里面都是lock() 调用;锁用的是 ReentrantLock 继承 * * 取count: 取两次count,然后比较,如果改变了,那么就加锁取真正的count; * get的时候,第一次不需要加锁,只有取到为null的时候才加锁; * 为什么读get不需要加锁,因为happen-before原则,要求其能够保证写在前; * * 扩容,segment的扩容是这样达到的,他是先添加,然后判断是否需要扩容,这样就避免了 加入没有添加而扩容了; * * 几个名次:偏移量、掩码 */ public class TestConcurrentMap { public static void main(String[] args) { } public static void testConcurrentMap(){ ConcurrentMap map; } /** * 里面定义了segment,是一个数组,put,add ,remove根据key取到hash,去取 segment的数组的位置,然后调用这个segment的put,里面实现用的lock(); * segment 继承了 ReetrantLock; * 其实他的操作基本全是 segment的操作; * * 取size和有意思,不是各个segment的count相加,而是 首先 取两次 count的和,然后看是否变化,如果变化就 锁,然后重新取; * 取是否有修改,只需要求 modCount而已; * */ public static void testConcurrentHashMap(){ ConcurrentHashMap map; } /**] * ConcurrentSkipListMap 里面实现用的 是 SkipList 跳表,相对 TreeMap的红黑树,在并发的时候好一些; * */ public static void testConcurrentSkipListMap(){ ConcurrentSkipListMap map; } }
Python
UTF-8
1,789
2.71875
3
[]
no_license
# coding: utf-8 # In[5]: import numpy as np import pandas as pd from pandas import DataFrame # In[9]: df=pd.read_csv("central-India_rainfall_act_dep_1901_2016.csv") df # In[18]: df1=pd.read_csv("south_pen-India_rainfall_act_dep_1901_2016.csv") df1 # In[33]: df2=pd.read_csv("ne-India_rainfall_act_dep_1901_2016.csv") df2 # In[23]: df3=pd.read_csv("nw-India_rainfall_act_dep_1901_2016.csv") df3 # In[35]: df1["Actual Rainfall: JUN"].max() # In[86]: df1[df1['Actual Rainfall: JUN']==df1['Actual Rainfall: JUN'].max()] [['YEAR','Actual Rainfall: JUN']] # In[85]: df2[df2['Actual Rainfall: JUN']==df2['Actual Rainfall: JUN'].max()] [['YEAR','Actual Rainfall: JUN']] # In[81]: df[df['Actual Rainfall: JUN']==df['Actual Rainfall: JUN'].min()] [["YEAR"]] #CENTRAL INDIA # In[78]: df1[df1['Actual Rainfall: JUN']==df1['Actual Rainfall: JUN'].min()] [["YEAR"]] #south india # In[79]: df2[df2['Actual Rainfall: JUN']==df2['Actual Rainfall: JUN'].min()] [["YEAR"]] #north east # In[80]: df3[df3['Actual Rainfall: JUN']==df3['Actual Rainfall: JUN'].min()] [["YEAR"]] #north west # In[54]: import pandas as pd df4=pd.read_excel("MONTHLY_ACTUAL_RAINFALL_FROM_2009_TO_2011.XLS") df4 # In[55]: import pandas as pd df5=pd.read_excel("METEOROLOGICAL_SUB_DIVISION_WISE_ANNUAL_RAINFALL.xls") df5 # In[82]: df5[df5['Sub-division']==df5['Sub-division'].min()][['2010 (in millimetre)','Sub-division']] # In[83]: import matplotlib.pyplot as plt plt.plot(df5['Sub-division'],df5['2002 (in millimetre)'],linestyle="dashed",marker='*',color="purple") x_pos=np.arange(len(df5)) plt.Xlabel("Sub divisions") plt.ylabel("Rainfall") plt.legend() plt.title('rainfall analysis') plt.show() # In[69]: import matpltlib.pyplot as plt rc('font', weight='bold') # In[ ]:
Java
UTF-8
474
1.679688
2
[]
no_license
package com.r.uebook.utils; /** * for storing the constants of the application */ public class ApplicationConstants { public static final long SPLASH_TIME_OUT = 2000; public static String APP_NAME = "UEBook"; //region prefs constants public static String USERNAME = "username"; public static String PASSWORD = "password"; public static String USER_DETAILS = "user_details"; public static String LOGGED_IN = "loggedIn"; //endregion }
Java
MacCentralEurope
2,562
3.5
4
[]
no_license
/* Busiest Time in The Mall The Westfield Mall management is trying to figure out what the busiest moment at the mall was last year. Youre given data extracted from the malls door detectors. Each data point is represented as an integer array whose size is 3. The values at indices 0, 1 and 2 are the timestamp, the count of visitors, and whether the visitors entered or exited the mall (0 for exit and 1 for entrance), respectively. Heres an example of a data point: [ 1440084737, 4, 0 ]. Note that time is given in a Unix format called Epoch, which is a nonnegative integer holding the number of seconds that have elapsed since 00:00:00 UTC, Thursday, 1 January 1970. Given an array, data, of data points, write a function findBusiestPeriod that returns the time at which the mall reached its busiest moment last year. The return value is the timestamp, e.g. 1480640292. Note that if there is more than one period with the same visitor peak, return the earliest one. Assume that the array data is sorted in an ascending order by the timestamp. Explain your solution and analyze its time and space complexities. Example: input: int [][] data = { {1487799425, 14, 1}, {1487799425, 4, 0}, {1487799425, 2, 0}, {1487800378, 10, 1}, {1487801478, 18, 0}, {1487801478, 18, 1}, {1487901013, 1, 0}, {1487901211, 7, 1}, {1487901211, 7, 0} }; output: 1487800378 // since the increase in the number of people // in the mall is the highest at that point */ package week5day2FizzBuzz; public class FizzBuzz { public static void main(String[] args) { int [][] data = { {1487799425, 14, 1}, {1487799425, 4, 0}, {1487799425, 2, 0}, {1487800378, 10, 1}, {1487801478, 18, 0}, {1487801478, 18, 1}, {1487901013, 1, 0}, {1487901211, 7, 1}, {1487901211, 7, 0} }; int timestamp = 0; int increase = 0; int temp = data[0][1]; int index = 0; for(int i = 1; i <= data.length - 1; i++) { if(data[i][2] == 0) { //data[i][1] = -data[i][1]; int tempincrease = temp - data[i][1]; if(tempincrease > increase) { increase = tempincrease; timestamp = data[i][0]; } } index++; } System.out.println(timestamp); } }
Python
UTF-8
1,422
2.921875
3
[ "Apache-2.0" ]
permissive
# coding=utf-8 """Test cases for posts""" from tentd.documents import Post from py.test import raises, mark def test_post_owner(entity, post): """Assert the post has the correct owner""" assert post in Post.objects(entity=entity) assert post == Post.objects(entity=entity).first() assert post.entity == entity def test_post_content(entity, post): """Assert the post content is the latest version""" assert post.latest.content['text'] == "Goodbye world" assert post.latest.content['coordinates'] == [2, 2] def test_post_json(post): """Test that posts can be exported to json""" assert 'content' in post.to_json() def test_post_versions(post): """Test that the versions are numbered correctly""" assert post.to_json()['version'] == 3 def test_unicode_post(entity): """Test that we can store unicode in posts""" post = Post.new( entity=entity, schema='https://tent.io/types/post/status/v0.1.0', content={ 'title': u"This is an essay post ⛺", 'body': u""" This is a essay post, intended for longer texts. Unlike a status post there is no limit on size. This is a unicode tent symbol: ⛺ This text does nothing.""".strip().replace('\t', '') }) assert u"⛺" in post.latest.content['title'] assert u"⛺" in post.latest.content['body']
Markdown
UTF-8
2,443
2.71875
3
[]
no_license
# BASH技巧 1.重定向 ``` echo "Chenfan@38" | passwd --stdin root >/dev/null # 无意义的信息丢到黑洞去 id chenfan >> user 2>> error # 错误信息输出到error,有用的信息输出到user中 ``` 2.自定义变量 ``` read -p "Pls input a number: " P_number echo $P_number ``` 3.正则表达式 ``` . 匹配单个字符 * 匹配前一个字符出现零次或多次 .* 匹配任意多个任意字符 [] 匹配集合中的任意单个字符,括号中为一个集合 [x-y] 匹配连续的字符串范围 \{n,m\} 匹配前一个字符重复n到m次 \{n,\} 匹配前一个字符至少n次 \{n\} 匹配前一个字符n次 ``` ``` #!/bin/bash for i in {1..80}: do cut -c$i $1 >> one.txt cut -c$i $2 >> two.txt done grep "[[:alnum:]]" one.txt > onebak.tmp grep "[[:alnum:]]" two.txt > twobak.tmp sort onebak.tmp | uniq -c | sort -k1, 1n -k2, 2n|tail -30 > oneresult sort twobak.tmp | uniq -c | sort -k1, 1n -k2, 2n|tail -30 > tworesult rm -rf one.txt two.txt onebak.tmp twobak.tmp vimdiff oneresult tworesult ``` 4.if语句 ``` #!/bin/bash if [ "$(id -u)" -eq "0" ]; then tar -czf /root/etc.tar.gz /etc &>/dev/null fi #!/bin/bash read -p "Enter a password: " Password [ "$Password" == "Chenfan@38" ] && echo "OK" || echo "Not Ok" ``` 5.case语句 ``` #!/bin/bash Date=$(date -d yesterday) Time=$(date +%Y%m%d) case $Date in Wed|Fri) tar -czf /usr/src/${Time}_log.tar.gz /var/log &> /dev/null;; *) echo "Today neither Wed nor Fri";; esac ``` 6 .for语句 ``` #!/bin/bash Domain=szzjcs.com for Mail_u in chenfan flanky tim; do mail -s "Log" $Mail_u@$Domain </var/log/messages done #!/bin/bash for i in {1..9}; do for ((j=1; j<=i; j++)); do printf "%-10s" $j*$i=$((j*i)) done echo done ``` 7 .while语句 ``` #!/bin/bash File=/var/log/messages while read -r line; do echo $line done < $File #!/bin/bash while True; do clear echo "-"*10 echo "1.Display Cpu Info:" echo "2.Display System Load:" echo "3.Exit Program:" echo "-"*10 read -p "Pls select an iterm(1-3): " U_select case $U_select in 1) echo $(cat /proc/cpuinfo) read -p "Press Enter to continue: ";; 2) echo $(uptime) read -p "press Enter to continue: ";; 3) exit ;; *) read -p "Pls select 1-3, press Enter to continue: ";; esac done ``` 8 .select语句 ``` #!/bin/bash echo "Where are you from? " select var in "BJ" "SH" "JJ" "SZ"; do break done echo "You are from $var" ```
C++
UTF-8
385
2.6875
3
[ "BSD-2-Clause" ]
permissive
#ifndef TRANSFORM_COMPONENT_HEADER #define TRANSFORM_COMPONENT_HEADER #include "components.h" #include "../vector2d.h" class TransformComponent : public Component { public: Vector2D position; TransformComponent(){ position.x = 0.0f; position.y = 0.0f; } TransformComponent(float x, float y){ position.x = x; position.y = y; } void update() override{ } }; #endif
C
UTF-8
901
4.46875
4
[]
no_license
/* Write a program that asks the user to enter a fraction, then reduces the fraction to lowest terms. Hint: To reduce a fraction to lowest terms, first compute the greatest common denominator of the numerator and denominator. Then divide both the numerator and denominator by the GCD.*/ #include<stdio.h> /* Function declaration.*/ int getGreatestCommonDenominator(int, int); int main(void){ int numerator, denominator, gcd; printf("Enter a fraction: "); scanf("%d/%d", &numerator, &denominator); gcd=getGreatestCommonDenominator(numerator, denominator); printf("In lowest terms: %d/%d", numerator/gcd, denominator/gcd); return 0; } int getGreatestCommonDenominator(int firstInt, int secondInt){ while(secondInt!=0){ int remainder=firstInt%secondInt; firstInt=secondInt; secondInt=remainder; } return firstInt; }
Java
UTF-8
9,781
2.84375
3
[]
no_license
package se.edument; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * NorthwindRepo repository class */ public class NorthwindRepo { private Connection dbconn; private Boolean inTransaction = false; /** * Constructor thast creates the connection object to be used by the methods * * @param connstr * @throws RuntimeException */ public NorthwindRepo(String connstr) throws RuntimeException { try { dbconn = DriverManager.getConnection(connstr); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } } /** * returns a list of all the products * * @return */ public ArrayList<Product> allProducts() { ArrayList<Product> productList = new ArrayList<>(); try { Statement stm = dbconn.createStatement(); ResultSet res = stm.executeQuery("Select ProductID, ProductName from dbo.products"); while (res.next()){ Product productObject = new Product(res.getInt(1),res.getString(2)); productList.add(productObject); } } catch (SQLException e) { e.printStackTrace(); } finally { if (dbconn!=null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return productList; } /** * returns a product by ID or null if not found * * @param productId * @return */ public Product getProduct(int productId) { try{ PreparedStatement pstm = dbconn.prepareStatement("select productid, productname " + "from dbo.products " + "where productID = ?"); pstm.setInt(1, productId); ResultSet res = pstm.executeQuery(); if (res.next()){ return new Product(res.getInt(1),res.getString(2)); } } catch (SQLException e){ e.printStackTrace(); } finally { if (dbconn != null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /*ArrayList<Product> products = allProducts(); for (Product elem : products) { if (elem.id == productId){ return elem; } }*/ return null; } /** * returns a product by name or null if not found * * @param productName * @return */ public Product getProduct(String productName) { try{ PreparedStatement pstm = dbconn.prepareStatement("select productid, productname " + "from dbo.products " + "where productname = ?"); pstm.setString(1, productName); ResultSet res = pstm.executeQuery(); if (res.next()){ return new Product(res.getInt(1),res.getString(2)); } } catch (SQLException e){ e.printStackTrace(); } finally { if (dbconn != null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } /** * Counts the number of products in the provided categoryId * * @param categoryId * @return */ public int countProductByCategory(int categoryId) { try{ PreparedStatement pstm = dbconn.prepareStatement("SELECT COUNT(*) FROM dbo.products " + "WHERE categoryID = ?"); pstm.setInt(1, categoryId); ResultSet resultSet = pstm.executeQuery(); if (resultSet.next()){ int numOfProdByCatID = resultSet.getInt(1); return numOfProdByCatID; } } catch (SQLException e){ e.printStackTrace(); } finally { if (dbconn!=null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return 0; } //==================================================================================== //==================================================================================== /** * returns a customer by ID (these are strings in Northwind) * * @param customerId * @return */ public Customer getCustomer(String customerId) { try { PreparedStatement pstm = dbconn.prepareStatement("SELECT customerid, companyname FROM Customers " + "WHERE customerid = ?"); pstm.setString(1, customerId); ResultSet res = pstm.executeQuery(); if (res.next()) { Customer customer = new Customer(res.getString(1), res.getString(2)); return customer; } } catch (SQLException e) { e.printStackTrace(); } finally { if (dbconn!=null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } /** * returns a list of customer objects associated with the company name provided * <p> * We return a list because we might have custonmers with the same company name * * @param companyName * @return */ public ArrayList<Customer> getCustomerByCompanyName(String companyName) { ArrayList<Customer> customers = new ArrayList<>(); try { PreparedStatement pstm = dbconn.prepareStatement("SELECT CustomerID, CompanyName " + "FROM Customers " + "WHERE companyName = ?"); pstm.setString(1, companyName); ResultSet res = pstm.executeQuery(); while (res.next()){ Customer customerObject = new Customer(res.getString(1), res.getString(2)); customers.add(customerObject); } return customers; } catch (SQLException e) { e.printStackTrace(); } finally { if(dbconn!=null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } /** * returns an order identified by the identifier passed in * * @param orderId * @return */ public Order getOrder(int orderId) { List<OrderLine> orderLines = new ArrayList<>(); try { PreparedStatement pstm = dbconn.prepareStatement( "SELECT Orders.CustomerID," + "[Order Details].ProductID, " + "[Order Details].Quantity " + "FROM [Order Details] " + "INNER JOIN Orders " + "ON [Order Details].OrderID = Orders.OrderID " + "WHERE Orders.OrderID = ?"); pstm.setInt(1, orderId); ResultSet res = pstm.executeQuery(); String customerID = ""; while (res.next()) { System.out.println(res.getInt(2) + " "+ res.getInt(3)); customerID = res.getString(1); OrderLine orderLine = new OrderLine(res.getInt(2), res.getInt(3)); orderLines.add(orderLine); } if (orderLines.size() > 0) { //we found data return new Order(orderId, customerID, orderLines); } } catch (SQLException e) { e.printStackTrace(); } finally { if (dbconn!=null){ try { dbconn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } /** * Insert a new order to the database * <p> * We only need to set the fields we have in the Order and OrderLine object * <p> * Do google for Statement.RETURN_GENERATED_KEYS fow how to get the inserted ID back. * <p> * To insert the order lines look at the executeBatch method. * see http://stackoverflow.com/questions/12012592/jdbc-insert-multiple-rows * * @param order * @return */ public int CreateNewOrder(Order order) throws SQLException { return 0; } /** * Private helper method that builds a Customer out of provided resultsets * That you can use but not required * * @param res * @return * @throws SQLException */ private Customer newCustomer(ResultSet res) throws SQLException { // todo, pull data from result set return new Customer(res.getString(1), res.getString(2)); } /** * Private method that is used to map a resultset to an object * That you can use but not required * @param res * @return * @throws SQLException */ private Product newProduct(ResultSet res) throws SQLException { Product prod = new Product(res.getInt(1), res.getString(2)); return prod; } }
SQL
UTF-8
189
3.71875
4
[]
no_license
SELECT properties.city AS city, count(properties.city) AS total_reservations FROM reservations JOIN properties ON property_id = properties.id GROUP BY city ORDER BY total_reservations DESC;
C++
UTF-8
608
2.71875
3
[]
no_license
#include "Approx_func_fabr.h" const shared_ptr<Approx_func> Approx_func_fabr::create_approx_func(const vector<pair<double, double>> &args_and_vls, Methods method){ if (method == Step) return shared_ptr<Approx_func>(new Simple_interpol(args_and_vls)); if (method == Linear) return shared_ptr<Approx_func>(new Linear_interpol(args_and_vls)); if (method == Quadratic) return shared_ptr<Approx_func>(new Quadratic_interpol(args_and_vls)); cout << "unsupported method was inputed - applying default(step) method " << endl; return shared_ptr<Approx_func>(new Simple_interpol(args_and_vls)); }
Java
UTF-8
3,286
1.90625
2
[ "Apache-2.0" ]
permissive
package net.pladema.clinichistory.hospitalization.controller.mapper; import net.pladema.clinichistory.hospitalization.controller.dto.InternmentGeneralStateDto; import net.pladema.clinichistory.hospitalization.controller.dto.internmentstate.DiagnosesGeneralStateDto; import net.pladema.clinichistory.hospitalization.controller.generalstate.dto.*; import net.pladema.clinichistory.hospitalization.controller.generalstate.mapper.*; import net.pladema.clinichistory.documents.service.ips.domain.*; import net.pladema.clinichistory.documents.service.generalstate.EncounterGeneralState; import net.pladema.clinichistory.hospitalization.service.domain.Last2VitalSignsBo; import org.mapstruct.IterableMapping; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import java.util.List; @Mapper(uses = {HealthConditionMapper.class, VitalSignMapper.class, AnthropometricDataMapper.class, MedicationMapper.class, ImmunizationMapper.class, AllergyConditionMapper.class}) public interface InternmentStateMapper { @Named("toListDiagnosisDto") @IterableMapping(qualifiedByName = "toDiagnosisDto") List<DiagnosisDto> toListDiagnosisDto(List<DiagnosisBo> listDiagnosisBo); @Named("toListHealthHistoryConditionDto") @IterableMapping(qualifiedByName = "toHealthHistoryConditionDto") List<HealthHistoryConditionDto> toListHealthHistoryConditionDto(List<HealthHistoryConditionBo> listHealthHistoryCondition); @Named("toListDiagnosesGeneralStateDto") @IterableMapping(qualifiedByName = "toDiagnosesGeneralStateDto") List<DiagnosesGeneralStateDto> toListDiagnosesGeneralStateDto(List<HealthConditionBo> diagnoses); @Named("toListMedicationDto") @IterableMapping(qualifiedByName = "toMedicationDto") List<MedicationDto> toListMedicationDto(List<MedicationBo> listMedicationBo); @Named("toListImmunizationDto") @IterableMapping(qualifiedByName = "toImmunizationDto") List<ImmunizationDto> toListImmunizationDto(List<ImmunizationBo> immunizationBos); @Named("toListAllergyConditionDto") @IterableMapping(qualifiedByName = "toAllergyConditionDto") List<AllergyConditionDto> toListAllergyConditionDto(List<AllergyConditionBo> allergyConditionBos); @Named("toInternmentGeneralStateDto") @Mapping(target = "diagnosis", source = "diagnosis", qualifiedByName = "toListDiagnosisDto") @Mapping(target = "personalHistories", source = "personalHistories", qualifiedByName = "toListHealthHistoryConditionDto") @Mapping(target = "familyHistories", source = "familyHistories", qualifiedByName = "toListHealthHistoryConditionDto") @Mapping(target = "vitalSigns", source = "vitalSigns", qualifiedByName = "toListVitalSignDto") @Mapping(target = "medications", source = "medications", qualifiedByName = "toListMedicationDto") InternmentGeneralStateDto toInternmentGeneralStateDto(EncounterGeneralState interment); @Named("toAnthropometricDataDto") AnthropometricDataDto toAnthropometricDataDto(AnthropometricDataBo anthropometricData); @Named("toHealthConditionDto") HealthConditionDto toHealthConditionDto(HealthConditionBo mainDiagnosis); @Named("toLast2VitalSignDto") Last2VitalSignsDto toLast2VitalSignDto(Last2VitalSignsBo vitalSignBos); }
Java
UTF-8
1,060
3.546875
4
[]
no_license
package day19arraylist; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class List03 { public static void main(String[] args) { //2.d way to create a list List<String> list= new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); List<String> list1=new ArrayList<>(); list1.add("A"); list1.add("B"); list1.add("C"); list1.add("D"); list1.add("E"); System.out.println(list.contains("A")); System.out.println(list.contains("X")); System.out.println(list.equals(list1)); Scanner in=new Scanner(System.in); System.out.println("letter"); // String ch=String.valueOf(in.next().charAt(0)); // // if(list.contains(ch)) { // list.set(list.indexOf(ch),"Got it"); // // }else { // list.add(ch); // } String str=in.next().toUpperCase().substring(0,1); if(list1.contains(str)) { list1.set(list1.indexOf(str), "Got it"); System.out.println(list1); } else { list1.add(str); System.out.println(list1); } } }
Markdown
UTF-8
2,016
3.1875
3
[]
no_license
# Nesting Subroutines and the Stack - Call instructions are branch instructions that do a bit more - Is the size of the link register the size of the stack? No the stack could be huge. - A link register is just yet just another register -> dedicated to holding return addresses - How many addresses will there be? Depends on ISA and implementation of ISA (typically 16 registers) some will be used for certain purposes. - You have general purpose R's and special ones - We allow for nested subroutines. If we only have one L.R. you will overwrite it. - Solution: We use the stack as our temporary space. Before me our second call we want to save the contents of LR to stack. You'll read it off the stack. A problem occurs if stack overflows. The second is if you don't maintain stack. You need to be diligent. - Certain conventions are used to maintaining the stack. You want the compile to generate code for you. ## Parameter Passing - Pass by parameter, memory, and on stack - Registers are fast. Use them if you can. You can only pass a small number of arguements. - Do you need to keep track of which register does what then? - Is SP a keyword in the stack? - The only way to access memory is with load and stores ## Stack Frames - Scratch space for the subroutine - Spilling to the stack - Performance Recommendation: You should make your subroutines short - Registers are fastest storage medium on CPU - Better than using stack and main memory - You may be able to store all the intermediate values in registers (eg. add two numbers) - But let's say you write a huge subroutine instead. If you have 32 registers you probably won't be able to do with 32 registers. - This is why you'll need to spill over to the stack but that's not good. Just write shorter subroutines. - We have a frame pointer -> accesses private workspace -> everything you have pushed on the stack prior to subroutine and in subroutine you can access with stack free pointer - Push arguements and return address
Java
UTF-8
1,908
2.203125
2
[]
no_license
package fpoly.java5.assignment.controller; import fpoly.java5.assignment.model.User; import fpoly.java5.assignment.modelform.UserLoginForm; import fpoly.java5.assignment.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpSession; import javax.validation.Valid; @Controller public class AuthController { @Autowired private UserService userService; @Autowired private HttpSession session; @GetMapping("/login") public String showFormLogin(Model model) { if (session.getAttribute("login") != null) { return "redirect:/home"; } model.addAttribute("userLoginForm", new UserLoginForm()); return "login"; } @PostMapping("/login") public String login(@Valid @ModelAttribute UserLoginForm userLoginForm, BindingResult result, Model model) { if (result.hasErrors()) { return "login"; } User login = userService.login(userLoginForm); if (login == null) { model.addAttribute("notify", "ten dang nhap hoac tai khoan sai"); return "login"; } if (!login.isActive()) { model.addAttribute("notify", "tai khoan dang bi khoa"); return "login"; } session.setAttribute("login", login); return "redirect:/home"; } @GetMapping("/logout") public String logout() { session.invalidate(); return "redirect:/home"; } }
Markdown
UTF-8
499
2.734375
3
[ "MIT" ]
permissive
#will I have this pleasure, my master being old also? You may want to add "of having a baby" (UDB). Sarah used this rhetorical question because she did not believe that she could have a child. This means "I cannot believe that I will experience the joy of having a child. My master is also too old." (See: [[:en:ta:vol1:translate:figs_rquestion]]) #my master being old also This means "since my husband is also old." #my master This is a title of respect that Sarah gave to her husband Abraham.
Java
UTF-8
719
2.859375
3
[]
no_license
import javax.swing.plaf.synth.SynthScrollBarUI; public class RotationPoint { public RotationPoint(){ String [] input = {"ptolemaic", "retrograde", "supplant", "undulate", "xenoepist", "asymptote", "babka", "banoffee", "engender", "karpatka", "othellolagkage"}; findRotationPoint(input); } private void findRotationPoint(String [] input) { int start=0; int end = input.length-1; while(start<=end && input[start].compareTo(input[end])>0 ){ int mid=(start+end)/2; if(input[mid].compareTo(input[end])>0){ start = mid+1; }else end = mid; } System.out.println(input[start]); } }
Java
UTF-8
14,147
1.820313
2
[ "Apache-2.0" ]
permissive
/** * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.oep.cmon.dao.nsd.service.persistence; import com.liferay.portal.service.persistence.BasePersistence; import org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro; /** * The persistence interface for the tai nguyen2 vai tro service. * * <p> * Caching information and settings can be found in <code>portal.properties</code> * </p> * * @author Liemnn * @see TaiNguyen2VaiTroPersistenceImpl * @see TaiNguyen2VaiTroUtil * @generated */ public interface TaiNguyen2VaiTroPersistence extends BasePersistence<TaiNguyen2VaiTro> { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this interface directly. Always use {@link TaiNguyen2VaiTroUtil} to access the tai nguyen2 vai tro persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this interface. */ /** * Caches the tai nguyen2 vai tro in the entity cache if it is enabled. * * @param taiNguyen2VaiTro the tai nguyen2 vai tro */ public void cacheResult( org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro taiNguyen2VaiTro); /** * Caches the tai nguyen2 vai tros in the entity cache if it is enabled. * * @param taiNguyen2VaiTros the tai nguyen2 vai tros */ public void cacheResult( java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> taiNguyen2VaiTros); /** * Creates a new tai nguyen2 vai tro with the primary key. Does not add the tai nguyen2 vai tro to the database. * * @param id the primary key for the new tai nguyen2 vai tro * @return the new tai nguyen2 vai tro */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro create(long id); /** * Removes the tai nguyen2 vai tro with the primary key from the database. Also notifies the appropriate model listeners. * * @param id the primary key of the tai nguyen2 vai tro * @return the tai nguyen2 vai tro that was removed * @throws org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException if a tai nguyen2 vai tro with the primary key could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro remove(long id) throws com.liferay.portal.kernel.exception.SystemException, org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException; public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro updateImpl( org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro taiNguyen2VaiTro, boolean merge) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns the tai nguyen2 vai tro with the primary key or throws a {@link org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException} if it could not be found. * * @param id the primary key of the tai nguyen2 vai tro * @return the tai nguyen2 vai tro * @throws org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException if a tai nguyen2 vai tro with the primary key could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro findByPrimaryKey(long id) throws com.liferay.portal.kernel.exception.SystemException, org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException; /** * Returns the tai nguyen2 vai tro with the primary key or returns <code>null</code> if it could not be found. * * @param id the primary key of the tai nguyen2 vai tro * @return the tai nguyen2 vai tro, or <code>null</code> if a tai nguyen2 vai tro with the primary key could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro fetchByPrimaryKey( long id) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns all the tai nguyen2 vai tros where vaiTroId = &#63; and daXoa = &#63;. * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @return the matching tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findByVaiTroID( java.lang.Long vaiTroId, int daXoa) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns a range of all the tai nguyen2 vai tros where vaiTroId = &#63; and daXoa = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @param start the lower bound of the range of tai nguyen2 vai tros * @param end the upper bound of the range of tai nguyen2 vai tros (not inclusive) * @return the range of matching tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findByVaiTroID( java.lang.Long vaiTroId, int daXoa, int start, int end) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns an ordered range of all the tai nguyen2 vai tros where vaiTroId = &#63; and daXoa = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @param start the lower bound of the range of tai nguyen2 vai tros * @param end the upper bound of the range of tai nguyen2 vai tros (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findByVaiTroID( java.lang.Long vaiTroId, int daXoa, int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns the first tai nguyen2 vai tro in the ordered set where vaiTroId = &#63; and daXoa = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching tai nguyen2 vai tro * @throws org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException if a matching tai nguyen2 vai tro could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro findByVaiTroID_First( java.lang.Long vaiTroId, int daXoa, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException, org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException; /** * Returns the last tai nguyen2 vai tro in the ordered set where vaiTroId = &#63; and daXoa = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching tai nguyen2 vai tro * @throws org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException if a matching tai nguyen2 vai tro could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro findByVaiTroID_Last( java.lang.Long vaiTroId, int daXoa, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException, org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException; /** * Returns the tai nguyen2 vai tros before and after the current tai nguyen2 vai tro in the ordered set where vaiTroId = &#63; and daXoa = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param id the primary key of the current tai nguyen2 vai tro * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next tai nguyen2 vai tro * @throws org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException if a tai nguyen2 vai tro with the primary key could not be found * @throws SystemException if a system exception occurred */ public org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro[] findByVaiTroID_PrevAndNext( long id, java.lang.Long vaiTroId, int daXoa, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException, org.oep.cmon.dao.nsd.NoSuchTaiNguyen2VaiTroException; /** * Returns all the tai nguyen2 vai tros. * * @return the tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findAll() throws com.liferay.portal.kernel.exception.SystemException; /** * Returns a range of all the tai nguyen2 vai tros. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param start the lower bound of the range of tai nguyen2 vai tros * @param end the upper bound of the range of tai nguyen2 vai tros (not inclusive) * @return the range of tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findAll( int start, int end) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns an ordered range of all the tai nguyen2 vai tros. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. * </p> * * @param start the lower bound of the range of tai nguyen2 vai tros * @param end the upper bound of the range of tai nguyen2 vai tros (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public java.util.List<org.oep.cmon.dao.nsd.model.TaiNguyen2VaiTro> findAll( int start, int end, com.liferay.portal.kernel.util.OrderByComparator orderByComparator) throws com.liferay.portal.kernel.exception.SystemException; /** * Removes all the tai nguyen2 vai tros where vaiTroId = &#63; and daXoa = &#63; from the database. * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @throws SystemException if a system exception occurred */ public void removeByVaiTroID(java.lang.Long vaiTroId, int daXoa) throws com.liferay.portal.kernel.exception.SystemException; /** * Removes all the tai nguyen2 vai tros from the database. * * @throws SystemException if a system exception occurred */ public void removeAll() throws com.liferay.portal.kernel.exception.SystemException; /** * Returns the number of tai nguyen2 vai tros where vaiTroId = &#63; and daXoa = &#63;. * * @param vaiTroId the vai tro ID * @param daXoa the da xoa * @return the number of matching tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public int countByVaiTroID(java.lang.Long vaiTroId, int daXoa) throws com.liferay.portal.kernel.exception.SystemException; /** * Returns the number of tai nguyen2 vai tros. * * @return the number of tai nguyen2 vai tros * @throws SystemException if a system exception occurred */ public int countAll() throws com.liferay.portal.kernel.exception.SystemException; }
Java
UTF-8
15,813
2.1875
2
[]
no_license
package com.chatRobot.controller; import com.chatRobot.model.*; import com.chatRobot.service.impl.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/page") public class PageController { /** * 配置页面跳转 * author :xiaoming */ @Autowired private GoodsServiceImpl goodsService; @Autowired private GoodsCartServiceImpl goodsCartService; @Autowired private UserServiceImpl userService; @Autowired private GoodsTypeServiceImpl goodsTypeService; @Autowired private ManagerServiceImpl managerService; @Autowired private OrderServiceImpl orderService; @RequestMapping("/toIndex") public String PageToIndex(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) { /** * @Author: sun xiaoming * @Description: 跳转到主页 * @Date: 2019/1/8 15:51 */ //获取商品信息,回显在主页上 //设置页码 和 页面大小 PageHelper.startPage(pn, 6); List<Goods> goodsList = goodsService.selectAllGoods(); //navigatePages : 连续显示的页数 PageInfo<Goods> pageInfo = new PageInfo(goodsList, 6); model.addAttribute("goodList", goodsList); // 将分页信息 查询得到数据信息 打包到 model中的pageinfo中。 model.addAttribute("PageInfo", pageInfo); return "index"; } // 导航条 点击事件控制: @RequestMapping("/pageInfo") @ResponseBody public Msg updateIndexWithPageNumber(Integer pn, Model model) { System.out.println(pn); PageHelper.startPage(pn, 6); List<Goods> goodsList = goodsService.selectAllGoods(); //navigatePages : 连续显示的页数 PageInfo<Goods> pageInfo = new PageInfo(goodsList, 6); // 将分页信息 查询得到数据信息 打包到 model中的pageinfo中。 //model.addAttribute("PageInfo", pageInfo); return Msg.success().add("pageInfo", pageInfo); } @RequestMapping("/toGoods") public String PageToGoodsWithID(Integer id, Model model) { /** * @Author: sun xiaoming * @Description: 跳转到对应商品详情页 * @parm: GoodsId and model */ Goods good = goodsService.selectGoodsWithId(id); GoodsModel goodsModel = goodsService.selectGoodsModelWithId(good.getGoodsModelId()); model.addAttribute("Goods", good); model.addAttribute("GoodsModelFile", goodsModel); return "GoodsInfo"; } @RequestMapping("/toCart") public String PageToGoodsCartWithUserId(Integer userId, Model model) { /** * @Description: 跳转到用户的购物车界面 */ List<Goods> goodsList = new ArrayList<>(); List<GoodsCart> goodsCartList = goodsCartService.selectByUserId(userId); if (!goodsCartList.isEmpty()) { //如果购物车非空 for (int i = 0; i < goodsCartList.size(); i++) { Goods goods = goodsService.selectGoodsWithId(goodsCartList.get(i).getGoodsId()); // 返回购物车中商品数量 赋值给对应的商品数量 goods.setGoodsAmount(goodsCartList.get(i).getGoodsAmount()); goodsList.add(goods); } model.addAttribute("goodsList", goodsList); return "GoodsCart"; } else { model.addAttribute("message", "购物车为空,请先购物。"); return "warn"; } } @RequestMapping("/toCheckOut") public String PageToCheckOut(Integer userId, Integer goodsId, Model model) { /** * @Author: sun xiaoming * @Description: 单一商品直接跳转到订单确认页面 * @Date: 2019/2/28 15:05 */ User user = userService.selectByPrimaryKey(userId); Goods goods = goodsService.selectGoodsWithId(goodsId); model.addAttribute("User", user); model.addAttribute("Goods", goods); return "CheckOut"; } // Good 商品页 @RequestMapping("/Good") public String PageToGood(Model model) { model.addAttribute("message", "页面正在开发中。。"); return "warn"; } // Furniture 家具页面 @RequestMapping("/Furniture") public String PageToFurniture(Model model) { model.addAttribute("message", "页面正在开发中。。"); return "warn"; } // Mail 邮箱 @RequestMapping("/Mail") public String PageToMail(Model model) { model.addAttribute("message", "页面正在开发中。。"); return "warn"; } // admin 未开发页面提示 @RequestMapping("/adminWarn") public String PageToAdminWarn(Model model) { model.addAttribute("message", "页面正在开发中。。"); return "admin/adminWarn"; } @RequestMapping("/warn") public String PageToWarn(String message, Model model) { model.addAttribute("message", message); return "warn"; } /*================= admin 请求 ================*/ @RequestMapping("/admin") public String PageToAdmin() { // 跳转到登陆界面 return "admin/adminLogin"; } @RequestMapping("/adminIndex") public String PageToAdminIndex(HttpSession session) { // 跳转到后台管理主界面 if (session.getAttribute("admin") == null) { //若管理员未登陆 return "admin/adminLogin"; } else { return "admin/adminIndex"; } } @RequestMapping("/adminProduct") public String adminProductwith() { /** * @Author: sun xiaoming * @Description: adminIndex 跳转到adminProduct 页面 */ return "admin/adminProduct/adminProduct"; } @RequestMapping("/adminProType") public String adminProType() { /** * @Author: sun xiaoming * @Description: 跳转到adminProtype 页面 */ return "admin/adminProduct/adminProType"; } @RequestMapping("/adminProModelFile") public String adminProModelFile() { /** * @Author: sun xiaoming * @Description: 跳转到adminProModel jsp */ return "admin/adminProduct/adminProModel"; } @RequestMapping("/getProductAdd") public String getProductAddJsp(Model model) { /** * @Author: sun xiaoming * @Description: return product add jsp页面 */ // 数据准备 查询到所有的产品类型 List<GoodsType> goodsTypeList = goodsTypeService.selectAll(); model.addAttribute("goodsTypeList", goodsTypeList); return "admin/adminProduct/ProductBase/ProductBaseAdd"; } @RequestMapping("/getProductEdit") public String getProductEdit(Integer goodsId, Model model) { Goods goods = goodsService.selectGoodsWithId(goodsId); List<GoodsType> goodsTypeList = goodsTypeService.selectAll(); model.addAttribute("goodsTypeList", goodsTypeList); model.addAttribute("Goods", goods); return "admin/adminProduct/ProductBase/EditProduct"; } @RequestMapping("/getProductDetail") public String getProductDetail(Integer goodsId, Model model) { /** * @Author: sun xiaoming * @Description: admin 下 返回商品详情页 */ try { Goods goods = goodsService.selectGoodsWithId(goodsId); GoodsModel goodsModel = goodsService.selectGoodsModelWithId(goods.getGoodsModelId()); GoodsType goodsType = goodsTypeService.selectWithTypeId(goods.getGoodsTypeId()); model.addAttribute("Goods", goods); model.addAttribute("goodsModel", goodsModel); model.addAttribute("goodsType", goodsType); return "admin/adminProduct/ProductBase/adminProductDetail"; } catch (Exception e) { e.printStackTrace(); return "warn"; } } @RequestMapping("/getProductFile") public String getProductFile(Integer goodsId, Model model) { /** * @Author: sun xiaoming * @Description: 对模型文件进行设置上传。参数设置。 */ List<GoodsModel> modelList = goodsService.selectAllGoodsModel(); model.addAttribute("GoodsModelList", modelList); Goods goods = goodsService.selectGoodsWithId(goodsId); model.addAttribute("Goods", goods); return "admin/adminProduct/ProductBase/FileProduct"; } /*============================*/ // 商品类型处理 @RequestMapping("/getProductTypeAdd") public String getProductTypeAdd() { return "admin/adminProduct/ProductType/ProductTypeAdd"; } @RequestMapping("/getProductTypeEdit") public String getProductTypeEdit(Integer goodstypeId, Model model) { try { GoodsType goodsType = goodsTypeService.selectWithTypeId(goodstypeId); model.addAttribute("goodsType", goodsType); return "admin/adminProduct/ProductType/ProductTypeEdit"; } catch (Exception e) { e.printStackTrace(); model.addAttribute("message", "根据typeId获取商品类型失败!"); return "warn"; } } @RequestMapping("/getProductTypeDetail") public String getProductTypeDetail(Integer goodstypeId, Model model) { /** * @Description: 返回 goodstype的详细信息 */ try { GoodsType goodsType = goodsTypeService.selectWithTypeId(goodstypeId); model.addAttribute("goodsType", goodsType); return "admin/adminProduct/ProductType/ProductTypeDetail"; } catch (Exception e) { e.printStackTrace(); model.addAttribute("message", "根据typeId查询商品模型信息失败!"); return "Warn"; } } /*============================*/ // 商品模型处理 @RequestMapping("/getProductModelFileAdd") public String getProductModelFileAdd() { /** * @Author: sun xiaoming * @Description: adminProModel jsp 请求 返回 addModelFile.jsp */ return "admin/adminProduct/ProductModel/ProductModelAdd"; } @RequestMapping("/getProductModelFileEdit") public String getProductModelFileEdit(Integer goodsModelFileId, Model model) { /** * @Description: adminProMode jsp 请求 返回 editModelFile.jsp */ try { GoodsModel goodsModel = goodsService.selectGoodsModelWithId(goodsModelFileId); model.addAttribute("GoodsModelFile", goodsModel); return "admin/adminProduct/ProductModel/ProductModelEdit"; } catch (Exception e) { e.printStackTrace(); return "admin/adminWarn"; } } /*============================*/ // 商品库存处理 @RequestMapping("/adminProStorge") public String getAdminProStroge() { /** * @Description: 获取商品库存页面 */ return "admin/adminProduct/adminProStorge"; } /*========== admin 用户管理 =================*/ @RequestMapping("/adminUser") public String getadminUser() { /** * @Description: adminIndex 进入 用户管理页面 */ return "admin/adminUser/adminUserIndex"; } // admin get UserAdd jsp @RequestMapping("/getUserAdd") public String getUserAdd() { /** * @Description: 获取 admin UserAdd jsp页面 */ return "admin/adminUser/adminBaseUser/adminBaseUseradd"; } // admin get UserEdit jsp @RequestMapping("/getUserEdit") public String getUserEdit(Integer userId, Model model) { // 获取 admin UserEdit jsp页面 try { User user = userService.selectByPrimaryKey(userId); model.addAttribute("User", user); return "admin/adminUser/adminBaseUser/adminBaseUserEdit"; } catch (Exception e) { e.printStackTrace(); return "warn"; } } // 左侧功能区点击时返回admin User base jsp @RequestMapping("/adminBaseUser") public String getadminBseUserJsp() { return "admin/adminUser/adminBaseUser/adminBaseUser"; } // 左侧功能区 点击是返回 admin User base jsp @RequestMapping("/adminManagerUser") public String getadminManagerUserJsp() { return "admin/adminUser/adminManager/adminManager"; } // admin manager add jsp @RequestMapping("/getManagerAdd") public String getManagerAdd() { return "admin/adminUser/adminManager/adminManagerAdd"; } // admin manager edit jsp @RequestMapping("/getManagerEdit") public String getgetManagerEdit(Integer managerId, Model model) { Manager manager = managerService.selectByManagerId(managerId); model.addAttribute("Manager", manager); return "admin/adminUser/adminManager/adminManagerEdit"; } /*========================== 订单管理 =========================================*/ @RequestMapping("/adminOrder") public String getadminOrder() { return "admin/adminOrder/adminOrderIndex"; } // admin order add jsp @RequestMapping("/getOrderAdd") public String getOrderadd(Model model) { try { List<User> users = userService.selectAllUsers(); List<Goods> goods = goodsService.selectAllGoods(); model.addAttribute("Users", users); model.addAttribute("Goods", goods); return "admin/adminOrder/adminOrderAdd"; } catch (Exception e) { e.printStackTrace(); model.addAttribute("message", "order数据查询失败,请重新操作"); return "admin/adminWarn"; } } // admin get order Edit jsp @RequestMapping("/getOrderEdit") public String getOrderAdd(Integer orderId, Model model) { try { Order order = orderService.selectByOrderId(orderId); model.addAttribute("Order", order); List<User> users = userService.selectAllUsers(); List<Goods> goods = goodsService.selectAllGoods(); model.addAttribute("Users", users); model.addAttribute("Goods", goods); return "admin/adminOrder/adminOrderEdit"; } catch (Exception e) { e.printStackTrace(); model.addAttribute("message", "查询order订单失败!"); return "admin/adminWarn"; } } // admin get console day order jsp @RequestMapping("/getConsoleDayOrder") public String getConsoleDayOrder() { return "admin/adminConsole/ConsoleDayOrder"; } // admin get console month order jsp @RequestMapping("/getConsoleMonthOrder") public String getConsoleMonthOrder() { return "admin/adminConsole/ConsoleMonthOrder"; } // admin get console order total jsp @RequestMapping("/getConsoleOrderTotal") public String getConsoleOrderTotal() { return "admin/adminConsole/ConsoleOrder"; } //admin get console product sell jsp @RequestMapping("/getConsoleProductSell") public String getConsoleProductSell() { return "admin/adminConsole/ConsoleProductSell"; } }
Java
UTF-8
3,516
2.53125
3
[]
no_license
package com.mead.android.crazymonkey.build; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.mead.android.crazymonkey.AndroidEmulator; import com.mead.android.crazymonkey.AndroidEmulatorContext; import com.mead.android.crazymonkey.CrazyMonkeyBuild; import com.mead.android.crazymonkey.Messages; import com.mead.android.crazymonkey.StreamTaskListener; import com.mead.android.crazymonkey.process.ForkOutputStream; import com.mead.android.crazymonkey.sdk.AndroidSdk; import com.mead.android.crazymonkey.sdk.Tool; import com.mead.android.crazymonkey.util.Utils; public abstract class Builder { public abstract boolean perform(CrazyMonkeyBuild build, AndroidSdk androidSdk, AndroidEmulator emulator, AndroidEmulatorContext emuContext, StreamTaskListener taskListener, String successText) throws IOException, InterruptedException; /** * Uninstalls the Android package corresponding to the given APK file from an Android device. * * @param build The build for which we should uninstall the package. * @param launcher The launcher for the remote node. * @param logger Where log output should be redirected to. * @param androidSdk The Android SDK to use. * @param deviceIdentifier The device from which the package should be removed. * @param apkPath The path to the APK file. * @return {@code true} iff uninstallation completed successfully. * @throws IOException If execution failed. * @throws InterruptedException If execution failed. */ protected static boolean uninstallApk(PrintStream logger, AndroidSdk androidSdk, String deviceIdentifier, File apkPath) throws IOException, InterruptedException { // Get package ID to uninstall String packageId = getPackageIdForApk(logger, androidSdk, apkPath); return uninstallApk(logger, androidSdk, deviceIdentifier, packageId); } /** * Uninstalls the given Android package ID from the given Android device. */ protected static boolean uninstallApk(PrintStream logger, AndroidSdk androidSdk, String deviceIdentifier, String packageId) throws IOException, InterruptedException { AndroidEmulator.log(logger, Messages.UNINSTALLING_APK(packageId)); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ForkOutputStream forkStream = new ForkOutputStream(logger, stdout); String adbArgs = String.format("%s uninstall %s", deviceIdentifier, packageId); Utils.runAndroidTool(forkStream, logger, androidSdk, Tool.ADB, adbArgs, null); // The package manager simply returns "Success" or "Failure" on stdout return stdout.toString().contains("Success"); } /** * Determines the package ID of an APK file. * */ private static String getPackageIdForApk(PrintStream logger, AndroidSdk androidSdk, File apkPath) throws IOException, InterruptedException { // Run aapt command on given APK ByteArrayOutputStream aaptOutput = new ByteArrayOutputStream(); String args = String.format("dump badging \"%s\"", apkPath.getName()); Utils.runAndroidTool(aaptOutput, logger, androidSdk, Tool.AAPT, args, new File(apkPath.getParent())); // Determine package ID from aapt output String packageId = null; String aaptResult = aaptOutput.toString(); if (aaptResult.length() > 0) { Matcher matcher = Pattern.compile("package: +name='([^']+)'").matcher(aaptResult); if (matcher.find()) { packageId = matcher.group(1); } } return packageId; } }
Python
GB18030
1,051
3.078125
3
[ "Artistic-2.0" ]
permissive
# -*- coding: cp936 -*- # ܣͼԤֲֵȡ # ŵocrĿ¼ # ļΪԭ֤ļļ import cv2 import os def read_img(fn): ''' õ֤ͼ :param fn:ͼļ· :return:ͼ ''' return cv2.imread(fn) def write_img(im, fn): cv2.imwrite(fn, im) def get_text_img(im): ''' õͼеı ''' return im[3:22, 127:184] def binarize(im): ''' ֵͼ ''' gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) (retval, dst) = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU) return dst def show_img(im): print im.ndim, im.dtype cv2.imshow("image", im) cv2.waitKey(0) if __name__ == '__main__': img_names = os.listdir('img') for img_name in img_names: im = read_img(os.path.join('img', img_name)) im = get_text_img(im) im = binarize(im) # show_img(im) write_img(im, os.path.join('ocr', img_name))
Java
UTF-8
1,045
2.609375
3
[]
no_license
package com.bragi.mvplcapp.data.entities; import android.support.annotation.NonNull; import java.util.Collections; import java.util.List; /** * A model of a Car brand, containing all information related to it. The names of the * car brand founders are stored as a list of the specific CarBrandFounder model. */ public class CarBrand { @NonNull public final long id; @NonNull public final String name; @NonNull public final String countryCode; @NonNull public final String logoImageUrl; @NonNull private final List<CarBrandFounder> founders; public CarBrand(long id, @NonNull String name, @NonNull String countryCode, @NonNull String logoImageUrl, @NonNull List<CarBrandFounder> founders) { this.id = id; this.name = name; this.countryCode = countryCode; this.logoImageUrl = logoImageUrl; this.founders = founders; } public List<CarBrandFounder> getFounders() { return Collections.unmodifiableList(founders); } }
C#
UTF-8
4,456
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApi.Models { public class Result { public List<StudentResult> GetResults(StudentSearchAttribute searchAttributeData) { if (searchAttributeData.MaxRange == 0) { searchAttributeData.MaxRange = 999999999; } List<StudentListModel> studentListModel = StudentDataModel.GetStudentDetail(); List<StudentTransactionListModel> studentTrasactionListModel = StudentTransactionDataModel.GetStudentTrsactionDetail(); List<StudentResult> studentJoinList = (from studentList in studentListModel join studentTrasactionList in studentTrasactionListModel on studentList.StudentId equals studentTrasactionList.StudentId where isValidAttribute(studentList, searchAttributeData.SearchByAttribute, searchAttributeData.SearchText) && (studentTrasactionList.StudentFees >= searchAttributeData.MinRange && studentTrasactionList.StudentFees <= searchAttributeData.MaxRange) select new StudentResult { StudentId = studentList.StudentId, StudentName = studentList.StudentName, StudentClass = studentList.StudentClass, StudentAge = studentList.StudentAge, StudentFees = studentTrasactionList.StudentFees, TrasactionDate = studentTrasactionList.TrasactionDate } ).ToList(); StudentViewList studentViewList = new StudentViewList(); studentViewList.StudentListData = Sort(studentJoinList, searchAttributeData.SortByAttribute); return studentViewList.StudentListData; } private bool isValidAttribute(StudentListModel studentList, string searchByAttribute, string searchText) { if (searchByAttribute == "StudentName") { if (studentList.StudentName == searchText) { return true; } else { return false; } } if (searchByAttribute == "StudentClass") { int number; if (!int.TryParse(searchText, out number)) return false; return studentList.StudentClass == Convert.ToInt32(searchText) ? true : false; } if (searchByAttribute == "StudentId") { int number; if (!int.TryParse(searchText, out number)) return false; if (studentList.StudentId == Convert.ToInt32(searchText)) { return true; } else { return false; } } return true; } private List<StudentResult> Sort(List<StudentResult> studentResult, string sortByAttribute) { if (sortByAttribute == "StudentId") studentResult = (from studentResultObject in studentResult orderby studentResultObject.StudentId select studentResultObject).ToList(); if (sortByAttribute == "StudentName") studentResult = (from studentResultObject in studentResult orderby studentResultObject.StudentName select studentResultObject).ToList(); if (sortByAttribute == "StudentClass") studentResult = (from studentResultObject in studentResult orderby studentResultObject.StudentClass select studentResultObject).ToList(); return studentResult; } } }
TypeScript
UTF-8
4,540
2.609375
3
[]
no_license
import DebugLog from './debuglog' const fspromises = window.require('fs/promises') export async function OpenFileHandle(filepath: string): Promise<{ handle: any; error: string }> { const result: { handle: any; error: string } = { handle: undefined, error: '' } const fileHandle = await fspromises.open(filepath, 'r').catch((err: any) => { err = FileSystemErrorMessage(err.code, err.message) DebugLog.mSaveDanger('UpOne上传文件失败:' + filepath, err) result.error = err return undefined }) if (fileHandle) result.handle = fileHandle return result } export function FileSystemErrorMessage(code: string, message: string): string { if (!code && !message) return '读取文件失败' if (code) { switch (code) { case 'EACCES': return '没有权限访问' case 'EEXIST': return '存在重名文件' case 'EISDIR': return '不能是文件夹' case 'EMFILE': return '同时打开文件过多' case 'ENFILE': return '同时打开文件过多' case 'ENOENT': return '该路径不存在' case 'ENOTDIR': return '不能是文件' case 'ENOTEMPTY': return '文件夹不为空' case 'EPERM': return '没有权限访问' case 'EBUSY': return '文件被其他程序占用' case 'ETIMEDOUT': return '操作超时' case 'EDQUOT': return '超出磁盘配额' case 'EFBIG': return '文件太大' case 'EIDRM': return '文件已被删除' case 'EIO': return 'IO错误' case 'ELOOP': return '路径级别过多' case 'ENAMETOOLONG': return '文件名太长' case 'ENODEV': return '找不到设备' case 'ENOMEM': return '没有足够的空间' case 'ENOSPC': return '没有可用空间' case 'EROFS': return '只读文件' } } if (message && typeof message == 'string' && message.indexOf('EACCES') >= 0) return '没有权限访问' const err = (code || '') + (message || '') if (err) return err return '读取文件失败' } export function ClearFileName(fileName: string): string { if (!fileName) return '' fileName = fileName.replace(/[<>:"/\\|?*]+/g, '') fileName = fileName.replace(/[\f\n\r\t\v]/g, '') while (fileName.endsWith(' ') || fileName.endsWith('.')) fileName = fileName.substring(0, fileName.length - 1) while (fileName.startsWith(' ')) fileName = fileName.substring(1) if (window.platform == 'win32') { // donothing } else if (window.platform == 'darwin') { while (fileName.startsWith('.')) fileName = fileName.substring(1) } else if (window.platform == 'linux') { // donothing } return fileName } export function CheckFileName(fileName: string): string { if (!fileName) return '不能为空' if (fileName.match(/[<>:"/\\|?*]+/g)) return '不能包含 < > : " / \\ | ? * ' if (fileName.match(/[\f\n\r\t\v]/g)) return '不能包含 \\f \\n \\r \\t \\v' if (fileName.endsWith(' ') || fileName.endsWith('.')) return '不能以空格或.结尾' if (fileName.startsWith(' ')) return '不能以空格开头' if (window.platform == 'win32') { // donothing } else if (window.platform == 'darwin') { if (fileName.startsWith('.')) return '不能以.开头' } else if (window.platform == 'linux') { // donothing } return '' } export function CleanStringForCmd(title: string) { title = title.replace(/[<>"/\\|?* '&%$^`,;=()![\]\-~#]+/g, '') return title } export function CheckWindowsBreakPath(filePath: string) { if (filePath.endsWith('$RECYCLE.BIN')) return true if (filePath.endsWith('$Recycle.Bin')) return true if (filePath.endsWith('$LOGFILE')) return true if (filePath.endsWith('$VOLUME')) return true if (filePath.endsWith('$BITMAP')) return true if (filePath.endsWith('$MFT')) return true if (filePath.endsWith('$WINDOWS.~BT')) return true if (filePath.endsWith('$WinREAgent')) return true if (filePath.endsWith('$GetCurrent')) return true if (filePath.endsWith('$SysReset')) return true if (filePath.endsWith('$Windows.~WS')) return true if (filePath.endsWith('System Volume Information')) return true if (filePath.endsWith('Documents and Settings')) return true if (filePath.endsWith('Config.Msi')) return true if (filePath.endsWith('pagefile.sys')) return true if (filePath.endsWith('swapfile.sys')) return true if (filePath.endsWith('hiberfil.sys')) return true return false }
PHP
UTF-8
5,812
2.90625
3
[ "MIT" ]
permissive
<?php include('_pre.php'); include('Common/Common/function.php'); include('helper.php'); include('fill_function.php'); include('filter_function.php'); /** * 生成验证码 * @param array $config * @return */ function create_verify_code(array $config) { $Verify = new \Think\Verify($config); return $Verify->entry(); } /** * 检查验证码 * @param string $code * @param int $verify_code_id * @return boolean */ function check_verify_code($code, $verify_code_id = '') { $Verify = new \Think\Verify(); return $Verify->check($code, $verify_code_id); } /** * 格式化的文件大小 * @param int $bytes * @return string */ function bytes_format($bytes) { // 单位 $unit = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'); // bytes的对数 $log_bytes = floor(log($bytes, 1024)); return round($bytes / pow(1024, $log_bytes), 2) . $unit[$log_bytes]; } /** * 生成随机码 * @param int $length * @param int $type * @return string */ function rand_code($length, $type) { $rand_factor = array("0123456789", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "~@#$%^&*(){}[]|"); if (($type < 0 && $type != -1) || $type > 4) { $type = 0; } if (0 == $type) { array_pop($rand_factor); $rand_src = implode("", $rand_factor); } else if (-1 == $type) { $rand_src = implode("", $rand_factor); } else { $rand_src = $rand_factor[$type]; } $code = ''; $count = strlen($rand_src) - 1; for ($i = 0; $i < $length; $i++) { $code .= $rand_src[rand(0, $count)]; } return $code; } /** * 删除目录或者文件 * @param string $path * @param boolean $is_del_dir * @return fixed */ function del_dir_or_file($path, $is_del_dir = FALSE) { $handle = opendir($path); if ($handle) { // $path为目录路径 while (false !== ($item = readdir($handle))) { // 除去..目录和.目录 if ($item != '.' && $item != '..') { if (is_dir("$path/$item")) { // 递归删除目录 del_dir_or_file("$path/$item", $is_del_dir); } else { // 删除文件 unlink("$path/$item"); } } } closedir($handle); if ($is_del_dir) { // 删除目录 return rmdir($path); } }else { if (file_exists($path)) { return unlink($path); } else { return false; } } } /** * 检查是否包含特殊字符 * @param string $subject 需要检查的字符串 * @return boolean 是否包含 */ function hasSpecialChar($subject) { $pattern = "/^(([^\^\.<>%&',;=?$\"':#@!~\]\[{}\\/`\|])*)$/"; if (preg_match($pattern, $subject)) { return false; } return true; } /** * 是否整数 * @param mixed $var * @return boolean */ function isint($var) { return (preg_match('/^\d*$/', $var) == 1); } /** * 是否浮点型 * @param mixed $var 需要检查的值 * @return boolean */ function isdouble($var) { return (preg_match('/^[+-]?(\d*\.\d+([eE]?[+-]?\d+)?|\d+[eE][+-]?\d+)$/', $var)); } /** * 检验是否有效日期 * @param string $date 需要检验的日期 * @param array $formats 有效的日期格式 * @return boolean */ function is_valid_date($date, $formats = array("Y-m-d", "Y/m/d")) { $unixtime = strtotime($date); if (!$unixtime) { return false; } foreach ($formats as $format) { if (date($format, $unixtime) == $date) { return true; } } return false; } /** * 得到指定值在数组中的位置,未找到返回false * @param array $search 被查找的数组 * @param mixed $target 目标值 * @return mixed */ function array_pos(array $search, $target) { $i = 0; foreach ($search as $item) { if ($item == $target) { return $i; } $i += 1; } return false; } /** * 只对字符串进行trim * @param mixed $val 需要trim的值 * @return mixed */ function trim_value($val) { if (is_string($val)) { return trim($val); } return $val; } /** * 得到操作系统信息 * @return string */ function get_system() { $sys = $_SERVER['HTTP_USER_AGENT']; if (stripos($sys, "NT 6.1")) { $os = "Windows 7"; } else if (stripos($sys, "NT 6.0")) { $os = "Windows Vista"; } else if (stripos($sys, "NT 5.1")) { $os = "Windows XP"; } else if (stripos($sys, "NT 5.2")) { $os = "Windows Server 2003"; } else if (stripos($sys, "NT 5")) { $os = "Windows 2000"; } else if (stripos($sys, "NT 4.9")) { $os = "Windows ME"; } else if (stripos($sys, "NT 4")) { $os = "Windows NT 4.0"; } else if (stripos($sys, "98")) { $os = "Windows 98"; } else if (stripos($sys, "95")) { $os = "Windows 95"; } else if (stripos($sys, "Mac")) { $os = "Mac"; } else if (stripos($sys, "Linux")) { $os = "Linux"; } else if (stripos($sys, "Unix")) { $os = "Unix"; } else if (stripos($sys, "FreeBSD")) { $os = "FreeBSD"; } else if (stripos($sys, "SunOS")) { $os = "SunOS"; } else if (stripos($sys, "BeOS")) { $os = "BeOS"; } else if (stripos($sys, "OS/2")) { $os = "OS/2"; } else if (stripos($sys, "PC")) { $os = "Macintosh"; } else if(stripos($sys, "AIX")) { $os = "AIX"; } else { $os = "未知操作系统"; } return $os; }
Java
UTF-8
1,219
2.609375
3
[]
no_license
package nl.ipsen3server.resources; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import nl.ipsen3server.controllers.LoggingController; import nl.ipsen3server.models.LogModel; /** * @author Anthony Schuijlenburg */ @Path("/log") public class LogResource { private LoggingController loggingController = new LoggingController(); //TODO logmodel needs to be send over and not created on the spot /** * @author Anthony Schuijlenburg * @param token The token of the user trying to post a log */ @POST @Path("/upload/") @Consumes(MediaType.APPLICATION_JSON) public Response createLog(LogModel logModel, @HeaderParam("token") String token) { return loggingController.createLog(logModel, token); } /** * @author Anthony Schuijlenburg * @param id The id of the experiment from which the logs need to be downloaded * @param token The token of the user requesting the logs * @return Returns the logs from the requested project */ @GET @Path("/download/{experimentId}") public Response showlogs(@PathParam("experimentId") int id, @HeaderParam("token") String token){ return loggingController.showlogs(id, token); } }
C++
UTF-8
2,027
2.890625
3
[]
no_license
// InputProccesor.h -------------------------------------------------------- // Shayan Raouf CSS343 Section Number // Creation Date: 2/22/2016 // Date of Last Modification: 2/19/2016 // ---------------------------------------------------------------------------- // Purpose - The input Proccessor class proccess the three main functions // needed to proccess for the Store class. // Functionality - // - void proccessMovies(BSTree<Movie*> movies[]) // - Takes an array of Binary Search Tree holding Movie pointers. // - Opens the necessary file and proccess all the different movies. // // - void proccessCustomers(HashTable<Customer>&) // - Takes an a Hash Table holding Customers by reference // - Opens the necessary file and proccess all the different Customers // // - void proccessCommands(BSTree<Movie*> movies[], HashTable<Customer>&) // - Takes an array of Binary Search Tree holding Movie pointers. // - Takes an a Hash Table holding Customers by reference // - Opens the necessary file and proccess all the different commends // // ---------------------------------------------------------------------------- #ifndef INPUT_PROCCESSOR #define INPUT_PROCCESSOR const char B = 'B'; const char R = 'R'; const char H = 'H'; const char I = 'I'; #include <string> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include "MovieFactory.h" #include "Movie.h" #include "Customer.h" #include "HashTable.h" #include "Transaction.h" #include "InventoryTransaction.h" #include "TransactionFactory.h" using namespace std; class InputProccesor { public: enum MOVIES { COMEDY_ENUM, CLASSICS_ENUM, DRAMA_ENUM, END }; // constructors InputProccesor(); ~InputProccesor(); // void function that proccesses the movies void proccessMovies(set<Movie*> movies[]); // void function that proccesses the customers void proccessCustomers(HashTable<Customer>&); // void function that proccesses the commands void proccessCommands(set<Movie*> movies[], HashTable<Customer>&); }; #endif
Java
UTF-8
1,123
2.046875
2
[]
no_license
package com.aiyi.blog.entity; import com.aiyi.core.annotation.po.ID; import com.aiyi.core.annotation.po.TableName; import com.aiyi.core.annotation.po.vali.Validation; import com.aiyi.core.annotation.po.vali.enums.ValidationType; import com.aiyi.core.beans.PO; import com.aiyi.core.util.MD5; @TableName(name = "blog_user") public class User extends PO { @ID private int id; @Validation(/*value = ValidationType.Email,*/ name = "用户名") private String email; private String nicker; @Validation(name = "密码") private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNicker() { return nicker; } public void setNicker(String nicker) { this.nicker = nicker; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
C#
UTF-8
5,088
2.5625
3
[]
no_license
// ---------------------------------------------------------------------------- // <copyright file="UnitOfWorkInterceptionBehavior.cs" company="SOGETI Spain"> // Copyright © 2016 SOGETI Spain. All rights reserved. // MVVM Course by Óscar Fernández González a.k.a. Osc@rNET. // </copyright> // ---------------------------------------------------------------------------- namespace SogetiSpain.MvvmCourse.Data { using System; using System.Collections.Generic; using Microsoft.Practices.Unity.InterceptionExtension; using NHibernate; /// <summary> /// Represents an interception behavior for a unit of work. /// </summary> public sealed class UnitOfWorkInterceptionBehavior : IInterceptionBehavior { #region Fields /// <summary> /// Defines the session factory. /// </summary> private readonly ISessionFactory sessionFactory; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="UnitOfWorkInterceptionBehavior"/> class. /// </summary> /// <param name="sessionFactory">The session factory.</param> public UnitOfWorkInterceptionBehavior(ISessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } #endregion Constructors #region Properties /// <summary> /// Gets a value indicating whether this behavior will actually do anything when invoked. /// </summary> /// <remarks> /// This is used to optimize interception. If the behaviors won't actually /// do anything (for example, PIAB where no policies match) then the interception /// mechanism can be skipped completely. /// </remarks> /// <value> /// <c>true</c> if this behavior will actually do anything when invoked; otherwise, <c>false</c>. /// </value> public bool WillExecute { get { return true; } } #endregion Properties #region Methods /// <summary> /// Returns the interfaces required by the behavior for the objects it intercepts. /// </summary> /// <returns> /// The required interfaces. /// </returns> public IEnumerable<Type> GetRequiredInterfaces() { return Type.EmptyTypes; } /// <summary> /// Execute the behavior processing. /// </summary> /// <param name="input">Inputs to the current call to the target.</param> /// <param name="getNext">Delegate to execute to get the next delegate in the behavior chain.</param> /// <returns> /// Return value from the target. /// </returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { IMethodReturn methodReturn = null; // If there is a running transaction, just run the method. if (NHibernateUnitOfWork.Current != null || !this.RequiresDbConnection(input)) { // Invoke the next behavior in the chain. methodReturn = getNext()(input, getNext); } else { try { NHibernateUnitOfWork.Current = new NHibernateUnitOfWork(this.sessionFactory); NHibernateUnitOfWork.Current.BeginTransaction(); try { // Invoke the next behavior in the chain. methodReturn = getNext()(input, getNext); NHibernateUnitOfWork.Current.Commit(); } catch { try { NHibernateUnitOfWork.Current.Rollback(); } catch { } throw; } } finally { NHibernateUnitOfWork.Current = null; } } return methodReturn; } /// <summary> /// Returns a value indicating if this behavior requires a database connection. /// </summary> /// <param name="methodInvocation">The method invocation.</param> /// <returns> /// <c>true</c> if this behavior requires a database connection; otherwise, <c>false</c>. /// </returns> private bool RequiresDbConnection(IMethodInvocation methodInvocation) { if (UnitOfWorkHelper.HasUnitOfWorkAttribute(methodInvocation)) { return true; } if (UnitOfWorkHelper.IsRepositoryMethod(methodInvocation)) { return true; } return false; } #endregion Methods } }
JavaScript
UTF-8
280
2.78125
3
[]
no_license
const [, , path] = process.argv; const fs = require('fs'); fs.readFile(path, 'utf8', (err, data) => { if (err) throw err; //подсчет количества строк в файле const rowCount = data.split('\n').length - 1; console.log(rowCount); });
Python
UTF-8
1,010
2.546875
3
[ "Apache-2.0" ]
permissive
"""The runner takes brain damage.""" from csrv.model.actions import action from csrv.model import cost from csrv.model import errors from csrv.model import events from csrv.model import game_object from csrv.model import modifiers from csrv.model import parameters class TakeBrainDamage(action.Action): DESCRIPTION = 'Take brain damage' def __init__(self, game, player, card, dmg=1, callback_name=None): action.Action.__init__(self, game, player, card) self.dmg = dmg self._is_mandatory = True self.callback_name = callback_name def resolve(self, response=None, ignore_clicks=False, ignore_all_costs=False): action.Action.resolve( self, ignore_clicks=ignore_clicks, ignore_all_costs=ignore_all_costs) self.game.runner.take_damage(1) self.game.runner.brain_damage += 1 if self.callback_name: getattr(self.card, self.callback_name)() @property def description(self): return 'Take %d brain damage from %s' % (self.dmg, self.card)
Java
UTF-8
1,700
3.609375
4
[]
no_license
package net.jcip.examples.chapter5; import java.util.*; /** * * @Author: cuixin * * @Date: 2019/8/15 16:00 */ public class UnsafeListIterator5_5 { public static void main(String[] args) { //错误演示,Arrays.asList里面没有实现remove等操作。 // List<String> source = Arrays.asList("Hello", "world"); List<String> source = new ArrayList<>(); source.add("Hello"); source.add("World"); List<String> list = Collections.synchronizedList(source); // wrongForEach(list); wrongForEach2(list); } public static void rightForeach(final List<String> list) { synchronized (list) { ListIterator<String> listIterator = list.listIterator(); while (listIterator.hasNext()) { String next = listIterator.next(); System.out.println(next); } } } public static void wrongForEach(final List<String> list) { ListIterator<String> listIterator = list.listIterator(); //抛出java.util.ConcurrentModificationException 异常此处,由于返回listIterator用的是底层的数据 //且底层数据list list.remove("Hello"); while (listIterator.hasNext()) { String next = listIterator.next(); System.out.println(next); } } public static void wrongForEach2(final List<String> list) { //抛出java.util.ConcurrentModificationException 异常此处,由于返回listIterator用的是底层的数据 //且底层数据list for (String item: list) { System.out.println(item); list.remove("Hello"); } } }
JavaScript
UTF-8
875
3.890625
4
[]
no_license
var noofticket = 5; var buyticket = prompt("Enter Your Total Ticket : "); var eachprice = 200; var disprice = 50; function ticket(theory, ...rest) { if(rest[2] < 5) { rest[3] = 0; return `${theory[0]} ${rest[0]} ${theory[1]} ${rest[1]} ${theory[2]} ${rest[2]} ${theory[3]} ${rest[3]} ${theory[4]}`; }else{ return `${theory[0]} ${rest[0]} ${theory[1]} ${rest[1]} ${theory[2]} ${rest[2]} ${theory[3]} ${rest[3]} ${theory[4]}`; } } document.write(ticket `There are ${noofticket} movie tickets Each Rs ${eachprice} and if You buy ${buyticket} tickets get discount Rs. ${disprice} Each <br>`) //string length property var str = "Hello GeekyShows"; document.write(str.length+"<br>"); //char At property var str = "Hello GeekyShows"; document.write(str.charAt(7)+"<br>"); //char Code At property var str = "Hello GeekyShows"; document.write(str.charCodeAt(7));
Python
UTF-8
12,447
2.6875
3
[]
no_license
## Assembler import logging import coloredlogs import glob import os import sys from ctypes import c_uint8 fmt = '[{levelname:7s}] {name:s}: {message:s}' logger = logging.getLogger(__name__) coloredlogs.DEFAULT_FIELD_STYLES['levelname']['color'] = 'white' if len(sys.argv) >= 2 and sys.argv[1] in ['-d', '--debug']: coloredlogs.install(level=logging.DEBUG, logger=logger, fmt=fmt, style='{') else: coloredlogs.install(level=logging.WARNING, logger=logger, fmt=fmt, style='{') class AssemblyError(Exception): pass class Assembler: # (Object Code, Size) mnemonics_table = { "JP": (0x0, 2), "JZ": (0x1, 2), "JN": (0x2, 2), "CN": (0x3, 1), "+": (0x4, 2), "-": (0x5, 2), "*": (0x6, 2), "/": (0x7, 2), "LD": (0x8, 2), "MM": (0x9, 2), "SC": (0xA, 2), "OS": (0xB, 1), "IO": (0xC, 1), } pseudo_table = ['@', '#', '$', 'K'] def __init__(self, filen=None, make_list=True, dump_tables=True): if not filen: raise RuntimeError('File name not provided to Assembler') logger.debug('Initializing Assembler') # Removes file extension self.filename = '.'.join(filen.split('.')[:-1]) logger.debug('Base filename: %s', self.filename) self.labels = {} self.obj_code = [] self.instruction_counter = 0 self.initial_address = 0 self.current_object_file = 0 try: with open(filen, 'r') as f: all_lines = f.readlines() except FileNotFoundError: logger.error('File %s not found', filen) raise AssemblyError('File not found') except UnicodeDecodeError: raise AssemblyError('Certifique-se que não há letras acentuadas no arquivo!') logger.debug('Preprocessing file') self.lines = [] for i, line in enumerate(all_lines): # Separate comments command, comment = (l.strip() for l in line.split(';')) if ';' in line else (line.strip(), '') if command == '' and comment == '': # skip blank lines continue l = command.split() self.lines.append((i+1, l, comment)) logger.debug('Finished preprocessing') self.list_file = None if (make_list): self.list_file = self.filename + '.lst' with open(self.list_file, 'w') as f: print('{} LIST FILE'.format(self.list_file), file=f) print('{}-----------'.format('-' * len(self.list_file)), file=f) print('ADDRESS OBJECT LINE SOURCE', file=f) self.lb_table_file = None if (dump_tables): self.lb_table_file = self.filename + '.asm.labels' with open(self.lb_table_file, 'w') as f: print('{} LABEL TABLE FILE'.format(self.lb_table_file), file=f) print('{}-----------------'.format('-' * len(self.lb_table_file)), file=f) print('LABEL VALUE', file=f) self.obj_file = self.filename + '.obj' for f in glob.glob(self.obj_file + '.*'): os.remove(f) def assemble(self): for self.step in [1, 2]: logger.debug('Initializing Step %d', self.step) self.instruction_counter = 0 for lineno, code, comment in self.lines: # logger.debug('Processing line %d', lineno) if len(code) == 0: # Comment only, do nothing on first step if self.step == 2: self.list(line=lineno, comment=comment) elif len(code) == 1: # Label only if self.step == 2: self.list(line=lineno, comment=comment, code=code, address=self.instruction_counter) continue label = code[0] if label in [*self.mnemonics_table, *self.pseudo_table]: # Lonely operation raise AssemblyError('Assembly error on line {:d} "{}": operation must have operator'.format(lineno, ' '.join(code))) if label in self.labels and self.labels[label] is not None: # Label already defined raise AssemblyError('Assembly error on line {:d} label "{}" already defined'.format(lineno, label)) self.labels[label] = self.instruction_counter elif len(code) == 2: # Operation and Operator self.process_code(lineno, code, comment) elif len(code) == 3: # Label, Operation and Operator if self.step == 1: label = code[0] if label in [*self.mnemonics_table, *self.pseudo_table]: # First element should be label raise AssemblyError('Assembly error on line {:d} "{}": operation on label position'.format(lineno, ' '.join(code))) if label in self.labels and self.labels[label] is not None: # Label already defined raise AssemblyError('Assembly error on line {:d} label "{}" already defined'.format(lineno, label)) self.labels[label] = self.instruction_counter self.process_code(lineno, code, comment) else: raise AssemblyError('Assembly error on line {:d}: Too many things!!'.format(lineno)) logger.debug('Finished Step %d', self.step) self.dump_label_table() self.save_obj() def process_code(self, lineno, code, comment): operation = code[-2] if operation not in [*self.mnemonics_table, *self.pseudo_table]: # Unknown operation raise AssemblyError('Assembly error on line {:d}: Unknown operation "{}"'.format(lineno, operation)) try: operator = int(code[-1]) # try decimal except ValueError: try: if code[-1][0] == '/': operator = int(code[-1][1:], 16) # try hex else: raise except ValueError: # label lb = code[-1].partition('+') if '+' in code[-1] else code[-1].partition('-') if '-' in code[-1] else [code[-1]] if self.step == 1: if lb[0] not in self.labels: self.labels[lb[0]] = None operator = None elif self.step == 2: if self.labels[lb[0]] is None: raise AssemblyError('Assembly error on line {:d}: undefined label "{}"'.format(lineno, code[-1])) if len(lb) == 1: operator = self.labels[lb[0]] else: operator = self.labels[lb[0]] + int(lb[2]) if lb[1] == '+' else self.labels[lb[0]] - int(lb[2]) # Pseudo instruction if operation in self.pseudo_table: if operation != '#' and type(operator) != type(int()): raise AssemblyError('Assembly error on line {:d}: {} operator must be an integer!'.format(lineno, operation)) if operation == '@': if operator > 0xFFFF: raise AssemblyError('Assembly error on line {:d}: operator out of range "{:0x}"'.format(lineno, operator)) # elif operator < 0x0100: # raise AssemblyError('Assembly error on line {:d}: memory area before 0x0100 should never be accessed'.format(lineno)) self.list(line=lineno, code=code, comment=comment) if self.step == 2 and self.instruction_counter != None: # New code block, save current self.save_obj() self.obj_code = [] self.initial_address = operator self.instruction_counter = operator elif operation == '$': if operator > 0xFFF: raise AssemblyError('Assembly error on line {:d}: operator out of range "{:0x}"'.format(lineno, operator)) self.list(line=lineno, code=code, comment=comment, address=self.instruction_counter) self.instruction_counter += operator if self.step == 2: self.obj_code.extend([c_uint8(0)] * operator) elif operation == 'K': if operator > 0xFF: raise AssemblyError('Assembly error on line {:d}: operator out of range "{:0x}"'.format(lineno, operator)) self.list(line=lineno, code=code, comment=comment, address=self.instruction_counter, object=operator) if self.step == 2: self.obj_code.append(c_uint8(operator)) self.instruction_counter += 1 elif self.step == 2 and operation == '#': if operator > 0xFFFF: raise AssemblyError('Assembly error on line {:d}: operator out of range "{:0x}"'.format(lineno, operator)) self.list(line=lineno, code=code, comment=comment) self.save_obj() self.initial_address = 0x0022 self.obj_code = [c_uint8(operator >> 8), c_uint8(operator & 0xFF)] # Normal instruction else: instruction_size = self.mnemonics_table[operation][1] if self.step == 1: self.instruction_counter += instruction_size return if instruction_size == 1: obj_code = self.mnemonics_table[operation][0] << 4 | operator self.obj_code.append(c_uint8(obj_code)) elif instruction_size == 2: obj_code = self.mnemonics_table[operation][0] << 12 | operator self.obj_code.append(c_uint8(obj_code >> 8)) self.obj_code.append(c_uint8(obj_code & 0xFF)) self.list(line=lineno, code=code, comment=comment, address=self.instruction_counter, object=obj_code) self.instruction_counter += instruction_size def list(self, **kwargs): if self.list_file is None or self.step != 2: return comm = '; {:s}'.format(kwargs['comment']) if 'comment' in kwargs and kwargs['comment'] != '' else '' addr = '{:-04X}'.format(kwargs['address']) if 'address' in kwargs else ' ' obj = '{:-6X}'.format(kwargs['object']) if 'object' in kwargs else ' ' code = '{:s} '.format(' '.join(kwargs['code'])) if 'code' in kwargs else '' line = '{:-4d}'.format(kwargs['line']) if 'line' in kwargs else ' ' with open(self.list_file, 'a') as f: print(' {} {} {} {}{}'.format( addr, obj, line, code, comm), file=f) def dump_label_table(self): if self.lb_table_file is None or self.step != 1: return with open(self.lb_table_file, 'a') as f: for label in self.labels: print('{:<15s} {:>04X}'.format(label, self.labels[label]), file=f) def save_obj(self): if self.step != 2: return logger.debug('Saving object') obj_codes = [self.obj_code[x:x+0xFF] for x in range(0, len(self.obj_code), 0xFF)] # Split into FF pc = self.initial_address for obj in obj_codes: chk = c_uint8(0xFF) with open(self.obj_file + '.{:d}'.format(self.current_object_file), 'w') as f: with open(self.obj_file + '.bin.{:d}'.format(self.current_object_file), 'wb') as fb: fb.write(pc.to_bytes(2, 'big')) fb.write((len(obj) & 0xFF).to_bytes(1, 'big')) print('{:02X} {:02X}'.format(pc >> 8, pc & 0xFF), end=' ', file=f) print('{:02X}'.format(len(obj)), end=' ', file=f) i = 3 for o in obj: fb.write((o.value & 0xFF).to_bytes(1, 'big')) print('{:02X}'.format(o.value), end=' ', file=f) chk.value ^= o.value i += 1 pc += 1 if i % 16 == 0: # Break line every few elements to improve readability print('', file=f) fb.write((chk.value & 0xFF).to_bytes(1, 'big')) print('{:02X}'.format(chk.value), end='', file=f) self.current_object_file += 1
Markdown
UTF-8
603
3.203125
3
[]
no_license
# Confidence Confidence brings people together - people generally want to talk to confident people The problem with this is that is it makes it seem like confidence is some type of magic, when if fact confidence just stems from your comfort in a particular subject, which you get from your experience with that subject **Confidence** is just knowing that you can go out and do something and be successful at it **Fear** keeps us from being exposed to new things, which means we remain inexperienced and incompetent at doing those things, which means we will not be confident when we talk about them
JavaScript
UTF-8
1,989
4.125
4
[]
no_license
console.time('computation'); /** * Checks if a number is prime or not * @param num - Number in consideration * @returns {boolean} - True for prime, false for non-prime */ function isPrimeNumber(num) { if (num <= 1) { // Numbers below or equal to 1 are all non-prime return false; } var sqrtNum = Math.floor(Math.sqrt(num)); for (var i = 2; i <= sqrtNum; i++) { if (num % i === 0) { // If a number is divisible by any number upto its sqrt, it's non-prime return false; } } return true; } /*** * Calculates the largest prime factor for any given number * @param num - Number whose largest prime factor needs to be computed * @returns {null|number} - Null when no prime factor exists, else the largest prime factor */ function getLargestPrimeFactor(num) { var primeFactors = []; var limit = num; if (isPrimeNumber(limit)) { // If the given number itself is a prime number, it will be the largest factor return limit; } while (true) { for (var i = 2; i <= limit; i++) { if (limit % i === 0) { if (primeFactors.includes(i)) { // Only change the limit if the number was already found to be prime limit = limit / i; break; } else if (isPrimeNumber(i)) { // Push prime numbers primeFactors.push(i); limit = limit / i; break; } } } if (isPrimeNumber(limit)) { // Break if the currentNumber itself is a prime number primeFactors.push(limit); break; } if (limit === 1) { // Break if limit is reduced to 1 break; } } if (!primeFactors.length) { return null; } return Math.max(...primeFactors); } const num = 600851475143; const factor = getLargestPrimeFactor(num); console.log(factor); console.timeEnd('computation');
Java
UTF-8
1,838
2.3125
2
[]
no_license
package com.hangman.sinapse.hangman; import java.util.Random; /** * Created by Jerry Jr on 26/02/2018. */ public class Palavras { private String[] temas = new String[] {"animais","paises","frutas","esportes"}; private String[] palavras = new String[] {"AVIÃO", "AERONAVE", "AUTOMÓVEL", "MOTOCICLETA", "BICICLETA", "IATE", "NAVIO", "TERRA", "MERCÚRIO", "PLUTÃO", "MARTE", "JUPTER", "NETUNO", "ELEFANTE", "ESCORPIÃO", "RINOCERONTE", "DINOSSAURO", "REFRIGERADOR", "ÁFRICA", "BRASIL", "TELEVISOR", "POLTRONA", "SECADORA", "ESCORREDOR", "LIQUIDIFICADOR", "EUROPA", "AMSTERDÃ", "ESTADOS UNIDOS", "GRÉCIA", "ARGENTINA", "VENEZUELA", "BOTAFOGO", "SÃO PAULO", "FLAMENGO", "PALMEIRAS", "FLUMINENSE", "AMOR", "INTELECTUAL", "SÁBIO", "CULTURA", "SABEDORIA", "TUCANO", "BEIJA-FLOR", "ZEBRA", "CRUZEIRO", "COMPUTADOR", "FACULDADE", "PIPOCA", "MACARRÃO", "FEIJOADA", "SABÃO EM PÓ", "LAVANDERIA", "COZINHA", "CHURRASCO", "PARANAENSE", "MINEIRO", "SANTISTA", "GAÚCHO", "CATARINENSE", "AFRICANO", "BRASILEIRO", "AMERICANO", "CARTEIRO", "LIXEIRO", "PROGRAMADOR", "LUMINÁRIA", "LUTADOR", "COZINHEIRO", "VENDEDOR", "FLORICULTURA", "JAPÃO", "ARÁBIA SAUDITA", "EQUADOR", "MÉXICO", "PORTUGUAL", "ALEMANHA", "PROFESSOR", "CHAVEIRO", "FAMÍLIA", "DOCUMENTÁRIO", "DOCUMENTOS", "FAMILIARES", "LANCHONETE"}; public Palavras() { } public String sorteio() { String sortTema = temas[(int)(random()*temas.length)]; String palavraSorteada = palavras[(int)(random()*palavras.length)]; return palavraSorteada; } public static double random() { Random r = new Random(); return r.nextDouble(); } }
Shell
UTF-8
1,313
3.234375
3
[]
no_license
### Bootstrapping # Install/configure SPF13 vim setup _PROFILE=1 SPF="$HOME/.spf13-vim-3" if [ ! -d $SPF ]; then git clone --depth=1 https://github.com/spf13/spf13-vim.git $SPF [ -z ${MSYSTEM+x} ] && sh $SPF/bootstrap.sh || printf "spf13 downloaded. Please complete installation using one of the bootstrapping scripts within ~/.spf13-vim-3\n" fi [ -s ~/.git-completion ] || curl -o .git-completion "https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash" [ -s ~/.git-prompt ] || curl -o .git-prompt "https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh" case $OSTYPE in darwin*) # Have to install themes manually to iterm2 [ ! -d ~/.solarized ] && git clone --depth=1 https://github.com/altercation/solarized .solarized && rm -rf .solarized/.git [ ! -d ~/.iterm2/schemes ] && git clone --depth=1 https://github.com/mbadolato/iTerm2-Color-Schemes .iterm2/schemes && rm -rf .iterm2/schemes/.git ;; msys) ;; linux-gnu) [ ! -d ~/.dircolors ] && git clone --depth=1 https://github.com/huyz/dircolors-solarized .dircolors && rm -r .dircolors/.git ;; esac [ -r $HOME/.bashrc ] && source $HOME/.bashrc source /Users/jared/.docker/init-bash.sh || true # Added by Docker Desktop
PHP
UTF-8
5,572
2.890625
3
[]
no_license
<?php include "db.php"; mysql_select_db($mysql_database, $dbuser) or exit('Error Selecting database: '.mysql_error()); ; /* user config variables */ $max_items = 7; /* max number of news items to show */ /* make database connection */ // $db = mysql_connect ('localhost','root','Berskin99'); //mysql_select_db ('test',$db); function displayNews($all = 0) { /* bring in two variables * $db is our database connection * $max_items is the maximum number * of news items we want to display */ global $max_items; /* query for news items */ if ($all == 0) { /* this query is for up to $max_items */ $querying = "SELECT id,title,newstext," . "DATE_FORMAT(postdate, '%Y-%m-%d') as date " . "FROM news ORDER BY postdate DESC LIMIT $max_items"; } else { /* this query will get all news */ $querying = "SELECT id,title,newstext," . "DATE_FORMAT(postdate, '%Y-%m-%d') as date " . "FROM news ORDER BY postdate DESC"; } $resulting = mysql_query ($querying); while ($row = mysql_fetch_assoc ($resulting)) { /* display news in a simple table */ //echo "&lt;TABLE border=\"1\" width=\"300\"&gt;\n"; /* place table row data in * easier to use variables. * Here we also make sure no * HTML tags, other than the * ones we want are displayed */ $date = $row['date']; $title = htmlentities ($row['title']); $news = nl2br (strip_tags ($row['newstext'], '')); /* display the data */ echo "$title posted on $date \n"; echo "$news \n"; /* get number of comments */ $comment_query = "SELECT count(*) FROM news_comments " . "WHERE news_id={$row['id']}"; $comment_result = mysql_query ($comment_query); $comment_row = mysql_fetch_row($comment_result); /* display number of comments with link */ echo "a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&amp;id={$row['id']}\"&gt;Comments&lt;/a&gt;" . "($comment_row[0]}&lt;/TD&gt;&lt;/TR&gt;\n"; /* finish up table*/ echo "&lt;/TABLE&gt;\n"; echo "&lt;BR&gt;\n"; } /* if we aren't displaying all news, * then give a link to do so */ if ($all == 0) { echo "&lt;a href=\"{$_SERVER['PHP_SELF']}" . "?action=all\"&gt;View all news&lt;/a&gt;\n"; } } function displayOneItem($id) { global $db; /* query for item */ $query = "SELECT * FROM news WHERE id=$id"; $result = mysql_query ($query); /* if we get no results back, error out */ if (mysql_num_rows ($result) == 0) { echo "Bad news id\n"; return; } $row = mysql_fetch_assoc($result); echo "&lt;TABLE border=\"1\" width=\"300\"&gt;\n"; /* easier to read variables and * striping out tags */ $title = htmlentities ($row['title']); $news = nl2br (strip_tags ($row['newstext'], '&lt;a&gt;&lt;b&gt;&lt;i&gt;&lt;u&gt;')); /* display the items */ echo "$title \n"; echo "$news \n"; //echo "&lt;/TABLE&gt;\n"; // echo "&lt;BR&gt;\n"; /* now show the comments */ displayComments($id); } function displayComments($id) { /* bring db connection variable into scope */ global $db; /* query for comments */ $query = "SELECT * FROM news_comments WHERE news_id=$id"; $result = mysql_query ($query); echo "Comments:&lt;BR&gt;&lt;HR width=\"300\"&gt;\n"; /* display the all the comments */ while ($row = mysql_fetch_assoc ($result)) { echo "&lt;TABLE border=\"1\" width=\"300\"&gt;\n"; $name = htmlentities ($row['name']); echo "$name \n"; $comment = strip_tags ($row['comment']); $comment = nl2br ($comment); echo "$comment \n"; //echo "&lt;/TABLE&gt;\n"; // echo "&lt;BR&gt;\n"; } /* add a form where users can enter new comments */ echo "&lt;HR width=\"300\"&gt;"; echo "&lt;FORM action=\"{$_SERVER['PHP_SELF']}" . "?action=addcomment&amp;id=$id\" method=POST&gt;\n"; echo "Name: &lt;input type=\"text\" " . "width=\"30\" name=\"name\"&gt;&lt;BR&gt;\n"; echo "&lt;TEXTAREA cols=\"40\" rows=\"5\" " . "name=\"comment\"&gt;&lt;/TEXTAREA&gt;&lt;BR&gt;\n"; echo "&lt;input type=\"submit\" name=\"submit\" " . "value=\"Add Comment\"\n"; echo "&lt;/FORM&gt;\n"; } function addComment($id) { global $db; /* insert the comment */ $query = "INSERT INTO news_comments " . "VALUES('',$id,'{$_POST['name']}'," . "'{$_POST['comment']}')"; mysql_query($query); echo "Comment entered. Thanks!&lt;BR&gt;\n"; echo "&lt;a href=\"{$_SERVER['PHP_SELF']}" . "?action=show&amp;id=$id\"&gt;Back&lt;/a&gt;\n"; } /* this is where the script decides what do do */ //echo "&lt;CENTER&gt;\n"; switch($_GET['action']) { case 'show': displayOneItem($_GET['id']); break; case 'all': displayNews(1); break; case 'addcomment': addComment($_GET['id']); break; default: displayNews(); } //echo "&lt;/CENTER&gt;\n"; ?>
Python
UTF-8
1,909
2.75
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Jul 28 18:44:13 2020 @author: generalguy26 """ #nds audio info can be found at https://www.akkit.org/info/gbatek.htm import audioread import struct import codec with audioread.audio_open('song.wav') as f: #audioread has little endian pcm16 values state = None data = b'' pcm16 = 0 headercounter = -4 blocksize = 0x8000 - 16 for buf in f: #buf is a 2048 byte buffer, we need to get the 16 bit (2 byte) pcm16 values from this for i in range(int(len(buf) / 4)): #loop through the buffer m = i * 4 #account for the division before headercounter += 4 #tracking how long it has been since a header has been inserted if headercounter % blocksize == 0: #header needs to be present at the beginning of every 0x8000 byte block, this checks if a header needs to be inserted headercounter = 0 #reset the tracker result = codec._calc_head(buf[m: m + 2]) #create the header print(result) data += result #insert the header to the bytes (apparently it doesn't really work and only inserts correctly at the beginning) pcm16 = buf[m : m + 2] #get first pcm16 value pcm16 = struct.unpack( '<h', pcm16)[0] #read as little endian short pcm162 = buf[m + 1 : m + 3] #get second pcm16 value pcm162 = struct.unpack( '<h', pcm162)[0] #read as little endian short sample = codec._encode_sample(pcm16) #calculate adpcm value for first pcm16 value sample2 = codec._encode_sample(pcm162) #calculate adpcm value for second pcm16 value print(sample, sample2) data += struct.pack('B', (sample2 << 4) | sample) #assemble values into a byte and append them to the datastream with open('audio.ima', 'wb+') as w: w.write(data) #write datastream to file