language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
JavaScript
UTF-8
2,392
2.859375
3
[]
no_license
document.addEventListener("DOMContentLoaded", start) let menuliste = []; let filter = "alle"; function start() { const filtrerknapper = document.querySelectorAll("nav button"); filtrerknapper.forEach(knap => knap.addEventListener("click", filtrerMenu)); document.querySelector("#detalje").style.display = "none"; hentData(); } function filtrerMenu() { console.log(this); document.querySelector(".valgt").classList.remove("valgt"); filter = this.dataset.kategori; this.classList.add("valgt"); visData(); } async function hentData() { let jsonData = await fetch("https://spreadsheets.google.com/feeds/list/17Dd7DvkPaFamNUdUKlrFgnH6POvBJXac7qyiS6zNRw0/od6/public/values?alt=json"); console.log(jsonData); menuliste = await jsonData.json(); console.log(menuliste); visData(); skjulDetalje(); } function visData() { const skabelon = document.querySelector("template").content; const liste = document.querySelector("#liste"); liste.textContent = ""; menuliste.feed.entry.forEach(menu => { if (menu.gsx$kategori.$t == filter || filter == "alle") { const klon = skabelon.cloneNode(true); const h2 = klon.querySelector("h2"); h2.textContent = menu.gsx$navn.$t; const kort = klon.querySelector(".kort"); kort.textContent = menu.gsx$kort.$t; const pris = klon.querySelector(".pris"); pris.textContent = menu.gsx$pris.$t + " kr"; klon.querySelector("img").src = "imgs/small/" + menu.gsx$billede.$t + "-sm.jpg"; klon.querySelector(".menu").addEventListener("click", () => { visDetalje(menu); }); liste.appendChild(klon); } }) } function visDetalje(menu) { document.querySelector("#detalje").style.display = "block"; document.querySelector("#detalje .luk").addEventListener("click", skjulDetalje); document.querySelector("#detalje h2").textContent = menu.gsx$navn.$t; document.querySelector("#detalje img").src = "imgs/large/" + menu.gsx$billede.$t + ".jpg"; document.querySelector("#detalje #lang").textContent = menu.gsx$lang.$t; document.querySelector("#detalje #pris").textContent = menu.gsx$pris.$t + " kr"; } function skjulDetalje() { document.querySelector("#detalje").style.display = "none"; }
Markdown
UTF-8
1,899
3.390625
3
[]
no_license
# 知识点整理 ## 1.怎样快速寻找符合自己需求的组件思路整理 - 以下拉刷新上拉加载组件为例 - step 1:明确需求是什么 - 可以下拉刷新 - 可以上拉加载 - step 2:有哪些渠道可以找到满足需求的组件 - 官方提供 - 官方插件市场 - github - step 3:根据 step2 中的渠道,找到大概可能满足需要的若干个插件,插件必须满足以下几个条件 - 稳定,使用的开发者较多 - 组件一直在被维护更新 - 使用起来不能过于复杂,API 易懂,并且接入项目容易 - step 4:选出的插件,逐个仔细看说明文档,挨个写 Demo 测试比较 ## 2.父子组件间的互相通信与方法调用(vue) - 父组件向子组件发送信息 - 静态传值 ```html <child title="child title"></child> ``` - 动态传值 ```html <child :title="title"></child> ``` - v-bind 单向绑定值,props ```javascript export default { props: { title: { type: String, default: '' } } } ``` - v-bind 单向绑定值,\$attrs - 注意:数据从父组件传递到子组件是单向流动的,所以父级数据更新会自动流到子组件,子组件的数据一直跟父组件是一致的,且子组件不能修改父组件传递过来的值,会报错。 - 子组件向父组件发送信息 + 通过 v-on 绑定事件,子组件通知父组件变更 @msgChangeFather="msgChange" ```html <child @msgChangeChild="msgChangeFather"></child> ``` ```javascript //child.vue,发送多个参数,可以使用object this.$emit('msgChangeChild', { name: 'zhangsan', age: 23, sex: 'male' }) //使用数组返回 this.$emit('msgChangeChild', ['hello', 'world']) ```
TypeScript
UTF-8
4,350
2.65625
3
[]
no_license
/** * 下注排行 */ module main { export class BetRankView extends GYLite.GYUIComponent { private static _instance: BetRankView public static getInstance(): BetRankView { return BetRankView._instance || (BetRankView._instance = new BetRankView) } private tabBtn: TabButton private list: GYLite.GYListV private list2: GYLite.GYListV private type: any constructor() { super() const s = this s.type = 1 s.tabBtn = new TabButton s.tabBtn.x = 62 s.tabBtn.y = 92 s.addElement(s.tabBtn) let g = SkinManager.createImage(s, 220, 130, 'war_top_gold_png', URLConf.gameImg + 'w1sheet.png') let y = SkinManager.createImage(s, g.x + g.width, g.y, 'war_top_silver_png', URLConf.gameImg + 'w1sheet.png') s.list = SkinManager.createListV(s, 55, 178, 230, 376, BetRankItem) s.list.scrollerPolicy = 2 s.list2 = SkinManager.createListV(s, 55, 178, 230, 376, BetRankItem) s.list2.scrollerPolicy = 2 s.list2.visible = false s.bindEvent() } private bindEvent(): void { const s = this s.tabBtn.bindClick(s.handleTabClick, s) } private handleTabClick(type: number): void { const s = this s.type = type if (type == 1) { // 下注排行 s.list.visible = true s.list2.visible = false UtilTool.clickSound() GameModel.getInstance().getBettingRank() } else { // 上轮赢家 s.list2.visible = true s.list.visible = false UtilTool.clickSound() let lastWin = GameModel.getInstance().lastWinRank lastWin = lastWin.map(item => { return { ...item, betgold: item.wingold, betsilver: item.winsilver } }) s.updateHistoryRankList(lastWin) } } /** * 刷新列表数据 */ public updateRankList(d: any[]): void { const s = this s.list.dataProvider = d } private updateHistoryRankList(d: any[]): void { const s = this s.list2.dataProvider = d } } export class BetRankItem extends GYLite.ItemRender { private head: GYLite.GYImage private username: GYLite.GYText private money: GYLite.GYText constructor() { super() const s = this s.width = 230 s.height = 376 / 10 s.head = SkinManager.createImage(s, 0, 0, '', URLConf.gameImg + 'w1sheet.png') s.head.width = 34 s.head.height = 34 TemplateTool.setBorderRadius(s.head) s.username = SkinManager.createText(s, s.head.x + s.head.width + 2, 16, '') s.username.size = 12 s.money = SkinManager.createText(s, s.head.x + s.head.width + 110, s.username.y, '') s.money.width = 85 s.money.size = 13 s.money.textAlign = 'center' s.bindEvent() } private bindEvent(): void { const s = this s.touchEnabled = true s.addEventListener(egret.TouchEvent.TOUCH_TAP, s.handleClick, s) } private handleClick(): void { const s = this UtilTool.clickSound() MainModel.getInstance().getInfoById(s._data.userId) } public setData(d: any): void { const s = this if (!d) { s.visible = false; return; } s.visible = true; s._data = d d.avatar && (s.head.source = Main.instance.getRes(d.avatar, Conf.img + 'head.png')) let grade = UtilTool.getGrade(d.exp) s.username.htmlText = `<font color=${NickNameColor.colorSets[grade]}>${d.nickName}</font>` s.money.htmlText = `<font color=0xEFCD02>${UtilTool.formatBet(d.betgold)}</font> ${UtilTool.formatBet(d.betsilver)}` } } }
Python
UTF-8
1,402
2.875
3
[]
no_license
import sys class TreeCounter: def __init__(self): self.prev_end = '' self.tree_found = 0 self.tree_size = 0 self.nodes = set() self.act_fp = '' self.outfile = sys.stdout def finishTree(self): self.tree_found += 1 self.tree_size += len(self.nodes) self.nodes.clear() def finishFpIndex(self): if self.tree_found != 0: avg_tree_size = self.tree_size / float(self.tree_found) self.outfile.write('avg edge size %f for fp index %s\n'% (avg_tree_size, self.act_fp)) self.tree_found = 0 self.tree_size = 0 def processLine(self, line): line.rstrip() spl = line.split(' ') end = spl[-1] if end != self.prev_end: self.finishTree() self.prev_end = end fp = spl[0] if fp != self.act_fp: self.finishFpIndex() self.act_fp = fp for ind, node in enumerate(spl[1:-1]): self.nodes.add((ind, int(node), int(spl[ind + 1]))) def init(self): line.rstrip() spl = line.split(' ') self.prev_end = spl[-1] self.act_fp = spl[0] def run(self, iFileName, oFileName): f = open(iFileName, 'r') self.outfile = open(oFileName, 'r') line = f.readline() init(line) processLine(line) for line in f: self.processLine(line) f.close() if __name__ == '__main__': treeCounter = TreeCounter() treeCounter.run(sys.argv[1], sys.argv[2])
C
UTF-8
540
2.859375
3
[]
no_license
/* ** msl.c for 42sh in /home/benki/Epitech/PSU_2016_42sh/lib/others ** ** Made by Lucas Benkemoun ** Login <lucas.benkemoun@epitech.eu> ** ** Started on Mon May 15 17:34:01 2017 Lucas Benkemoun ** Last update Mon May 15 17:34:02 2017 Lucas Benkemoun */ short int msl(short int nb) { short int i; i = 0; if (nb < 0 && (nb *= -1) && i++) {} while (nb > 9) if ((nb /= 10) && ++i) {} return (++i); } long int mll(long int nb) { long int i; i = 0; if (nb < 0 && (nb *= -1) && i++) {} while (nb > 9) if ((nb /= 10) && ++i) {} return (++i); }
Ruby
UTF-8
640
3.46875
3
[ "Apache-2.0" ]
permissive
class Cipher ALPHABET = [*'a'..'z'].freeze attr_reader :key def initialize(key = Key.generate) raise ArgumentError unless Key.valid?(key) @key = key end def encode(plaintext) = shift(plaintext, :+) def decode(ciphertext) = shift(ciphertext, :-) private def shift(str, op) str.chars.map.with_index do |c, idx| alphabet_idx = ALPHABET.index(c) key_idx = ALPHABET.index(key[idx % key.size]) ALPHABET[alphabet_idx.send(op, key_idx) % ALPHABET.size] end.join end module Key def self.valid?(key) = key.match(/\A[a-z]+\z/) def self.generate = ALPHABET.sample(100).join end end
Java
UTF-8
1,927
2.28125
2
[]
no_license
package ru.haqon.layout.activities; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.text.SimpleDateFormat; import ru.haqon.resistor.logic.OhmStringFormatter; import ru.haqon.R; import ru.haqon.data.AppSQLiteDBHelper; import ru.haqon.data.models.HistoryModel; public class HistoryActivity extends AppCompatActivity { private TableLayout _table; private OhmStringFormatter _formatter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _formatter = new OhmStringFormatter(this); setContentView(R.layout.activity_history); initHistoryTableAndLoadRows(); } private void initHistoryTableAndLoadRows() { _table = (TableLayout) findViewById(R.id.table); AppSQLiteDBHelper db = new AppSQLiteDBHelper(this.getApplicationContext()); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); for (HistoryModel model : db.selectHistoryTableInDateDesc()) { TableRow row = (TableRow) LayoutInflater.from(HistoryActivity.this).inflate(R.layout.table_row_template, null); ((TextView) row.findViewById(R.id.tableHistoryDate)).setText(sdf.format(model.getDate())); ((TextView) row.findViewById(R.id.tableHistoryValue)).setText(_formatter.format(model.getValueInOhm())); _table.addView(row); } _table.requestLayout(); } public void btnClearTableOnClick(View view) { AppSQLiteDBHelper db = new AppSQLiteDBHelper(this.getApplicationContext()); db.deleteHistoryTableData(); _table.removeViews(1, Math.max(0, _table.getChildCount() - 1)); } }
C#
UTF-8
1,101
2.96875
3
[]
no_license
using System; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; namespace ABMath.IridiumExtensions { public static class TDistributionExtensions { /// <summary> /// returns max. likelihood estimator of scale factor for t-dn, assuming mean of data is zero /// </summary> /// <param name="dn"></param> /// <param name="data">data to be used</param> /// <returns></returns> public static double MLEofSigma(this StudentT dn, Vector<double> data) { double sd2 = VectorExtensions.Variance(data); int n = data.Count; int dof = (int)dn.DegreesOfFreedom; // now use iterative recursion for (int iteration = 0; iteration < 20; ++iteration) { double sum = 0.0; for (int i = 0; i < n; ++i) sum += sd2*data[i]*data[i]/(sd2*dof + data[i]*data[i]); sd2 = (dof + 1)*sum/n; } return Math.Sqrt(sd2); } } }
Markdown
UTF-8
397
2.59375
3
[]
no_license
# Flutter Dashboard A standalone dashboard which shows your day at a glance. This program will be running 24/7 on a monitor and works similar to how smart mirrors have been implemented. ![Dashboard UI](/Dashboard_Layout_7-27-2020.png) With a modular design, different elements of the dashboard can be added/removed and users can log in through a google account to access personalized features.
PHP
UTF-8
4,834
2.671875
3
[]
no_license
<?php namespace HtmlForm\tests; use HtmlForm\Form; class FormTest extends Base { /** * @var Form */ protected $testClass; /** * @var array[] */ private $mocks; /** * Set up before every test */ public function setUp() { $this->testClass = new Form(); parent::setUp(); $this->mocks = array( "textbox" => $this->getMock("\\HtmlForm\\Elements\\Textbox", array("compileLabel"), array("name", "label", array( "beforeElement" => "<div class=\"before\">", "afterElement" => "</div>", "defaultValue" => "default" ))) ); } public function testBuildAction() { } public function testSetConfigWithNoUserConfig() { $given = array(); $expected = array( "method" => "post", "action" => "index.php?test=aha", "id" => "hfc", "repopulate" => true, "attr" => array(), "beforeElement" => "", "afterElement" => "" ); $method = $this->getMethod("setConfig"); $method->invoke($this->testClass, $given); $this->assertEquals($expected, $this->getProperty("config")); } public function testSetConfigWithData() { $given = array( "action" => "otherPage.php", "method" => "get" ); $expected = array( "method" => "get", "action" => "otherPage.php", "id" => "hfc", "repopulate" => true, "attr" => array(), "beforeElement" => "", "afterElement" => "" ); $method = $this->getMethod("setConfig"); $method->invoke($this->testClass, $given); $this->assertEquals($expected, $this->getProperty("config")); } public function testBeforeElement() { $method = $this->getMethod("beforeElement"); $beforeElement = $method->invoke($this->testClass, $this->mocks["textbox"]); $this->assertEquals("<div class=\"before\">", $beforeElement); } public function testAfterElement() { $method = $this->getMethod("afterElement"); $afterElement = $method->invoke($this->testClass, $this->mocks["textbox"]); $this->assertEquals("</div>", $afterElement); } public function testAddHoneypot() { } public function testAddFieldset() { } public function testIsValid() { } public function testPassedHoneypot() { } public function testSetErrorMessage() { $given = "My custom error."; $this->testClass->setErrorMessage($given); $validator = $this->getProperty("validator"); $this->assertContains($given, $validator->errors); } public function testSaveToSession() { } public function testGetValue() { $method = $this->getMethod("getValue"); // if nothing set $result = $method->invoke($this->testClass, $this->mocks["textbox"]); $this->assertEquals("default", $result); // if set in $_POST $_POST["name"] = "hi"; $result = $method->invoke($this->testClass, $this->mocks["textbox"]); $this->assertEquals("hi", $result); // if set in $_SESSION $this->setProperty("config", array("id" => "testing")); $_SESSION["testing"]["name"] = "hello"; $result = $method->invoke($this->testClass, $this->mocks["textbox"]); $this->assertEquals("hello", $result); } public function testCleanValue() { $method = $this->getMethod("cleanValue"); $given = "Something\'s gotta give"; $expected = stripslashes($given); $result = $method->invoke($this->testClass, $given); $this->assertEquals($expected, $result); $given = array($given); $expected = array($expected); $result = $method->invoke($this->testClass, $given); $this->assertEquals($expected, $result); } public function testDisplay() { } public function testRender() { } public function testGetOpeningTag() { } public function testGetClosingTag() { $method = $this->getMethod("getClosingTag"); $result = $method->invoke($this->testClass); $this->assertEquals("</form>", $result); } public function testRenderElementsWithAddable() { // add fieldset $fieldset = new \HtmlForm\Fieldset("The Legend"); $fieldset->elements[] = new \HtmlForm\Elements\Textbox("firstName", "first name", array( "required" => true, "beforeElement" => "<div class=\"form_field clearfix\">", "afterElement" => "</div>" )); $this->setProperty("elements", array($fieldset)); $expected = "<form method=\"post\" action=\"index.php?test=aha\" id=\"hfc\" ><fieldset><legend>The Legend</legend><div class=\"form_field clearfix\"><label for=\"firstName\">* first name</label><input type=\"text\" name=\"firstName\" value=\"\" /></div></fieldset></form>"; $method = $this->getMethod("renderElements"); $result = $method->invoke($this->testClass, $this->testClass); $this->assertEquals($expected, $result); } public function testRenderElementsWithoutAddable() { $this->setExpectedException('PHPUnit_Framework_Error'); //type hinted $method = $this->getMethod("renderElements"); $method->invoke($this->testClass, array()); } }
Java
UTF-8
778
2.9375
3
[]
no_license
package atividade; import java.io.Serializable; /** * * @author davi * */ public class Resultado implements Serializable { /** * */ private String resultado; /** * */ private int id; public Resultado(String resultado, int id) { this.resultado = resultado; this.id = id; } @Override public String toString() { return resultado; } @Override public boolean equals(Object obj) { if (obj != null && obj instanceof Resultado) { Resultado r = (Resultado) obj; if (this.getResultado().equals(r.getResultado())) { return true; } } return false; } @Override public int hashCode() { return this.getResultado().hashCode(); } public int getId() { return id; } public String getResultado() { return resultado; } }
Python
UTF-8
202
2.78125
3
[ "MIT" ]
permissive
import random # this line is needed for us to check the results, don't modify it please random.seed(int(input())) # use a function from the random module in the next line print(random.randint(1, 6))
JavaScript
UTF-8
741
2.671875
3
[]
no_license
(function () { 'use strict'; angular.module('LunchCheck', []) .controller('LunchCheckController', LunchCheckController); LunchCheckController.$inject = ['$scope','$filter']; function LunchCheckController($scope, $filter) { $scope.arrayFood = ""; $scope.message=""; $scope.sayMessage = function () { var arrayOfStrings = $scope.arrayFood.split(','); var arrayLength = arrayOfStrings.length; if (arrayLength < 4 && arrayLength != 1){ $scope.message = "Enjoy!"; } else if (arrayLength == 1) { if($scope.arrayFood.trim() == ""){ $scope.message = "Please enter data first" ; }else { $scope.message = "Enjoy!" ; } } else { $scope.message = "Too Much!"; } }; } })();
C++
GB18030
848
4.125
4
[]
no_license
/* һ numsдһ 0 ƶĩβͬʱַԪص˳ ʾ: : [0,1,0,3,12] : [1,3,12,0,0] ˵: ԭϲܿ顣 ٲ */ #include <iostream> #include <vector> using namespace std; //0Ԫǰ void moveZeroes(vector<int>& nums) { int len = nums.size(); if (!len || len == 1) return; int k = 0; for (int i = 0; i < len; i++) { if (nums[i] != 0) nums[k++] = nums[i]; } while (k < len) { nums[k++] = 0; } } int main() { vector<int> nums; int n; while (cin >> n) { nums.push_back(n); if (cin.get() == '\n') break; } moveZeroes(nums); for (int i = 0; i < nums.size(); i++) { cout << nums[i] << ' '; } cout << endl; system("pause"); return 0; }
Java
UHC
499
3.859375
4
[]
no_license
package msa01; /* * logical operator : * && (and - T϶ T)& * || (or - ϳ T̸ T)| * ! (not - T̸ F, F̸ T)~ * ^ (XOR - ̸ F, ٸ̸ T)^ * */ public class OpTest4 { public static void main(String[] args) { boolean r1 = 10>=10; //T boolean r2 = 100==10; //F System.out.println(r1 && r2); //F System.out.println(r1 || r2); //T System.out.println(!r1); //F System.out.println(r1^r2); //T } }
Python
UTF-8
1,776
2.5625
3
[]
no_license
# encoding:utf-8 from winreg import * import sys usb_name = [] uid_flag = [] usb_path = [] #连接注册表根键 以HKEY_LOCAL_MACHINE为例 regRoot = ConnectRegistry(None, HKEY_LOCAL_MACHINE) #检索子项 subDir = r"SYSTEM\CurrentControlSet\Enum\USBSTOR" #获取指定目录下所有键的控制 keyHandle = OpenKey(regRoot, subDir) #获取该目录下所有键的个数(0-下属键个数 1-当前键值个数) count = QueryInfoKey(keyHandle)[0] print(count) #穷举USBSTOR键获取键名 for i in range(count): subKeyName = EnumKey(keyHandle, i) subDir_2 = r'%s\%s' % (subDir, subKeyName) #print(subDir_2) #根据获取的键名拼接之前的路径作为参数 获取当前键下所属键的控制 keyHandle_2 = OpenKey(regRoot, subDir_2) num = QueryInfoKey(keyHandle_2)[0] #遍历子键内容 for j in range(num): subKeyName_2 = EnumKey(keyHandle_2, j) #print(subKeyName_2) result_path = r'%s\%s' % (subDir_2, subKeyName_2) #获取具体键值内容并判断Service为disk keyHandle_3 = OpenKey(regRoot, result_path) numKey = QueryInfoKey(keyHandle_3)[1] for k in range(numKey): #获取USB名称 name, value, type_ = EnumValue(keyHandle_3, k) if(('Service' in name) and ('disk'in value)): value,type_ = QueryValueEx(keyHandle_3,'FriendlyName') usb = value uid = subKeyName_2 path = "USBSTOR" + "\\" + subKeyName + "\\" + subKeyName_2 print(usb) print(uid) print(path) print("") #关闭键值 CloseKey(keyHandle) CloseKey(regRoot)
Java
UTF-8
266
2.5625
3
[]
no_license
package com.itvdn.homework.javaessential.lesson3.task3; public class Car extends Vehicle { public Car(double latitude, double longitude, int price, int speed, int yearOfProduction) { super(latitude, longitude, price, speed, yearOfProduction); } }
Java
UTF-8
372
2.21875
2
[]
no_license
/* ***************************************************************************** * @Author: phd * @Date: 2018/9/8 * @Site: github.com/phdsky * @Description: NULL **************************************************************************** */ public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
C#
UTF-8
14,089
2.59375
3
[]
no_license
using Dragnet.Constants; using Dragnet.DataObjects; using Dragnet.IRepository; using Dragnet.Models; using System; using System.Collections.Generic; using System.Data; using System.Text; namespace Dragnet.Repository { public class PersonManagement : CommonMethods, IPerson { IDBManager dbManager = null; public List<Person> GetCommiteLevel() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> CommitteeLevelList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id ,LevelofOrganizationName from LevelofOrganization order by LevelofOrganizationName"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), OccupationName = dr["OccupationName"] == DBNull.Value ? " " : dr["OccupationName"].ToString(), OccuAbbrevation = dr["OccupationAbbrevation"] == DBNull.Value ? " " : dr["OccupationAbbrevation"].ToString(), }; CommitteeLevelList.Add(person); } dr.Close(); return CommitteeLevelList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetCommitteeCadre() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> CommitteeCadreList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id,committeeCadreName from committeecadre order by committeeCadreName"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), CommitteCadreName = dr["committeeCadreName"] == DBNull.Value ? " " : dr["committeeCadreName"].ToString() }; CommitteeCadreList.Add(person); } dr.Close(); return CommitteeCadreList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetDistricts() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> DistrictsList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select id,District_commissionerate,Tracking from District_Commissionerate"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), DistrictCommissionerate = dr["District_commissionerate"] == DBNull.Value ? " " : dr["District_commissionerate"].ToString(), Tracking = dr["Tracking"] == DBNull.Value ? " " : dr["Tracking"].ToString() }; DistrictsList.Add(person); } dr.Close(); return DistrictsList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetEducationQualification() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> EduQuaList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select * from EducationQualification order by EducationQualification"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), EducationQualification = dr["EducationQualification"] == DBNull.Value ? " " : dr["EducationQualification"].ToString() }; EduQuaList.Add(person); } dr.Close(); return EduQuaList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetMarialStatus() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> MaritalStatusList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id,MaritalStatusName from PersonMaritalStatus"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), MaritalStatusName = dr["MaritalStatusName"] == DBNull.Value ? " " : dr["MaritalStatusName"].ToString() }; MaritalStatusList.Add(person); } dr.Close(); return MaritalStatusList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetOccupation() { throw new NotImplementedException(); } public List<Person> GetOrgName() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> OrgNameList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id,OrganizationName from OrganizationDetails order by OrganizationName"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), OrgName = dr["OrganizationName"] == DBNull.Value ? " " : dr["OrganizationName"].ToString() }; OrgNameList.Add(person); } dr.Close(); return OrgNameList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetOrgTypes() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> OrgTypeList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.StoredProcedure, "getMasters_addActivity"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), TypeofOrganization = dr["TypeofOrganization"] == DBNull.Value ? " " : dr["Religion"].ToString() }; OrgTypeList.Add(person); } dr.Close(); return OrgTypeList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetPersonType() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> personTypeList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id,PersonType from PersonTypes order by PersonType"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), PersonType = dr["PersonType"] == DBNull.Value ? " " : dr["PersonType"].ToString() }; personTypeList.Add(person); } dr.Close(); return personTypeList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetPoliceStations() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> PoliceStationList = new List<Person>(); try { dbManager.Open(); dbManager.CreateParameters(1); dbManager.AddParameters(0, "@orgID", GetDBNullOrValue(1), ParameterDirection.Input, DaoConstants.InParamSize); dr = dbManager.ExecuteReader(CommandType.StoredProcedure, "SelectPSByOrgID"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), PoliceStation = dr["PoliceStation"] == DBNull.Value ? " " : dr["PersonType"].ToString() }; PoliceStationList.Add(person); } dr.Close(); return PoliceStationList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } public List<Person> GetReligion() { if (dbManager == null) dbManager = new DBManager(); IDataReader dr = null; Person person = null; List<Person> ReligionList = new List<Person>(); try { dbManager.Open(); dr = dbManager.ExecuteReader(CommandType.Text, "select Id,Religion from Religions order by Religion"); while (dr.Read()) { person = new Person() { ID = dr["Id"] == DBNull.Value ? default(int) : Convert.ToInt32(dr["Id"]), Religion = dr["Religion"] == DBNull.Value ? " " : dr["Religion"].ToString() }; ReligionList.Add(person); } dr.Close(); return ReligionList; } catch (Exception ex) { if (dr != null) dr.Close(); return null; } finally { if (dr != null) dr.Close(); dbManager.Dispose(); dbManager = null; } } } }
C
ISO-8859-10
4,789
2.59375
3
[]
no_license
#include "tipos.h" #include "color.h" #include "clientes.h" #ifndef BICICLETAS_H_INCLUDED #define BICICLETAS_H_INCLUDED typedef struct { int id; char marca[20]; int idTipo; int idColor; int idCliente; float rodado; int isEmpty; bClientes clientes; }bBicicleta; #endif // BICICLETAS_H_INCLUDED char menu(); /** \brief menu de opciones de gestion de bicicletas */ int altaBicicleta(bBicicleta bicicletas[], int tam_b, bTipos tipos[], int tam_t, bColores colores[], int tam_c, int idBici, int idCliente); /** \brief permite al usuario ingresar datos y dar de alta bicicleta * \param bicicletas[] bBicicleta estructura, array bicicleta * \param tam_b int tamao del array bicicletas * \param colores[] bColores estructura, vector colores * \param tam_c int tamao del array colores * \param rodado[] bBicicleta array rodado de bicicleta * \param tipos[] bTipos estructura, array tipos * \param tam_t int tamao del array tipos * \param clientes[] bClientes array clientes * \param tam_cl int tamao del array clientes * \return int devuelve si esta ok */ int initBicicletas(bBicicleta bicicletas[], int tam_b); /** \brief inicializa el array de la estructura en 0 * \param bicicletas[] bBicicleta estructura, array bicicleta * \param tam_b int tamao del array bicicletas * \return int devuelve si esta ok */ int modificarBicicleta(bBicicleta bicicletas[],int tam_b,bColores colores[],int tam_c, bBicicleta rodado[], bTipos tipos[],int tam_t, bClientes clientes[], int tam_cl); /** \brief permite modificar una bicicleta ingresada * \param bicicletas[] bBicicleta campo array de estructura bicicleta * \param tam_b int tamao array bicicletas * \param colores[] bColores campo array de estructura colores * \param tam_c int tamao de array colores * \param rodado[] bBicicleta rodados * \param tipos[] bTipos estructura,array tipos * \param tam_t int tama0 de array tipos * \param clientes[] bClientes campo array de estructura clientes * \param tam_cl int tamao del array clientes * \return int devuelve si esta ok */ int buscarBicicleta(bBicicleta bicicletas[],int tam_b,int idBici); /** \brief busca lugar bicicleta * \param bicicletas[] bBicicleta estructura, campo bicicleta * \param tam_b int tamanio del vector bicicleta * \param idBici int id de la bicicleta * \return int retorna si esta ok */ void mostrarBicicleta(bBicicleta bicicletas, bTipos tipos[],int tam_t,bColores colores[], int tam_c, bClientes clientes[], int tam_cl); /** \brief muestra una bicicleta * \param bicicletas bBicicleta estructura, campo bicicleta * \param tipos[] bTipos campo array de estructura tipos * \param tam_t int tamao del array * \param colores[] bColores campo array de estructura colores * \param tam_c int tamao array colores * \param clientes[] bClientes campo array de estructura clientes * \param tam_cl int tamo de array clientes * \return void no retorna nada */ int mostrarBicicletas(bBicicleta bicicletas[], int tam_b, bColores colores[], int tam_c, bTipos tipos[], int tam_t, bClientes clientes[], int tam_cl); /** \brief muestra todas las bicicletas ingresadas por el usuario * \param bicicletas[] bBicicleta campo array de estructura bicicleta * \param tam_b int tamao de array bicicletas * \param colores[] bColores campo array de estructura colores * \param tam_c int tamao array colores * \param tipos[] bTiposcampo array de estructura tipos * \param tam_t int tamao array tipos * \param clientes[] bClientes campo array de estructura clientes * \param tam_cl int tamao array clientes * \return int retorna si esta ok */ int bajaBicicleta(bBicicleta bicicletas[],int tam_b,bTipos tipos[], int tam_t, bColores colores[],int tam_c, bClientes clientes[],int tam_cl); /** \brief le permite al usuario dar de baja una bicicleta ingresada * \param bicicletas[] bBicicleta campo array de estructura bicicleta * \param tam_b int tamao array bicicletas * \param tipos[] bTipos campo array de estructura tipos * \param tam_t int tamao array tipos * \param colores[] bColores campo array de estructura colores * \param tam_c int tamao array colores * \param clientes[] bClientes campo array de estructura clientes * \param tam_cl inttamao array clientes * \return int retorna si esta ok */ void ordenarBicicletas(bBicicleta bicicletas[], int tam_b, bTipos tipos[], int tam_t, bColores colores[], int tam_c); /** \brief ordena las bicicletas * \param bicicletas[] bBicicleta * \param tam_b int tamao array bicicletas * \param tipos[] bTipos campo array de estructura tipos * \param tam_t int tamao array tipos * \param colores[] bColores campo array de estructura colores * \param tam_c inttamao array colores * \return void no retorna */
C++
UTF-8
1,395
3.546875
4
[]
no_license
// https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal #include <algorithm> #include<vector> using namespace std; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { private: TreeNode* helper(vector<int>::iterator pre_start, vector<int>::iterator pre_end, vector<int>::iterator in_start, vector<int>::iterator in_end ) { if (pre_start == pre_end || in_start == in_end) return nullptr; auto root_val = *pre_start; auto root = new TreeNode(root_val); auto root_it = find(in_start,in_end,root_val); auto offset = distance(in_start,root_it); root->left = helper(pre_start+1,pre_start+1+offset,in_start,root_it); root->right = helper(pre_start+1+offset,pre_end,root_it+1,in_end); return root; } public: TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return helper(preorder.begin(),preorder.end(),inorder.begin(),inorder.end()); } };
Java
UTF-8
588
2.015625
2
[]
no_license
package com.del.command; import lombok.Data; @Data public class Contact { private Integer cid; private String name; private String email; private String phno; public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhno() { return phno; } public void setPhno(String phno) { this.phno = phno; } }
Java
UTF-8
3,172
3.265625
3
[]
no_license
package com.example.jiteshvartak.onlinetestalgorithmspractice;/* IMPORTANT: Multiple classes and nested static classes are supported */ /* * uncomment this if you want to read input. //imports for BufferedReader import java.io.BufferedReader; import java.io.InputStreamReader; */ //import for Scanner and other utility classes import java.util.*; class PrimeGoodBad { public static void main(String args[] ) throws Exception { /* * Read input from stdin and provide input before running * Use either of these methods for input //BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int N = Integer.parseInt(line); */ //Scanner Scanner s = new Scanner(System.in); int T = s.nextInt(); int pl[]= {2, 3,5,7,11,13,17,19 , 23}; for (int x = 0; x < T; x++) { int H = s.nextInt(); int M = s.nextInt(); int S = s.nextInt(); int good = 0; int bad = 0; for(int i = S ; i< 60;i++){ boolean isDiv = false; for(int j=0;j<pl.length;j++){ if(H % pl[j] ==0 && M % pl[j]==0 && i % pl[j] ==0 ){ bad ++; isDiv = true; break; } } if(!isDiv){ good++; } } for(int i = M + 1;i<60;i++){ for(int j = 0;j<60;j++){ boolean isDiv = false; for(int k = 0;k<pl.length;k++){ if(H % pl[k] ==0 && i % pl[k]==0 && j % pl[k] ==0 ){ bad ++; isDiv = true; break; } } if(!isDiv){ good++; } } } for(int i = H + 1;i<24;i++){ for(int j=0;j<60;j++){ for(int k=0;k<60;k++){ boolean isDiv = false; for(int l =0;l<pl.length;l++){ if(i % pl[l] ==0 && j % pl[l]==0 && k % pl[l] ==0 ){ bad ++; isDiv = true; break; } } if(!isDiv){ good++; } } } } print(bad +":"+good); } } static void print(String str){ System.out.println(str); } }
Markdown
UTF-8
4,003
3.40625
3
[ "MIT" ]
permissive
# Step 0: Install tools For both macOS and Windows - follow the instructions [here](https://github.com/Codexpanse/workshops/blob/master/level_1/steps.md). # Step 1: Internet vs Web - The Internet is the network of networks ([wiki](https://en.wikipedia.org/wiki/Internet) - The web is the est of apps that use the Internet for communication - This communication often uses [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol), a special language for communication (do not confuse with a programming language) - web clients send HTTP requests to web servers - web servers send HTTP responses back ![](https://i.imgur.com/1uarUI0.png) **[⬇ Download this PDF cheatsheet an HTTP ⬇](https://rakhim.org/ce/HTTP_notes_diagram_1.pdf)** # Step 2: Netcat client ## Make a HTTP request via netcat. ### Windows 1. Run `cmder` installed in the previous step. ### macOS 1. Launch `Terminal.app` ### Make a connection Type: ``` nc 127.0.0.1 8080 Host: localhost ``` Hit `Enter` twice in the end. ![](https://i.imgur.com/b8ANTXs.png) **[⬇ Download this PDF cheatsheet an HTTP ⬇](https://rakhim.org/ce/HTTP_notes_diagram_2.pdf)** (If you're on macOS High Sierra or Mojave, type `nc` instead of `telnet`.) # Step 3: Basics of Python Try out Python on [https://repl.it](https://repl.it). Login and choose "Python". Enter code in the right pane, hit `Run`. ```python # numbers 2 + 3 # print something onto the screen print("Something") # True, False and conditions cloudy = True if cloudy: print("Take umbrella!") else: print("Relax") # strings as variables cloudy = True message_1 = "Take umbrella!" message_2 = "Relax!" if cloudy: print(message_1) else: print(message_2) # concatenation (glue) name = "Jake" print(message_1 + name) # input name = input("What's your name? ") print(message_1 + name) ``` # Step 4: Create a simple HTTP server Even a simple HTTP server, which consists of just 4 lines of code, is a pretty complex program. Each line includes tens and tens of different concepts. One way to go — a classic, “proper” way — is to start with the basics of Python and make our way up the ladder of difficulty. We’d need to learn about variables, modules, importing, TCP, handlers, with-statements and command line arguments. It’s quite a list, and each concept requires you to at least gave some idea about a dozen more. It’ll take us a few days or even weeks! Another way to go is to just give you those 4 lines to copy and paste and hope it works. You’ll have no idea what’s happening, but the HTTP server will probably be launched successfully. I believe there’s the third way. I will indeed give you 4 lines of code to copy and paste. But this is a loan, not a gift. You’ll have to pay back! In the next workshops we will look back and cover the missing parts. I call this a “learning credit card”. We’ll always jump ahead and do something cool, but then at some point we’ll come back and “pay the debt”. As long as we’re disciplines and don’t take too many “knowledge loans”, we’ll be fine and it’ll be fun! Here is the code: ```python import http.server import socketserver host = "localhost" port = 8080 server = socketserver.TCPServer((host, port), http.server.SimpleHTTPRequestHandler) print("Server started...") server.serve_forever() ``` Save this file as `server.py` in a folder called `server` on your Desktop, navigate to that folder in the Terminal: ### Windows Assuming your folder is saved on the Desktop, in the Terminal type `cd C:\Users\YOUR_USERNAME\Desktop\server` Don’t forget to change `YOUR_USERNAME` to your actual username. ### macOS Assuming your folder is saved on the Desktop, type `cd /Users/YOUR_USERNAME/Desktop/server` in the Terminal. ## Then run the server ### Windows ``` py server.py ``` ### macOS ``` python3 server.py ``` # Step 5: Back to the client Now you repeat the HTTP request using the netcat app. You should see a response.
JavaScript
UTF-8
1,134
2.78125
3
[]
no_license
import React, { Component } from 'react'; class NewTask extends Component { constructor(props) { super(props); this.state = { userInput: "" } this.handleChange = this.handleChange.bind(this); this.handleButton = this.handleButton.bind(this); } handleChange( input ) { this.setState( { userInput: input }, () => { console.log( input ) } ); } handleButton() { this.props.add( this.state.userInput ); this.setState( { userInput: '' } ); } render() { return ( <div> <div> <input type={ "text" } value={ this.state.userInput } onChange={ (e) => { this.handleChange( e.target.value ) } } placeholder={ "Add your todo" } size={ 40 } maxLength={ 35 } /> </div> <div> <button onClick={ this.handleButton }>Add</button> </div> </div> ); } } export default NewTask;
Java
UTF-8
1,341
2.890625
3
[]
no_license
package me.lemon.timer.util; import java.awt.*; import java.awt.image.BufferedImage; public class ScreenUtil { private static Robot robot; public static BufferedImage captureFullScreen(int screenNumber) { try { Rectangle screenRect = new Rectangle(0, 0, 0, 0); if(screenNumber == -1) { for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) { screenRect = screenRect.union(gd.getDefaultConfiguration().getBounds()); } } else { screenRect = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[screenNumber].getDefaultConfiguration().getBounds(); } return robot.createScreenCapture(screenRect); } catch(Exception e) { return null; } } public static BufferedImage captureAreaOfScreen(Rectangle area, int screenNumber) { try { Rectangle screenRect = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[screenNumber].getDefaultConfiguration().getBounds(); Rectangle desiredRect = new Rectangle((int) (screenRect.getX() + area.getX()), (int) (screenRect.getY() + area.getY()), (int) (area.getWidth()), (int) (area.getHeight()) ); return robot.createScreenCapture(desiredRect); } catch(Exception e) { return null; } } static { try { robot = new Robot(); } catch(Exception e) {} } }
JavaScript
UTF-8
1,662
2.828125
3
[ "MIT" ]
permissive
import {NEW_QUOTE} from './actions' const QUOTES = [ {quote: 'You can’t turn back the clock. But you can wind it up again.', author:'Bonnie Prudden'}, {quote: 'The bad news is time flies. The good news is you’re the pilot.', author: 'Michael Altshuler'}, {quote: 'I will always choose a lazy person to do a difficult job because he will find an easy way to do it.', author: 'Ziad K. Abdelnour'}, {quote: 'The best way to appreciate your job is to imagine yourself without one.', author: 'Oscar Wilde'}, {quote: 'Expecting the world to treat you fairly because you are a good person is a little like expecting the bull not to attack you because you are a vegetarian.', author: 'Dennis Wholey'}, {quote: 'Light travels faster than sound. This is why some people appear bright until you hear them speak.', author: 'Alan Dundes'}, {quote: 'The difference between stupidity and genius is that genius has its limits.', author: 'Albert Einstein'}, {quote: 'I am not in competition with anyone but myself. My goal is to improve myself continuously.', author: 'Bill Gates'}, {quote: 'If you\'re not careful, the newspapers will have you hating the people who are being oppressed, and loving the people who are doing the oppressing.', author: 'Malcolm X'}, {quote: 'You dont lose if you get knocked down; you lose if you stay down.', author: 'Muhammad Ali'} ] export const quoteReducer = (state = {id: 0, quotes: QUOTES}, action) => { const rand = Math.floor( Math.random()*QUOTES.length); switch (action.type) { case NEW_QUOTE: return { id: rand, quotes: QUOTES }; default: return state; } }
Markdown
UTF-8
731
2.609375
3
[ "MIT" ]
permissive
--- title: Chủ nghĩa Hư vô UID: 210831220447 created: Dec 28, 2020 9:48 PM tags: - '#created/2020/Dec/28' - '#seed🥜' - '#permanent/concept' aliases: - Nihilism --- # Chủ nghĩa Hư vô ## Notes: Chủ nghĩa hư vô (Nihilism) là chủ nghĩa phủ nhận giá trị, ý nghĩa của cuộc sống. Thế giới này là vô nghĩa, hư vô vì nó được ngẫu nhiên được tạo ra. Thế giới này được tạo thành một cách ngẫu nhiên trong một vũ trụ bao la này, không có ý nghĩa vĩnh cửu nào. Con người ta tồn tại cũng do ngẫu nhiên. ## Ideas & thoughts: ## Questions: ## Tham khảo: ```dataview list from [[Chủ nghĩa Hư vô]] sort file.name asc ```
Go
UTF-8
2,850
2.515625
3
[ "BSD-3-Clause" ]
permissive
// Simon is an implementation of the memory game for children. package main import ( "image" "log" "math/rand" "time" "golang.org/x/exp/shiny/driver" "golang.org/x/exp/shiny/imageutil" "golang.org/x/exp/shiny/materialdesign/colornames" "golang.org/x/exp/shiny/screen" "golang.org/x/mobile/event/key" "golang.org/x/mobile/event/lifecycle" "golang.org/x/mobile/event/mouse" "golang.org/x/mobile/event/paint" "golang.org/x/mobile/event/size" ) func init() { rand.Seed(time.Now().UnixNano()) } var ( inset = 1 sz image.Rectangle game *Game pict *Picture ) func main() { driver.Main(func(s screen.Screen) { options := &screen.NewWindowOptions{Width: 350, Height: 350} window, err := s.NewWindow(options) if err != nil { log.Fatal(err) } defer window.Release() for { e := window.NextEvent() switch e := e.(type) { case mouse.Event: if e.Button != mouse.ButtonLeft { continue } if game == nil || game.Player() { pt := image.Pt(int(e.X)-inset, int(e.Y)-inset) if pe, ok := pict.PlayerEvent(pt); ok { window.Send(pe) } } case PlayerEvent: pict.DrawEvent(e) window.Send(paint.Event{}) if game == nil { if e.Center() { game = new(Game) window.Send(ErrGameTurn) } } else if e.Up { if err := game.Play(e.Color()); err != nil { window.Send(err) } if !game.Player() { window.Send(ErrGameTurn) } } case ErrBadColor: window.Send(NewLostEvent(e.Want)) case LostEvent: time.Sleep(100 * time.Millisecond) pict.DrawEvent(e) window.Send(paint.Event{}) if e.Up { e.Count++ } if e.Count < 3 { e.Up = !e.Up window.Send(e) } case error: switch e { case ErrGameTurn: if c, err := game.Display(); err != nil { window.Send(err) } else { window.Send(NewGameEvent(c)) } case ErrGameOver: game = nil } case GameEvent: time.Sleep(300 * time.Millisecond) pict.DrawEvent(e) window.Send(paint.Event{}) if e.Down() { e.Up = true window.Send(e) } else { window.Send(ErrGameTurn) } case size.Event: if pict != nil { pict.Release() } sz = e.Bounds() var err error pict, err = NewPicture(sz.Inset(inset), s) if err != nil { log.Fatal(err) } pict.Draw() case paint.Event: for _, r := range imageutil.Border(sz, inset) { window.Fill(r, colornames.White, screen.Src) } rect := sz.Inset(inset) dp := image.Pt(rect.Min.X, rect.Min.Y) window.Copy(dp, pict.Texture(), pict.Bounds(), screen.Src, nil) window.Publish() case key.Event: if e.Code == key.CodeEscape { return } case lifecycle.Event: if e.To == lifecycle.StageDead { return } } } }) }
Markdown
UTF-8
3,409
3.578125
4
[]
no_license
# 二叉树的最近公共祖先 ### 信息卡片 - 时间: 2020-1-13 - 题目链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/er-cha-shu-de-zui-jin-gong-gong-zu-xian-by-leetcod/ - 难度:中等 - 题目描述: ``` 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4] 示例 1: 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 输出: 3 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 示例 2: 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 输出: 5 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 说明: 所有节点的值都是唯一的。 p、q 为不同节点且均存在于给定的二叉树中。 ``` ### 参考答案 > 思路 深度遍历+回溯递归。以要找的节点分别为p和q为例: 首先分析公共祖先一共可以分为以下三种情况: - 如果一个节点的左右都能达到终点,那么当前节点一定是公共祖先。 - 如果当前节点左树可以找到一个值,当前节点值等于另一个值,那么祖先也就是当前值。 - 如果当前节点右树可以找到一个值,当前节点值等于另一个值,那么祖先也一定就是当前值。 这三种情况用代码表示就是: - left=1,right=1,mid=0 - left=1,right=0,mid=1 - left=0,right=2,mid=1 left表示向左子树递归是否能找到通向p/q,能找到赋值1,不能的话赋值0 right表示向右子树递归是否能找到通向p/q,能找到赋值1,不能的话赋值0 mid表示当前节点是否等于p/q,等于的话赋值1,不等于赋值0 所以用代码表示就是: ``` if (mid + left + right == 2) { this.ans = currentNode; } ``` 即只要其中两个值=1当前节点便是公共祖先节点。 以p=11,q=9,root=1为例: 这时left=2,left一直向下递归,发现左子树可以找到9,右子树可以找到11,所以2就是公共祖先。 ![5.7](..\assets\5.7.png) > 代码 ```js /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { TreeNode res = null; public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { help(root,p,q); return res; } public int help(TreeNode root,TreeNode p, TreeNode q){ if(root == null) return 0; int left = help(root.left,p,q); int right = help(root.right,p,q); int mid = (root == p || root == q) ? 1 : 0; if(left + right + mid >= 2){ res = root; return 1; } if(left + right + mid > 0){ return 1; } return 0; } } ``` ### 其他优秀解答 > 暂无
C
UTF-8
3,423
2.765625
3
[]
no_license
#include "../../src/usb1352.h" #include <time.h> #include <errno.h> typedef struct test_frame { uint8_t type; uint16_t seq; uint8_t tx_addr; uint8_t rx_addr; uint8_t length; char payload[190]; } test_frame; pthread_cond_t transfer_cond; pthread_mutex_t transfer_mutex; void* tx_thread(void* dev) { usb1352_dev* p_dev = (usb1352_dev*)dev; test_frame frame; FILE* img; int count; uint16_t seq; int start; struct timespec transfer_clock; img = fopen("wakgood_slave.jpg", "rb"); scanf("%d", &start); if (start == 123) { frame.type = 1; frame.seq = seq; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &frame); seq = 0; printf("start\n"); } usleep(1000000); while (1) { count = fread(frame.payload, 1, 190, img); if (count < 190) { if (feof(img) != 0) { frame.type = 3; frame.seq = seq; frame.length = count; while (1) { clock_gettime(CLOCK_REALTIME, &transfer_clock); transfer_clock.tv_sec += 1; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &frame); if (pthread_cond_timedwait(&transfer_cond, &transfer_mutex, &transfer_clock) != ETIMEDOUT) { break; } } seq += 1; printf("done\n"); break; } } else { frame.type = 2; frame.seq = seq; frame.length = count; while (1) { clock_gettime(CLOCK_REALTIME, &transfer_clock); transfer_clock.tv_sec += 1; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &frame); if (pthread_cond_timedwait(&transfer_cond, &transfer_mutex, &transfer_clock) != ETIMEDOUT) { break; } } seq += 1; } } printf("send count: %d\n", seq); } void* rx_thread(void* dev) { usb1352_dev* p_dev = (usb1352_dev*)dev; test_frame frame, ack_frame; struct timespec start, end, result; FILE* img; uint16_t count; while (1) { usb1352_spi_data_receive(p_dev, sizeof(test_frame), &frame); if (frame.type == 1) { printf("start\n"); img = fopen("wakgood_master.jpg", "wb"); count = 0; clock_gettime(CLOCK_REALTIME, &start); ack_frame.type = 4; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &ack_frame); } else if (frame.type == 3) { if (frame.seq == count) { fwrite(frame.payload, 1, frame.length, img); printf("done\n"); fclose(img); clock_gettime(CLOCK_REALTIME, &end); result.tv_sec = end.tv_sec - start.tv_sec; result.tv_nsec = end.tv_nsec - start.tv_nsec; count += 1; printf("recv count: %d\n", count); printf("p_dev count: %d\n", p_dev->count); printf("%ldsec %ldnsec\n", result.tv_sec, result.tv_nsec); ack_frame.type = 4; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &ack_frame); } } else if (frame.type == 2) { // printf("cur seq: %d\n", frame.seq); if (frame.seq == count) { count += 1; fwrite(frame.payload, 1, frame.length, img); ack_frame.type = 4; usb1352_spi_data_transfer(p_dev, sizeof(test_frame), &ack_frame); } } else if (frame.type == 4) { pthread_cond_signal(&transfer_cond); } usleep(1000); } } int main(void) { usb1352_dev* my_dev; pthread_t tx_thread_t; pthread_t rx_thread_t; my_dev = usb1352_init(); pthread_cond_init(&transfer_cond, NULL); pthread_mutex_init(&transfer_mutex, NULL); pthread_create(&tx_thread_t, NULL, tx_thread, my_dev); pthread_create(&rx_thread_t, NULL, rx_thread, my_dev); while (1); }
JavaScript
UTF-8
11,586
3.65625
4
[]
no_license
'use strict'; ///////////////////////////////////////////////// ///////////////////////////////////////////////// // LECTURES const account1 = { owner: 'Jonas Schmedtmann', movements: [200, 450, -400, 3000, -650, -130, 70, 1300], interestRate: 1.2, // % pin: 1111, }; const account2 = { owner: 'Jessica Davis', movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30], interestRate: 1.5, pin: 2222, }; const account3 = { owner: 'Steven Thomas Williams', movements: [200, -200, 340, -300, -20, 50, 400, -460], interestRate: 0.7, pin: 3333, }; const account4 = { owner: 'Sarah Smith', movements: [430, 1000, 700, 50, 90], interestRate: 1, pin: 4444, }; const accounts = [account1, account2, account3, account4]; const currencies = new Map([ ['USD', 'United States dollar'], ['EUR', 'Euro'], ['GBP', 'Pound sterling'], ]); const movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; ///////////////////////////////////////////////// //let arr = ['a', 'b', 'c', 'd', 'e']; //SLICE /*console.log(arr.slice(2)); //does not mutate the original array, returns the new one console.log(arr.slice(2, 4)); console.log(arr.slice(-2)); //last 2 elements console.log(arr.slice(1, -2)); console.log(arr.slice()); //shallow copy of the new array */ //SPLICE: as slice, but mutates the original array //parameters: what elements must be deleted from the array. //First parameter - start element, second - number of elements //console.log(arr.splice(2)); //arr.splice(3); //console.log(arr); //REVERSE //const arr2 = ['j', 'i', 'h', 'g', 'j']; //console.log(arr2.reverse()); //mutates the array //console.log(arr2); //CONCAT //const letters = arr.concat(arr2); //does not mutate the array //console.log(letters); //the same //console.log([...arr, ...arr2]); //JOIN //console.log(letters.join(' - ')); //for (const movement of movements) { /*for (const [i, movement] of movements.entries()) { if (movement > 0) { console.log(`Movement ${i + 1}: You deposited ${movement}.`); } else { console.log(`Movement ${i + 1}: You withdrew ${Math.abs(movement)}.`); } } */ //FOR EACH takes a function and applies it to all elements //console.log('--- FOR EACH ---'); /*movements.forEach(function (movement, i, array) { if (movement > 0) { console.log(`Movement ${i + 1}: You deposited ${movement}.`); } else { console.log(`Movement ${i + 1}: You withdrew ${Math.abs(movement)}.`); } }); */ //FOR EACH for maps /* currencies.forEach(function (value, key, map) { console.log(`${key}: ${value}`); });*/ //FOR EACH for sets /* const currenciesUnique = new Set(['USD', 'GBP', 'USD', 'EUR']); console.log(currenciesUnique); currenciesUnique.forEach(function (value, key, map) { console.log(`${key}: ${value}`); });*/ //key and value are the same to avoid confusion /* const checkDogs = function (dogsJulia, dogsKate) { const newDogsJulia = dogsJulia.slice(1, -2); const dogs = newDogsJulia.concat(dogsKate); dogs.forEach(function (value, key, array) { console.log(`Dog number ${key + 1} is ${ value < 3 ? 'still a puppy🐶' : `an adult, and is ${value} years old` }`); }); }; checkDogs([3, 5, 2, 12, 7], [4, 1, 15, 8, 3]); checkDogs([9, 16, 6, 8, 3], [10, 5, 6, 1, 4]); //MAP EXAMPLE const euroToUsd = 1.1; const movementsUSD = movements.map(mov => mov * euroToUsd); console.log(movements); console.log(movementsUSD); const movementsUSDfor = []; for (const mov of movements) { movementsUSDfor.push(mov * euroToUsd); } console.log(movementsUSDfor); const movementsDescriptions = movements.map( (mov, i) => `Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdrew'} ${Math.abs( mov )}` ); console.log(movementsDescriptions); //FILTER filters out some elements. Need to receive a boolean function as a parameter const deposits = movements.filter(function (mov) { return mov > 0; }); console.log(movements); console.log(deposits); const depositsFor = []; for (const mov of movements) if (mov > 0) depositsFor.push(mov); console.log(depositsFor); const withdrawals = movements.filter(elem => elem < 0); console.log(withdrawals); console.log(movements); //accumulator -> SNOWBALL. Parameters are the function and the initial value of accumulator const balance = movements.reduce(function (accumulator, cur, i, arr) { console.log(`Iteration ${i}: ${accumulator}`); return accumulator + cur; }, 0); console.log(balance); let balance2 = 0; for (const mov of movements) { balance2 += mov; } console.log(balance2); //Maximum value of the movements array const maxValue = movements.reduce( (accumulator, value, index, array) => Math.max(accumulator, value), movements[0] ); console.log(maxValue); const data1 = [5, 2, 4, 1, 15, 8, 3]; const data2 = [16, 6, 10, 5, 6, 1, 4]; const calcAverageHumanAge = function (data) { const humanAgeAverage = data .map(dogAge => (dogAge <= 2 ? 2 * dogAge : 16 + dogAge * 4)) .filter(humanAge => humanAge >= 18) .reduce((accumulator, elem, i, arr) => accumulator + elem / arr.length, 0); return humanAgeAverage; }; console.log(calcAverageHumanAge(data1)); console.log(calcAverageHumanAge(data2)); const firstWithdrawal = movements.find(mov => mov < 0); //will return only the first element of the array satisfying this condition console.log(movements); console.log(firstWithdrawal); console.log(accounts); const account = accounts.find(acc => acc.owner === 'Jessica Davis'); console.log(account); for (const acc of accounts) { if (acc.owner === 'Jessica Davis') { console.log(acc); } } console.log(movements); //EQUALITY console.log(movements.includes(-130)); //CONDITION const anyDeposits = movements.some(mov => mov > 1500); console.log(anyDeposits); //EVERY console.log(movements.every(mov => mov > 0)); console.log(account4.movements.every(mov => mov > 0)); //separate callback const deposit = mov => mov > 0; console.log(movements.some(deposit)); console.log(movements.every(deposit)); console.log(movements.filter(deposit)); const arr = [[1, 2, 3], [4, 5, 6], 7, 8]; console.log(arr.flat()); // returns [1, 2, 3, 4, 5, 6 ,7 ,8] const arrDeep = [[[1, 2], 3], [4, [5, 6]], 7, 8]; console.log(arrDeep.flat()); // returns [[1, 2], 3, 4, [5, 6], 7, 8] //flat goes only one level deep. //To change this behavious depth value is given to the function console.log(arrDeep.flat(2)); const accountMovements = accounts.map(acc => acc.movements); console.log(accountMovements); const allMovements = accountMovements.flat(); console.log(allMovements); const overallBalance = allMovements.reduce((a, b) => a + b, 0); console.log(overallBalance); //the same with chaining const overallBalance1 = accounts .map(acc => acc.movements) .flat() .reduce((acc, mov) => acc + mov, 0); console.log(overallBalance1); //the same with flatMap const overallBalance2 = accounts .flatMap(acc => acc.movements) .reduce((acc, mov) => acc + mov, 0); console.log(overallBalance2); //flatMap goes only 1 level deep. If there is a need to go deeper, usage of flat and map are still required //SORTING const owners = ['Jonas', 'Zach', 'Adam', 'Martha']; console.log(owners.sort()); //mutates the original array!! console.log(owners); //Numbers: sort method does sorting based on strings console.log(movements); console.log(movements.sort()); //WRONG! //return < 0 A, B //return >= 0 B, A //ascending order: console.log(movements.sort((a, b) => a - b)); //descending order: console.log(movements.sort((a, b) => b - a)); const a = [1, 2, 3, 4, 5, 6, 7]; console.log(new Array(1, 2, 3, 4, 5, 6, 7)); //if only one argument is passed, it created an array with this number of empty elements const x = new Array(7); console.log(x); //we also cannot call map method on the new array //console.log(x.map(() => 5)); //but we can call fill method. This method fills the entire array with the given value //x.fill(1); //console.log(x); //fills the array with value 1 starting from the 3rd position and ending on the 5th postion: x.fill(1, 3, 5); console.log(x); arr.fill(23, 2, 6); console.log(arr); //Array.from const y = Array.from({ length: 7 }, () => 1); // array on ones console.log(y); const z = Array.from({ length: 7 }, (_, index) => index + 1); //values from 1 to 7 console.log(z); const zz = Array.from({ length: 100 }, () => Math.floor(Math.random() * 6) + 1); console.log(zz); //1. const bankDepositSum = accounts .flatMap(acc => acc.movements) .filter(mov => mov > 0) .reduce((sum, cur) => sum + cur, 0); console.log(bankDepositSum); //2. let numDeposits1000 = accounts .flatMap(acc => acc.movements) .filter(mov => mov >= 1000).length; console.log(numDeposits1000); //other solution numDeposits1000 = accounts .flatMap(acc => acc.movements) .reduce((count, cur) => count + (cur >= 1000 ? 1 : 0), 0); console.log(numDeposits1000); let a = 10; console.log(a++); //10 console.log(a); //11 //3. const { deposits, withdrawals } = accounts .flatMap(acc => acc.movements) .reduce( (sum, cur) => { //cur > 0 ? (sum.deposits += cur) : (sum.withdrawals -= cur); sum[cur > 0 ? 'deposits' : 'withdrawals'] += Math.abs(cur); return sum; }, { deposits: 0, withdrawals: 0 } ); console.log(deposits, withdrawals); //4. //this is a nice title -> This Is a Nice Title const convertTitleCase = function (title) { const capitalize = str => str[0].toUpperCase() + str.slice(1); const exceptions = ['a', 'and', 'an', 'the', 'but', 'or', 'on', 'in', 'with']; const titleCase = title .toLowerCase() .split(' ') .map(word => (exceptions.includes(word) ? word : capitalize(word))) .join(' '); return capitalize(titleCase); }; console.log(convertTitleCase('this is a nice title')); console.log(convertTitleCase('this is a LONG title but not too long')); console.log(convertTitleCase('and here is another title with an EXAMPLE')); */ //challenge 4 const dogs = [ { weight: 22, curFood: 250, owners: ['Alice', 'Bob'] }, { weight: 8, curFood: 200, owners: ['Matilda'] }, { weight: 13, curFood: 275, owners: ['Sarah', 'John'] }, { weight: 32, curFood: 340, owners: ['Michael'] }, ]; //task1 /*dogs.map(dog => { dog['recommendedFood'] = dog['weight'] ** 0.75 * 28; return dog; });*/ dogs.forEach( dog => (dog.recommendedFood = Math.trunc(dog.weight ** 0.75 * 28)) ); console.log(dogs); //task 2 const sarahDog = dogs.find(dog => dog.owners.includes('Sarah')); console.log( sarahDog.curFood > sarahDog.recommendedFood * 1.1 ? 'Dog eats too much' : sarahDog.curFood < sarahDog.recommendedFood * 0.9 ? 'Dog eats too little' : 'Dog eats healthy' ); //task 3 const ownersEatTooMuch = dogs .filter(dog => dog.curFood > dog.recommendedFood * 1.1) .map(dog => dog.owners); const ownersEatTooLittle = dogs .filter(dog => dog.curFood < dog.recommendedFood * 0.9) .map(dog => dog.owners); console.log(ownersEatTooMuch, ownersEatTooLittle); //task 4 console.log(`${ownersEatTooMuch.flat().join(' and ')}'s dogs eat too much!"`); console.log( `${ownersEatTooLittle.flat().join(' and ')}'s dogs eat too little!"` ); //task 5 console.log(dogs.some(dog => dog.curFood === Math.round(dog.recommendedFood))); //task 6 console.log( dogs.some( dog => dog.curFood < dog.recommendedFood * 1.1 && dog.curFood > dog.recommendedFood * 0.9 ) ); //task 7 console.log( dogs.filter( dog => dog.curFood < dog.recommendedFood * 1.1 && dog.curFood > dog.recommendedFood * 0.9 ) ); //task 8 console.log(dogs.slice().sort((a, b) => a.recommendedFood - b.recommendedFood)); console.log(dogs);
Python
UTF-8
1,356
2.90625
3
[ "MIT" ]
permissive
#!/usr/bin/env python import time import argparse from pmw3901 import PMW3901, PAA5100, BG_CS_FRONT_BCM, BG_CS_BACK_BCM print("""motion.py - Detect flow/motion in front of the PMW3901 sensor. Press Ctrl+C to exit! """) parser = argparse.ArgumentParser() parser.add_argument('--board', type=str, choices=['pmw3901', 'paa5100'], required=True, help='Breakout type.') parser.add_argument('--rotation', type=int, default=0, choices=[0, 90, 180, 270], help='Rotation of sensor in degrees.') parser.add_argument('--spi-slot', type=str, default='front', choices=['front', 'back'], help='Breakout Garden SPI slot.') args = parser.parse_args() # Pick the right class for the specified breakout SensorClass = PMW3901 if args.board == 'pmw3901' else PAA5100 flo = SensorClass(spi_port=0, spi_cs_gpio=BG_CS_FRONT_BCM if args.spi_slot == 'front' else BG_CS_BACK_BCM) flo.set_rotation(args.rotation) tx = 0 ty = 0 try: while True: try: x, y = flo.get_motion() except RuntimeError: continue tx += x ty += y print("Relative: x {:03d} y {:03d} | Absolute: x {:03d} y {:03d}".format(x, y, tx, ty)) time.sleep(0.01) except KeyboardInterrupt: pass
C#
UTF-8
1,955
2.796875
3
[]
no_license
using EnvDTE; using System.CodeDom; namespace Pretorianie.Tytan.Core.Data.Refactoring { /// <summary> /// Class describing named <c>CodeVariable</c> element. /// </summary> public class CodeVariableNamedElement : CodeNamedElement { private readonly CodeVariable variable; /// <summary> /// Init constructor. /// </summary> public CodeVariableNamedElement(CodeVariable variable, bool isDisabled, string paramName) : base(isDisabled, paramName) { this.variable = variable; } /// <summary> /// Gets the name of the referenced type. /// </summary> public override string ReferecedTypeName { get { return variable.Type.AsString; } } /// <summary> /// Gets the indication if given element is static. /// </summary> public override bool IsStatic { get { return variable.IsShared; } } /// <summary> /// Gets the name of special element. /// </summary> public override string GetName(ElementNames type) { switch (type) { case ElementNames.DefaultValid: case ElementNames.AsVariable: return variable.Name; default: return null; } } /// <summary> /// Gets the <c>CodeExpression</c> element that can reference current element. /// </summary> public override CodeExpression GetReferenceExpression(string className) { if (IsStatic) return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(className), Name); return new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), Name); } } }
Python
UTF-8
3,493
3.1875
3
[]
no_license
import re from officialComm import convertScrapedtoSent #identifying individual date patterns def dateInfo(articleBody): #regex pattern to recognize various date patterns #examples of what the below pattern recognizes: "04-04-2004; 04/04/04; 4/04/04; 4/4/05; April 04, 2004; March 24, 2004; April. 24, 2004; April 24 2004; 24 Mar 2004; 24 March 2004; 4 June. 2004; 24 August, 2010; Mar 22nd, 2006; Jul 21st, 2007; Mar 24th, 2004; Jan 2009; Dec 2009; Oct 2014; 6/2004; 12/2004; 2018; 2019" #Establishes the regular expressions pattern to catch dates that are in or similar to the above formats #Starts with optional days, goes to optional months, optional numbers, and optional letters in various orders and repetitions regex = re.compile(r'(?:Monday|Mon|Tuesday|Tues|Wednesday|Wed|Thursday|Thu|Friday|Fri|Saturday|Sat|Sunday|Sun)?[\s,.]*(?:January|Jan|February|Feb|March|Mar|April|Apr|May|June|Jun|July|Jul|August|Aug|September|Sept|October|Oct|November|Nov|December|Dec)?[\s,.]*(?:\d{1,2}[-/th|st|nd|rd\s]*)(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)?[a-z\s,.]*(?:\d{1,2}[-/th|st|nd|rd)\s,])?(?:\d{2,4})+') dates = [] #For a particular sentence in a sccraped paragraph, a date is identified for para in articleBody: temp = convertScrapedtoSent(para) for sent in temp: datePattern = regex.findall(sent) #For a specific date, remove any starting space if there is one for date in datePattern: if date[0]==' ': date = date[1:] #The following condition is to eliminate any numbers like "25,000" being picked up as dates because of the comma if ',' in date: s = date.split(',') if s[1][0]==' ': if s[1][1].isdigit(): #If a comma has a year following it, this date will be appended to the rest of the collected dates from a body of text dates.append(date) else: #Ignore and continue from the entity if it has a comma but the following word is not numbers (25, or 30 should not be a date) continue elif len(s[0])>1 and s[1][0]!=' ' and s[1][0].isdigit() and s[0][-1].isdigit(): #Ignore and continue if there is a comma between 2 numbers (300,000) continue elif date.isdigit(): #if it is all numbers and nothing else temp = int(date) #Restrict the date timeframe between these years if temp < 1980 or temp > 2020: continue else: dates.append(date) #Condition for dashed dates - check individual portions around the dashes by splitting the entity elif "-" in date: day = date.split("-") if(len(day)==3): #Condition to make sure that dashed entity really is a date by checking how many indexes are in the split porition if len(day[0])<3 and len(day[1])<3 and len(day[2])<5: dates.append(date) #If an enetity does not have a comma or is just numbers, add to the collection of dates else: dates.append(date) return dates
TypeScript
UTF-8
171
2.703125
3
[]
no_license
var heroeslist:Array<string> = ["Dead Pool", "Flash", "Ant Man", "Aqua Man", "Wonder Women"] for(let hero of heroeslist){ console.log( hero+" says hello !!! " ); }
C++
UTF-8
1,193
3.140625
3
[]
no_license
#include "Castle.h" #include<cstdlib> bool Castle::isDestroyed() { if (Health < 0) return true; else return false; } int Castle::GetNumberOfEnemies() { return NumberOfEnemies; } void Castle::SetNumberOfEnemies(int N) { if (N > 0) NumberOfEnemies = N; else NumberOfEnemies = 10; //Set the number of enemies with avaible number } double Castle::GetHealth() const { return Health; } void Castle::SetHealth(double h) { if (h > 0) Health = h; else Health = 0; // killed } void Castle::DecrementHealth(double damage) { if (isDestroyed()) return; Health -= damage; } void Castle::SetPower(double P) { if (P > 0) Power = P; else Power = 10; //Set the power with avaiable number } double Castle::GetPower() const { return Power; } void Castle::SetStatus(ENMY_STATUS S) { status = S; } ENMY_STATUS Castle::GetStatus() const { return status; } void Castle::Damage(Enemy* &E) { double damage, distance = (double)E->GetDistance(), K; if (dynamic_cast<Healer*>(E)) { K = 2; } else { K = 1; } damage = (1 / distance) * Power * (1 / K); E->SetHealth(min(0,E->GetHealth() - damage)); } double Castle::GetMaxHealth() const { return MaxHealth; }
Java
UTF-8
307
2.3125
2
[]
no_license
package Utils.Comparator; import Egyedek.Partner; import java.util.Comparator; public class PartnerNevComparator implements Comparator<Partner>{ @Override public int compare(Partner p1, Partner p2) { return p1.getNev().compareTo(p2.getNev()); } }
Markdown
UTF-8
11,911
3.484375
3
[ "MIT" ]
permissive
# Transitions de liste Jusqu'à présent, nous avons géré les transitions pour: - Des noeuds individuels - Plusieurs nœuds où un seul est rendu à la fois Alors qu'en est-il lorsque nous avons toute une liste d'éléments que nous voulons rendre simultanément, par exemple avec `v-for`? Dans ce cas, nous utiliserons le composant `<transition-group>`. Avant de plonger dans un exemple, il y a quelques choses importantes à savoir sur ce composant: - Par défaut, il ne génère pas un élément wrapper, mais vous pouvez spécifier un élément à rendre avec l'attribut `tag`. - [Les modes de transitions](/guide/transitions-enterleave#modes-de-transition) ne sont pas disponibles, parce que nous n'alternons plus entre des éléments qui s'excluent mutuellement. - Les éléments à l'intérieur **doivent toujours** avoir un attribut `key` unique. - Les classes de transition CSS seront appliquées aux éléments internes et non au groupe / conteneur lui-même. ## Transitions d'entrées/sorties des listes Passons maintenant à un exemple, la transition entre l'entrée et la sortie en utilisant les mêmes classes CSS que nous avons utilisées précédemment: ```html <div id="list-demo"> <button @click="add">Ajouter</button> <button @click="remove">Supprimer</button> <transition-group name="list" tag="p"> <span v-for="item in items" :key="item" class="list-item"> {{ item }} </span> </transition-group> </div> ``` ```js const Demo = { data() { return { items: [1, 2, 3, 4, 5, 6, 7, 8, 9], nextNum: 10 } }, methods: { randomIndex() { return Math.floor(Math.random() * this.items.length) }, add() { this.items.splice(this.randomIndex(), 0, this.nextNum++) }, remove() { this.items.splice(this.randomIndex(), 1) } } } Vue.createApp(Demo).mount('#list-demo') ``` ```css .list-item { display: inline-block; margin-right: 10px; } .list-enter-active, .list-leave-active { transition: all 1s ease; } .list-enter-from, .list-leave-to { opacity: 0; transform: translateY(30px); } ``` <common-codepen-snippet title="Transition List" slug="e1cea580e91d6952eb0ae17bfb7c379d" tab="js,result" :editable="false" :preview="false" /> Il y a un problème avec cet exemple. Lorsque vous ajoutez ou supprimez un élément, ceux qui l'entourent s'emboîtent instantanément dans leur nouvel emplacement au lieu de le faire tout en douceur. Nous réglerons cela plus tard. ## Mouvements de transition des listes Le composant `<transition-group>` a une autre astuce dans sa manche. Il peut non seulement animer l'entrée et la sortie, mais aussi les changements de position. Le seul nouveau concept que vous devez connaître pour utiliser cette fonctionnalité est l'ajout de **la classe `v-move`**, qui est ajoutée lorsque les éléments changent de position. Comme les autres classes, son préfixe correspondra à la valeur d'un attribut `name` fourni et vous pouvez également spécifier manuellement une classe avec l'attribut `move-class`. Cette classe est surtout utile pour spécifier le timing de transition et la courbe d'accélération, comme vous le verrez ci-dessous: ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script> <div id="flip-list-demo"> <button @click="shuffle">Mélanger</button> <transition-group name="flip-list" tag="ul"> <li v-for="item in items" :key="item"> {{ item }} </li> </transition-group> </div> ``` ```js const Demo = { data() { return { items: [1, 2, 3, 4, 5, 6, 7, 8, 9] } }, methods: { shuffle() { this.items = _.shuffle(this.items) } } } Vue.createApp(Demo).mount('#flip-list-demo') ``` ```css .flip-list-move { transition: transform 0.8s ease; } ``` <common-codepen-snippet title="Transition-group example" slug="049211673d3c185fde6b6eceb8baebec" tab="html,result" :editable="false" :preview="false" /> Cela peut sembler magique, mais sous le capot, Vue utilise une technique d'animation appelée [FLIP](https://aerotwist.com/blog/flip-your-animations/) pour faire la transition en douceur des éléments de leur ancienne position à leur nouvelle position à l'aide de transformations. Nous pouvons combiner cette technique avec notre implémentation précédente pour animer chaque changement possible de notre liste! ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script> <div id="list-complete-demo" class="demo"> <button @click="shuffle">Mélanger</button> <button @click="add">Ajouter</button> <button @click="remove">Supprimer</button> <transition-group name="list-complete" tag="p"> <span v-for="item in items" :key="item" class="list-complete-item"> {{ item }} </span> </transition-group> </div> ``` ```js const Demo = { data() { return { items: [1, 2, 3, 4, 5, 6, 7, 8, 9], nextNum: 10 } }, methods: { randomIndex() { return Math.floor(Math.random() * this.items.length) }, add() { this.items.splice(this.randomIndex(), 0, this.nextNum++) }, remove() { this.items.splice(this.randomIndex(), 1) }, shuffle() { this.items = _.shuffle(this.items) } } } Vue.createApp(Demo).mount('#list-complete-demo') ``` ```css .list-complete-item { transition: all 0.8s ease; display: inline-block; margin-right: 10px; } .list-complete-enter-from, .list-complete-leave-to { opacity: 0; transform: translateY(30px); } .list-complete-leave-active { position: absolute; } ``` <common-codepen-snippet title="Transition-group example" slug="373b4429eb5769ae2e6d097fd954fd08" tab="js,result" :editable="false" :preview="false" /> ::: tip Une note importante est que ces transitions FLIP ne fonctionnent pas avec des éléments définis sur `display: inline`. Comme alternative, vous pouvez utiliser `display: inline-block` ou placer des éléments dans un contexte flex. ::: Ces animations FLIP ne sont pas non plus limitées à un seul axe. Les éléments d'une grille multidimensionnelle peuvent être [transitionnés](https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-list-move-transitions): <!-- TODO: example --> ## Transitions de liste échelonnées En communiquant avec les transitions JavaScript via des attributs de données, il est également possible d'échelonner les transitions dans une liste: ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script> <div id="demo"> <input v-model="query" /> <transition-group name="staggered-fade" tag="ul" :css="false" @before-enter="beforeEnter" @enter="enter" @leave="leave" > <li v-for="(item, index) in computedList" :key="item.msg" :data-index="index" > {{ item.msg }} </li> </transition-group> </div> ``` ```js const Demo = { data() { return { query: '', list: [ { msg: 'Bruce Lee' }, { msg: 'Jackie Chan' }, { msg: 'Chuck Norris' }, { msg: 'Jet Li' }, { msg: 'Kung Fury' } ] } }, computed: { computedList() { var vm = this return this.list.filter(item => { return item.msg.toLowerCase().indexOf(vm.query.toLowerCase()) !== -1 }) } }, methods: { beforeEnter(el) { el.style.opacity = 0 el.style.height = 0 }, enter(el, done) { gsap.to(el, { opacity: 1, height: '1.6em', delay: el.dataset.index * 0.15, onComplete: done }) }, leave(el, done) { gsap.to(el, { opacity: 0, height: 0, delay: el.dataset.index * 0.15, onComplete: done }) } } } Vue.createApp(Demo).mount('#demo') ``` <common-codepen-snippet title="Staggered Lists" slug="c2fc5107bd3025ceadea049b3ee44ec0" tab="js,result" :editable="false" :preview="false" /> ## Transitions réutilisables Les transitions peuvent être réutilisées via le système de composants de Vue. Pour créer une transition réutilisable, il suffit de placer un composant `<transition>` ou `<transition-group>` à la racine, puis de passer tous les enfants dans le composant de transition. <!-- TODO: refactor to Vue 3 --> Voici un exemple utilisant un template de composant: ```js Vue.component('my-special-transition', { template: '\ <transition\ name="very-special-transition"\ mode="out-in"\ @before-enter="beforeEnter"\ @after-enter="afterEnter"\ >\ <slot></slot>\ </transition>\ ', methods: { beforeEnter(el) { // ... }, afterEnter(el) { // ... } } }) ``` Et les [composants fonctionnels](render-function.html#Functional-Components) sont particulièrement bien adaptés à cette tâche: ```js Vue.component('my-special-transition', { functional: true, render: function(createElement, context) { var data = { props: { name: 'very-special-transition', mode: 'out-in' }, on: { beforeEnter(el) { // ... }, afterEnter(el) { // ... } } } return createElement('transition', data, context.children) } }) ``` ## Transitions dynamiques Eh Oui, même les transitions dans Vue sont basées sur les données! L'exemple le plus basique d'une transition dynamique lie l'attribut `name` à une propriété dynamique. ```html <transition :name="transitionName"> <!-- ... --> </transition> ``` Cela peut être utile lorsque vous avez défini des transitions/animations CSS à l'aide des conventions de classe de transition de Vue et que vous souhaitez basculer entre elles. En réalité, tout attribut de transition peut être lié dynamiquement. Et ce ne sont pas seulement des attributs. Les hooks d'événement étant des méthodes, ils ont accès à toutes les données du contexte. Cela signifie qu'en fonction de l'état de votre composant, vos transitions JavaScript peuvent se comporter différemment. ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.2.3/velocity.min.js"></script> <div id="dynamic-fade-demo" class="demo"> Fade In: <input type="range" v-model="fadeInDuration" min="0" :max="maxFadeDuration" /> Fade Out: <input type="range" v-model="fadeOutDuration" min="0" :max="maxFadeDuration" /> <transition :css="false" @before-enter="beforeEnter" @enter="enter" @leave="leave" > <p v-if="show">hello</p> </transition> <button v-if="stop" @click="stop = false; show = false"> Start animating </button> <button v-else @click="stop = true">Stop it!</button> </div> ``` ```js const app = Vue.createApp({ data() { return { show: true, fadeInDuration: 1000, fadeOutDuration: 1000, maxFadeDuration: 1500, stop: true } }, mounted() { this.show = false }, methods: { beforeEnter(el) { el.style.opacity = 0 }, enter(el, done) { var vm = this Velocity( el, { opacity: 1 }, { duration: this.fadeInDuration, complete: function() { done() if (!vm.stop) vm.show = false } } ) }, leave(el, done) { var vm = this Velocity( el, { opacity: 0 }, { duration: this.fadeOutDuration, complete: function() { done() vm.show = true } } ) } } }) app.mount('#dynamic-fade-demo') ``` <!-- TODO: example --> Enfin, le moyen ultime de créer des transitions dynamiques consiste à utiliser des composants qui acceptent des props pour changer la nature de la ou des transitions à utiliser. Cela peut sembler ringard, mais la seule limite est vraiment votre imagination.
Java
UTF-8
633
1.898438
2
[]
no_license
package dk.fitfit.remotetexting.business.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; // Inspired by http://tuhrig.de/why-using-springs-value-annotation-is-bad/ @Service public class ConfigurationService { @Value("${security.oauth2.client.clientId}") private String clientId; @Value("${fcm.auth_key}") private String AUTH_KEY_FCM; @Value("${fcm.api_url}") private String API_URL_FCM; public String getClientId() { return clientId; } public String getAuthKey() { return AUTH_KEY_FCM; } public String getApiUrl() { return API_URL_FCM; } }
Markdown
UTF-8
3,691
2.53125
3
[]
no_license
# Introduce This is a template for react-native project [react-native: 0.61.5]() [typescript: ts, tsx](https://reactnative.dev/docs/typescript) [redux-saga](https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html) [reactnavigation 5x](https://reactnavigation.org/docs/navigating/) [react-native-config](https://github.com/luggit/react-native-config) [redux-logger](https://github.com/LogRocket/redux-logger) # Environments There are 3 environments in app: **Develop, Staging and Production.** To change Base url, Version name, Version code, event App name,... for each environment, you must change in .env file. > Develop: **.env** > Staging : **.env.staging** > Production : **.env.production** Example .env file: ``` APP_ID='com.company.app' VER_CODE='1' VER_NAME='1.0.0' APP_NAME = 'App' ``` ## Android Keystore Config develop/staging keystore ``` keystore/keystore.properties ``` Config production keystore ``` keystores-production/keystore.properties ``` Config your keystore file, password, alias... ## Run and build Run commands to remove and install node module: ``` npm rm-i ``` IOS only: ``` cd ios && pod install && cd .. ``` ### ANDROID - **Run android:** Start server first : ``` npm start ``` Run on emulator **(emulator must be opened before)** or real device: ``` npm run android npm run android-stg npm run android-prod ``` Build command: ``` npm run android-build npm run android-build-stg npm run android-build-prod ``` APK file will be exported in **node-modules/android/app/build/outputs/apk/** folder ### IOS - **Run ios (only simulator):** ``` npm run ios npm run ios-stg npm run ios-prod ``` # Coding Rules ## Components - **Only perform interface** - **On render function: should not contain the entire screen interface definition, because it will make your code be ugly, not look good** **example** ``` render(){ return( // render ui a ..... ..... ..... // render ui b ..... ..... ..... // render ui a ..... ..... ..... // render ui b ..... ..... ..... ) } ``` **should be** ``` renderA = () => { return( // render ui a ..... ..... ..... ) } renderB = () => { return( // render ui b ..... ..... ..... ) } renderC = () => { return( // render ui c ..... ..... ..... ) } renderD = () => { return( // render ui d ..... ..... ..... ) } render(){ return( //renderA //renderB //renderC //renderD ) } ``` ## Container - **Contain component logic & redux logic** ```$xslt - Container will connect to screen - Screen will call logic on container via prop ``` ## Navigate between screen **Use: Navigate.ts** ```$xslt - navigateAndRest - navigateTo - goBack - popToRoot ``` ## Communicate with redux-saga - Declare api in formation: [Config](src/networking/Config.ts) ```$xslt Movies: new API('/movies.json', 'get'), ``` - Declare action for active saga: [Action](src/saga/Action.ts) ```$xslt MOVIES: new SagaAction('MOVIES'), ``` - combine your action to saga, that will run by saga middleware: [index](src/saga/index.ts) ```$xslt yield doAsync(Actions.MOVIES, Config.API.Movies); ``` - finally dispatch action from screen container ```$xslt dispatch({ type: Action.MOVIES.value }) ``` after that saga will auto active and dispatch response to your reducer
Java
UTF-8
973
2.140625
2
[]
no_license
package Day4NG; import org.testng.annotations.Test; import util.StartBrowser; import org.testng.annotations.BeforeTest; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.annotations.AfterTest; public class FirstNG { WebDriver driver; @Test(priority=1) public void titleTest() { driver.get("http://google.com"); String title=driver.getTitle(); Assert.assertEquals(title,"Google"); } @Test(priority=2,description="Search Box Detail Testing") public void searchBoxTest() { WebElement E=driver.findElement(By.name("q")); Assert.assertEquals(E.isDisplayed(),true); Assert.assertEquals(E.isEnabled(),true); Assert.assertEquals(E.getAttribute("maxlength"),"2048"); } @BeforeTest public void beforeTest() { driver=StartBrowser.startBrowser("chrome"); } @AfterTest public void afterTest() { } }
C#
UTF-8
402
3.328125
3
[]
no_license
using System; class Compare { static void Main() { float a = 5.55f; float b = 6.35f; Boolean Compare = (a == b); Console.WriteLine("The result is {0}", Compare); Boolean Compare1 = (a > b); Console.WriteLine("The result is {0}", Compare1); Boolean Compare2 = (a < b); Console.WriteLine("The result is {0}", Compare2); } }
Python
UTF-8
1,214
2.6875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue May 19 22:13:11 2020 ANN example @author: user1 """ import numpy as np import pandas as pd import tensorflow as tf dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3 : 13].values y = dataset.iloc[:, -1].values from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1,2])], remainder='passthrough') X1 = np.array(ct.fit_transform(X)) # Remove first and third column to avoid from dummy variable trap X = X1[:,1:] idxs = list(range(0, 12)) idxs.pop(2) #this removes 2 from the list X = X[:, idxs] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # ANN import keras from keras.models import Sequential from keras.layers import Dense #initilize ANN classifier = Sequential() #add first layer and hidden layer classifier.add(Dense(6, input_shape=(11,) ,kernel_initializer='uniform', activation = 'relu'))
Python
UTF-8
132
3.203125
3
[]
no_license
ano = int(input()) while(True): ano += 1 t = set(str(ano)) if len(t) == len(str(ano)): print(ano) break
Java
UTF-8
1,420
2.140625
2
[]
no_license
package com.ofnicon.luizahei101.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import com.ofnicon.luizahei101.R; import com.ofnicon.luizahei101.core.Core; public class NotificationActivity extends AppCompatActivity { String text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); text = getIntent().getStringExtra("text"); setTextAndBG(text); findViewById(R.id.share_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Core.shareNotice(NotificationActivity.this, text); } }); findViewById(R.id.more_button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setTextAndBG(Core.getNotificationText(NotificationActivity.this)); } }); } private void setTextAndBG(String text) { ((TextView) findViewById(R.id.notification_tv)).setText(text); View layout = findViewById(R.id.notification_activity_layout); layout.setBackgroundResource(getResources().getIdentifier(Core.getBackground(this), "drawable", getPackageName())); } }
Shell
UTF-8
676
3.59375
4
[]
no_license
#!/bin/sh set -e # export PGHOST # export PGPORT # export PGDATABASE # export PGUSER # export PGPASSWORD # export GCS_BUCKET # export GCS_PROJECT # export SLEEP_SECONDS backup(){ echo "Starting backup..." pg_dump -v -w -c | gzip -9 > $PGDATABASE.sql.gz FILE_NAME="$PGDATABASE-$(date +"%Y%m%d%H%M").sql.gz" gcsupload -bucket "$GCS_BUCKET" -project "$GCS_PROJECT" -name "$FILE_NAME" -source "$PGDATABASE.sql.gz" echo "Backup complete..." rm -v $PGDATABASE.sql.gz } if [ -z $SLEEP_SECONDS ]; then backup else while true do backup echo "Sleeping for $SLEEP_SECONDS seconds.." sleep $SLEEP_SECONDS done fi
Java
UTF-8
4,006
2.84375
3
[]
no_license
package components.tables; import database.Query; import utils.CustomTableFormat; import windows.MainWindow; import javax.swing.event.ListSelectionEvent; import java.sql.Connection; import java.sql.SQLException; /** * Tabla que muestra las categorías, extiendo de una clase para tener funciones en común con las demás tablas. */ public class CategoryTable extends GenericTable { /** * Acciones al establecer conexión con esta tabla. * @param connection Conexión para hacer las queries de las demás tablas. * @param table Aquí no hace nada pero lo necesito como parámetro en las otras tablas del extends. */ @Override public void onConnect(Connection connection, GenericTable table) { super.onConnect(connection, this); super.connection = connection; try { CustomTableFormat tbl = Query.getAlbums(connection); for (String column : tbl.columnNames) { super.model.addColumn(column); } for (String[] row : tbl.rows) { super.model.addRow(row); } // Funciones de categorías a demás de activar las otras tablas. if (super.model.getRowCount() > 0) { super.selectFirst(); buildTable.onConnect(connection, this); MainWindow.genericLabel1.setText("Editar categoría seleccionada"); MainWindow.genericLabel2.setText("Insertar build"); MainWindow.genericLabel3.setText(""); MainWindow.genericButton1.setText("Editar"); MainWindow.genericButton1.setVisible(true); MainWindow.genericButton2.setText("Insertar"); MainWindow.genericButton2.setVisible(true); MainWindow.genericButton3.setText(""); MainWindow.genericButton3.setVisible(false); } } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * Reseteo al cerrar las conexiones. */ @Override public void onClosed() { super.onClosed(); if (buildTable != null) { buildTable = null; } if (authorTable != null) { authorTable = null; } } /** * Acciones al pulsar en alguna categoría. * @param listSelectionEvent el Event Listener. */ @Override public void valueChanged(ListSelectionEvent listSelectionEvent) { super.valueChanged(listSelectionEvent); if (listSelectionEvent.getValueIsAdjusting()) { // Da dos pulsos, uno al presionar el click y otro al soltarlo, este es el fix. if (getSelectedRow() == -1) return; if (buildTable != null && getSelectedRow() != -1) { buildTable.onClosed(); if (buildTable.authorTable != null) { buildTable.authorTable.onClosed(); } buildTable.onConnect(connection, this); // Refresco las conexiones cada vez que selecciono un nuevo album. } } } /** * A diferencia del de arriba, este solo cambia las acciones cuando detecta que cambias de tabla. * @param i parámetros * @param i1 raros * @param b del * @param b1 override */ @Override public void changeSelection(int i, int i1, boolean b, boolean b1) { super.changeSelection(i, i1, b, b1); if (getSelectedRow() == -1) return; MainWindow.genericLabel1.setText("Editar categoría seleccionada"); MainWindow.genericLabel2.setText("Insertar build"); MainWindow.genericLabel3.setText(""); MainWindow.genericButton1.setText("Editar"); MainWindow.genericButton1.setVisible(true); MainWindow.genericButton2.setText("Insertar"); MainWindow.genericButton2.setVisible(true); MainWindow.genericButton3.setText(""); MainWindow.genericButton3.setVisible(false); } }
Swift
UTF-8
758
2.625
3
[]
no_license
// // SettingsOverlayView.swift // AMillionMaps // // Created by Malte Klemm on 17.07.20. // Copyright © 2020 Malte Klemm. All rights reserved. // import SwiftUI struct SettingsOverlayView<Content: View>: View { @Environment(\.colorTheme) var colorTheme: ColorTheme let viewBuilder: () -> Content init(_ viewBuilder: @escaping () -> Content) { self.viewBuilder = viewBuilder } var body: some View { ZStack { Rectangle().foregroundColor(colorTheme.uiBackground.tinted(amount: 0.05).color).softHorizontalInnerShadow(Rectangle(), spread: 0.1, radius: 5) self.viewBuilder() } } } struct SettingsOverlayView_Previews: PreviewProvider { static var previews: some View { SettingsOverlayView { Text("Hi") } } }
Markdown
UTF-8
2,205
3.03125
3
[]
no_license
# CS426-Assignment-6,7 and 8 CS 426 Assignment 7 added features: For this assignment, we added several improvements to the physics and lighting. For the physics, we improved the jump and double jump while also adding a dash. Since this game is centered around climbing, it's appropriate to have multiple movement based abiltiies to reach harder platforms. We also added some lighting for each of the Ai's to make them stand out. The attack and patrol Ai's have flashlights and actively go after the player. These ai's act as the guards of the tower. They can push players off platforms, shoot at the player to obstruct movement and send the player back to the beginning upon collision. Towers are full of rats. We have an animated model of old man rat at the very bottom of the tower. His job is to guard the teleporter but other than that, he's completely harmless. There are also rats who act as guides. On some floors, animated rats point you towards the right direction. The third animation is a place holder for now since there's no rigged model that fits the theme. CS 426 Assignment 8 added features: -Included a title screen with instructions on how to control the character. Since our game doesn't really make much use of on screen interactive buttons. The best changes we can make to the UI is a title screen that explains to the player everything he needs to know about how to control the character. -Included a play button to transition to starting scene. -Added 2 new levels. Since our game is a bit too easy at this point in time, added a few new levels with harder jumps. -Added new background music to each level. This is to give each level a different feel. -Added a new feature that teleports the player back to a checkpoint in a case where the player falls. Required because there's no way back up. CS 426 Assignment 9 added features: - We added a new dash because our test users said that it was too clunky. - We added better box coliders for platforms. - We added 3 shaders to the maps to make the look of the game more sophisticated. It makes the game look better, since it matches our theme better as well. - We also added a credit and instruction screen for the requirements.
Swift
UTF-8
7,026
2.65625
3
[]
no_license
// // TransmissionConnector.swift // TorrentConnect // // Created by Turchenko Alexander on 26.08.15. // Copyright © 2015 Turchenko Alexander. All rights reserved. // import Foundation enum RequestError { case authorizationError case parseError case fileError(String) } struct TransmissionAdapter { let parser = TransmissionParser() let rpc = TransmissionRpc() fileprivate let _credentialsManager = CredentialsManager() fileprivate func getBasicHeader(_ host: String, port: Int) -> String? { if let credentials = _credentialsManager.getCredentials(host, port: port) { let loginString = "\(credentials.username):\(credentials.password)" let loginData = loginString.data(using: String.Encoding.utf8) let base64EncodedCredential = loginData!.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength64Characters) return "Basic \(base64EncodedCredential)" } return nil } fileprivate func setupAuthorization(_ request: URLRequest) -> URLRequest { var newRequst = request if let url = newRequst.url { if let basicHeader = getBasicHeader(url.host!, port: (url as NSURL).port!.intValue) { newRequst.setValue(basicHeader, forHTTPHeaderField: "Authorization") } } return newRequst } fileprivate func postRequest(_ url: URL, request: RpcRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" urlRequest.httpBody = request.toJson().data(using: String.Encoding.utf8) urlRequest = setupAuthorization(urlRequest) let requestTask = URLSession.shared.dataTask(with: urlRequest, completionHandler: completionHandler) requestTask.resume() } fileprivate func authorizedRequest(_ connection: TransmissionServerConnection, request: RpcRequest, success: @escaping (Data) -> (), error: @escaping (RequestError) -> ()) { let url = connection.settings.getServerUrl() let sessionId = connection.sessionId let body = request.toJson() var urlRequest = URLRequest(url: url as URL) urlRequest.httpMethod = "POST" urlRequest.httpBody = body.data(using: String.Encoding.utf8) urlRequest = setupAuthorization(urlRequest) urlRequest.setValue(sessionId, forHTTPHeaderField: "X-Transmission-Session-Id") let requestTask = URLSession.shared.dataTask(with: urlRequest, completionHandler: { data, response, _ in if let response = response as? HTTPURLResponse { if response.statusCode == 409 || response.statusCode == 401 { error(RequestError.authorizationError) return } } if let data = data { success(data) } }) requestTask.resume() } } extension TransmissionAdapter { func connect(_ settings: ConnectionSettings, success: @escaping (TransmissionServerConnection) -> (), error: @escaping (RequestError) -> ()) { let url = settings.getServerUrl() postRequest(url as URL, request: rpc.getSessionId()) { _, response, _ in if let sessionId = self.parser.getSessionId(response) { let connection = TransmissionServerConnection(settings: settings, sessionId: sessionId) success(connection) } else { error(.authorizationError) } } } func torrents(_ connection: TransmissionServerConnection, success: @escaping ([Torrent]) -> (), error: @escaping (RequestError) -> ()) { self.authorizedRequest(connection, request: rpc.getTorrents(), success: { data in switch self.parser.getTorrents(data) { case .first(let torrents): success(torrents) case .second(let requestError): error(requestError) } }, error: error) } func stop(_ connection: TransmissionServerConnection, ids: [Int], success: @escaping () -> (), error: @escaping (RequestError) -> ()) { self.authorizedRequest(connection, request: rpc.stopTorrents(ids), success: { _ in success() }, error: error) } func start(_ connection: TransmissionServerConnection, ids: [Int], success: @escaping () -> (), error: @escaping (RequestError) -> ()) { self.authorizedRequest(connection, request: rpc.startTorrents(ids), success: { _ in success() }, error: error) } func add(_ connection: TransmissionServerConnection, url: String, paused: Bool, success: @escaping () -> (), error: @escaping (RequestError) -> ()) { self.authorizedRequest(connection, request: rpc.addTorrent(url: url, paused: paused), success: { _ in success() }, error: error) } func add(_ connection: TransmissionServerConnection, filename: String, paused: Bool, success: @escaping () -> (), error: @escaping (RequestError) -> ()) { let trydata = try? Data(contentsOf: URL(fileURLWithPath: filename)) if let data = trydata { let metainfo = data.base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithLineFeed) self.authorizedRequest(connection, request: rpc.addTorrent(metainfo: metainfo, paused: paused), success: { _ in success() }, error: error) return } error(.fileError(filename)) } func delete(_ connection: TransmissionServerConnection, ids: [Int], deleteLocalData: Bool, success: @escaping () -> (), error: @escaping (RequestError) -> ()) { authorizedRequest(connection, request: rpc.deleteTorrents(ids, deleteLocalData: deleteLocalData), success: { _ in success() }, error: error) } func files(_ connection: TransmissionServerConnection, ids: [Int], success: @escaping ([TorrentFile]) -> (), error: @escaping (RequestError) -> ()) { authorizedRequest(connection, request: rpc.getTorrentFiles(ids), success: { data in switch self.parser.getTorrentFiles(data) { case .first(let files): success(files) case .second(let requestError): error(requestError) } }, error: error) } func move(_ connection: TransmissionServerConnection, ids: [Int], location: String, success: @escaping () -> (), error: @escaping (RequestError) -> ()) { authorizedRequest(connection, request: rpc.moveTorrents(ids, location: location), success: { _ in }, error: error) } func setFiles(_ connection: TransmissionServerConnection, id: Int, wanted: [Int], unwanted: [Int], success: @escaping () -> (), error: @escaping (RequestError) -> ()) { authorizedRequest(connection, request: rpc.wantFiles(forTorrent: id, wanted: wanted, unwanted: unwanted), success: { _ in success() }, error: error) } }
Java
UTF-8
5,771
3.671875
4
[]
no_license
/** * Demonstrate the StockManager and Product classes. * The demonstration becomes properly functional as * the StockManager class is completed. * * @author David J. Barnes and Michael Kölling. * @version 2016.02.29 */ public class StockDemo { // The stock manager. private StockManager manager; /** * Create a StockManager and populate it with a few * sample products. */ public StockDemo() { manager = new StockManager(); manager.addProduct(new Product(100, "Fishhh")); manager.addProduct(new Product(101, "Burgers")); manager.addProduct(new Product(102, "Fishcakes")); manager.addProduct(new Product(103, "Bubble Tea")); manager.addProduct(new Product(104, "Bread")); manager.addProduct(new Product(105, "Bakewells")); manager.addProduct(new Product(106, "Oraaange")); manager.addProduct(new Product(107, "Milk")); manager.addProduct(new Product(108, "Panccakes")); manager.addProduct(new Product(109, "Milkshake")); } /** * Provide a very simple demonstration of how a StockManager * might be used. Details of one product are shown, the * product is restocked, and then the details are shown again. */ public void demo() { System.out.println(""); // Prints the list of products and their details System.out.println("manager.printStockList();"); System.out.println(""); manager.printStockList(); System.out.println(""); // Accepting delivery of various quantities to multiple products System.out.println("manager.acceptDelivery(100, 5)"); System.out.println("manager.acceptDelivery(101, 3)"); System.out.println("manager.acceptDelivery(102, 34)"); System.out.println("manager.acceptDelivery(103, 65)"); System.out.println("manager.acceptDelivery(104, 75)"); System.out.println("manager.acceptDelivery(105, 190)"); System.out.println("manager.acceptDelivery(106, 9)"); System.out.println("manager.acceptDelivery(107, 10)"); System.out.println("manager.acceptDelivery(108, 53)"); System.out.println("manager.acceptDelivery(109, 154)"); System.out.println(""); manager.acceptDelivery(100, 5); manager.acceptDelivery(101, 3); manager.acceptDelivery(102, 34); manager.acceptDelivery(103, 65); manager.acceptDelivery(104, 75); manager.acceptDelivery(105, 190); manager.acceptDelivery(106, 9); manager.acceptDelivery(107, 10); manager.acceptDelivery(108, 53); manager.acceptDelivery(109, 154); System.out.println(""); // Print method to prove delivery System.out.println("manager.printStockList();"); System.out.println(""); manager.printStockList(); System.out.println(""); // Sells various quantities of some products System.out.println("manager.sellProduct(100, 10)"); System.out.println("manager.sellProduct(101, 2)"); System.out.println("manager.sellProduct(102, 34)"); System.out.println("manager.sellProduct(103, 66)"); System.out.println("manager.sellProduct(104, 56)"); System.out.println("manager.sellProduct(105, 145)"); System.out.println("manager.sellProduct(106, 8)"); System.out.println("manager.sellProduct(107, 25)"); System.out.println("manager.sellProduct(108, 46)"); System.out.println("manager.sellProduct(109, 79)"); System.out.println(""); manager.sellProduct(100, 10); manager.sellProduct(101, 2); manager.sellProduct(102, 34); manager.sellProduct(103, 66); manager.sellProduct(104, 56); manager.sellProduct(105, 145); manager.sellProduct(106, 8); manager.sellProduct(107, 25); manager.sellProduct(108, 46); manager.sellProduct(109, 79); System.out.println(""); // Print method to prove sale of products System.out.println("manager.printStockList();"); System.out.println(""); manager.printStockList(); System.out.println(""); // Rename a few products System.out.println("manager.renameProduct(100, 'Fish');"); System.out.println("manager.renameProduct(106, 'Oranges');"); System.out.println("manager.renameProduct(108, 'Pancakes');"); manager.renameProduct(100, "Fish"); manager.renameProduct(106, "Oranges"); manager.renameProduct(108, "Pancakes"); System.out.println(""); // Print method to prove name changes System.out.println("manager.printStockList();"); System.out.println(""); manager.printStockList(); System.out.println(""); // Remove a product based on ID System.out.println("manager.removeProduct(109);"); System.out.println(""); manager.removeProduct(109); // Print method to prove removal of product System.out.println("manager.printStockList();"); System.out.println(""); manager.printStockList(); System.out.println(""); // Printing a list of products low on stock System.out.println("manager.checkStockLevels();"); System.out.println(""); manager.checkStockLevels(); System.out.println(""); // Printing products based on a part of their name System.out.println("manager.printPartialProductName('B');"); System.out.println(""); manager.printPartialProductName("B"); System.out.println(""); } /** * Returns the stock manager */ public StockManager getManager() { return manager; } }
Markdown
UTF-8
3,656
2.765625
3
[]
no_license
# Git 常用命令(Git Bash) 取得项目的 git 仓库 ```shell $ git clone xxx ``` 查看仓库状态 ```shell $ git status ``` 列出仓库的所有分支,包括远程分支 ```shell $ git branch -a ``` 基于 master 分支创建并切换到新的分支 master_hotfix ```shell $ git checkout master $ git checkout -b master_hotfix ``` 删除本地 master_hotfix 分支 ```shell $ git branch -d master_hotfix ``` 删除远程 origin/master_hotfix 分支 ```shell $ git push origin --delete master_hotfix ``` 将本地 master_hotfix 分支合并到本地 master 分支 ```shell $ git checkout master $ git merge master_hotfix ``` 把所有文件放入暂存区域 ```shell $ git add . ``` 提交,自动暂存已修改和删除的文件,并同时书写 commit message ```shell $ git commit -am 'hello world' ``` 在 master 分支 push 之前修改最后一次提交的 commit message ```shell $ git checkout master $ git commit --amend ``` 将本地的 master 分支推送到 origin 主机,同时指定 origin 为默认主机(后面就可以不加任何参数使用 git push 了) ```shell $ git push -u origin master ``` 更新本地仓库中的所有远程分支,并删除所有本地存在但远程上不存在的远程分支 ```shell $ git fetch -p ``` 拉取 origin/master 远程分支的最新信息并合并到本地 master 分支 ```shell $ git checkout master $ git pull # 等价于 $ git checkout master $ git fetch $ git merge origin/master ``` 改写 master 分支的本地历史,将 HEAD 指向 becd81c9 这次提交 ```shell $ git checkout master $ git reset --hard becd81c9 ``` 改写 master 分支的本地历史,将 HEAD 指向 becd81c9 这次提交,同时保留更改的文件 ```shell $ git checkout master $ git reset --mixed becd81c9 ``` 改写 master 分支的远程历史,撤销 becd81c9 这次提交 ```shell $ git checkout master $ git revert becd81c9 $ git push ``` 将分支 master_hotfix 的 becd81c9 这次提交复制到 master 分支 ```shell $ git checkout master $ git cherry-pick becd81c9 ``` 预览 master 分支与 master_hotfix 分支的差异 ```shell $ git diff master master_hotfix ``` 内建的图形化 git ```shell $ gitk ``` 显示历史记录时,每个提交的信息只显示一行 ```shell $ git log --pretty=oneline ``` 查看 git 已有的配置信息 ```shell $ git config --list ``` 查看 git 作者 ```shell $ git config --global user.name ``` 配置 git 作者 ```shell $ git config --global user.name 'xxx' ``` 查看 git 邮箱 ```shell $ git config --global user.email ``` 配置 git 邮箱 ```shell $ git config --global user.email 'xxx@xxx.xxx' ``` 将分支名 master_old 改为 master_new ```shell $ git branch -m master_old master_new $ git push origin --delete master_old $ git push -u origin master_new ``` 查看未合并到 master 的分支 ```shell $ git branch --no-merged master ``` 查找包含 becd81c9 这次提交的分支列表 ```shell $ git branch --contains becd81c9 ``` 查看当前分支所有提交者及其提交次数,按次数由高到低排序 ```shell $ git log | grep "^Author: " | awk '{print $2}' | sort | uniq -c | sort -k1,1nr ``` 分析 Git 日志来统计代码量 ```shell $ git log --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }' - ``` # 参考 [Git-Book](https://git-scm.com/book/zh/v2) [git 简明指南](https://www.runoob.com/manual/git-guide/) [Learn Git Branching](https://learngitbranching.js.org/) [图解 Git](http://marklodato.github.io/visual-git-guide/index-zh-cn.html)
Python
UTF-8
5,180
2.65625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # @file: railgun/website/hw.py # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This file is released under BSD 2-clause license. """This module contains the proxies to :class:`~railgun.common.hw.Homework` and :class:`~railgun.common.hw.HwSet` instances. What is a proxy? A proxy is a container to another object. All the access, including getting or setting the attributes, calling methods, and any other operations, will be redirected from the container to the actual object. Why proxy? Because we can change the behaviour of a given object without change its code. For example, :class:`~railgun.common.hw.Homework` contains the titles and descriptions for all languages. However, the visitor only wants one version. Rather than accessing the correct resources carefully with an explicit language identity, we wrap the original objects with a simple proxy object, and we may just use `hw.title` to replace `hw.info[lang].title`. """ import os from flask import g, url_for from flask.ext.login import current_user from railgun.common.hw import HwSet, utc_now from .context import app from .i18n import get_best_locale_name class HwProxy(object): """Per-request proxy to :class:`~railgun.common.hw.Homework`. The best locale for current user will be detected during :meth:`__init__` method. :param hw: The original :class:`~railgun.common.hw.Homework` object. :type hw: :class:`~railgun.common.hw.Homework` """ def __init__(self, hw): self.hw = hw # determine the best info to be selected locale = get_best_locale_name(hw.get_name_locales()) self.info = [i for i in hw.info if i.lang == locale][0] def __getattr__(self, key): return getattr(self.hw, key) # the following methods are extensions to common.hw.Homework. def is_locked(self): """Whether this homework is locked? You may put the uuid of locked homework in ``config.LOCKED_HOMEWORKS``. If you wish to lock all homework assignments, put a "``*``" in it. """ return self.hw.uuid in app.config['LOCKED_HOMEWORKS'] or \ '*' in app.config['LOCKED_HOMEWORKS'] def is_hidden(self): """Whether this homework is hidden? You may put the uuid of hidden homework in ``config.HIDDEN_HOMEWORKS``. If you wish to lock all homework assignments, put a "``*``" in it. """ return self.hw.uuid in app.config['HIDDEN_HOMEWORKS'] or \ '*' in app.config['HIDDEN_HOMEWORKS'] def attach_url(self, lang): """Get the attachment url for given programming language. The url should refer to :func:`~railgun.website.views.hwpack`. :param lang: The identity of programming language. :type lang: :class:`str` :return: The attachment url address. """ return url_for('hwpack', slug=self.slug, lang=lang) def attach_size(self, lang): """Get the attachment file size for given programming language. If the file does not exist, return :data:`None`. :param lang: The identity of programming language. :type lang: :class:`str` :return: The attachment file size or :data:`None`. """ fpath = os.path.join( app.config['HOMEWORK_PACK_DIR'], '%s/%s.zip' % (self.slug, lang) ) if os.path.isfile(fpath): return os.path.getsize(fpath) return None class HwSetProxy(object): """Per-request proxy to :class:`~railgun.common.hw.HwSet`. You may hide some homework assignments to the visitor, so a proxy to :class:`~railgun.common.hw.HwSet` is necessary. :param hwset: The original :class:`~railgun.common.hw.HwSet` object. :type hwset: :class:`~railgun.common.hw.HwSet` """ def __init__(self, hwset): # cache all HwProxy instances self.items = [HwProxy(hw) for hw in hwset] # build slug-to-hw and uuid-to-hw lookup dictionary self.__slug_to_hw = {hw.slug: hw for hw in self.items} self.__uuid_to_hw = {hw.uuid: hw for hw in self.items} def __iter__(self): """Iterate through all :class:`HwProxy` instances. :return: Iterable object of :class:`HwProxy` instances. """ if not current_user.is_anonymous() and current_user.is_admin: return iter(self.items) return (i for i in self.items if not i.is_hidden()) def get_by_uuid(self, uuid): """Get the homework with given uuid. :param uuid: The homework uuid. :type uuid: :class:`str` :return: The requested :class:`HwProxy` or :data:`None` if not found. """ return self.__uuid_to_hw.get(uuid, None) def get_by_slug(self, slug): """Get the homework with given slug. :param slug: The homework slug. :type slug: :class:`str` :return: The requested :class:`HwProxy` or :data:`None` if not found. """ return self.__slug_to_hw.get(slug, None)
Java
UTF-8
407
1.539063
2
[]
no_license
package com.puzzle; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan(value="com.puzzle.mapper") public class ApplyJobApplication { public static void main(String[] args) { SpringApplication.run(ApplyJobApplication.class, args); } }
Python
UTF-8
504
3.421875
3
[ "LicenseRef-scancode-public-domain" ]
permissive
import os def count_lines(filename, comment): """ Count lines in a file excluding the comment :param filename: Path to the file to count :param comment: Comment char or string at the beginning of the line to exclude :return: """ count = 0 if os.path.exists(filename) and os.path.getsize(filename) != 0: with open(filename, 'r') as fin: for line in fin: if not line.startswith(comment): count += 1 return count
Java
UTF-8
290
2.09375
2
[]
no_license
package array; import java.util.ArrayList; import java.util.List; /** * @author Baitao Zou * date 2021/02/08 */ public class Skyline218 { public List<List<Integer>> getSkyline(int[][] buildings) { List<List<Integer>> result = new ArrayList<>(); return result; } }
C#
UTF-8
419
3.046875
3
[]
no_license
using System; namespace CourseLibrary.API.Helpers { public static class DateTimeExtensions { public static int GetAge(this DateTimeOffset dateTime) { var currentDate = DateTime.Today; var age = currentDate.Year - dateTime.Year; if(currentDate < dateTime.Date) { age--; } return age; } } }
JavaScript
UTF-8
474
3.109375
3
[]
no_license
/** * Created by yuzhou on 15/8/20. */ var obj_txt = '{"firstname": "terry", "lastname": "lee", "addr":{' + '"street": "中国村创业大街氪空间", "city": "北京"}}'; var obj = JSON.parse(obj_txt); var str = "<h4>解析后的JSON对象数据结构:</h4><hr/>"; str += "姓: " + obj.firstname + "<br/>"; str += "名: " + obj.lastname + "<br/>"; str += "地址: " + obj.addr.street + "<br/>"; str += "城市: " + obj.addr.city + "<br/>"; document.write(str);
C++
UTF-8
3,486
3.171875
3
[]
no_license
// // Created by yh on 17-6-22. // #include "machine.h" #include <stdlib.h> #include <vector> #include "ctime" #include <sys/timeb.h> Machine::Machine() { initilized_ = false; top_index_ = 0; } Machine::~Machine() {} /* 初始化牌组 对于花色:0代表黑桃、1代表红桃、2代表梅花、3代表方块 对于值:0代表two,1代表three ... 12代表A */ void Machine::init(const Cards hole_com_cards) { cards_.cards_.clear(); for (int i = 0; i < SUIT_SIZE; ++i) { for (int j = 0; j < CARD_RANK; ++j) { Card c; c.value_ = j; c.suit_ = i; cards_.cards_.push_back(c); } } size_t len = cards_.cards_.size(); know_cards_ = hole_com_cards; top_index_ = 0; initilized_ = true; } /* 洗牌!!游戏每次开始时候调用,允许多次调用。 随机序列生成的逻辑是这样的: 从后往前,N个数为例。 先生成一0~~N-1的随机数i,然后置换i和N之间的位置 同理处理N-1.... */ void Machine::shuffleCards() { if(initilized_ == false) { //error std::cout << "error! you must init Machine first"<<std::endl; } else { int len = cards_.cards_.size(); removeKonwnCards();//把目前已知的牌删除 int len1 = cards_.cards_.size(); int konwn_cards_num = know_cards_.cards_.size(); // 要取得[a,b]的随机整数,使用(rand() % (b-a+1))+ a (结果值含a和b) int card_num = SUIT_SIZE*CARD_RANK -konwn_cards_num; int rand_int = 0; for (int i = card_num - 1; i > 0 ; i--) { //struct timeb timeSeed; //ftime(&timeSeed); //double time = timeSeed.time * 1000 + timeSeed.millitm; // srand(timeSeed.time * 1000 + timeSeed.millitm); // milli time rand_int = rand()%i;//[0 - 51-konwn_cards_num] swapCard(i,rand_int); } top_index_ = 0; } } Card Machine::dealCard() { Card c = cards_.cards_[top_index_]; top_index_++; if(top_index_ == SUIT_SIZE*CARD_RANK) { shuffleCards(); } return c; } void Machine::swapCard(int i, int j) { Card temp; temp.suit_ = cards_.cards_[i].suit_; temp.value_ = cards_.cards_[i].value_; cards_.cards_[i] = cards_.cards_[j]; cards_.cards_[j] = temp; } void Machine::showCards() { for (int i = 0; i < SUIT_SIZE*CARD_RANK ; ++i) { std::cout <<SUIT_NAME[cards_.cards_[i].suit_]<<" " << cards_.cards_[i].value_<<std::endl; } } void Machine::removeKonwnCards()//用于计算胜率的时候,把已知的牌移除,使得胜率计算更加准确 { if(know_cards_.cards_.size()>7) { std::cout<<"error occurs,int the removeKonwnCards() "<<std::endl; } std::vector<Card>::iterator it ; for(int i = 0;i< know_cards_.cards_.size(); ++i) { int known_card_rank = convertCardToNum(know_cards_.cards_[i]); it = cards_.cards_.begin(); while (it != cards_.cards_.end()) { int cards_rank = convertCardToNum( *it ); if(cards_rank == known_card_rank) { cards_.cards_.erase(it); it++; break; } else { it++; } } } } int Machine::convertCardToNum(const Card c) { int card_rank = c.suit_ * 13 + c.value_; return card_rank; }
C#
UTF-8
1,806
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MySql.Data.MySqlClient; using System.Data; using System.Security.Cryptography; using System.Text; public partial class login : System.Web.UI.Page { //Mysql bağlantısı MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=db;User Id=root;password=''"); protected void Page_Load(object sender, EventArgs e) {} //Login butonu protected void b1_Click(object sender, EventArgs e) { //Girilen kullanıcı adı ve parolası(SHA1 algoritması ile hash yapılarak sorgular) veri tabanında sorgulanarak kullanıcı girişinin sağlanması con.Open(); SHA1 sha = new SHA1CryptoServiceProvider(); String pw = t2.Text; String hashpw = Convert.ToBase64String(sha.ComputeHash(Encoding.UTF8.GetBytes(pw))); MySqlCommand cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from users where customerId='" + t1.Text + "' and password='" + hashpw + "'"; cmd.ExecuteNonQuery(); DataTable dt = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(cmd); da.Fill(dt); foreach (DataRow dr in dt.Rows) { Session["customerId"] = dr["customerId"].ToString(); Response.Redirect("index.aspx"); } con.Close(); //Geçersiz kullanıcı durumunda uyarı Label1.Text = "Invalid username or password"; } //Register butonu ile register sayfasına yönlendirme protected void b2_Click(object sender, EventArgs e) { Response.Redirect("register.aspx"); } }
Python
UTF-8
157
2.6875
3
[]
no_license
n=int(input()) m=int(input()) t=int(input()) mx,my=n,m for _ in range(t): l=eval('[' + input()+ ']') mx=min(mx,l[0]) my=min(my,l[1]) print(mx*my)
Java
UTF-8
387
1.882813
2
[]
no_license
package com.samuel.vitorio.workshopmongo.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.samuel.vitorio.workshopmongo.domain.Post; @Repository public interface PostRepository extends MongoRepository<Post, String>{ List<Post> findByTitleContaining(String text); }
Java
UTF-8
964
2.65625
3
[]
no_license
package intermediateModelHelper.indexing.structure; import intermediateModel.interfaces.IASTVar; import intermediateModelHelper.envirorment.Env; import java.util.ArrayList; import java.util.List; /** * @author Giovanni Liva (@thisthatDC) * @version %I%, %G% */ public class IndexEnv { List<IndexParameter> vars = new ArrayList<>(); public IndexEnv() { } public IndexEnv(List<IndexParameter> vars) { this.vars = vars; } public IndexEnv(Env e){ convertEnv(e); } private void convertEnv(Env e) { for(IASTVar v : e.getVarList()){ vars.add(new IndexParameter( v.getType(), v.getName() )); } if(e.getPrev() != null){ convertEnv(e.getPrev()); } } public List<IndexParameter> getVars() { return vars; } public void setVars(List<IndexParameter> vars) { this.vars = vars; } public IndexParameter getVar(String name){ for(IndexParameter p : vars){ if(p.getName().equals(name)){ return p; } } return null; } }
Java
UTF-8
1,831
1.875
2
[]
no_license
package com.example.mysql; //import com.mantri.budgetbuddy.R; //import android.support.v7.app.ActionBarActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener{ Button bRegister, bSubmit ,bConnect; EditText etuserName, etuserPass; String loginName, loginPass; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etuserName = (EditText) findViewById(R.id.etUserName); etuserPass = (EditText) findViewById(R.id.etPassword); bSubmit = (Button) findViewById(R.id.bSubmit); bRegister = (Button) findViewById(R.id.bCreateUser); bConnect = (Button) findViewById(R.id.bOnlineConnect); bSubmit.setOnClickListener(this); bRegister.setOnClickListener(this); bConnect.setOnClickListener(this); } /**** public void userReg(View v) { startActivity(new Intent(this, Register.class)); } public void userLogin(View v) { } ****/ @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.bCreateUser: startActivity(new Intent(this, Register.class)); break; case R.id.bSubmit: loginName = etuserName.getText().toString(); loginPass = etuserPass.getText().toString(); /**** String method = "login"; BackGroundTask bgt = new BackGroundTask(this); //String result=""; bgt.execute(method,loginName,loginPass); ***/ break; case R.id.bOnlineConnect: //startActivity(new Intent(this, JSONConnect.class)); startActivity(new Intent(this, OnlineAccount.class)); break; } } }
Python
UTF-8
5,210
2.5625
3
[]
no_license
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt import os import sys import datetime from DayCSVData import DayCSVData class TestStrategy(bt.Strategy): params = ( ('maperiod', 15), ('printlog', False) ) def log(self, txt, dt=None, doprint=False): ''' Logging function for this strategy''' if self.params.printlog or doprint: dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close self.datahigh = self.datas[0].high self.datahighdelay = self.datas[0].high(-1) self.preclose = self.datas[0].close(-1) self.order = None self.buyprice = None self.buycomm = None # self.sma = bt.indicators.MovingAverageSimple(self.datas[0], period=self.params.maperiod) self.upmove = self.datahigh - self.datahigh(-1) # bt.indicators.ExponentialMovingAverage(self.datas[0], period=25) # bt.indicators.WeightedMovingAverage(self.datas[0], period=25, subplot=True) # bt.indicators.Stochastic(self.datas[0]) # rsi = bt.indicators.RSI(self.datas[0]) # bt.indicators.SmoothedMovingAverage(rsi, period=15) # bt.indicators.ATR(self.datas[0], plot=False) # sma0 = bt.indicators.SMA(self.data0, period=15) # def notify_order(self, order): # if order.status in [order.Submitted, order.Accepted]: # return # # if order.status in [order.Completed]: # if order.isbuy(): # self.log('BUY EXECUTED, price: %.2f, cost: %.2f, comm: %.2f' % # (order.executed.price, # order.executed.value, # order.executed.comm)) # # self.buyprice = order.executed.price # self.buycomm = order.executed.comm # # elif order.issell(): # self.log('BUY EXECUTED, price: %.2f, cost: %.2f, comm: %.2f' % # (order.executed.price, # order.executed.value, # order.executed.comm)) # # self.bar_executed = len(self) # # elif order.status in [order.Canceled, order.Margin, order.Rejected]: # self.log("Order Canceled/Margin/Rejected") # # self.order = None # # def notify_trade(self, trade): # if not trade.isclosed: # return # # self.log('OPERATION PROFIT, gross %.2f, net %.2f' % # (trade.pnl, trade.pnlcomm)) def next(self): # Simply log the closing price of the series from the reference # self.log('Close, %.2f' % self.dataclose[0], doprint=True) self.log('close, %.2f' % self.dataclose[0], doprint=True) self.log('preclose, %.2f' % self.preclose[0], doprint=True) r_t = self.dataclose[0]-self.preclose[0] r_t = r_t/self.dataclose[0] self.log('rt, %.8f' % r_t, doprint=True) # if self.order: # return # # if not self.position: # if self.dataclose[0] > self.sma[0]: # self.log('BUY created, %.2f' % self.dataclose[0]) # self.order = self.buy() # # else: # if self.dataclose[0] < self.sma[0]: # self.log('SELL created, %.2f' % self.dataclose[0]) # self.order = self.sell() # def stop(self): # self.log('(MA Period %2d) Ending Value %.2f' % # (self.params.maperiod, self.broker.getvalue()), doprint=True) if __name__ == '__main__': cerebro = bt.Cerebro(stdstats=False, optdatas=True) modpath = os.path.dirname(os.path.abspath(sys.argv[0])) datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt') data = bt.feeds.YahooFinanceCSVData( dataname=datapath, # Do not pass values before this date fromdate=datetime.datetime(2000, 1, 1), # Do not pass values after this date todate=datetime.datetime(2000, 12, 31), reverse=False) data1 = DayCSVData( # dataname="D:/data/day_data/whole_data.csv", dataname="D:/data/day_data/sh600000_qfq.csv", fromdate=datetime.datetime(2011, 1, 1), todate=datetime.datetime(2011, 12, 31), ) # cerebro.adddata(data) cerebro.adddata(data1) cerebro.addsizer(bt.sizers.FixedSize, stake=10) cerebro.broker.set_cash(1000.0) cerebro.broker.setcommission(commission=0.0) cerebro.addstrategy(TestStrategy) # cerebro.optstrategy( # TestStrategy, # maperiod=range(10, 31) # ) # print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) from time import time st_time = time() cerebro.run() end_time = time() elapse = end_time - st_time print('whole time elapse: %f' % elapse) # print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) # cerebro.plot()
Python
UTF-8
800
3.21875
3
[]
no_license
""" ID: warwick2 LANG: PYTHON3 TASK: friday """ with open('friday.in', 'r') as fin: in_text = fin.read() start_year = 1900 years = int(in_text) hits = [0, 0, 0, 0, 0, 0, 0] months = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] day = 2 for i in range(start_year, start_year+years): leap = i % 4==0 and (i%100 != 0 or i % 400 == 0) months[1] = 29 if leap else 28 days = 366 if leap else 365 date = 1 month = 0 for _ in range(days): if date == 13: hits[day] += 1 if (date+1) % months[month] == 1: date = 1 month += 1 else: date += 1 day += 1 day = day % 7 out = ' '.join([str(x) for x in hits]) out += '\n' with open('friday.out', 'w') as fout: fout.write(out)
Python
UTF-8
1,414
3.03125
3
[ "MIT" ]
permissive
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT """ This test will initialize the display using displayio and draw a solid white background, a smaller black rectangle, and some white text. """ import board import displayio import terminalio from adafruit_display_text import label import adafruit_displayio_ssd1306 displayio.release_displays() i2c = board.I2C() # uses board.SCL and board.SDA # i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller display_bus = displayio.I2CDisplay(i2c, device_address=0x3C) display = adafruit_displayio_ssd1306.SSD1306(display_bus, width=128, height=32) # Make the display context splash = displayio.Group() display.show(splash) color_bitmap = displayio.Bitmap(128, 32, 1) color_palette = displayio.Palette(1) color_palette[0] = 0xFFFFFF # White bg_sprite = displayio.TileGrid(color_bitmap, pixel_shader=color_palette, x=0, y=0) splash.append(bg_sprite) # Draw a smaller inner rectangle inner_bitmap = displayio.Bitmap(118, 24, 1) inner_palette = displayio.Palette(1) inner_palette[0] = 0x000000 # Black inner_sprite = displayio.TileGrid(inner_bitmap, pixel_shader=inner_palette, x=5, y=4) splash.append(inner_sprite) # Draw a label text = "Hello World!" text_area = label.Label(terminalio.FONT, text=text, color=0xFFFF00, x=28, y=15) splash.append(text_area) while True: pass
PHP
UTF-8
341
2.546875
3
[ "Apache-2.0" ]
permissive
<?php namespace blog; require_once __DIR__ . '/BlogView.php'; class StaticView extends BlogView { public function __construct($model) { parent::__construct($model); } protected function viewName() { return $this->model['content']; } protected function isActiveCaption($subUrl = null) { return !$subUrl; } }
PHP
UTF-8
923
2.515625
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "t_prodi". * * @property integer $id_prodi * @property string $nama_prodi * * @property TKelas[] $tKelas */ class Prodi extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 't_prodi'; } /** * @inheritdoc */ public function rules() { return [ [['nama_prodi'], 'required'], [['nama_prodi'], 'string', 'max' => 50], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_prodi' => 'Id Prodi', 'nama_prodi' => 'Nama Prodi', ]; } /** * @return \yii\db\ActiveQuery */ public function getTKelas() { return $this->hasMany(TKelas::className(), ['id_prodi' => 'id_prodi']); } }
Python
UTF-8
743
3.125
3
[]
no_license
# -*- coding: utf-8 -*- # LeetCode 883-三维形体投影面积 """ Created on Tues Apr 26 09:33 2022 @author: _Mumu Environment: py38 """ from typing import List class Solution: def projectionArea(self, grid: List[List[int]]) -> int: ans = 0 m = len(grid) n = len(grid[0]) col_max = [0] * n for i in range(m): raw_max = 0 for j in range(n): if grid[i][j]: ans += 1 col_max[j] = max(col_max[j], grid[i][j]) raw_max = max(raw_max, grid[i][j]) ans += raw_max ans += sum(col_max) return ans if __name__ == '__main__': s = Solution() print(s.projectionArea([[2, 0]]))
PHP
UTF-8
688
2.71875
3
[]
no_license
<?php class Controller { protected $urlParameters; protected $urlKeys; public function __construct($urlParameters = null) { if($urlParameters) $this->urlParameters = explode ('/', $urlParameters); else $this->urlParameters = array(); } protected function changeToArray($parameters = null){ $url = array(); $params = array(); $urlArray = array(); if($this->urlParameters){ var_dump($url); var_dump($this->urlKeys); $urlArray = array_combine($this->urlKeys, $this->urlParameters); } return array_merge($urlArray, $parameters); } }
Python
UTF-8
910
2.8125
3
[]
no_license
from gmail import GMail, Message import random # sickness = ["mệt", "đau đầu", "đau lưng", "đau bụng"] # sickness_list = ["sốt xuất huyết", "kiết lỵ", "đau tim", "hắc lào"] sickness_list = ["thương hàn", "kiết lị", "ebola", "sốt xuất huyết", "hiv"] gmail = GMail("Co Bau<codaubo@gmail.com>", "ngotungduongbn1997") html_template = ''' <p>Ch&agrave;o sếp,</p> <p>S&aacute;ng nay ngủ dậy em thấy <strong>{{symptom}}</strong>, b&aacute;c sỹ bảo em bị <strong>sick</strong>. Sếp cho em nghỉ l&agrave;m h&ocirc;m nay nh&eacute;.&nbsp;<img src="https://html5-editor.net/tinymce/plugins/emoticons/img/smiley-cry.gif" alt="cry" /></p> <p>Em cảm ơn sếp,</p> <p><strong>Nh&acirc;n vi&ecirc;n</strong></p> ''' html_content = html_template.replace("sick", random.choice(sickness_list)) msg = Message("Test Message", to = "codaubo97@gmail.com", html=html_template) gmail.send(msg)
Java
UTF-8
1,006
2.125
2
[]
no_license
package helloworld.example.com.jingdong.user.presenter; import helloworld.example.com.jingdong.net.OnNetLisenter; import helloworld.example.com.jingdong.user.UserBean; import helloworld.example.com.jingdong.user.model.IUserModel; import helloworld.example.com.jingdong.user.model.UserModel; import helloworld.example.com.jingdong.view.IUserActivity; /** * Created by 李天祥 on 2017/12/13. */ public class UserPresenter { private IUserActivity iUserActivity; private IUserModel iUserModel; public UserPresenter(IUserActivity iUserActivity) { this.iUserActivity = iUserActivity; iUserModel = new UserModel(); } public void getUser(String d){ iUserModel.getUser(d, new OnNetLisenter<UserBean>() { @Override public void onSuccess(UserBean userBean) { iUserActivity.showData(userBean.getData()); } @Override public void onFailure(Exception e) { } }); } }
Markdown
UTF-8
5,355
3.421875
3
[]
no_license
--- layout: post title: 乐理知识 categories: - Music tags: - ukulele - 乐理 - 和弦 --- 觉得ukulele很有意思,特意买了一个来玩,很漂亮很小巧,既然买了就要好好学\~ 和弦一直弄不明白,从头找了点理论来便于理解,但是要背的和弦还是要背,要练的指法还是要练,玩一样东西就要玩得像个样子\~(虽然小时候学过小提琴,但似乎都还给老师了\>\<我真的没有音乐天赋么= =) ### 音 音的产生是一种物理现象,是由物体的振动而产生。物体振动产生音波,并通过空气传播。我们人耳能听到的声音,大致在每秒振动11-20000次的范围内。而音乐中所使用的音,一般每秒振动27-4100次这个范围。 ### 音名,唱名,简谱 乐音体系中的各音级,都有着各自的名称。被广泛采用的就是:C D E F G A B. 被广泛采用的还有do re mi fa sol la si, 这些多用于歌唱,又叫做唱名。 音名就是音高的名称,即C、D、E、F、G、A、B。音名和音高的关系是绝对的;与音名相对的唱名则不同,唱名和音高的关系是相对的。每高或低八度的音高的音名是一样。而音名不同,音高也可以一样,见异名同音。 音名 C D E F G A B 唱名 do re mi fa sol la si 简谱 1 2 3 4 5 6 7 ### 简谱中的音符,休止符,附点,延音线 在确定了音之后,接下来的问题就是这个音唱多长的问题了。 表示音的进行的符号,叫**音符**。 5 ─ ─ ─ 全音符 4拍 5 ─ 二分音符 2拍 5 四分音符 1拍 5(下面一横线) 八分音符 1/2拍 5(下面两横线) 十六分音符 1/4拍 有音的进行,那肯定有音的停止。表示音的休止的符号,叫**休止符**。在简谱中用0表示。 4/4表示以4分音符一拍,一小节有4拍。大家也可以数下一小节是否是4拍。 附点:音符后加个点。在一个音符后面加附点,就是延长这个音符的一半 延音线:简谱中,把2个或2个以上的音,用括弧连起来,把这些音弹成一个音,时值是相加总和。 ### 音程,度数,音数 音程:两音之间的高低关系,之间的距离。 度数:音的计量单位 Do,1度。 Do Re,2度 依次类推。 特别注意 1和升1,是1度。 1和降2,是2度 音数:2音之间,半音和全音的个数 半音:键盘上相邻的2个音 全音:键盘上隔开1个音 1度就是只有1个音。那当然1个音的话也构不成半音和全音,所以音数是0. 我们也多记一个名字,叫纯一度 纯一度,音数是0 八度,当然就是八个音,如从中音的Do到高音的Do,相跨8个音。大家可以点下有多少个半音和全音,就能找到音数是多少。 纯八度,音数是6 2度就有大小之分了。 大二度,音数是1(即一个全音) 小二度,音数是0.5(即一个半音) 大三度,音数是2 小三度,音数是1.5 纯四度,音数为2.5 其音响效果是最和谐 增四度,音数为3 纯五度,音数是3.5 减五度,音数是3 大六度,音数为4.5 小六度,音数为4 小七度,音数为5 大七度,音数为5.5 ### 和弦: 三个或三个以上,按照**三度**关系叠加的音的结合。(有的童鞋可能会把和弦这个概念错误理解成只有吉他才有的东西,要知道和弦是音的叠加,在不同乐器上都能表现出来。之所以常常听见吉他和弦是因为吉他初学者只需掌握几个和弦的按法就可以进行弹唱表演了,所以这个说法比较流行罢了) 常用的是**三和弦**,由3个音组成,分别是根音,三(度)音,五(度)音 Em和弦组成3 5 7 Am和弦组成6 1 3 C和弦组成1 3 5 B7和弦组成7 #2 #4 6 (属于七和弦) 90%的和弦都是这样的,又叫做三和弦。 三和弦也有大小之分,有大三和弦和小三和弦 大三和弦:前大三度,后小三度,色彩较为**明亮**,如C和弦(1 3 5) 小三和弦:前小三度,后大三度,色彩较为**暗淡**,小三和弦后面有个m,如Am(6,1,3) 增三和弦,大三度+大三度;减三和弦,小三度+小三度 三和弦的基础上加一个三度,就是**七和弦** C7(1,3,5,7) 在此我把七和弦做了个归类,方便大家记忆 大小七和弦,大3+小3+小3 小小七和弦,小3+大3+小3 减小七和弦, 小3+小3+大3 减减七和弦, 小3+小3+小3 --- 学到现在,基本的指弹已经没问题了,但是,想要弹出好听的音乐,必须常练习。冰冻三尺,非一日之寒 在网上找到了练习左手和右手的方法。每天各10分钟。 ### 右手 拇指控制3,4弦,食指2弦,中指1弦。 p i m 指的配合练习。P指43234靠弦组合练习。i m勾弦组合练习。 交替练习,每根弦交替弹4下,3下,2下,1下 ,由慢到快,最后速度到100。 接下来是几种节奏 - (41)321(41)321 - (41)3212321 - (41)3231323 - (421)3(21)3 - (43)(21)(43)(21) <br > ### 左手 爬格子:2345,5432,2435,5342 --- 这就是,所谓的,为了偷懒,不怕麻烦吧。
Java
UTF-8
1,942
2.96875
3
[]
no_license
package com.aliaj; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import static java.lang.Math.sqrt; /** * Created by alitsiya.yusupova on 10/24/16. */ public class Fourth { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("team.in")); try { String a0 = br.readLine(); System.out.println(a0); String[] a = a0.split("\\s+"); String b0 = br.readLine(); String[] b = b0.split("\\s+"); String c0 = br.readLine(); String[] c = c0.split("\\s+"); double res = 0; res = calc(Integer.parseInt(a[0]),Integer.parseInt(b[1]),Integer.parseInt(c[2]), res); res = calc(Integer.parseInt(a[0]),Integer.parseInt(b[2]),Integer.parseInt(c[1]), res); res = calc(Integer.parseInt(a[1]),Integer.parseInt(b[0]),Integer.parseInt(c[2]), res); res = calc(Integer.parseInt(a[1]),Integer.parseInt(b[2]),Integer.parseInt(c[0]), res); res = calc(Integer.parseInt(a[2]),Integer.parseInt(b[0]),Integer.parseInt(c[1]), res); res = calc(Integer.parseInt(a[2]),Integer.parseInt(b[1]),Integer.parseInt(c[0]), res); System.out.println(res); // String everything = sb.toString(); // String[] ary = everything.split("\\s+"); // Long res = Long.parseLong(ary[0]) + Long.parseLong(ary[1])*Long.parseLong(ary[1]); // System.out.println(res); PrintWriter writer = new PrintWriter("team.out", "UTF-8"); writer.println(res); writer.close(); } finally { br.close(); } } public static double calc(int a, int b, int c, double res) { double result = sqrt(a*a + b*b +c*c); return result > res ? result : res; } }
C++
UTF-8
397
2.984375
3
[]
no_license
#include <iostream> #include <vector> #include <limits.h> using namespace std; int dfs(int n, int m) { if(m == n) return 0; if(n <= 0) return INT_MAX; cout << n << " " << m << endl; int a = dfs(n - 1, m), b = dfs(2 * n, m); return 1 + min(a, b); } int main() { int n, m; cin >> n >> m; cout <<dfs(n, m) << endl; return 0; }
C++
UTF-8
311
2.671875
3
[]
no_license
#include "Thread.h" static DWORD CALLBACK ThreadProc (LPVOID pf) { Proc* f = (Proc*)pf; (*f)(); delete f; return 0; } void Thread::init (Proc* f) { handle = CreateThread(NULL, 0, ThreadProc, (LPVOID)f, 0, NULL); } bool Thread::join (DWORD time) { return WaitForSingleObject(handle, time) == WAIT_OBJECT_0; }
JavaScript
UTF-8
2,808
2.609375
3
[]
no_license
// Load Dependencies import React from 'react' import {fetchMaps} from './../actions/apiCalls' // Main dashoard export default class AddressTable extends React.Component { constructor(props){ super(props); fetchMaps(); } addAddress = (newAddress) => { this.setState((prevState) => { return { locations: prevState.locations.concat({ address:'This is a new address', latitude:0, longitude:0}) } }) } render() { return ( <div className="container"> <div className="row"> <h1>This is the Dashboard</h1> <p>Cras eu magna pretium, accumsan nunc ac, hendrerit purus. Aliquam dictum, risus id hendrerit bibendum, diam felis luctus velit, ac dapibus turpis mauris ac lorem. Pellentesque venenatis magna nibh, sed bibendum neque laoreet eu. Praesent lorem eros, venenatis eu tincidunt sed, condimentum nec mi. Curabitur cursus est non tempus lobortis. Integer ac odio in eros aliquet cursus. Fusce ultricies lacus a tincidunt porta. Nunc sed sapien viverra, venenatis tortor et, gravida lorem. Praesent vehicula, neque id laoreet vehicula, lectus libero commodo enim, et tristique tellus mi non sapien. Donec sit amet semper purus, et sodales leo. Mauris pulvinar condimentum pulvinar. Nulla facilisi.</p> <p>Suspendisse sollicitudin, felis eget vestibulum semper, eros neque accumsan lectus, ut maximus justo risus eu felis. Nullam sagittis posuere nisi, et bibendum ex consectetur ut. Suspendisse vel luctus augue, a congue nulla. Donec congue elit et erat varius pretium. Aliquam erat volutpat. Vivamus porttitor purus ipsum, a convallis nunc ornare sed. Pellentesque id rutrum metus. Donec et nunc ac augue fringilla feugiat eu vitae nisi. In viverra ligula nunc, vitae ornare sapien finibus hendrerit. Donec nec dui vestibulum, mattis tellus vel, aliquam purus. Cras congue ac est sed tempus.</p> <p>Nam elementum mollis justo nec porttitor. Vestibulum semper est dui, quis scelerisque ipsum bibendum vitae. Mauris luctus lorem vitae ex ultricies, in pretium nulla elementum. Sed iaculis elit quis tortor dignissim ornare. Cras vehicula, diam sed commodo eleifend, nisl dolor bibendum eros, at pretium enim odio eu leo. Integer commodo eros varius justo tristique consequat. Maecenas mollis rhoncus nibh, vitae iaculis ipsum aliquam in. Pellentesque imperdiet luctus dictum. Nam quis scelerisque urna. Ut ipsum est, condimentum nec lacus ut, vestibulum ultricies est. Nullam iaculis pulvinar tincidunt. Ut risus lectus, feugiat a dignissim id, feugiat nec lacus. Nulla et egestas mauris. Suspendisse potenti.</p> </div> </div> ); } } //
Java
UTF-8
1,742
3.109375
3
[]
no_license
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class DateUtilsTest { @Nested @DisplayName("A year is a leap year") class AYearIsALeapYear { @Test @DisplayName("Year is divisible by four, but not by one hundred") public void yearIsDivisibleByFourButNotByOneHundred() { assertTrue(DateUtils.isLeapYear(2020)); } @Test @DisplayName("Year is divisible by four hundred") public void yearIsDivisibleByFourHundred() { assertTrue(DateUtils.isLeapYear(2000)); } } @Nested @DisplayName("A year is not a leap year") class AYearIsNotALeapYear { @Test @DisplayName("Year is not divisible by four") public void yearIsNotDivisibleByFour() { assertFalse(DateUtils.isLeapYear(1999)); } @Test @DisplayName("Year is divisible by one hundred, but not by four hundred") public void yearIsDivisibleByOneHundredButNotByFourHundred() { assertFalse(DateUtils.isLeapYear(2100)); } } @Nested @DisplayName("A year is not supported") class AYearIsNotSupported { @Test @DisplayName("Year is negative") public void yearIsNegative() { try { DateUtils.isLeapYear(-1); } catch (IllegalArgumentException ex) { assertEquals(ex.getMessage(), "Year must be larger than or equal to zero"); } } } }
Java
UTF-8
3,064
1.914063
2
[]
no_license
package com.pixectra.app; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.pixectra.app.Adapter.subscriptionAdapter; import com.pixectra.app.Models.subscription; import com.pixectra.app.Utils.SessionHelper; import java.util.ArrayList; /** * Created by prashu on 3/17/2018. */ public class subscription_list extends AppCompatActivity { RecyclerView recyclerview; DatabaseReference dataref; FirebaseDatabase db; subscriptionAdapter adap; ArrayList<subscription> list; DatabaseReference ref; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.subscription_list); db = FirebaseDatabase.getInstance(); ref = db.getReference("CommonData/" + new SessionHelper(this).getUid() + "/Subscriptions"); Toolbar toolbar = findViewById(R.id.toolbar_subs); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Subscriptions"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); list = new ArrayList<>(); adap = new subscriptionAdapter(this, list); ref.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { list.clear(); for (DataSnapshot data : dataSnapshot.getChildren()) { subscription subscriptions = data.getValue(subscription.class); assert subscriptions != null; subscriptions.setKey(data.getKey()); list.add(subscriptions); } findViewById(R.id.progress_subs).setVisibility(View.GONE); adap.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { findViewById(R.id.progress_subs).setVisibility(View.GONE); } }); RecyclerView recycler = findViewById(R.id.subs_recycler); recycler.setAdapter(adap); LinearLayoutManager layout = new LinearLayoutManager(getApplicationContext()); recycler.setLayoutManager(layout); /* } @Override public void onCancelled(DatabaseError databaseError) { } });*/ } }
Java
UTF-8
1,250
2.390625
2
[]
no_license
package com.gw.das.service; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; public class RedisTest { private static final Logger logger = LoggerFactory.getLogger(RedisTest.class); private RedisTemplate<String, Object> redisTemplate; private String key = "rightList"; @SuppressWarnings("unchecked") @Before public void init() { redisTemplate = ApplicationUtil.getService(RedisTemplate.class); } /** * 添加队列消息 * 获取队列消息 */ @Test public void add() { // list队列 ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(key, "1"); list.rightPush(key, "2"); list.rightPush(key, "3"); } /** * 获取队列消息 */ @Test public void get() { // list队列 ListOperations<String, Object> list = redisTemplate.opsForList(); String value1 = list.leftPop(key) + ""; String value2 = list.leftPop(key) + ""; String value3 = list.leftPop(key) + ""; logger.info(value1); logger.info(value2); logger.info(value3); } }
Java
UTF-8
10,016
2.984375
3
[]
no_license
package falstad; import falstad.MazeController.UserInput; import generation.CardinalDirection; import generation.Cells; import generation.MazeConfiguration; /** * The BasicRobot Class implements the Robot interface, the BasicRobot object called inside the MazeApplication.java file after the * ManualDriver.java object is created. The BasicRobot setMaze is set in mazeController inside switch to switchToPlayingScreen() so that * it receives the properties of a maze after it has been created. setMaze is then called again in setState under case STATE_GENERATING: so that * it can be reset when we finish a game and decide to start over. * * The BasicRobot Class is responsible for taking the commands passed to it from ManualDriver.java and either rotating the robot * or moving the robot to a new cell location. The rotate method passes a keyDown(direction) call to the maze controller, which then * actually rotates the robot in the visual maze. The same applies to the move method. The distanceToObstacle Method is called inside of the move * method in order to test to see if... We do not currently use the isAtExit, CanSeeExit, IsInsideRoom, hasRoomSensor, getCurrentDirection, * getOdometerReading, resetOdometer, getEnergyForFullRotation, getEnergyForStepFoward methods. They are not needed for the driving the maze manually. * * Collaborators: Robot, ManualDriver, MazeApplication, MazeController * * @authors Chris Wolinski & Marcelino Dayrit * */ public class BasicRobot implements Robot{ private static float battery; private boolean hasStopped; private MazeController control; private CardinalDirection curDir ; private boolean forwardSensor; private boolean backwardSensor ; private boolean leftSensor ; private boolean rightSensor; private int odometer; private static int pathLength; private int curPos[]; private Cells cells; public BasicRobot(){ this.control = null; hasStopped = false; battery = 3000; setForwardSensor(true); setBackwardSensor(true); setLeftSensor(true); setRightSensor(true); this.curPos = new int[2]; pathLength = 0; this.curPos[0] = 0; this.curPos[1] = 0; setCurDir(CardinalDirection.East); } public void test() { } @Override public void rotate(Turn turn) { if(!hasStopped()) { switch(turn) { case LEFT: if(battery < 3) { hasStopped = true; switchToExitScreen(); break; } setCurDir(getCurDir().rotateClockwise()); control.keyDown(UserInput.Left, 1); battery = battery-3; if (battery == 0) { hasStopped = true; switchToExitScreen(); } break; case RIGHT: if(battery < 3) { hasStopped = true; switchToExitScreen(); break; } setCurDir(getCurDir().rotateCounterClockwise()); control.keyDown(UserInput.Right, -1); battery = battery-3; if (battery == 0) { hasStopped = true; switchToExitScreen(); } break; case AROUND: if(battery<6) { hasStopped = true; switchToExitScreen(); break; } if(battery >= 6) { setCurDir(getCurDir().oppositeDirection()); control.keyDown(UserInput.Left, 1); control.keyDown(UserInput.Left, 1); battery = battery - 6; if (battery == 0) { hasStopped = true; switchToExitScreen(); } break; } } } } @Override public void move(int distance, boolean manual) { while(distance > 0){ if(battery<5){ battery = 0; hasStopped = true; switchToExitScreen(); break; } if(manual){ distance = 1; } if(distanceToObstacle(Direction.FORWARD) > 0){ switch(getCurDir()){ case East: control.keyDown(UserInput.Up,1); battery = battery -5; distance--; pathLength++; break; case West: control.keyDown(UserInput.Up,1); battery = battery -5; distance--; pathLength++; break; case North: control.keyDown(UserInput.Up,1); battery = battery -5; distance--; pathLength++; break; case South: control.keyDown(UserInput.Up,1); battery = battery -5; distance--; pathLength++; break; } if(battery <= 0) { hasStopped=true; switchToExitScreen(); } } else { control.setCurrentPosition(this.control.getCurrentPosition()[0],this.control.getCurrentPosition()[1]); battery = battery -5; distance--; if(battery <= 0) { hasStopped=true; switchToExitScreen(); } } } } @Override public int[] getCurrentPosition() throws Exception { return this.control.getCurrentPosition(); } @Override public void setMaze(MazeController maze) { this.control = maze; curPos[0] = this.control.getCurrentPosition()[0]; curPos[1] = this.control.getCurrentPosition()[1]; cells= new Cells(this.control.mazeConfig.getWidth(),this.control.mazeConfig.getHeight()); cells = this.control.mazeConfig.getMazecells(); setCurDir(CardinalDirection.East); pathLength = 0; battery = 3000; } @Override public boolean isAtExit() { curPos = this.control.getCurrentPosition(); if(cells.isExitPosition(curPos[0], curPos[1])) { hasStopped = true; } return cells.isExitPosition(curPos[0], curPos[1]); } /** * The switchToExitScreen method is usually called after hasStopped is changed to true in order to * end the game and send the screen to the finish screen. * */ public void switchToExitScreen() { if(hasStopped()) { this.control.switchToFinishScreen(); } else { return; } } @Override public boolean canSeeExit(Direction direction) throws UnsupportedOperationException { assert hasDistanceSensor(direction); if (!hasDistanceSensor(direction)) { throw new UnsupportedOperationException(); } if (distanceToObstacle(direction) != Integer.MAX_VALUE) { return false; } else { return true; } } @Override public boolean isInsideRoom() throws UnsupportedOperationException { curPos = this.control.getCurrentPosition(); return cells.isInRoom(curPos[0], curPos[1]); } @Override public boolean hasRoomSensor() { return true; } @Override public CardinalDirection getCurrentDirection() { return this.control.getCurrentDirection(); } @Override public float getBatteryLevel() { return battery; } @Override public void setBatteryLevel(float level) { if(battery <=0) { hasStopped = true; switchToExitScreen(); } battery = level; } @Override public int getOdometerReading() { return odometer; } @Override public void resetOdometer() { odometer = 0; } @Override public float getEnergyForFullRotation() { return 12; } @Override public float getEnergyForStepForward() { return 5; } @Override public boolean hasStopped() { return hasStopped; } @Override public int distanceToObstacle(Direction direction) throws UnsupportedOperationException { assert hasDistanceSensor(direction); if(!hasDistanceSensor(direction)) { throw new UnsupportedOperationException(); } int steps = 0; curPos = this.control.getCurrentPosition(); int curX = this.control.getCurrentPosition()[0]; int curY = this.control.getCurrentPosition()[1]; if(battery>0){ battery = battery - 1; } else { hasStopped = true; switchToExitScreen(); } CardinalDirection SensorDirection; SensorDirection = getCurDir(); switch(direction) { case LEFT: SensorDirection = getCurDir().rotateClockwise(); break; case RIGHT: SensorDirection = getCurDir().rotateCounterClockwise(); break; case BACKWARD: SensorDirection = getCurDir().oppositeDirection(); break; case FORWARD: SensorDirection = getCurDir(); break; } int mWidth = this.control.mazeConfig.getWidth(); int mHeight = this.control.mazeConfig.getHeight(); while(true) { if (curX>= mWidth || curY>=mHeight || curX < 0 || curY<0){ return Integer.MAX_VALUE; } else { switch(SensorDirection){ case East: if(cells.hasWall(curX, curY, CardinalDirection.East)){ return steps; } curX++; break; case West: if(cells.hasWall(curX, curY, CardinalDirection.West)){ return steps; } curX--; break; case South: if(cells.hasWall(curX, curY, CardinalDirection.South)){ return steps; } curY++; break; case North: if(cells.hasWall(curX, curY, CardinalDirection.North)){ return steps; } curY--; break; } steps++; } } } @Override public boolean hasDistanceSensor(Direction direction) { if (direction == Direction.FORWARD) return isForwardSensor(); else if (direction == Direction.BACKWARD) return isBackwardSensor(); else if (direction == Direction.LEFT) return isLeftSensor(); else if (direction == Direction.RIGHT) return isRightSensor(); else return false; } /** * getPathLength gets the pathlength for the Endscreen in MazeView.java * @return pathlength */ public static int getPathLength() { return pathLength; } /** * getBatteryLevelGame gets the battery left for the Endscreen in MazeView.java * @return battery */ public static float getBatteryLevelGame() { return battery; } public boolean isForwardSensor() { return forwardSensor; } public void setForwardSensor(boolean forwardSensor) { this.forwardSensor = forwardSensor; } public boolean isBackwardSensor() { return backwardSensor; } public void setBackwardSensor(boolean backwardSensor) { this.backwardSensor = backwardSensor; } public boolean isLeftSensor() { return leftSensor; } public void setLeftSensor(boolean leftSensor) { this.leftSensor = leftSensor; } public boolean isRightSensor() { return rightSensor; } public void setRightSensor(boolean rightSensor) { this.rightSensor = rightSensor; } public CardinalDirection getCurDir() { return curDir; } public void setCurDir(CardinalDirection curDir) { this.curDir = curDir; } }
C
UTF-8
1,110
3.5625
4
[]
no_license
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> //Mingyuan Li //Computer system //HW3 //2/17/2016 //User give a number, program use one thread to find out all prime numbers and list int *list; int prime; int count; int N; void *calculate_prime(void *param); int main(int argc, char *argv[]) { int i; if(argc != 2) { printf("You should enter the range...\n"); exit(0); } N =atoi(argv[1]); if(N < 2) { printf("There is not have prime number less than 2\n"); exit(0); } pthread_t t1; list = malloc(sizeof(int) * N); printf("Prime numbers are....\n"); pthread_create(&t1, 0, calculate_prime, NULL); pthread_join(t1, NULL); } void *calculate_prime(void *param) { int i; int j; int flag; for(i = 2; i <= N; i++) { flag = 0; for(j = 2; j <= i/2; j++) { if(i % j == 0) { flag = 1; break; } } if(flag == 0) printf("%d\n", i); } pthread_exit(0); }
C#
UTF-8
2,730
2.8125
3
[ "MIT" ]
permissive
using System; using System.IO; using EnvDTE; using Jfevia.ProductivityShell.Vsix.Helpers; namespace Jfevia.ProductivityShell.Vsix.Extensions { internal static class ProjectExtensions { /// <summary> /// Gets the output folder. /// </summary> /// <param name="project">The project.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"> /// Unable to find project directory /// or /// OutputPath property is null or empty /// </exception> public static string GetOutputFolder(this Project project) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var directoryName = Path.GetDirectoryName(project.FullName); if (directoryName == null) throw new InvalidOperationException("Unable to find project directory"); var property = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath"); if (string.IsNullOrWhiteSpace(property.Value?.ToString())) throw new InvalidOperationException("OutputPath property is null or empty"); return Path.Combine(directoryName, property.Value.ToString()); } /// <summary> /// Gets the output file path. /// </summary> /// <param name="project">The project.</param> /// <returns>The output file path.</returns> /// <exception cref="InvalidOperationException">OutputFileName property is null or empty</exception> public static string GetOutputFilePath(this Project project) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var outputFolder = GetOutputFolder(project); var property = project.Properties.Item("OutputFileName"); if (string.IsNullOrWhiteSpace(property.Value?.ToString())) throw new InvalidOperationException("OutputFileName property is null or empty"); return Path.Combine(outputFolder, property.Value.ToString()); } /// <summary> /// Gets the relative path. /// </summary> /// <param name="project">The project.</param> /// <param name="solution">The solution.</param> /// <returns>The relative path.</returns> public static string GetRelativePath(this Project project, Solution solution) { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); var solutionPath = $@"{Path.GetDirectoryName(solution.FullName)}\"; return PathHelpers.GetPathRelativeTo(project.FullName, solutionPath); } } }
Python
UTF-8
4,179
3.828125
4
[]
no_license
import numpy as np from utils import manhattanDistance from random import randrange # all four possible dir of given cell dirs = [[1, 0],[0, -1],[-1, 0],[0, 1]] class MazeGenerator(): # Provided cell, list of current walls, get the walls around the cells def getWalls(self, cell,walls): wallSet = set(walls) dirs = [[1, 0],[0, -1],[-1, 0],[0, 1]] wall = [] # generate all four walls possible, only add ones which are in the # walls list for dir in dirs: x = cell[0] + dir[0] y = cell[1] + dir[1] if (x, y) in wallSet: wall.append((x,y)) return wall # Get neighbor cells from given a cell co-ordinate def getNeighborCells(self,cell, cells, maze): cellSet = set(cells) neighbors = [] for dir in dirs: x = cell[0] + dir[0] * 2 y = cell[1] + dir[1] * 2 if (x, y) in cellSet and (x, y) not in maze: neighbors.append((x,y)) return neighbors # Provided a cell, get random closest cell to 'cell' in maze set def getClosestRandomCell(self, cell, maze): nei = [] for mazeCell in maze: if mazeCell != cell and manhattanDistance(cell, mazeCell) == 2: nei.append(mazeCell) return nei[randrange(len(nei))] # method to remove wall between cell1 and cell2 def removeWall(self,cell1, cell2, maze): # Wall is either on left or right side of cell1 if cell1[0] == cell2[0]: x = cell1[0] # wall is on right side of cell1 if cell1[1] < cell2[1]: y = cell1[1] + 1 # wall on left side of cell1 else: y = cell1[1] - 1 # wall is either up or down of cell1 else: y = cell1[1] # wall is on south of cell1 if cell1[0] < cell2[0]: x = cell1[0] + 1 # wall is on north of cell1 else: x = cell1[0] - 1 # convert the wall to cell by adding it to the maze maze.add((x,y)) return (x,y) # Prim's Maze generator algorithm def prims_maze(self, w, h): def _prims_maze(w,h): grid = np.ones((w, h)) cells = [] walls = [] for i in range(h): for j in range(w): if i % 2 == 1 and j % 2 == 1: grid[i, j] = 0 cells.append((i,j)) elif i != 0 and j != 0 and i != h - 1 and j != w - 1: walls.append((i,j)) return grid, cells, walls grid,cells, walls = _prims_maze(w,h) maze = set() # keeps track of valid cells in maze frontier = [] # unvisited cells initialCell = cells[randrange(len(cells))] frontier.extend(self.getNeighborCells(initialCell, cells, maze)) maze.add(initialCell) while frontier: # get the random index from the frontier index = randrange(len(frontier)) # get the random cell from frontier via random index randomFrontierCell = frontier[index] # Add the cell to maze maze.add(randomFrontierCell) # remove the cell from the frontier frontier.remove(randomFrontierCell) # Get Closest maze Cell to this cell to open path with # Breaks ties randomly openPathWith = self.getClosestRandomCell(randomFrontierCell, maze) # remove the wall between random cell from frontier and closest cell in maze self.removeWall(randomFrontierCell, openPathWith, maze) # add all neighbors of random cell to the frontier frontier.extend(self.getNeighborCells(randomFrontierCell, cells, maze)) # construct the maze in 2d Array for cell in maze: grid[cell[0], cell[1]] = 0 # Open Start and End of the grid grid[1,0] = 0 grid[w-2, h-1] = 0 # return the maze return grid
SQL
UTF-8
5,429
2.796875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Aug 19, 2019 at 03:41 AM -- Server version: 5.7.26 -- PHP Version: 7.2.18 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `profile_finder` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `id` mediumint(9) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `avatar` text, `signup_date` int(10) DEFAULT NULL, `is_reg` varchar(3) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=58 DEFAULT CHARSET=utf8; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `password`, `email`, `avatar`, `signup_date`, `is_reg`) VALUES (25, 'admin', '9580ab5d9db022c73d6678b07c86c9db', 'vigo@k3opticsf.com', NULL, NULL, NULL), (3, 'ashok1', '395ed6d51453439a5f75a8d12538955a', 'lipa75@zdecadesgl.com', NULL, NULL, NULL), (6, 'Vimal', 'b743a101400a153d5ee5e4247d9c018b', 'vimaljose@gmail.com', NULL, NULL, NULL), (7, 'Athulya', '563ecb53afd143f2b6ede561e68bdf65', 'athulyaj@yahoo.com', NULL, NULL, NULL), (8, 'Priyanka ', 'fd89c56e6c65ced2ac4f50ef3890147e', 'Priyanka@gmail.com', NULL, NULL, NULL), (9, 'augustine ', 'de1a66c642f5a172ad63edd8e24c7f7e', 'augustine@yahoo.com', NULL, NULL, NULL), (10, 'FAISAL ', 'f4668288fdbf9773dd9779d412942905', 'FAISAL@gmail.com', NULL, NULL, NULL), (11, 'anzal', '7d6f52a53948db5daa3f6c0b559c75e9', 'anza@gmail.com', NULL, NULL, NULL), (12, 'Radhu', '03270b7c92a8829a8b85bf997f529b11', 'Radh@yahoo.com', NULL, NULL, NULL), (13, 'Anoop ', '8c688dc123bb1d13512b66530b5aed15', 'Anoop@gmail.com', NULL, NULL, NULL), (14, 'Aboobacker ', '28b5a60bb0cfcf9eb567ad399b1d5648', 'Aboobacker@yahoo.com', NULL, NULL, NULL), (15, 'Rakesh ', '9d41518f17e96cb3c93e8a679a10222d', 'Rakesh@gmail.com', NULL, NULL, NULL), (16, 'john', '527bd5b5d689e2c32ae974c6229ff785', 'joh@gmail.com', NULL, NULL, NULL), (17, 'Stephy ', 'bf2bdf6470f3ad281d0a7cf3b269e7ea', 'Stephy@yahoo.com', NULL, NULL, NULL), (18, 'Manu ', 'a360c69d36727180983b84eb335bbc21', 'Manu@gmail.com', NULL, NULL, NULL), (19, 'Abilash ', '1ebf4bcadb3d67b3e18964b40361ca51', 'Abilash@yahoo.com', NULL, NULL, NULL), (20, 'Akhil ', 'bc229506da9ffc7fdca513fdc3ec5eb0', 'Akhil@gmail.com', NULL, NULL, NULL), (21, 'INDIA', '11a98374ebec8e0c7a54751d2161804d', 'INDIA@gmail.com', NULL, NULL, NULL), (22, 'Agasthya ', '8f38f74f99774a935c6b9346cfb540de', 'Agasthya@gmail.com', NULL, NULL, NULL), (23, 'JISNY', 'bd650f3a2a18c9bb3648d134c929e4d8', 'JISN@yahoo.com', NULL, NULL, NULL), (27, 'ashok', 'bb2d1a99fc70551dab323d042deb6843', 'ashok@ashok.com', NULL, NULL, 'no'), (28, 'ameer', '4fd871a3338408a1fa1641c518c9d909', 'ameer@gmail.com', NULL, NULL, NULL), (29, 'rifas', 'ab7649ef31676db2e7b1ceaa0a998081', 'rifas@yahoo.com', NULL, NULL, NULL), (30, 'sreekanth', 'd14c5392a9c246f3236f33fc3ed00b92', 'sreekanth@gmail.com', NULL, NULL, NULL), (31, 'ajesh', '1b001b580cdde79a1ae7c6682490ad1e', 'ajesh@yahoo.com', NULL, NULL, NULL), (32, 'melwin', 'd7ce29db30922835724429cc8079d646', 'melwin@gmail.com', NULL, NULL, NULL), (33, 'dhanya', 'bbdfe4160a243e698e39493da90d5ea5', 'dhanya@gmail.com', NULL, NULL, NULL), (34, 'sibinesh', 'ca9079265ee2eb2ce9dbdb7ec5b9c019', 'sibinesh@gmail.com', NULL, NULL, NULL), (35, 'anju', '9abfae448bc00ea3214033a3086e6539', 'anjueapen@yahoo.com', NULL, NULL, NULL), (36, 'anjusanal', '93e12c8b57b69400551e0d3326e625ef', 'anjusanal@gmail.com', NULL, NULL, NULL), (37, 'vyshakh', '8cea17d95b6cbbbe776605514cc3cb1b', 'vyshakh@gmail.com', NULL, NULL, NULL), (38, 'shahanija', 'd5340025872e650faa7d175f5df09a41', 'shahanija@yahoo.com', NULL, NULL, NULL), (39, 'anu', '89a4b5bd7d02ad1e342c960e6a98365c', 'anu@gmail.com', NULL, NULL, NULL), (40, 'bibin', '2da0e0aae058a32f35c573a85fb5b799', 'bibin@gmail.com', NULL, NULL, NULL), (41, 'niyas', '502bdd090083d2cab14b41699bfb60bd', 'niyas@yahoo.com', NULL, NULL, NULL), (42, 'romy', '1ff70a20b5bf17ac9bea662c19c2fa42', 'romy@gmail.com', NULL, NULL, NULL), (43, 'shany', '4416ea7a6dad88875282c936abbf0374', 'shany@gmail.com', NULL, NULL, NULL), (44, 'vidhu', 'e3fc87a1b882f97990949222f20b4401', 'vidhu@gmail.com', NULL, NULL, NULL), (45, 'vaisakh', 'f1328dde27ebdfbac150114bb930831b', 'vaisakh@gmail.com', NULL, NULL, NULL), (46, 'amal', '16b5480e7b6e68607fe48815d16b5d6d', 'amal@yahoo.com', NULL, NULL, NULL), (47, 'titty', '316121edac491a0a80932b36e01217b7', 'titty@gamil.com', NULL, NULL, NULL), (48, 'basil', '6862efb4028e93ac23a6f90a9055bae8', 'basilmathai@gmail.com', NULL, NULL, NULL), (49, 'muhammedanvar', 'd0cb7734bc2e5840db630f0ae7c29684', 'muhammedanvar@gmail.com', NULL, NULL, NULL), (50, 'sreelesh', '5c20857f754bf33bbb0b9c144bdada53', 'sreelesh@yahoo.com', NULL, NULL, NULL), (51, 'arjun', '7626d28b710e7f9e98d9dfbe9bf0d123', 'arjun@gmail.com', NULL, NULL, NULL), (52, 'arun', '722279e9e630b3e731464b69968ea4b4', 'arun@gmail.com', NULL, NULL, NULL), (53, 'sahad', 'b5daf0ea8373e89446af65a150a2ae61', 'sahad@yahoo.com', NULL, NULL, NULL), (54, 'arunmathew', '966c4d7316f2be7c85f368e4e47e15da', 'arunmathew@gmail.com', NULL, NULL, NULL), (55, 'athul', 'c782779b77215248bb2372c545132ae1', 'athul@gamil.com', NULL, NULL, NULL), (56, 'jithin', '1c4317a963b252091890e123b4a2790d', 'jithin@gmail.com', NULL, NULL, NULL), (57, 'sreejith', 'f04891a08e96bc978e4e4b20f4cd9910', 'sreejith@gmail.com', NULL, NULL, NULL); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Shell
UTF-8
4,619
3.734375
4
[ "Apache-2.0" ]
permissive
#! /bin/bash -norc set -u NAME=${0##*/}; DIRE=${0%/*}; if [[ -z "${DIRE}" ]]; then DIRE="."; fi; if [[ "${DIRE}" = "${NAME}" ]]; then DIRE="."; fi; DIRE="$(cd ${DIRE}; echo ${PWD})"; TAB=" "; # must be a TAB not a run of spaces unset CDPATH; # because when bash (I love it!) is involved, CDPATH can hose up a subshell/make, etc. unset BASH_ENV; unset ENV; # unset the ENV environmental variable so any # Korn shells below this line do not attempt to # source it. Ditto for BASH_ENV # the environment variable # ECHO # is examined, if it is TRUE/YES/ON (case insensitve) # then turn on shell debugging case ${ECHO:-null} in [Tt][Rr][Uu][Ee] ) set -x ;; [Yy][Ee][Ss] ) set -x ;; [Oo][Nn] ) set -x ;; esac # create a suite of temp files and then functions to clean them up TDIR=${TMPDIR:-/tmp}; # why examine TMPDIR? see tmpnam(3), but DO NOT export TDIR T0=${TDIR}/${NAME}-$$-0; T1=${TDIR}/${NAME}-$$-1; T2=${TDIR}/${NAME}-$$-2; T3=${TDIR}/${NAME}-$$-3; T4=${TDIR}/${NAME}-$$-4; T5=${TDIR}/${NAME}-$$-5; T6=${TDIR}/${NAME}-$$-6; T7=${TDIR}/${NAME}-$$-7; T8=${TDIR}/${NAME}-$$-8; T9=${TDIR}/${NAME}-$$-9; # create helper functions for the "trap" command function RmTmps { # usage: RmTmps - will clear all the tmp files /bin/rm -f ${T0} ${T1} ${T2} ${T3} ${T4} ${T5} ${T6} ${T7} ${T8} ${T9} } # this function will clean up temp files then exit function Exit { # usage: Exit N (N defaults to zero (0)) __evalue=${?}; # grab the most recent exit status RmTmps; if (( ${#} == 0 )); then exit ${__evalue}; else exit ${1}; fi } function EError { Error "${@}"; Exit 1; } function Error { oV=${VERBOSE}; VERBOSE=1; Verbose ${@} VERBOSE=${oV}; } function Verbose { if (( VERBOSE > 0 )); then ( _n=''; if (( ${#} > 0 )); then if [[ "${1}" = "-n" ]]; then _n=-n; fi; echo ${_n} ${NAME}: "${@}"; else echo ''; fi; ) 1>&2; fi; } trap "Exit 2" 1 2 15; # exit if hit with HUP, INT or TERM signals, you can extend this list if (( ${#} == 0)); then set -- --help; fi; let DEF_VERBOSE=1 || true; let VERBOSE=-1 || true; let DEF_CLEAN=1 || true; let CLEAN=-1 || true; let DEF_XLEAN=1 || true; let XLEAN=-1 || true; DEF_VERSION=""; VERSION='not.defined.yet' if [[ ${OSTYPE} =~ darwin* ]]; then KILLDIR="/Library/Python/2.7/site-packages"; else KILLDIR="/usr/lib/python2.7/site-packages"; fi; GOTO="${DIRE}/../tagProtect"; DEF_TARDIR="${GOTO}/Python" DEF_TARDIR="$(cd ${DEF_TARDIR} 2>/dev/null; echo ${PWD})"; USAGE=" usage: ${NAME} [options] optons: --clean | -c clean up after build --extraclean | -x extra --clean, adds rm of installed file list "; while (( ${#} > 0 )); do case "${1}" in # ((((((((((((((((( --help | -h ) echo "${USAGE}"; exit 0;; --run | -r | -) : ;; # ignore it --clean | -c ) let CLEAN=1 || true;; --noclean | -C ) let CLEAN=0 || true;; --no-clean ) let CLEAN=0 || true;; --extra* | -e ) let XLEAN=1 || true;; --x* | -x ) let XLEAN=1 || true;; --noextra* | -E ) let XLEAN=0 || true;; --no-extra* ) let XLEAN=0 || true;; -X ) let XLEAN=1 || true;; --verbose | -v ) if (( VERBOSE <= 0 )); then let VERBOSE=1 || true; else let VERBOSE++ || true; fi;; --verbose=0 ) let VERBOSE=0 || true;; --verbose=[1-9]* ) let VERBOSE=${1#--verbose=} || exit 1;; --v0 ) let VERBOSE=0 || true;; --v[1-9]* ) let VERBOSE=${1#-v} || exit 1;; --noverbose | -V ) let VERBOSE=0 || true;; *) echo "${NAME}: arg \"${1}\" unrecognized, aborting!" 1>&2; Exit 1;; esac; shift; # off the one just done done if (( VERBOSE < 0 )); then VERBOSE=${DEF_VERBOSE}; fi; if (( CLEAN < 0 )); then CLEAN=${DEF_CLEAN}; fi; if (( XLEAN < 0 )); then XLEAN=${DEF_XLEAN}; fi; if (( XLEAN > 0 )); then CLEAN=1; fi; if [[ "${TARDIR:-not set}" = "not set" ]]; then TARDIR="${DEF_TARDIR}"; fi; cd "${TARDIR}" || { Error ${NAME}: current directory is ${PWD}; EError ${NAME}: failed to cd to ${TARDIR}; } echo python setup.py sdist --verbose; python setup.py sdist --verbose || Exit 1; if (( CLEAN )); then /bin/rm -rf svnplus.egg-info/ if (( XLEAN )); then : # no action just now fi; fi; Exit;
Python
UTF-8
607
3.234375
3
[]
no_license
import requests def get_commit(ID): result = {} r = requests.get("https://api.github.com/users/" + ID +"/repos") repos = r.json() for repo in repos: repo_name = repo["name"] r = requests.get("https://api.github.com/repos/" + ID + "/" + repo_name + "/commits") commits = r.json() result[repo_name] = len(commits) return result def print_commits(result): for key, value in result.items(): print(f'Repo: {key} Number of commits: {value}') if __name__ == '__main__': ID = input('input an ID:') print(print_commits(get_commit(ID)))
JavaScript
UTF-8
1,588
2.5625
3
[]
no_license
/* Card List Scripts */ $(document).ready(function () { // Cards SETS and TAFFY loaded in prior includes _cards = TAFFY(CARDS); write_sets(); run_search($('#search-input').val()); function write_sets() { var outp = ''; $.each(SETS, function(key, set) { outp += '<div><a class="cardset" href="cardlist.php?q=e:' + set.code + '">' + key + '</a></div>'; }); $('#sets').html (outp); } function run_search(filter) { var outp = ""; var f = parsefilter(filter); var cardfilter; if ( $.isEmptyObject(f) == false) { cardfilter = f; } $('#search-cardlist').empty(); _cards(cardfilter).order("code").each(function (r) { /* <th>Name</th> <th>Type</th> <th>Faction</th> <th>Cost</th> <th>Strength</th> <th>Set</th> */ outp = '<tr>' + '<td><span class="card" data-code="' + r.code + '">' + (r.Unique ? '&diams;&nbsp;' : '') + r.name + '</td>' + '<td>' + (typeof r.Type !== "undefined" ? r.Type : "") + '</td>' + '<td>' + (typeof r.Faction !== "undefined" ? r.Faction : "") + '</td>' + '<td>' + (typeof r.Cost !== "undefined" ? r.Cost : "") + (typeof r.Gold !== "undefined" ? r.Gold : "") + '</td>' + '<td>' + (typeof r.Strength !== "undefined" ? r.Strength : "") + (typeof r.Initiative !== "undefined" ? r.Initiative : "") + '</td>' + '<td>' + r.Set + ' #' + r.Number + '</td>'; $('#search-cardlist').append (outp); //outp += '<div class="card" data-code="' + r.code + '">' + (r.Unique ? '&diams;&nbsp;' :'' ) + r.name + '</div>'; }); } });
C#
UTF-8
2,087
2.734375
3
[ "MIT" ]
permissive
using ModernWpf; using System.Threading; using System.Windows; using System.Windows.Threading; namespace MultiThreadingSample { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Title = "Thread ID: " + Thread.CurrentThread.ManagedThreadId; } private void ToggleAppThemeHandler(object sender, RoutedEventArgs e) { ClearValue(ThemeManager.RequestedThemeProperty); Application.Current.Dispatcher.BeginInvoke(() => { var tm = ThemeManager.Current; if (tm.ActualApplicationTheme == ApplicationTheme.Dark) { tm.ApplicationTheme = ApplicationTheme.Light; } else { tm.ApplicationTheme = ApplicationTheme.Dark; } }); } private void ToggleWindowThemeHandler(object sender, RoutedEventArgs e) { if (ThemeManager.GetActualTheme(this) == ElementTheme.Light) { ThemeManager.SetRequestedTheme(this, ElementTheme.Dark); } else { ThemeManager.SetRequestedTheme(this, ElementTheme.Light); } } private void NewWindowHandler(object sender, RoutedEventArgs e) { var left = Left; var top = Top; var width = Width; var thread = new Thread(() => { var window = new MainWindow(); window.Left = left + width + 12; window.Top = top; window.Closed += delegate { Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal); }; window.Show(); Dispatcher.Run(); }); thread.SetApartmentState(ApartmentState.STA); thread.IsBackground = true; thread.Start(); } } }
JavaScript
UTF-8
1,350
2.515625
3
[]
no_license
import { Component } from "react"; import { Button, Form } from "semantic-ui-react"; class WishlistForm extends Component { state = { name: "", description: ""}; componentDidMount() { if (this.props.id) { const { id, name, description } = this.props; this.setState({ id, name, description }); } } handleChange = (e) => { const { name, value } = e.target; this.setState({ [name]: value }); }; handleSubmit = (e) => { e.preventDefault(); if (this.props.id) { const { updateWishlist, id, toggleForm } = this.props; updateWishlist(id, this.state); toggleForm(); } else { this.props.addWishlist(this.state); } this.setState({ name: "", description: "" }); }; render() { const { name, description } = this.state; return ( <Form onSubmit={this.handleSubmit}> <Form.Input type="text" name="name" value={name} onChange={this.handleChange} required placeholder="Name" /> <Form.TextArea type="text" name="body" value={description} onChange={this.handleChange} required placeholder="Text" /> <Button type="submit">Submit</Button> </Form> ); } } export default WishlistForm;
C++
UTF-8
1,473
2.8125
3
[]
no_license
#ifndef CONNECTED_CLIENT_H #define CONNECTED_CLIENT_H #include "Communication_server.h" #include <iostream> #include <string.h> #include <vector> #include <pthread.h> using namespace std; class Connected_client{ public: void init(string username, int sockfd, int num_connections, int port, int header_size, int max_payload); // If this is the second client from the same user, the vector of files and its mutex must be the same void init(string username, int sockfd, int num_connections, int port, int header_size, int max_payload, vector<File_server> *user_files_pointer, pthread_mutex_t *user_files_mutex_pointer); string *get_username(); int *get_sockfd(); int get_num_connections(); pthread_t get_thread(); vector<File_server> *get_user_files(); int get_user_files_size(); pthread_mutex_t *get_user_files_mutex(); // This method MUST BE CALLED after the creation of an object void set_thread(pthread_t thread); // Returns num_connections+1 if num_connections+1 < max_connections, -1 otherwise int new_connection(); void remove_connection(); Communication_server com; private: string username; int sockfd; int num_connections; int max_connections; string mtimes_file_path; pthread_t thread; vector<File_server> user_files; vector<File_server> *user_files_pointer; pthread_mutex_t user_files_mutex; pthread_mutex_t *user_files_mutex_pointer; void files_from_disk(); }; #endif // CONNECTED_CLIENT_H
TypeScript
UTF-8
6,342
2.546875
3
[]
no_license
import { expect } from 'chai'; import { Request, Response } from 'express'; import * as admin from 'firebase-admin'; import 'mocha'; import * as sinon from 'sinon'; import { isAuthorized } from './authorized'; import { Roles, UserManagerRoles } from './roles'; describe('authorized.ts', () => { let req: Partial<Request>; let res: Partial<Response>; let next; beforeEach(() => { req = {headers: {}, params: {}}; res = { status: sinon.stub(), send: sinon.stub(), locals: { uid: Math.random().toString(), email: 'test@domain.com', role: Roles.user } }; next = sinon.stub(); }); describe('when called with invalid request', () => { it('should return status: 403', () => { req = {headers: {}}; isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return {message: "Unauthorized:..."}', () => { req = {headers: {}}; isAuthorized({hasRole: ['user']})(req as Request, res as Response, next); const responseMessage = (res.send as sinon.SinonStub).lastCall.args[0]; expect(responseMessage).to.have.property('message').match(/^Unauthorized:/); }); }); describe('when called with res without locals field (locals filled in isAuthenticated)', () => { beforeEach(() => { res = { status: sinon.stub(), send: sinon.stub(), }; }); it('should return status: 403', () => { isAuthorized({hasRole: ['user']})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return {message: "Unauthorized:..."}', () => { isAuthorized({hasRole: ['user']})(req as Request, res as Response, next); const responseMessage = (res.send as sinon.SinonStub).lastCall.args[0]; expect(responseMessage).to.have.property('message').match(/^Unauthorized:/); }); }); describe('when called with valid req, res', () => { const testUid = 'testUid'; before(async function () { await admin.firestore().doc(`users/${testUid}`).set({ uid: testUid, role: Roles.user }); }); after(async () => { await admin.firestore().doc(`users/${testUid}`).delete(); }); it('should call next if allowSameUser is set and ids match', async () => { req.params.id = testUid; res.locals.uid = testUid; await isAuthorized({hasRole: [], allowSameUser: true})(req as Request, res as Response, next); sinon.assert.calledOnce(next as sinon.SinonStub); }); it('should return 403 if allowSameUser is set and ids do not match', async () => { req.params.id = testUid; res.locals.uid = testUid + 'a'; await isAuthorized({hasRole: [], allowSameUser: true})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return 403 if role is not provided', async () => { req.params.id = testUid; res.locals.uid = testUid; res.locals.role = null; await isAuthorized({hasRole: []})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should call next if role is provided and in hasRole', async () => { req.params.id = testUid; res.locals.uid = 'randomUid'; res.locals.role = UserManagerRoles[0]; await isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledOnce(next as sinon.SinonStub); }); it('should return 403 if role is provided and is not in hasRole', async () => { req.params.id = testUid; res.locals.uid = testUid; res.locals.role = Roles.user; await isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return 403 when allowUser: true, role: admin, roleTo: invalidRole', () => { req.params.id = testUid; res.locals.uid = testUid; res.locals.role = Roles.admin; req.body = {role: 'invalid' + Roles.admin}; isAuthorized({hasRole: UserManagerRoles, allowSameUser: true})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return 403 when role: invalidRole, roleTo: admin', () => { res.locals.role = 'invalid' + Roles.admin; req.body = {role: Roles.admin}; isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should call next when allowUser: true, role: admin, roleTo: admin', async () => { res.locals.uid = 'testId'; res.locals.role = Roles.admin; req.params.id = testUid; req.body = {role: Roles.admin}; await isAuthorized({hasRole: UserManagerRoles, allowSameUser: true})(req as Request, res as Response, next); sinon.assert.calledOnce(next as sinon.SinonStub); }); it('should call next when role: admin, roleTo: owner', async () => { res.locals.uid = 'randomId'; res.locals.role = Roles.admin; req.params.id = testUid; req.body = {role: Roles.owner}; await isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledOnce(next as sinon.SinonStub); }); it('should return 403 when allowUser: true, role: owner, roleTo: admin', () => { res.locals.uid = 'randomId'; res.locals.role = Roles.owner; req.params.id = testUid; req.body = {role: Roles.admin}; isAuthorized({hasRole: UserManagerRoles, allowSameUser: true})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); it('should return 403 when role: user, roleTo: admin', () => { res.locals.uid = 'randomId'; res.locals.role = Roles.user; req.params.id = testUid; req.body = {role: Roles.admin}; isAuthorized({hasRole: UserManagerRoles})(req as Request, res as Response, next); sinon.assert.calledWith(res.status as sinon.SinonStub, 403); }); }); });
Markdown
UTF-8
14,575
3.25
3
[ "MIT" ]
permissive
# 尚观科技H5课程 ## web前端简单介绍 web前端包含:pc端页面 和移动端页面(web端当前的就业形势) 认识网页 ​ 网页主要由文字、图片、超链接、输入框、表格、表单等元素构成,除了这些常见的元素之外,还有音频、视频、以及falsh等 **web标准** 1.w3c万维网联盟组织,用来指定web标准的机构。 2.web标准:制作网页要遵循的规范。 3.web标准规范的分类:结构标准 表现标准 行为标准 4.结构:html 表现:css 行为:javascript **结构标准:**相当于人的身体 **表现标准:**相当于人的衣服 **行为标准:**相当于人的动作 **浏览器** 浏览器是网页运行的平台,常用的浏览器有IE、火狐(Firefox)、谷歌(Chrome)、Safari和Opera等。 **所学课程大体介绍:** 课程一: html语言 html就是用来制作网页的,h5是html的最新标准,其实也就是升级版的Html 课程二: css样式 css就是对网页进行美化的(也叫网页的美容师) 课程三: js 是一门松散的面向对象的语言,在网页中,它的作用就是让网页动起来,让网页具有生命力。 **html简介** html (Hyper Text Markup Language ) 中文译为“超文本标记语言”,主要是通过html标记对网页中的文本,图片,声音等内容进行描述 HTML之所以称为超文本标记语言,不仅是因为他通过标记描述网页内容,同时也由于文本中包含了所谓的“超级链接”,通过超链接可以实现网页的跳转。从而构成了丰富多彩的Web页面。 **html基本文档格式:** 学习任何一门语言,都要首先掌握它的基本格式,就像写信需要符合书信的格式要求一样。HTML标记语言也不例外,同样需要遵从一定的规范。 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> ``` **标签解释:** \<html>称为根标记,用于告知浏览器其自身是一个 HTML 文档,\<html>标记标志着HTML文档的开始,\</html>标记标志着HTML文档的结束,在他们之间的是文档的头部和主体内容。 \<html lang="en"> 向搜索引擎表示该页面是html语言,并且语言为英文网站,其"lang"的意思就是“language”,语言的意思,而“en”即表示english 这个主要是给搜索引擎看的,搜索引擎不会去判断该站点是中文站还是英文站,所以这句话就是让搜索引擎知道,你的站点是中文站,对html页面本身不会有影响 \<head>标记用于定义HTML文档的头部信息,也称为头部标记,紧跟在\<html>标记之后,主要用来封装其他位于文档头部的标记。 一个HTML文档只能含有一对\<head>标记,绝大多数文档头部包含的数据都不会真正作为内容显示在页面中。 \<title>标记用于定义HTML页面的标题,即给网页取一个名字,必须位于\<head>标记之内。一个HTML文档只能含有一对\<title>\</title>标记,\<title>\</title>之间的内容将显示在浏览器窗口的标题栏中。其基本语法格式如下: ```html <title>网页名称</title> ``` \<body>标记用于定义HTML文档所要显示的内容,也称为主体标记。浏览器中显示的所有文本、图像、音频和视频等信息都必须位于\<body>标记内,\<body>标记中的信息才是最终展示给用户看的。 一个HTML文档只能含有一对\<body>标记,且\<body>标记必须在\<html>标记内,位于\<head>头部标记之后. **html标签关系** 1.嵌套关系 2.并列关系 嵌套关系:类似父亲和儿子之间的关系 ```html <html> <head></head> <body></body> </html> ``` 并列关系:类似与兄弟之间的关系 ```html <head></head> <body></body> ``` **html标签分类** 双标记也称体标记,是指由开始和结束两个标记符组成的标记。其基本语法格式如下: ```html <标记名></标记名> ``` 该语法中“<标记名>”表示该标记的作用开始,一般称为“开始标记(start tag)”,“</标记名>” 表示该标记的作用结束,一般称为“结束标记(end tag)”。和开始标记相比,结束标记只是在前面加了一个关闭符“/”。 单标记也称空标记,是指用一个标记符号即可完整地描述某个功能的标记。其基本语法格式如下: ```html <标记名/> ``` **前端主流开发工具** Dreamweaver sublime webStorm 等,目前主流的开发工具是sublime,所以在以后的课程中我们会使用sublime这个开发工具。、 **创建第一个网页** **水平线标记** 在网页中常常看到一些水平线将段落与段落之间隔开,使得文档结构清晰,层次分明。这些水平线可以通过插入图片实现,也可以简单地通过标记来完成,\<hr />就是创建横跨网页水平线的标记。其基本语法格式如下: \<hr />是单标记,在网页中输入一个\<hr />,就添加了一条默认样式的水平线。 **换行标记** 在HTML中,一个段落中的文字会从左到右依次排列,直到浏览器窗口的右端,然后自动换行。如果希望某段文本强制换行显示,就需要使用换行标记\<br />,这时如果还像在word中直接敲回车键换行就不起作用了。 **段落标记** 在网页中要把文字有条理地显示出来,离不开段落标记,就如同我们平常写文章一样,整个网页也可以分为若干个段落,而段落的标记就是\<p>。\<p>是HTML文档中最常见的标记,默认情况下,文本在一个段落中会根据浏览器窗口的大小自动换行。 **标题标记** 为了使网页更具有语义化,我们经常会在页面中用到标题标记,HTML提供了6个等级的标题,即\<h1>、\<h2>、\<h3>、\<h4>、\<h5>和\<h6>,从\<h1>到\<h6>重要性递减。其基本语法格式如下: ```html <hn>标题文本</hn> ``` **文本样式标记** 多种多样的文字效果可以使网页变得更加绚丽,为此HTML提供了文本样式标记\<font>,用来控制网页中文本的字体、字号和颜色。其基本语法格式如下: ```html <font>文本内容</font> ``` 在网页中,有时需要为文字设置粗体、斜体或下划线效果,这时就需要用到HTML中的文本格式化标记,使文字以特殊的方式显示。 | 标记 | 显示效果 | | ----------------------------- | -------------------------- | | \<b>\</b>和\<strong>\</strong> | 文字以粗体方式显示(XHTML推荐使用strong) | | \<i>\</i>和\<em>\</em> | 文字以斜体方式显示(XHTML推荐使用em) | | \<s>\</s>和\<del>\</del> | 文字以加删除线方式显示(XHTML推荐使用del) | | \<u>\</u>和\<ins>\</ins> | 文字以加下划线方式显示(XHTML不赞成使用u) | 在HTML中还有一种特殊的标记——注释标记。如果需要在HTML文档中添加一些便于阅读和理解但又不需要显示在页面中的注释文字,就需要使用注释标记。其基本语法格式如下: ```html <!-- 注释语句 --> ``` 注释内容不会显示在浏览器窗口中,但是作为HTML文档内容的一部分,也会被下载到用户的计算机上,查看源代码时就可以看到。 注释的作用及重要性比如: ```html <!DOCTYPE html> <html lang="en"> <!-- 这个公司没有年终奖,美女也不多,不要想着在这能拿年终奖或者泡个妹子。这个项目有很多意外的bug,早点闪人吧-!!!!!! --> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> ``` **其他常用标记** ```html <br> <!-- 换行 --> <wbr> <!-- br:在一个段落里面,加上这个标签之后,不论加在哪都能直接换行 --> HTML5<b>HTML5</b> <br> <!-- 标记一段文字强调,实际意义为加粗 --> HTML5<strong>HTML5</strong> <br> <!-- 给文本加粗 --> HTML5<i>HTML5</i> <br> <!-- 倾斜标签 --> HTML5<em>HTML5</em> <br> <!-- 倾斜,用法跟i一样 --> HTML5<code>HTML5</code> <br> <!-- 表示计算机代码 --> HTML5<var>HTML5</var> <br> <!-- 表示程序输出 --> HTML5<s>HTML5</s> <br> <!-- 删除线 --> HTML5<del>HTML5</del> <br> <!-- 删除线 --> HTML5<u>HTML5</u> <br> <!-- 下划线 --> HTML5<ins>HTML5</ins> <br> <!-- 下划线 --> HTML5<small>HTML5</small> <br> <!-- 添加小号字体 --> HTML<sup>5</sup> <br> <!-- 上标 --> HTML5<sub>5</sub> <br> <!-- 下标 --> a<sup>2</sup>+b<sup>2</sup>=c<sup>2</sup> <br> HTML5<abbr>HTML5</abbr> <br> <!-- 表示缩写 --> HTML5<dfn>HTML5</dfn> <br> <!-- 表示定义术语 --> HTML5<q>HTML5</q> <br> <!-- 表示引用他处的内容 --> HTML5<cite>HTML5</cite> <br> <!-- 引用其他作品的标题 --> HTML5<bdo dir="rtl">HTML5</bdo> <br> <!-- 文字排序顺序 默认是ltr 如果想倒叙的话就设置成rtl --> <ruby> <!-- 语言元素 --> 饕 <rp><rp><rt>tao</rt></rp></rp> 餮 <rp><rp><rt>tie</rt></rp></rp> </ruby> <br> HTML5<mark>HTML5</mark> <br> <!-- 加一个标记,效果为背景变黄 --> <time>2016/10/31</time> <br> <!-- 时间标签 --> HTML5<span>HMTL5</span> <br> <!-- 表示一般性文本,没有实际作用 --> ``` 图像标记\<img/> HTML网页中任何元素的实现都要依靠HTML标记,要想在网页中显示图像就需要使用图像标记,接下来将详细介绍图像标记\<img />以及和他相关的属性。其基本语法格式如下: ```html <img src="图像URL" /> ``` \<img/>标记属性 | 属性 | 属性值 | 描述 | | ------ | ---- | ------------ | | src | URL | 图像的路径 | | alt | 文本 | 图像不能显示时的替换文件 | | width | 像素 | 图像的宽度 | | height | 像素 | 图像的高度 | | height | 像素 | 图像的高度 | **路径** 相对路径:相对路径不带有盘符,通常是以HTML网页文件为起点,通过层级关系描述目标图像的位置。例如: ```html <img src="box/index.bng"> ``` 相对路径设置分为以下三种: 1. 图像文件和html文件位于同一文件夹:只需输入图像文件的名称即可,如img src="logo.gif"。 2. 图像文件位于html文件的下一级文件夹:输入文件夹名和文件名,之间用“/”隔开,如img src="img/img01/logo.gif" /。 3. 图像文件位于html文件的上一级文件夹:在文件名之前加入“../” ,如果是上两级,则需要使用 “../ ../”,以此类推,如img src="../logo.gif"。 绝对路径: 绝对路径一般是指带有盘符的路径。指在一个电脑中根目录的位置。 首先是file:///开头,然后是磁盘符,然后是一个个的目录层次,找到相对应文件。这种方式有一个致命的问题,当整个目录转移到另外的盘符或者其他电脑时,目录结构一旦出现变化,就会失效 **创建超链接** 在HTML中创建超链接非常简单,只需用a/a标记环绕需要被链接的对象即可,其基本语法格式如下: ```html <a href="跳转目标" target="目标窗口的弹出方式">文本或图像</a> ``` 在上面的语法中,\<a>标记是一个行内标记,用于定义超链接,href和target为其常用属性,下面对它们进行具体地解释。 href:用于指定链接目标的url地址,当为\<a>标记应用href属性时,它就具有了超链接的功能。 target:用于指定链接页面的打开方式,其取值有_self和_blank两种,其中_self为默认值,_blank为在新窗口中打开方式。 注意:暂时没有确定链接目标时,通常将a标记的href属性值定义为"#"(href="#"),表示该链接暂时为一个空连接。 不仅可以创建文本超链接,在网页中各种网页元素,如图像、表格、音频、视频等都可以添加超链接。 **锚点链接** 通过创建锚点链接,用户能够快速定位到目标内容。 创建锚点链接分为两步: 使用“a href=”#id名“链接文本a创建链接文本。 使用相应的id名标注跳转目标的位置。 **特殊符号标记** ![](1.png) **列表** 1. 无序列表 无序列表的各个列表项之间没有顺序级别之分,是并列的。其基本语法格式如下: ```html <ul> <li></li> <li></li> <li></li> <li></li> </ul> ``` 在上面的语法中,\<ul>\</ul>标记用于定义无序列表,\<li>\</li>标记嵌套在\<ul>\</ul>标记中,用于描述具体的列表项,每对\<ul>\</ul>中至少应包含一对\<li>\</li>。 ​ 无序列表中type属性的常用值有三个,它们呈现的效果不同. 默认值:disc 方块:square 空心圆:circle 2. 有序列表 有序列表即为有排列顺序的列表,其各个列表项按照一定的顺序排列定义,有序列表的基本语法格式如下: ```html <ol> <li></li> <li></li> <li></li> <li></li> </ol> ``` 在上面的语法中,\<ol>\</ol>标记用于定义有序列表,\<li>\</li>为具体的列表项,和无序列表类似,每对\<ol>\</ol>中也至少应包含一对\<li>\</li>。 有序列表其他属性 type start ```html <ol type=value1 start=value2> <li></li> </ol> ``` value1表示有序列表项目符号的类型, value2表示项目开始的数值. start是编号开始的数字,如start=2则编号从2开始,如果从1开始可以省略,或是在\<li>标签中设定value="n"改变列表行项目的特定编号,例如\<li value="7">。type=用于编号的数字,字母等的类型,如type=a,则编号用英文字母。使用这些属性,把它们放在\<ol>或\<li>的的初始标签中。 type值可取: 1 a A i I ​ 3. 自定义列表 定义列表常用于对术语或名词进行解释和描述,定义列表的列表项前没有任何项目符号。其基本语法如下: ```html <dl> <dt>段落一</dt> <dd>段落一内容</dd> <dd>段落一内容</dd> <dt>段落二</dt> <dd>段落二内容</dd> <dd>段落二内容</dd> </dl> ``` 4. pre表示其格式应被保留的内容 5. figure表示图片 figcaption表示figure元素的标题
TypeScript
UTF-8
479
2.9375
3
[ "Apache-2.0" ]
permissive
export default class SimpleUser { id: number; firstName: string; familyName: string; groupIds: number[]; constructor (id: number, firstName: string, familyName: string, groupIds: number[]) { this.id = id this.groupIds = groupIds this.firstName = firstName this.familyName = familyName } getFullName() { return this.firstName + " " + this.familyName; } getFullNameFamilyFirst() { return this.familyName + " " + this.firstName; } }
Java
UTF-8
9,023
2.03125
2
[ "MIT" ]
permissive
package com.appwoodoo.sdk.dialogs; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.FragmentManager; import android.support.v7.appcompat.BuildConfig; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.appwoodoo.sdk.storage.SharedPreferencesHelper; import java.net.URL; public class DialogFragment extends android.support.v4.app.DialogFragment { private com.appwoodoo.sdk.model.Dialog dialogData = new com.appwoodoo.sdk.model.Dialog(); public void setDialogData(com.appwoodoo.sdk.model.Dialog dialogData) { this.dialogData = dialogData; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); Typeface typeface = DialogsHelper.getInstance().getViewOptions().getDialogTypeFace(); LinearLayout linearLayout = new LinearLayout(getContext()); linearLayout.setBackgroundColor(DialogsHelper.getInstance().getViewOptions().getDialogPanelBackgroundColour()); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); linearLayout.setPadding(0, 0, 0, 0); linearLayout.setLayoutParams(params); linearLayout.setOrientation(LinearLayout.VERTICAL); if (dialogData.getBodyText() != null && !"".contentEquals(dialogData.getBodyText())) { TextView bodyText = new TextView(getContext()); LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); titleParams.setMargins(35, 10, 35, 15); bodyText.setLayoutParams(titleParams); bodyText.setPadding(5, 5, 5, 5); bodyText.setGravity(Gravity.LEFT); bodyText.setTextSize(16); bodyText.setTextColor( DialogsHelper.getInstance().getViewOptions().getDialogTextColour() ); if (typeface != null) { bodyText.setTypeface(typeface); } bodyText.setText(dialogData.getBodyText()); linearLayout.addView(bodyText); } if (dialogData.getBodyImage() != null) { final ImageView bodyImageView = new ImageView(getContext()); LinearLayout.LayoutParams imageLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); imageLayoutParams.setMargins(0, 0, 0, 0); bodyImageView.setLayoutParams(imageLayoutParams); bodyImageView.setPadding(0, 0, 0, 0); bodyImageView.setScaleType(ImageView.ScaleType.CENTER_CROP); linearLayout.addView(bodyImageView); final ProgressBar progressView = new ProgressBar(getContext()); LinearLayout.LayoutParams progressLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50); progressLayoutParams.setMargins(10, 10, 0, 10); progressView.setLayoutParams(progressLayoutParams); bodyImageView.setPadding(0, 0, 0, 0); progressView.setIndeterminate(true); progressView.getIndeterminateDrawable().setColorFilter(DialogsHelper.getInstance().getViewOptions().getDialogPanelForegroundColour(), PorterDuff.Mode.MULTIPLY); linearLayout.addView(progressView); progressView.setVisibility(View.VISIBLE); AsyncTask<Void, Void, Drawable> at = new AsyncTask<Void, Void, Drawable>() { @Override protected Drawable doInBackground(Void... params) { try { URL url = new URL(dialogData.getBodyImage()); return Drawable.createFromStream(url.openStream(), "src"); } catch (Exception e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Drawable drawable) { try { progressView.setVisibility(View.GONE); bodyImageView.setImageDrawable(drawable); } catch(Exception e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } } }; at.execute((Void) null); } builder.setView(linearLayout); if (dialogData.getTitle() != null) { LinearLayout titleLayout = new LinearLayout(getContext()); LinearLayout.LayoutParams titleLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); titleLayout.setLayoutParams(titleLayoutParams); linearLayout.setPadding(0, 0, 0, 0); titleLayout.setOrientation(LinearLayout.VERTICAL); TextView titleText = new TextView(getContext()); LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); titleText.setLayoutParams(titleParams); titleParams.setMargins(35, 20, 35, 15); titleText.setPadding(5, 5, 5, 5); titleText.setGravity(Gravity.LEFT); titleText.setTextSize(26); titleText.setTextColor( DialogsHelper.getInstance().getViewOptions().getDialogTitleColour() ); if (typeface != null) { titleText.setTypeface(typeface); } titleText.setText(dialogData.getTitle()); titleLayout.addView(titleText); builder.setCustomTitle(titleLayout); } SharedPreferences preferences = SharedPreferencesHelper.getInstance().getSharedPreferences(getContext()); final SharedPreferences.Editor edit = preferences.edit(); if (dialogData.getActionButtonTitle() != null && dialogData.getActionButtonUrl() != null) { builder.setPositiveButton(dialogData.getActionButtonTitle(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { try { edit.putBoolean(DialogsHelper.APW_SP_DIALOG_ALREADY_OPENED_PREFIX + dialogData.getObjectid(), true); edit.apply(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( dialogData.getActionButtonUrl() )); startActivity(intent); } catch(Exception e) { if (BuildConfig.DEBUG) { e.printStackTrace(); } } } }); } if (dialogData.getCloseButtonTitle() != null) { builder.setNegativeButton(dialogData.getCloseButtonTitle(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int which) { edit.putBoolean(DialogsHelper.APW_SP_DIALOG_ALREADY_OPENED_PREFIX + dialogData.getObjectid(), true); edit.apply(); DialogFragment.this.getDialog().cancel(); } }); } Dialog returnDialog = builder.create(); ColorDrawable cd = new ColorDrawable( DialogsHelper.getInstance().getViewOptions().getDialogPanelBackgroundColour() ); Window window = returnDialog.getWindow(); if (window != null) { window.setBackgroundDrawable(cd); } return returnDialog; } @Override public void onStart() { super.onStart(); if (dialogData.getActionButtonTitle() != null && dialogData.getActionButtonUrl() != null) { Button positiveButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE); positiveButton.setTextColor( DialogsHelper.getInstance().getViewOptions().getDialogPanelForegroundColour() ); } if (dialogData.getCloseButtonTitle() != null) { Button negativeButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_NEGATIVE); negativeButton.setTextColor( DialogsHelper.getInstance().getViewOptions().getDialogPanelForegroundColour() ); } } @Override public void show(FragmentManager manager, String tag) { // If dialogData already exists, close it first (in case it needs an update) if (manager.findFragmentByTag(tag) != null) { DialogFragment fragment = (DialogFragment) manager.findFragmentByTag(tag); fragment.getDialog().cancel(); } super.show(manager, tag); } }
C++
UTF-8
485
2.6875
3
[]
no_license
#ifndef GGP_SCENE_H #define GGP_SCENE_H #include <string> #include "GameObject.h" class Camera; class Scene : public GameObject { protected: Camera * activeCamera; float totalTime; public: Scene(std::string _uniqueID); //Extra init method that runs before start. Useful to create objects and set up the scene virtual void Init(); virtual void Start(); virtual void Update(float _deltaTime); //Resize event void OnResize(float width, float height); }; #endif //GGP_SCENE_H
Swift
UTF-8
1,204
2.609375
3
[]
no_license
// // ConfigurationManager.swift // ZRahman_TV_Remote_Phone // // Created by Zak on 3/1/16. // Copyright © 2016 csc471.depaul.edu. All rights reserved. // import UIKit class ConfigurationManager: NSObject { private var id: Int private var channelNumber: Int private var channelLabel:String init(idIn:Int, channelNumberIn:Int, channelLabelIn: String){ id = idIn channelNumber = channelNumberIn channelLabel = channelLabelIn } func saveFavChannel(fcObj fcObj: ConfigurationManager, idIn : Int, channelNumberIn: Int, channelLabelIn: String) { fcObj.id = idIn fcObj.channelNumber = channelNumberIn fcObj.channelLabel = channelLabel } func getId()->Int{ return id; } func setId(idIn:Int){ id = idIn; } func getChannelNumber()->Int{ return channelNumber; } func setChannelNumber(channelNumberIn:Int){ channelNumber = channelNumberIn; } func getChannelLabel()->String{ return channelLabel; } func setChannelLabel(channelLabelIn:String){ channelLabel = channelLabelIn; } }
Markdown
UTF-8
1,099
2.875
3
[ "CC-BY-4.0" ]
permissive
--- layout: default title: "pdftk" date: 2021-06-25 18:12:13 +02:00 --- {% raw %} <h2 id="pdftk"> <a href="/en/common/pdftk.html">pdftk</a> <a href="#pdftk"><svg class="icon"> <use href="/assets/images/unicode_sprite.svg#link" /> </svg></a> </h2> > PDF toolkit. > More information: <https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit>. #### Extract pages 1-3, 5 and 6-10 from a PDF file and save them as another one: ```shell pdftk {{input.pdf}} cat {{1-3 5 6-10}} output {{output.pdf}} ``` #### Merge (concatenate) a list of PDF files and save the result as another one: ```shell pdftk {{file1.pdf file2.pdf ...}} cat output {{output.pdf}} ``` #### Split each page of a PDF file into a separate file, with a given filename output pattern: ```shell pdftk {{input.pdf}} burst output {{out_%d.pdf}} ``` #### Rotate all pages by 180 degrees clockwise: ```shell pdftk {{input.pdf}} cat {{1-endsouth}} output {{output.pdf}} ``` #### Rotate third page by 90 degrees clockwise and leave others unchanged: ```shell pdftk {{input.pdf}} cat {{1-2 3east 4-end}} output {{output.pdf}} ``` {% endraw %}