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
Go
UTF-8
550
2.828125
3
[]
no_license
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" ) type myTable struct { gorm.Model MyColumn1 string MyColumn2 Annotation } func main() { connectionString := fmt.Sprintf("myconnectionString") database, err := gorm.Open("mysql", connectionString) if err != nil { panic(err) } data := myTable{ MyColumn1: "MyColumn1Value1", MyColumn2: Annotation{Values: map[string]string{ "key1": "value1", "key2": "value2", }}, } database.AutoMigrate(&myTable{}) database.Create(&data) }
C++
UTF-8
2,804
2.671875
3
[]
no_license
#include <MilightTransport.h> // default constructor MilightTransport::MilightTransport(NRF24L01Simple &radioref): radio(radioref) { } // open an communicaiton channel for give (5 byte long) address bool MilightTransport::openChannel (uint8_t* address, uint8_t len, uint8_t channel){ uint8_t rev_address[5]; reverseBits(address,rev_address,5); if (!radio.begin(NRF24L01Simple::BITRATE1MBPS)) { Serial.println("Cannot communicate with radio"); while (1); // Wait here forever. } // Set the PA Level low to prevent power supply related issues since this is a // getting_started sketch, and the likelihood of close proximity of the devices. RF24_PA_MAX is default. radio.powerUp(NRF24L01Simple::POWER_LOW, NRF24L01Simple::CHECKSUM_OFF); radio.setChannel(channel); radio.setRxPipe(1, rev_address, 5, false, 10); radio.startRx(); return true; } bool MilightTransport::packetAvailable(){ radio.checkStatus(); return radio.hasData(); } bool MilightTransport::getPacket(uint8_t* packet, uint8_t len) { ReceivePacket_t* pkt = radio.getData(); radio.startRx(); uint8_t* data = pkt->data; reverseBits(data, packet, len); // reverse bits return validateChecksum( packet, len); } // reverse the bits in the input byte void MilightTransport::reverseBits(uint8_t* input, uint8_t* output, uint8_t len) { for (int8_t i = 0; i < len; i++){ uint8_t inp = input[i]; uint8_t result = 0; for (uint8_t j = 0 ; j < 7; j++){ // bit 0 of result is bit 0 if byte result |= (inp & 0x1); result = result << 1; inp = inp >> 1; } // shift in bit 8 result |= (inp & 0x1); output[i] = result; } /* for (int8_t i = 0; i < len; i++){ Serial.print("i: " ); Serial.print(i); Serial.print(" inp: " ); Serial.print(input[i], HEX ); Serial.print(" outp hex: " ); Serial.print(output[i], HEX ); Serial.print(" outp dec: " ); Serial.println (output[i] ); } */ } #define CRC_POLY 0x8408 bool MilightTransport::validateChecksum(uint8_t *data, uint8_t len) { uint16_t state = 0; for (uint8_t i = 0; i < len - 2; i++) { uint8_t byte = data[i]; for (int j = 0; j < 8; j++) { if ((byte ^ state) & 0x01) { state = (state >> 1) ^ CRC_POLY; } else { state = state >> 1; } byte = byte >> 1; } } /* Serial.print(" calculated checksum: " ); Serial.print(state, HEX ); Serial.print(" actual: " ); Serial.print(data[len -2], HEX ); Serial.print(" " ); Serial.println(data[len -1], HEX ); */ uint8_t l = state & 0xFF; uint8_t h = (state >> 8) & 0xFF; return l == data[len-2] && h == data[len-1]; }
Ruby
UTF-8
513
4.59375
5
[]
no_license
# Write a method called `palindrome?` which should accept a string as a parameter and return # a boolean that indicates whether the string is a palindrome. # A palindrome is a word that reads the same both forwards and backwards. Examples: eye, madam, racecar # ```p palindrome?("racecar") #=> true # p palindrome?("wazzzzup") #=> false``` # p palindrome?("wazzzzup") #=> false``` def palindrome(string) if string == string.reverse return true else return false end end p palindrome("bloooooooolb")
Python
UTF-8
159
4.0625
4
[]
no_license
def factors(n): for i in range(1,n+1): if (n%i==0): print(i) n=int(input("Enter the number")) print("Factors of %d are"%n) factors(n)
Markdown
UTF-8
1,864
2.625
3
[]
no_license
# # 题目描述 <p> <img border="0" src="/source/joyoi/tyvj-2697/img/aHR0cDovL3d3dy5qb3lvaS5jbi9wcm9ibGVtL3R5dmotMjY5Ny9wcm9ibGVtc19pbWFnZXMvMzE4Ni8xOTIwXzEuanBn.jpg"> </p> # 输入格式 <p> <img border="0" src="/source/joyoi/tyvj-2697/img/aHR0cDovL3d3dy5qb3lvaS5jbi9wcm9ibGVtL3R5dmotMjY5Ny9wcm9ibGVtc19pbWFnZXMvMzE4Ni8xOTIwXzIuanBn.jpg"> </p> # 输出格式 <p> 仅包含一个非负整数,表示公司的最小总耗费。</p> # 提示 <p> 第一个季度生产 2件产品,第二个季度生产5 件产品,第三个季度不生产产 <br>品,第四个季度生产 1 件产品,成本为 2 * 5 + 5 * 1 + 0 * 5 + 1 * 5 = 20。 <br>因为第一个季度最多只能生产 2 件产品,无法满足 3 件的订购量,因此将 1 <br>件产品的订购量推迟到第二个季度,赔偿给用户的损失费为 5。 <br>第二个季度由于第一个季度推迟了一件产品的订购需求, 因而订购量变为 3。 <br>该季度生产了5件产品, 剩下的2件保存下来。 第三个季度直接销售库存的产品, <br>再多出来的 1 件产品继续储存到第四个季度,加上第四个季度生产了 1 件产品, <br>因此满足了所有订单需求。总的储存费用为 2 * 2 + 1 * 1 = 5。 <br>总的费用为 20 + 5 + 5 = 30。 <br> <br>对于 30%的数据,N&#3409;< = 1,000。 <br>对于 100%的数据,1 < =&#3409;N < =&#3409; 100,000,1< =&#3409;Di, Ui, Pi, Mi,Ci < =&#3409; 10,000。 <br></p> # 样例数据 <style> table,table tr th, table tr td { border:1px solid #0094ff; } table { width: 200px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse;} </style> <table> <tr> <td>输入样例</td> <td>输出样例</td> </tr> <tr><td>4 3 2 1 2 2 5 2 2 5 1 5 5 1 2 1 5 3 3 </td><td>30</td></tr></table>
TypeScript
UTF-8
477
3.59375
4
[]
no_license
interface Animal { mover(distancia: number); } class Minhoca implements Animal { mover(distancia: number) { console.log('Minhoca rasteja ' + distancia + ' metros'); } } class Cavalo implements Animal { mover(distancia: number) { console.log('Cavalo trotou ' + distancia + ' metros'); } } let cavalo: Cavalo = new Cavalo(); cavalo.mover(4); let animal: Animal = new Cavalo(); animal.mover(5); animal = new Minhoca(); animal.mover(3);
C++
UTF-8
2,285
2.625
3
[]
no_license
// This file is part of Barrel project. Read README for more information. // Author: peuhkura@gmail.com #include "Exporter.hpp" #include <Grapevine/Core/Exception.hpp> #include <iostream> #include <fstream> Exporter::Exporter() { } Exporter::~Exporter() { } void Exporter::addMesh(FBX2Vanda::Mesh* mesh) { meshes_.push_back(mesh); } void Exporter::addMaterial(FBX2Vanda::Material* material) { materials_.push_back(material); } void Exporter::write(std::string const& fileOut) { /*typedef std::map<std::string, int> MaterialIDs; MaterialIDs materialIDs; Grapevine::Log::D("Linking materials to meshes..."); // Assign IDs for materials int j = 0; for (std::vector<FBX2Vanda::Material*>::iterator i = materials_.begin(); i != materials_.end(); ++i) { FBX2Vanda::Material* barrelMaterial = *i; Grapevine::Log::D("material '%s', id %d", barrelMaterial->getMaterialName()->c_str(), j); barrelMaterial->setMaterialID(j); materialIDs[barrelMaterial->getMaterialName()->c_str()] = j++; } // Find materials and their IDs for every mesh for (std::vector<FBX2Vanda::Mesh*>::iterator i = meshes_.begin(); i != meshes_.end(); ++i) { FBX2Vanda::Mesh* barrelMesh = *i; int materialID = -1; MaterialIDs::iterator j = materialIDs.find(barrelMesh->getMaterialName()->c_str()); if(j == materialIDs.end()) { Grapevine::Log::D("mesh '%s' has no material", barrelMesh->getName()->c_str()); } else { materialID = j->second; Grapevine::Log::D("mesh '%s' linked to material '%s' having id %d", barrelMesh->getName()->c_str(), j->first.c_str(), materialID); } barrelMesh->setMaterialID(materialID); }*/ std::ofstream fileStream; fileStream.open (fileOut.c_str(), std::ios::out | std::ios::trunc | std::ios::binary); fileStream << "[VandaS]"; Grapevine::Log::D("Export meshes..."); for (std::vector<FBX2Vanda::Mesh*>::iterator i = meshes_.begin(); i != meshes_.end(); ++i) { //FBX2Vanda::Mesh* mesh = *i; (*i)->write(fileStream); } Grapevine::Log::D("end write..."); fileStream << "[VandaE]"; fileStream.close(); Grapevine::Log::D("end done."); }
C++
UTF-8
3,778
2.609375
3
[]
no_license
#include <entity/common.h>/*{{{*/ #include <entity/group_dim.h> #include <entity/vector_dim.h> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/algorithm/string.hpp> /*}}}*/ using namespace boost; using namespace std; namespace logs { namespace entity { /*}}}*/ vector_dimension::vector_dimension() :_basename(item_def::name_of(item_def::ADDI)) { } vector_dimension::vector_dimension(const std::string& name) :_basename(name) { } int vector_dimension::count() { return _dim_array.size(); } vector_dimension::vector_dimension(const vector_dimension& other) :_dim_array(other._dim_array) { } std::string vector_dimension::create_son_name(const std::string& name) { string son_name=_basename+"."+name; return son_name; } void vector_dimension::set_basename(const std::string& basename) { _basename = basename; } string vector_dimension::name() const { return item_def::name_of(item_def::ADDI)+"*"; } string vector_dimension::value() const {/*{{{*/ stringstream buf; dim_vector::const_iterator pos = _dim_array.begin(); for(; pos!= _dim_array.end(); ++ pos) { dimension::shared_ptr dim =*pos; if(dim) buf<<dim->name()<<"="<<dim->value(); } return buf.str(); }/*}}}*/ bool vector_dimension::true_equal(const dimension& other) const {/*{{{*/ const vector_dimension* other_ptr = dynamic_cast< const vector_dimension* >(&other); if( 0 == other_ptr ) return false; const vector_dimension& other_vect= * other_ptr; REQUIRE(_dim_array.size()== other_vect._dim_array.size()); dim_vector::const_iterator pos = _dim_array.begin(); dim_vector::const_iterator other_pos = other_vect._dim_array.begin(); for(; pos!=_dim_array.end(); ++pos,++other_pos) { if((*pos).get()!=0 && other_pos->get()!=0) { if(!( *(*pos) == *(*other_pos))) return false; } else if (! (pos->get() ==0 && other_pos->get() == 0) ) { return false; } } return true; }/*}}}*/ bool vector_dimension::in(const dimension& other) const {/*{{{*/ const vector_dimension* other_ptr = dynamic_cast< const vector_dimension* >(&other); if( 0 == other_ptr ) return false; const vector_dimension& other_vect= * other_ptr; REQUIRE(_dim_array.size()== other_vect._dim_array.size()); dim_vector::const_iterator pos = _dim_array.begin(); dim_vector::const_iterator other_pos = other_vect._dim_array.begin(); for(; pos!=_dim_array.end(); ++pos,++other_pos) { if((*pos).get()!=0 && other_pos->get()!=0) { if(!( *(*pos) == *(*other_pos))) return false; } } return true; }/*}}}*/ bool vector_dimension::equal(const dimension& other)const { return true_equal(other); } bool vector_dimension::less(const dimension& other)const { throw improve::no_realization(__FUNCTION__); } bool vector_dimension::have_son(const string& name) const {/*{{{*/ if(name.empty()) return false; if(_dim_array.empty()) return false; dim_vector::const_iterator pos = _dim_array.begin(); for(;pos!=_dim_array.end();++pos) { dimension* ptr = (*pos).get(); if(ptr->name()==name) { return true; } } return false; }/*}}}*/ const dimension* vector_dimension::son_dim(const string& name) {/*{{{*/ REQUIRE(have_son(name)); dim_vector::iterator pos = _dim_array.begin(); for(;pos!=_dim_array.end();++pos) { dimension* ptr = (*pos).get(); if(ptr->name()==name) return ptr; } return NULL; }/*}}}*/ const vector_dimension& vector_dimension::operator=(const vector_dimension& other) { _dim_array=other._dim_array; return *this; } void vector_dimension::add_son(dimension::shared_ptr dim) { _dim_array.push_back(dim); } dimension* vector_dimension::clone()const { return new vector_dimension(*this); } } }
Python
UTF-8
3,079
2.890625
3
[]
no_license
#!/usr/bin/python3 import json import time import re import requests secrets_file = 'slack_secret.json' f = open(secrets_file, 'r') content = f.read() auth_info = json.loads(content) token = auth_info["access_token"] f.close() from slackclient import SlackClient sc = SlackClient(token) def Message_Match(user_ID, message_text): regex_expression = '.*@' + user_id +'.*bot.*' regex = re.compile(regex_expression) match = regex.match(message_text) return match != None def Extract_CityName(message_text): regex_expression = '[H,h]ow\'s the weather in ([A-z, ]+)\?' regex = re.compile(regex_expression) matches = regex.finditer(message_text) for match in matches: return match.group(1) return None key = '097217bc8c67dcadb7f7f7b295429be1' def Get_WeatherData(key, city): import requests return requests.get('http://api.openweathermap.org/data/2.5/weather?q={city}&appid={key}'.format(city=city,key=key)).json() def Kelvin_to_Farenheit(temp_kelvin): return (temp_kelvin - 273) * (9/5) + 32 def Return_WeatherResults(city, user): key = '097217bc8c67dcadb7f7f7b295429be1' data = Get_WeatherData(key, city) if city == None: return "I'm sorry @{user}, I'm not sure I understand. Try rephrasing in this form: \n \'Hey @maxdavish bot, how's the weather in London?\'".format(user=user) if 'message' in data.keys(): return "I'm sorry @{user}, I'm not familiar with that place. Please try again.".format(user=user) else: city = city temperature = round(Kelvin_to_Farenheit(data['main']['temp']), 1) hightemp = round(Kelvin_to_Farenheit(data['main']['temp_max']), 1) lowtemp = round(Kelvin_to_Farenheit(data['main']['temp_min']), 1) description = data['weather'][0]['description'] result = "@{user}, currently in {city} it's {temperature} degrees farenheit with {description}, with a high of {hightemp} and a low of {lowtemp}.".format(user=user, city=city,temperature=temperature,description=description,hightemp=hightemp,lowtemp=lowtemp) return result def message_matches(user_id, message_text): regex_expression = '.*@' + user_id + '.*bot.*' regex = re.compile(regex_expression) match = regex.match(message_text) return match != None if sc.rtm_connect(): while True: time.sleep(1) response = sc.rtm_read() for item in response: if item.get("type") != 'message': continue if item.get("user") == None: continue user_id = auth_info["user_id"] message_text = item.get('text') if not message_matches(user_id, message_text): continue response = sc.api_call("users.info", user=item["user"]) username = response['user'].get('name') city_name = Extract_CityName(message_text) message = Return_WeatherResults(city_name, username) sc.api_call("chat.postMessage", channel="#assignment2_bots", text=message)
Java
UTF-8
2,362
2.0625
2
[ "Apache-2.0" ]
permissive
package com.stylefeng.guns.modular.business.service; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.stylefeng.guns.modular.system.model.YddSealmail; import com.baomidou.mybatisplus.service.IService; import java.util.Date; import java.util.List; /** * <p> * 下件信息表 服务类 * </p> * * @author stylefeng * @since 2018-07-22 */ public interface IYddSealmailService extends IService<YddSealmail> { /** * 根据单号、开始时间、结束时间查询下件信息列表 * */ List<YddSealmail> getYddSealmails(String barcode, String chute,String beginTime, String endTime); /** * 根据供件台号、开始时间、结束时间查询格口吞吐量 * */ String getSupplyEfficiency(String inductionid, String beginTime, String endTime); /** * 根据格口号、开始时间、结束时间查询格口吞吐量 * */ String getThroughputs(String chute, String beginTime, String endTime); /** * 根据开始时间、结束时间查询分拣总量 * */ String getSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询自动分拣正常分拣总量 * */ Integer getAutoNormalSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询人工补码正常分拣总量 * */ Integer getBumaNormalSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询异常口分拣总量 * */ Integer getExceptionSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询超时异常口分拣总量 * */ Integer getTimeoutExceptionSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询无条码异常口分拣总量 * */ Integer getNoBarcodeExceptionSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询百世直接推送异常口分拣总量 * */ Integer getExceptionByBestSortCounts(String beginTime, String endTime); /** * 根据开始时间、结束时间查询分拣趋势(20分钟一次统计) * */ String getSortingEfficiency(String beginTime, String endTime); }
PHP
UTF-8
877
2.796875
3
[]
no_license
<?php require_once './lib.php'; class SmsJob{ private $name; private $mobile; /** * 预处理 */ public function setUp(){ $this->name = $this->args['name']; $this->mobile = $this->args['mobile']; stdout('新注册用户信息:'); stdout('姓名:'.$this->name); stdout('手机号:'.$this->mobile); } /** * 具体任务 */ public function perform(){ for($i=0;$i<10;$i++){ if($i === 0){ stdout('开始执行具体任务'); } stdout('发送短信中--第'.($i+1).'秒'); if($i === 10){ stdout('任务执行完毕'); } sleep(1); } } /** * 后续处理 */ public function tearDown(){ stdout('任务执行完毕'); stdout(); } }
JavaScript
UTF-8
2,063
3.9375
4
[]
no_license
// on body tag function startGame() { // 1 establish default 1st turn document.turn = "👽"; // 2 display this message and switch it based on who's turn it is setMessage(document.turn + " is up next!") } // 3 where that message gets displayed? function setMessage(msg) { document.getElementById("message").innerText = msg; } // if the selected sqaure is blank, switch the turn like normal // if its used display new message and do not switch turn function nextMove(square) { if (square.innerText == '') { square.innerText = document.turn; switchTurn(); } else { setMessage("This square is used, try another! ಠ_ಠ") } } // after each selection is made //check for winner // display most up to date message function switchTurn() { if (checkForWinner(document.turn)) { setMessage("You win " + document.turn + " good job! (•‿•) ") } else if (document.turn == "👽") { document.turn = "🚀"; setMessage("It's currently " + document.turn + " 's turn! ☚") } else { document.turn = "👽"; setMessage("It's currently " + document.turn + " 's turn! ☚") } } // how winner is checked for // if any combo is true return result function checkForWinner(move) { var result = false; if (checkRow(1, 2, 3, move) || checkRow(4, 5, 6, move) || checkRow(7, 8, 9, move) || checkRow(1, 4, 7, move) || checkRow(2, 5, 8, move) || checkRow(3, 6, 9, move) || checkRow(1, 5, 9, move) || checkRow(3, 5, 7, move)) { result = true; } return result; } // how the check row is recided if true or false function checkRow(a, b, c, move) { var result = false; if (getBox(a) == move && getBox(b) == move && getBox(c) == move) { result = true; } return result; } //display winner message // winning combos based on each "td" id ex s3 = s + 3 function getBox(number) { return document.getElementById("s" + number).innerText; } // test commit
C#
UTF-8
11,566
2.578125
3
[ "MIT" ]
permissive
/* The MIT License (MIT) Copyright (c) 2014 Kolibri Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // from // https://github.com/kolibridev/clippy/blob/master/Clippy/Clippy.cs using System; using System.Runtime.InteropServices; using System.Text; // ReSharper disable once CheckNamespace namespace FlatRedBall.Forms.Clipboard { public class ClipboardImplementation { #region DllImports [DllImport("user32.dll")] static extern IntPtr GetClipboardData(uint uFormat); [DllImport("user32.dll")] static extern bool IsClipboardFormatAvailable(uint format); [DllImport("kernel32.dll")] private static extern IntPtr GlobalAlloc(uint uFlags, UIntPtr dwBytes); [DllImport("kernel32.dll")] private static extern uint GetLastError(); [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr hMem); [DllImport("kernel32.dll")] private static extern IntPtr GlobalFree(IntPtr hMem); [DllImport("kernel32.dll")] private static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalUnlock(IntPtr hMem); [DllImport("kernel32.dll", EntryPoint = "CopyMemory", SetLastError = false)] public static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CloseClipboard(); [DllImport("user32.dll")] private static extern IntPtr SetClipboardData(uint uFormat, IntPtr data); #endregion #region Result Code public enum ResultCode { Success = 0, ErrorOpenClipboard = 1, ErrorGlobalAlloc = 2, ErrorGlobalLock = 3, ErrorSetClipboardData = 4, ErrorOutOfMemoryException = 5, ErrorArgumentOutOfRangeException = 6, ErrorException = 7, ErrorInvalidArgs = 8, ErrorGetLastError = 9 }; #endregion #region Result Class public class Result { public ResultCode ResultCode { get; set; } public uint LastError { get; set; } public bool OK { // ReSharper disable once RedundantNameQualifier get { return ClipboardImplementation.ResultCode.Success == ResultCode; } } } #endregion public static string GetText() { if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return null; if (!OpenClipboard(IntPtr.Zero)) return null; string data = null; var hGlobal = GetClipboardData(CF_UNICODETEXT); if (hGlobal != IntPtr.Zero) { var lpwcstr = GlobalLock(hGlobal); if (lpwcstr != IntPtr.Zero) { data = Marshal.PtrToStringUni(lpwcstr); GlobalUnlock(lpwcstr); } } CloseClipboard(); return data; } [STAThread] public static Result PushStringToClipboard(string message) { var isAscii = (message != null && (message == Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(message)))); if (isAscii) { return PushUnicodeStringToClipboard(message); } else { return PushAnsiStringToClipboard(message); } } [STAThread] public static Result PushUnicodeStringToClipboard(string message) { return __PushStringToClipboard(message, CF_UNICODETEXT); } [STAThread] public static Result PushAnsiStringToClipboard(string message) { return __PushStringToClipboard(message, CF_TEXT); } // ReSharper disable InconsistentNaming const uint CF_TEXT = 1; const uint CF_UNICODETEXT = 13; // ReSharper restore InconsistentNaming [STAThread] private static Result __PushStringToClipboard(string message, uint format) { try { try { if (message == null) { return new Result { ResultCode = ResultCode.ErrorInvalidArgs }; } if (!OpenClipboard(IntPtr.Zero)) { return new Result { ResultCode = ResultCode.ErrorOpenClipboard, LastError = GetLastError() }; } try { uint sizeOfChar; switch (format) { case CF_TEXT: sizeOfChar = 1; break; case CF_UNICODETEXT: sizeOfChar = 2; break; default: throw new Exception("Not Reachable"); } var characters = (uint)message.Length; uint bytes = (characters + 1) * sizeOfChar; // ReSharper disable once InconsistentNaming const int GMEM_MOVABLE = 0x0002; // ReSharper disable once InconsistentNaming const int GMEM_ZEROINIT = 0x0040; // ReSharper disable once InconsistentNaming const int GHND = GMEM_MOVABLE | GMEM_ZEROINIT; // IMPORTANT: SetClipboardData requires memory that was acquired with GlobalAlloc using GMEM_MOVABLE. var hGlobal = GlobalAlloc(GHND, (UIntPtr)bytes); if (hGlobal == IntPtr.Zero) { return new Result { ResultCode = ResultCode.ErrorGlobalAlloc, LastError = GetLastError() }; } try { // IMPORTANT: Marshal.StringToHGlobalUni allocates using LocalAlloc with LMEM_FIXED. // Note that LMEM_FIXED implies that LocalLock / LocalUnlock is not required. IntPtr source; switch (format) { case CF_TEXT: source = Marshal.StringToHGlobalAnsi(message); break; case CF_UNICODETEXT: source = Marshal.StringToHGlobalUni(message); break; default: throw new Exception("Not Reachable"); } try { var target = GlobalLock(hGlobal); if (target == IntPtr.Zero) { return new Result { ResultCode = ResultCode.ErrorGlobalLock, LastError = GetLastError() }; } try { CopyMemory(target, source, bytes); } finally { var ignore = GlobalUnlock(target); } if (SetClipboardData(format, hGlobal).ToInt64() != 0) { // IMPORTANT: SetClipboardData takes ownership of hGlobal upon success. hGlobal = IntPtr.Zero; } else { return new Result { ResultCode = ResultCode.ErrorSetClipboardData, LastError = GetLastError() }; } } finally { // Marshal.StringToHGlobalUni actually allocates with LocalAlloc, thus we should theorhetically use LocalFree to free the memory... // ... but Marshal.FreeHGlobal actully uses a corresponding version of LocalFree internally, so this works, even though it doesn't // behave exactly as expected. Marshal.FreeHGlobal(source); } } catch (OutOfMemoryException) { return new Result { ResultCode = ResultCode.ErrorOutOfMemoryException, LastError = GetLastError() }; } catch (ArgumentOutOfRangeException) { return new Result { ResultCode = ResultCode.ErrorArgumentOutOfRangeException, LastError = GetLastError() }; } finally { if (hGlobal != IntPtr.Zero) { var ignore = GlobalFree(hGlobal); } } } finally { CloseClipboard(); } return new Result { ResultCode = ResultCode.Success }; } catch (Exception) { return new Result { ResultCode = ResultCode.ErrorException, LastError = GetLastError() }; } } catch (Exception) { return new Result { ResultCode = ResultCode.ErrorGetLastError }; } } } }
JavaScript
UTF-8
1,976
3.203125
3
[ "MIT" ]
permissive
$(document).ready(function(){ $("input[type='button']").click(function(){ //create an array for storing name ie quiz1 to quiz10 arr = []; for (i = 1; i <= 10; i++) { query = "quiz"+i; arr.push(query); } //Do a form validation to check if all the questions have been answered var inputs = document.getElementById("quiz").elements; var count = 0; for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == 'radio' && inputs[i].checked) { count++; } } if(count<10) { alert("please answer all the questions"); document.location.reload(); } else { alert("Thank you for answering all the questions"); } //Create an array for storing the checked values arr2=[]; for (var index = 0; index < arr.length; index += 1) { var questions = parseInt($("input[name=" + arr[index] + "]:checked").val()); arr2.push(questions); } //Do a total of the checked values collected var total = 0; for (var index = 0; index < arr2.length; index += 1) { total += arr2[index]; } //Display the total marks document.getElementById('finalscore').innerHTML="you have scored " + total + "%"; //excellent, fair and poor grading if(total >= 80) { document.getElementById('message').innerHTML="Excellent you have passed"; } else if (total >= 50 && total < 80) { document.getElementById('message').innerHTML="This is Fair"; } else { document.getElementById('message').innerHTML="Poor please retake the test"; } }); }); // scrolldown progress bar $(document).ready(function(){ $(window).scroll(function() { var a = $(window).scrollTop();//shows position of the scroll in pixels var b = $(document).height();//full height of doc var c = $(window).height();//window height scrollPercent = (a / (b - c)) * 100; var position = scrollPercent; $("#progressbar").attr('value', position); //setting the value of the progressbar }); });
JavaScript
UTF-8
2,781
3.34375
3
[]
no_license
var rollsSlider = document.getElementById("rolls"); var rollsOutput = document.getElementById("rollsValue"); rollsOutput.innerHTML = rollsSlider.value; rollsSlider.oninput = function() { rollsOutput.innerHTML = this.value; calculateRolls(); } var daysSlider = document.getElementById("days"); var daysOutput = document.getElementById("daysValue"); daysOutput.innerHTML = daysSlider.value; daysSlider.oninput = function() { daysOutput.innerHTML = this.value; calculateRolls(); } var peopleSlider = document.getElementById("people"); var peopleOutput = document.getElementById("peopleValue"); peopleOutput.innerHTML = peopleSlider.value; peopleSlider.oninput = function() { peopleOutput.innerHTML = this.value; calculateRolls(); } var lifeSlider = document.getElementById("life"); var lifeOutput = document.getElementById("lifeValue"); lifeOutput.innerHTML = lifeSlider.value; lifeSlider.oninput = function() { lifeOutput.innerHTML = this.value; calculateRolls(); } function calculateRolls() { const nbrolls = rollsSlider.value; const nbdays = daysSlider.value; const nbpeople = peopleSlider.value; const timelife = lifeSlider.value; const paperDays = nbrolls * timelife; const ratio = paperDays / nbdays / nbpeople * 100 ; const ratioDiv = document.getElementById('ratio'); if (ratio>200){ const emoji = ": this is the percentage of the quarantine that you will survive. 🤣 Wow! I accuse you of buing all the toilet paper from the store... "; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; }else if (ratio>100){ const emoji = ": this is the percentage of the quarantine that you will survive. 😉 Nice, you will survive it!"; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; } else if (ratio == 100){ const emoji = ": this is the percentage of the quarantine that you will survive. 😯 Really close! You will survive finishing your last roll in the last day! "; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; } else if (ratio > 75){ const emoji = ": this is the percentage of the quarantine that you will survive. 😐 Sad...You will not survive all your quarantine days, but it will be close."; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; } else if (ratio > 30){ const emoji = ": this is the percentage of the quarantine that you will survive. 😔 You will be in trouble from nearly half of the confinement, enjoy your last days!"; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; } else if (ratio > 0){ const emoji = ": this is the percentage of the quarantine that you will survive. 💩 Were you sleeping when everybody else was rushing to Carrefour? Probably, and you will perish really soon!"; ratioDiv.innerText = `${Math.round(ratio)}% ${emoji}`; } };
C++
UTF-8
504
2.828125
3
[]
no_license
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "../include/doctest.h" #include "../src/word_treatment.h" using namespace std; TEST_CASE("split") { vector <string> expected = {"teste", "123", "456"}; CHECK(split("teste 123 456", " ") == expected); } TEST_CASE("treat") { string a = "aBcDe"; treat(a); CHECK(a == "abcde"); string b = "t3st3_tre@t!"; treat(b); CHECK(b == "t3st3tret"); // string c = "ácêñtò"; // treat(c); // CHECK(c == "acento"); }
PHP
UTF-8
1,137
2.75
3
[]
no_license
<?php namespace FormBuilder; use \SER\BSPA\Form\FormBuilder; use \SER\BSPA\Form\StringField; use \SER\BSPA\Form\TextField; use \SER\BSPA\Form\SelectField; use \SER\BSPA\Form\MaxLengthValidator; use \SER\BSPA\Form\NotNullValidator; class AdminCommentFormBuilder extends FormBuilder { public function build() { $this->form->add(new StringField([ 'label' => 'Auteur', 'name' => 'author', 'value' => '', 'maxLength' => 50, 'disabled' => 'disabled', 'validators' => [ new MaxLengthValidator('L\'auteur spécifié est trop long (50 caractères maximum)', 50), new NotNullValidator('Merci de spécifier l\'auteur du commentaire'), ], ])) ->add(new TextField([ 'label' => 'Message', 'name' => 'message', 'rows' => 7, 'cols' => 50, 'validators' => [ new NotNullValidator('Merci de spécifier votre commentaire'), ], ])) ->add(new SelectField([ 'label' => 'Statut', 'name' => 'state', 'selects' => [0 => 'censuré', 1 => 'public'], ])); } }
JavaScript
UTF-8
645
2.734375
3
[]
no_license
const ADD_MESSAGE = 'reducers/chat/add-message'; export function addMessage(message, human) { return { type: ADD_MESSAGE, message, human, }; } function addMessageReducer(state, action) { const message = { type: 'message', id: state.messages.length, message: action.message, human: action.human, }; const messages = [...state.messages, message]; return { ...state, messages }; } const defaultState = { messages: [], }; export function chatReducer(state = defaultState, action) { switch (action.type) { case ADD_MESSAGE: return addMessageReducer(state, action); default: return state; } }
C++
UTF-8
978
2.78125
3
[ "MIT" ]
permissive
#include <math.h> #include <string> #include <algorithm> #include <queue> #include <vector> #include <iostream> #include <stdio.h> using namespace std; int main() { int i, n, escalador, ngrupos, tammin, tammax, tamtemp, vlento, flag; while (1) { cin >> n; if (!n) { return 0; } tammin = 1; tammax = 1; ngrupos = 1; tamtemp = 1; flag = 0; cin >> vlento; for (i = 1; i < n; i++) { cin >> escalador; if (escalador >= vlento) { tamtemp++; } else if (escalador < vlento || i == n - 1) { if (!flag) { tammin = tamtemp; flag = 1; } else { tammin = min(tammin, tamtemp); } tammax = max(tammax, tamtemp); ngrupos++; tamtemp = 1; vlento = escalador; } } if (!flag) { tammin = tamtemp; }else{ tammin = min(tammin, tamtemp);} tammax = max(tammax, tamtemp); cout << ngrupos << " " << tammin << " " << tammax << endl; } return 0; }
Java
UTF-8
948
2.21875
2
[ "MIT" ]
permissive
package com.baeldung.logging; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.web.SecurityFilterChain; @EnableWebSecurity public class SecurityConfig { @Value("${spring.websecurity.debug:false}") boolean webSecurityDebug; @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.debug(webSecurityDebug); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/**") .permitAll(); return http.build(); } }
Java
UTF-8
1,865
2.671875
3
[]
no_license
package com.example.david.reddit_android; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.util.Log; public class GetData { public static HttpURLConnection getCon(String url){ System.out.println("URL: "+url); HttpURLConnection hcon = null; try { hcon=(HttpURLConnection)new URL(url).openConnection(); hcon.setReadTimeout(30000); // Timeout at 30 seconds hcon.setRequestProperty("JD", "Reddit_Android"); } catch (MalformedURLException e) { Log.e("getCon()", e.toString()); } catch (IOException e) { Log.e("getCon()", e.toString()); } return hcon; } public static String Read(String url){ byte[] t= Cache.read(url); String cached=null; if(t!=null) { cached=new String(t); t=null; } if(cached!=null) { Log.d("MSG","Using cache for "+url); return cached; } HttpURLConnection hcon= getCon(url); if(hcon==null) return null; try{ StringBuffer sb=new StringBuffer(8192); String tmp=""; BufferedReader br=new BufferedReader( new InputStreamReader( hcon.getInputStream() ) ); while((tmp=br.readLine())!=null) sb.append(tmp).append("\n"); br.close(); Cache.write(url, sb.toString()); return sb.toString(); }catch(IOException e){ Log.d("READ FAILED", e.toString()); return null; } } }
Python
UTF-8
799
2.578125
3
[]
no_license
from Cube import * from Configurator import * from itertools import product import cPickle repo_filename = 'repo.dat' def get_repo(filename): try: f = open(filename, 'r') except: return create_repo(filename) return cPickle.load(f) def create_repo(filename, depth=4): repository = {} depth = 5; basic_moves = [] for f in xrange(6): for n in xrange(1,4): basic_moves.append((f,n)) for i,moves in enumerate(product(basic_moves, repeat=depth)): c = Cube() for move in moves: c.rotate(*move) t = c.get_current_tuple_representation() repository.setdefault(t, moves) print i f = open('repo.dat', 'w') cPickle.dump(repository, f) f.close() return repository
C#
UTF-8
3,058
2.703125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Ver { public sealed class AssemblyVersionWriter : IAssemblyVersionWriter { //[assembly: AssemblyVersion("1.0.0.0")] //[assembly: AssemblyFileVersion("1.0.0.0")] private const string VersionSignatureTemplate = @"^(?<FrontSignature>\[assembly: {VersionKind})(?<LeftPadding>[^""]+"")(?<AssemblyVersion>([^""]+))(?<RightPadding>.+)$"; private static readonly string AssemblyVersionPattern = VersionSignatureTemplate.Replace("{VersionKind}", "AssemblyVersion"); private static readonly string AssemblyFileVersionPattern = VersionSignatureTemplate.Replace("{VersionKind}", "AssemblyFileVersion"); private bool _disposed; private readonly string _filePath; private readonly Func<string, string> _fileReader; private readonly Action<string, string> _fileWriter; private readonly List<Func<string, string>> _writeBuffer; public AssemblyVersionWriter(string filePath, Func<string, string> fileReader, Action<string, string> fileWriter) { if (filePath == null) throw new ArgumentNullException(nameof(filePath)); if (string.IsNullOrWhiteSpace(filePath)) throw new ArgumentException("String cannot be empty.", nameof(filePath)); if (fileReader == null) throw new ArgumentNullException(nameof(fileReader)); if (fileWriter == null) throw new ArgumentNullException(nameof(fileWriter)); _filePath = filePath; _fileReader = fileReader; _fileWriter = fileWriter; _writeBuffer = new List<Func<string, string>>(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void WriteAssemblyVersion(string version, bool isFileVersion = false) { if (isFileVersion) { _writeBuffer.Add(fileContent => UpdateAssemblyVersion(version, fileContent, AssemblyFileVersionPattern)); } else { _writeBuffer.Add(fileContent => UpdateAssemblyVersion(version, fileContent, AssemblyVersionPattern)); } } private void Dispose(bool disposing) { if (_disposed) return; if (disposing) { Flush(); _disposed = true; } } private void Flush() { if (_writeBuffer.Count == 0) return; var fileContent = _fileReader(_filePath); _writeBuffer.ForEach(buffer => fileContent = buffer(fileContent)); _fileWriter(_filePath, fileContent); } private string UpdateAssemblyVersion(string version, string fileContent, string versionPattern) { return Regex.Replace(fileContent, versionPattern, "${FrontSignature}${LeftPadding}" + version + "${RightPadding}", RegexOptions.Multiline); } } }
Java
UTF-8
588
1.867188
2
[]
no_license
package com.freetsinghua.redisdemo2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; /** @author z.tsinghua */ @SpringBootApplication @EnableAsync public class Redisdemo2Application { private static Logger logger = LoggerFactory.getLogger(Redisdemo2Application.class); public static void main(String[] args) { SpringApplication.run(Redisdemo2Application.class, args); } }
JavaScript
UTF-8
4,788
2.703125
3
[]
no_license
import React, { Fragment, useEffect, useState } from "react"; import formData from "./data.json"; export default () => ( <> <h1>Welcome to React Parcel Micro App!</h1> <p>Hard to get more minimal than this React app.</p> <Form formData={formData} /> </> ); const Form = ({ formData }) => { const [page, setPage] = useState(0); const [currentPageData, setCurrentPageData] = useState(formData[page]); const [values, setValues] = useState({}); useEffect(() => { const upcomingPageData = formData[page]; setCurrentPageData(upcomingPageData); setValues((currentValues) => { const newValues = upcomingPageData.fields.reduce((obj, field) => { if (field.component === "field_group") { for (const subField of field.fields) { obj[subField._uid] = ""; } } else { obj[field._uid] = ""; } return obj; }, {}); return { ...newValues, ...currentValues }; }); }, [page, formData]); const naivgatePages = (direction) => () => { const findNextPage = (page) => { const upcomingPageData = formData[page]; if (upcomingPageData.conditional?.field) { const segments = upcomingPageData.conditional.field.split("_"); const fieldId = segments[segments.length - 1]; const fieldToMatchValue = values[fieldId]; if (fieldToMatchValue !== upcomingPageData.conditional.value) { return findNextPage(direction === "next" ? page + 1 : page - 1); } } return page; }; setPage(findNextPage(direction === "next" ? page + 1 : page - 1)); }; const nextPage = naivgatePages("next"); const prevPage = naivgatePages("prev"); const fieldChanged = (fieldId, value) => { setValues((currentValues) => { currentValues[fieldId] = value; return currentValues; }); setCurrentPageData((currentPageData) => ({ ...currentPageData })); }; const onSubmit = (e) => { e.preventDefault(); }; return ( <form onSubmit={onSubmit}> <h2>{currentPageData.label}</h2> {currentPageData.fields .filter(fieldMeetsCondition(values)) .map((field) => { switch (field.component) { case "field_group": return ( <FieldGroup key={field._uid} field={field} fieldChanged={fieldChanged} values={values} /> ); case "options": return ( <Option key={field._uid} field={field} fieldChanged={fieldChanged} value={values[field._uid]} /> ); default: return ( <Field key={field._uid} field={field} fieldChanged={fieldChanged} value={values[field._uid]} /> ); } })} {page > 0 && <button onClick={prevPage}>Back</button>} &nbsp; {page < formData.length - 1 && <button onClick={nextPage}>Next</button>} </form> ); }; const Field = ({ field, fieldChanged, type, value }) => ( <div key={field._uid}> <label htmlFor={field._uid}>{field.label}</label> <input type={type || field.component} id={field._uid} name={field._uid} value={value} onChange={(e) => fieldChanged(field._uid, e.target.value)} /> </div> ); const FieldGroup = ({ field, fieldChanged, values }) => ( <fieldset> <h3>{field.label}</h3> {field.fields.map((field) => ( <Field key={field._uid} field={field} fieldChanged={fieldChanged} value={values[field._uid]} /> ))} </fieldset> ); const Option = ({ field, fieldChanged, value }) => ( <div> <h3>{field.label}</h3> {field.options.map((option, index) => ( <Fragment key={option.value}> <label htmlFor={option.value}> <input type="radio" id={option.value} name={field._uid} value={option.value} checked={value === option.value} onChange={(e) => { fieldChanged(field._uid, e.target.value); }} /> {option.label} </label> {index < field.options.length - 1 && <br />} </Fragment> ))} </div> ); const fieldMeetsCondition = (values) => (field) => { if (field.conditional && field.conditional.field) { const segments = field.conditional.field.split("_"); const fieldId = segments[segments.length - 1]; return values[fieldId] === field.conditional.value; } return true; };
Markdown
UTF-8
6,923
3.625
4
[ "MIT" ]
permissive
# let,const와 블록레벨 스코프 ## 1. var 키워드 문제점 > 같은 스코프 내에서 변수를 중복 선언하면 나중에 작성된 변수 선언문은 자바스크립트 엔진에 의해 var 키워드가 없는 것처럼 동작한다. 이때 에러는 발생하지 않는다. ### 1.1. 변수 중복선언 가능 > 만약 동일한 변수 이름이 이미 선언되어 있는 것을 모르고 변수를 중복 선언하면서 값까지 할당했다면 의도치 않게 먼저 선언된 변수값이 변경되는 부작용이 발생한다. 따라서 **변수의 중복 선언은 문법적으로 허용되지만 사용하지 않는 것이 좋다.** ### 1.2. 함수레벨 스코프 > var 변수는 오로지 함수레벨 스코프만은 지역변수로 인정한다. 따라서 제어문을 사용할때 의도치 않게 값이 변경되는 경우가 생길 수 있다. var i = 10; for(var i = 0; i < 100; i++){ // doSomthing } console.log(i); ### 1.3. 변수 호이스팅 > var 키워드로 변수를 선언하면 변수 호이스팅에 의해 변수 선언문이 스코프의 선두로 끌어 올려진 것처럼 동작한다. 즉, 변수 호이스팅에 의해 var 키워드로 선언한 변수는 변수 선언문 이전에 참조할 수 있다. 단, 할당문 이전에 변수를 참조하면 언제나 undefined를 반환한다.<br> **변수 선언문 이전에 변수를 참조하는 것은 변수 호이스팅에 의해 에러를 발생시키지는 않지만 프로그램의 흐름 상 맞지 않을 뿐더러 가독성을 떨어뜨리고 오류를 발생시킬 여지를 남긴다.** ## 2. let 키워드 (ES6) ### 2.1. 변수 중복선언금지 > let 키워드로 동일한 이름을 갖는 변수를 중복 선언하면 문법 에러(SyntaxError)가 발생한다. ### 2.2. 블록레벨 스코프 > let 키워드는 모든 코드블록(함수, 제어문등...)을 지역스코프로 인정하는 지역레벨 스코프를 따른다. let i = 99; const foo = function(){ let i = 100; for( let i = 0; i < 5; i++){ console.log(i); // 0, 1, 2, 3, 4 } console.log(i); // 100 } foo(); console.log(i); // 99 ### 2.3. 변수 호이스팅(var와 차이점) > let 변수의 자바스크립트 엔진상의 흐름. 일시적 사각지대의 존재로 호이스팅이 존재하지 않는것처럼 느껴짐.<br> hoisting -> 일시적사각지대(temporal dead zone; tdz) -> 초기화단계(undefined 할당) -> 할당단계(실질적인 값이 할당) - var 키워드는 일시적 사각지대가 존재하지않기 때문에 변수가 할당는 런타임시점 이전에 var 키워드로 선언된 변수를 참조하면 undefined를 반환한다. - 하지만 let 키워드로 선언한 변수는 **선언단계와 초기화단계가 분리되어 실행된다.** // 런타임이전에 변수가 선언 되었다 하지만 초기화는 진행되지않아서 변수를 참조할수 없고 참조하게 된다면 reference error (일시적 사각지대) console.log(param); // reference error : param is not defined let param; // 변수 선언단계 console.log(param); // param = undefined param = 100; // 변수에 값할당 console.log(param); // 100 ### 2.4. 전역객체와 let // 전역변수선언 var x = 1; // 암묵적 전역변수 y = 101; console.log(window.x); // 1 => 전역변수 x는 전역객체(window)의 프로퍼티이다. console.log(x); // 1 => window객체를 생략해도 변수가 전역변수면 window객체를 생략해도 값을 가져올 수 있다. // 암묵적 전역변수도 window객체의 프로퍼티이다. console.log(y); // 101 console.log(window.y); // 101 // 함수선언문도 전역객체의 프로퍼티이다. function foo(){ // ... return console.log('hi'); } console.log(foo); // f foo() { } console.log(window.foo); // f foo() { } // var 대신 let 키워드를 사용했을때 let z = 5; // let키워드를 사용한 변수는 전역객체의 프로퍼티가 아니다. console.log(window.z); // undefined console.log(z); // 5 ## 3. const 키워드 (ES6) ### 3.1. 선언과 초기화 > const 키워드로 선언된 변수는 반드시 선언과 동시에 할당이 이루어져야한다.<br> const 키워드로 선언한변수는 let 키워드로 선언한 변수와 마찬가지로 블록레벨 스코프를 가지며 호이스팅이 발생하지 않는 것처럼 동작한다. const xyz; // syntaxError : missing initializer in const declaration ### 3.2. 재할당 금지 > var 또는 let 키워드로 선언한변수는 재할당이 자유로우나 const 키워드로 선언한 변수는 재할당이 금지된다. const xxx = 1; xxx = 2; // type error : assignment to constant variable ### 3.3. 상수 > const 키워드로 선언한 변수에 원시값을 할당할 경우, 변수값을 변경할 수 없다. 이러한 특징을 이용해 const 키워드를 상수를 표현하는데 사용하기도 한다.<br> **상수는 재할당이 금지된 변수** const TAX_RATE = 0.1; // 변수이름은 대문자로 선언하여 상수임을 명확히 나타낸다. (세율은 변경되지 않을것을 의미) let preTaxPrice = 1000000; // 세전 가격 let aferTaxPrice = preTaxPrice - (preTaxPrice * TAX_RATE); // 세후 가격 console.log(aferTaxPrice); - 상수는 프로그램전체에서 공통으로 사용되므로 만약 세율이 변경되면 상수만을 변경하면되기 때문에 유지보수성이 향상된다. ### 3.4. 객체 const person = { firstName : 'Lee' }; person.firstName = 'kim'; // 객체는 변경가능한 값이다. console.log(person.firstName); // kim - const 키워드는 재할당을 금지할뿐 "불변"을 의미하지 않는다.<br> 즉, 새로운 값(위 코드에서는 person 객체)을 재할당하는 것은 불가능하지만 객체의 값을 변경할 수 없는 것은 아니다. ## 4. 변수 선언문 결론 > 변수 선언에는 기본적으로 const를 사용하고 let은 재할당이 필요한 경우에 한정해 사용하는 것이 좋다. 원시 값의 경우, 가급적 상수를 사용하는 편이 좋다. 그리고 객체를 재할당하는 경우는 생각보다 흔하지 않다. const 키워드를 사용하면 의도치 않은 재할당을 방지해 주기 때문에 보다 안전하다. - ES6를 사용한다면 var 키워드는 사용하지 않는다. - 재할당이 필요한 경우에 한정해 let 키워드를 사용한다. 이때 변수의 스코프는 최대한 좁게 만든다. - 변경이 발생하지 않고 읽기 전용으로 사용하는(재할당이 필요 없는 상수) 원시 값과 객체에는 const 키워드를 사용한다. const 키워드는 재할당을 금지하므로 var, let 키워드보다 안전하다.
Java
UTF-8
2,620
2.28125
2
[]
no_license
package com.jekirdek.client.dto; import java.io.Serializable; import java.util.Date; import com.google.gwt.user.client.rpc.IsSerializable; public class DocumentGrid implements IsSerializable, Serializable { private static final long serialVersionUID = -859340668983893170L; private String documentName; private Date announcementDate; private String documentStoreOid; private Date uploadDate; public DocumentGrid() { super(); } public DocumentGrid(String fileName, Date announcementDate) { super(); this.documentName = fileName; this.announcementDate = announcementDate; } public String getDocumentName() { return documentName; } public void setDocumentName(String fileName) { this.documentName = fileName; } public Date getAnnouncementDate() { return announcementDate; } public void setAnnouncementDate(Date announcementDate) { this.announcementDate = announcementDate; } public String getDocumentStoreOid() { return documentStoreOid; } public void setDocumentStoreOid(String fileObjid) { this.documentStoreOid = fileObjid; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((announcementDate == null) ? 0 : announcementDate.hashCode()); result = prime * result + ((documentName == null) ? 0 : documentName.hashCode()); result = prime * result + ((documentStoreOid == null) ? 0 : documentStoreOid.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DocumentGrid other = (DocumentGrid) obj; if (announcementDate == null) { if (other.announcementDate != null) return false; } else if (!announcementDate.equals(other.announcementDate)) return false; if (documentName == null) { if (other.documentName != null) return false; } else if (!documentName.equals(other.documentName)) return false; if (documentStoreOid == null) { if (other.documentStoreOid != null) return false; } else if (!documentStoreOid.equals(other.documentStoreOid)) return false; return true; } @Override public String toString() { return "DocumentGrid [fileName=" + documentName + ", announcementDate=" + announcementDate + ", fileObjid=" + documentStoreOid + "]"; } public Date getUploadDate() { return uploadDate; } public void setUploadDate(Date uploadDate) { this.uploadDate = uploadDate; } }
Shell
UTF-8
189
2.734375
3
[ "Apache-2.0" ]
permissive
#!/bin/bash echo ${TILER_LIB} | wget --no-use-server-timestamps --base=`cat $TILER_URL` --input-file=- -O lib/libtile.a if [ $? != 0 ]; then rm $TILER_URL rm -f lib/libtile.a exit 1 fi
C
UTF-8
186
3.25
3
[]
no_license
#include <stdio.h> #include <stdlib.h> void insertnodetotail(struct node *head,struct node *new) { while(head->next!=NULL) { head=head->next; } head->next=new; new->next=NULL; }
TypeScript
UTF-8
2,164
2.59375
3
[ "MIT" ]
permissive
import * as Faker from "faker" import { IFakerOption, IPluginMessage } from "./faker" figma.showUI(__html__, { height: 340, width: 240 }) const textNodes: TextNode[] = [] function traverseNodes(parentNode: SceneNode) { if (parentNode.type === "TEXT") { textNodes.push(parentNode) } else if ("children" in parentNode) { for (const child of parentNode.children) { if ( child.type === "GROUP" || child.type === "FRAME" || child.type === "INSTANCE" || child.type === "COMPONENT" || child.type === "TEXT" ) { traverseNodes(child) } } } } function clearTextNodes() { textNodes.length = 0 } function traverseSelection() { const selection = figma.currentPage.selection for (const selectedNode of selection) { traverseNodes(selectedNode) } } function replaceText(fakerOption: IFakerOption) { if (textNodes.length) { const fakerMethodArray = fakerOption.methodName.split(".") const fakerMethod = Faker[fakerMethodArray[0]][fakerMethodArray[1]] for (const textNode of textNodes) { figma.loadFontAsync(textNode.fontName as FontName).then(() => { textNode.characters = fakerMethod().toString() }) } } else { figma.closePlugin("Select at least one text node before using Faker.") } } const lsKey = "figma-faker" async function setLsRecents(fakerOptions: Array<IFakerOption>) { await figma.clientStorage.setAsync(lsKey, fakerOptions) } async function getLsRecents() { figma.clientStorage.getAsync(lsKey).then((lsRecentOptions) => { if (lsRecentOptions) { const pluginMessage: IPluginMessage = { type: "ls-recents-ready", data: lsRecentOptions, } figma.ui.postMessage(pluginMessage) } }) } figma.ui.onmessage = (pluginMessage: IPluginMessage) => { if (pluginMessage.type === "run-faker") { clearTextNodes() traverseSelection() replaceText(pluginMessage.data as IFakerOption) } if (pluginMessage.type === "set-ls-recents") { setLsRecents(pluginMessage.data as Array<IFakerOption>) } if (pluginMessage.type === "get-ls-recents") { getLsRecents() } }
C++
UTF-8
591
2.640625
3
[]
no_license
void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); } void loop() { if (Serial.available()){ Serial.read(); // char inChar = Serial.read(); // Serial.println(inChar); // int num = Serial.parseInt(); // Serial.println(num); // if (inChar == '1'){ // Serial.println('1'); // digitalWrite(LED_BUILTIN, HIGH); // } else { // Serial.println('0'); // digitalWrite(LED_BUILTIN, LOW); // } Serial.write('6'); // Serial.println(); // Serial.write(Serial.read()); Serial.println(); } // delay(1000); }
Java
ISO-8859-1
2,716
2.859375
3
[]
no_license
package de.dhbw.muehle.model.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; public class dbconnection { Connection c; Statement stmt; public dbconnection(){ Connection c = null; Statement stmt = null; } //Verbindung zur Datenbank aufbauen public void databaseconnection(){ try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:res/FallstudieMuehle.db"); System.out.println("Opened database successfully"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } // In die Datenbank schreiben public void databasewrite(String Name, String posAlt, String posNeu){ try{ String sql = "INSERT INTO MUEHLESPIELZUGPROTOKOLL (NAME, POSALT, POSNEU, DATUM) VALUES(?,?,?,?)"; PreparedStatement stmt = c.prepareStatement(sql); stmt.setString(1, Name); stmt.setString(2, posAlt); stmt.setString(3, posNeu); stmt.setDate(4, new java.sql.Date( System.currentTimeMillis() )); stmt.executeUpdate(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } //Aus der Datenbank lesen public void databaseread(){ try{ stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM MUEHLESPIELZUGPROTOKOLL;" ); while ( rs.next() ) { int ZugId = rs.getInt("ZugID"); String Spielername = rs.getString("NAME"); String Spielposition_alt = rs.getString("POSALT"); String Spielposition_neu = rs.getString("POSNEU"); Date Datum = rs.getDate("DATUM"); System.out.println( "ZUGID = " + ZugId ); System.out.println( "Spielername = " + Spielername ); System.out.println( "Position Alt = " + Spielposition_alt ); System.out.println( "Position Neu = " + Spielposition_neu ); System.out.println( "Datum = " + Datum ); System.out.println(); } rs.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } //Datenbank schlieen public void databaseclose(){ try { stmt.close(); c.close(); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } } }
Java
UTF-8
2,603
2.078125
2
[]
no_license
package com.workana.bluecare; import android.annotation.SuppressLint; import android.app.Activity; import android.app.KeyguardManager; import android.app.KeyguardManager.KeyguardLock; import android.content.Context; import android.os.Bundle; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; @SuppressWarnings("deprecation") public class DialogActivity extends Activity { private KeyguardLock kgl; private WakeLock screenLock; private TextView deviceNameTxt; private TextView deviceAddressTxt; private Button dismissBtn; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras != null) { String deviceName = extras.getString("DEVICE_NAME"); String deviceAddress = extras.getString("DEVICE_ADDRESS"); this.requestWindowFeature(Window.FEATURE_NO_TITLE); screenLock = ((PowerManager) getSystemService(POWER_SERVICE)) .newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG"); KeyguardManager kgm = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); boolean isKeyguardUp = kgm.inKeyguardRestrictedInputMode(); kgl = kgm .newKeyguardLock("Blue care"); if (isKeyguardUp) { kgl.disableKeyguard(); isKeyguardUp = false; } screenLock.acquire(); setContentView(R.layout.dialog_alert); deviceNameTxt = (TextView) findViewById(R.id.deviceNameTxt); deviceAddressTxt = (TextView) findViewById(R.id.macAddressTxt); deviceNameTxt.setText(deviceName); deviceAddressTxt.setText(deviceAddress); dismissBtn = (Button) findViewById(R.id.OkBtn); dismissBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { disposeActivity(); } }); } } private void disposeActivity() { this.finish(); } public void onAttachedToWindow() { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); } @SuppressLint("Wakelock") @Override protected void onDestroy() { screenLock.release(); kgl.reenableKeyguard(); super.onDestroy(); } }
Markdown
UTF-8
7,199
2.75
3
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
##### cc) Des Propheten Jehu Gerichtsdrohung gegen Baesa __16__ <sup>1</sup>Da erging das Wort des HERRN an Jehu, den Sohn Hananis, gegen Baesa also: <sup>2</sup>»Weil ich dich aus dem Staub erhoben und dich zum Fürsten über mein Volk Israel gemacht habe, du aber auf dem Wege Jerobeams gewandelt bist und mein Volk Israel zur Sünde verführt hast, so daß sie mich durch ihre Sünden zum Zorn reizen, <sup>3</sup>so will ich nun Baesa und sein Haus wegfegen und will es mit deinem Hause machen wie mit dem Hause Jerobeams, des Sohnes Nebats. <sup>4</sup>Wer von den Angehörigen Baesas in der Stadt stirbt, den sollen die Hunde fressen, und wer von ihnen auf dem freien Felde stirbt, den sollen die Vögel des Himmels fressen!«<sup title="vgl. 14,11">&#x2732;</sup> – <sup>5</sup>Die übrige Geschichte Baesas aber und was er unternommen hat sowie seine tapferen Taten, das findet sich bekanntlich aufgezeichnet im Buch der Denkwürdigkeiten<sup title="oder: Chronik">&#x2732;</sup> der Könige von Israel. – <sup>6</sup>Als Baesa sich dann zu seinen Vätern gelegt und man ihn in Thirza begraben hatte, folgte ihm sein Sohn Ela in der Regierung nach. <sup>7</sup>Übrigens war das Wort des HERRN gegen Baesa und dessen Haus durch den Mund des Propheten Jehu, des Sohnes Hananis, sowohl wegen alles des Bösen ergangen, durch das er sich gegen den HERRN versündigt hatte, um ihn durch sein ganzes Tun zum Zorn zu reizen, so daß er es dem Hause Jerobeams gleichtat, als auch deshalb, weil er dieses ausgerottet hatte. #### Regierung des Königs Ela von Israel <sup>8</sup>Im sechsundzwanzigsten Jahre der Regierung Asas, des Königs von Juda, wurde Ela, der Sohn Baesas, König über Israel und regierte in Thirza zwei Jahre. <sup>9</sup>Gegen ihn verschwor sich sein Diener Simri, einer seiner Obersten, der über die Hälfte der Kriegswagen gesetzt war. Als sich Ela nun einst in Thirza bei einem Gelage im Hause Arzas, seines Haushofmeisters in Thirza, berauscht hatte, <sup>10</sup>drang Simri dort ein und erschlug ihn im siebenundzwanzigsten Jahre der Regierung Asas, des Königs von Juda, und wurde König an seiner Statt. <sup>11</sup>Als er nun König geworden war, ermordete er, sobald er auf seinem Throne saß, alle zum Hause Baesas Gehörigen; er ließ keinen von ihnen übrig, der männlichen Geschlechts war, weder seine Blutsverwandten noch seine Freunde. <sup>12</sup>So rottete Simri das ganze Haus Baesas aus, gemäß der Drohung, die der HERR durch den Mund des Propheten Jehu gegen Baesa ausgesprochen hatte, <sup>13</sup>wegen all der Sünden, die Baesa und sein Sohn Ela begangen und zu denen sie Israel verführt hatten, um den HERRN, den Gott Israels, durch ihren Götzendienst zum Zorn zu reizen. <sup>14</sup>Die übrige Geschichte Elas aber und alles, was er unternommen hat, findet sich bekanntlich aufgezeichnet im Buch der Denkwürdigkeiten<sup title="oder: Chronik">&#x2732;</sup> der Könige von Israel. ##### dd) Regierung des Königs Simri von Israel <sup>15</sup>Im siebenundzwanzigsten Jahre der Regierung Asas, des Königs von Juda, wurde Simri König für sieben Tage in Thirza, während das Heer die Philisterstadt Gibbethon belagerte. <sup>16</sup>Als nun das Heer im Lager die Kunde erhielt, Simri habe eine Verschwörung angestiftet und den König schon ermordet, da erhob das ganze israelitische Heer noch an demselben Tage Omri, den obersten Befehlshaber des israelitischen Heeres, im Lager zum König über Israel. <sup>17</sup>Darauf zog Omri mit allen Israeliten von Gibbethon ab und belagerte Thirza. <sup>18</sup>Als nun Simri sah, daß die Stadt erobert war, begab er sich in die Burg des königlichen Palastes, steckte den königlichen Palast über sich in Brand und fand so den Tod <sup>19</sup>um seiner Sünden willen, die er begangen hatte, indem er tat, was dem HERRN mißfiel, indem er auf dem Wege Jerobeams wandelte und in dessen Sünde, durch die er sich verschuldet hatte, indem er Israel zur Sünde verleitete. <sup>20</sup>Die übrige Geschichte Simris aber und seine Verschwörung, die er angestiftet hatte, das findet sich bekanntlich aufgezeichnet im Buche der Denkwürdigkeiten<sup title="oder: Chronik">&#x2732;</sup> der Könige von Israel. ##### ee) Spaltung des Reiches Israel; Omri Alleinherrscher <sup>21</sup>Damals spaltete sich das Volk Israel in zwei Parteien: die eine Hälfte des Volkes hielt es mit Thibni, dem Sohne Ginaths, um ihn zum König zu machen, die andere Hälfte dagegen war für Omri. <sup>22</sup>Aber die Partei Omris gewann die Oberhand über die Anhänger Thibnis, des Sohnes Ginaths; und als Thibni starb<sup title="oder: im Kampf den Tod fand">&#x2732;</sup>, wurde Omri König. ##### ff) Regierung des Königs Omri von Israel; Gründung der Hauptstadt Samaria <sup>23</sup>Im einunddreißigsten Jahre der Regierung Asas, des Königs von Juda, wurde Omri König über Israel und regierte zwölf Jahre. Als er in Thirza sechs Jahre regiert hatte, <sup>24</sup>kaufte er den Berg Samaria von Semer für zwei Talente Silber, befestigte dann den Berg und nannte die Stadt, die er dort gründete, Samaria nach dem Namen Semers, des früheren Besitzers des Berges. <sup>25</sup>Omri tat aber, was dem HERRN mißfiel, ja, er trieb es noch ärger als alle seine Vorgänger; <sup>26</sup>er wandelte ganz auf dem Wege Jerobeams, des Sohnes Nebats, und in den Sünden, zu denen jener die Israeliten verführt hatte, so daß sie den HERRN, den Gott Israels, durch ihren Götzendienst erzürnten. <sup>27</sup>Die übrige Geschichte Omris aber, seine Unternehmungen und die tapferen Taten, die er vollführt hat, das alles findet sich bekanntlich aufgezeichnet im Buch der Denkwürdigkeiten<sup title="oder: Chronik">&#x2732;</sup> der Könige von Israel. <sup>28</sup>Als Omri sich dann zu seinen Vätern gelegt und man ihn in Samaria begraben hatte, folgte ihm sein Sohn Ahab in der Regierung nach. #### g) Die Sünden des Königs Ahab von Israel und seiner Gemahlin Isebel <sup>29</sup>Ahab, der Sohn Omris, wurde König über Israel im achtunddreißigsten Jahre der Regierung Asas, des Königs von Juda; und Ahab, der Sohn Omris, regierte über Israel zweiundzwanzig Jahre in Samaria. <sup>30</sup>Er tat aber, was dem HERRN mißfiel, und trieb es noch ärger als alle seine Vorgänger. <sup>31</sup>Und nicht genug, daß er in den Sünden Jerobeams, des Sohnes Nebats, wandelte, heiratete er auch noch Isebel, die Tochter des Sidonierkönigs Ethbaal, und wandte sich dann dem Dienste Baals zu und betete ihn an. <sup>32</sup>Er errichtete dem Baal auch einen Altar in dem Baaltempel, den er in Samaria erbaut hatte, <sup>33</sup>und ließ das Ascherabild anfertigen und verübte noch andere Greuel, um den HERRN, den Gott Israels, noch heftiger zu erzürnen als alle israelitischen Könige, die vor ihm geherrscht hatten. #### Wiederaufbau der Stadt Jericho <sup>34</sup>Während seiner Regierung baute Hiel von Bethel die Stadt Jericho wieder auf. Die Grundlegung kostete seinem ältesten Sohne Abiram das Leben, und die Einsetzung der Tore brachte seinem jüngsten Sohne Segub den Tod, wie der HERR es durch den Mund Josuas, des Sohnes Nuns, vorausgesagt hatte<sup title="vgl. Jos 6,26">&#x2732;</sup>.
Java
UTF-8
4,380
2.046875
2
[]
no_license
package com.king.block.user; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.Toast; import com.king.block.Global; import com.king.block.R; import org.json.JSONObject; import java.io.DataOutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; public class AchieveActivity extends AppCompatActivity { private GridView gv; private AchieveAdapter achieveAdapter; private ArrayList<Achieve> achieve_list = null; Global global; int plan=14,todo=13; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_achieve); global = (Global)getApplication(); initTop(); initData(); initGv(); } private void initTop() { ImageView back = (ImageView) findViewById(R.id.back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { achieve_list.clear(); AchieveActivity.this.finish(); } }); } //调用接口 //通过user_id查询成就信息 private void getInfo() { try { URL url = new URL(global.getURL() + "/achieve/query"); // 打开连接 HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestProperty("accept", "*/*"); con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Cache-Control", "no-cache"); con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.connect(); DataOutputStream out = new DataOutputStream(con.getOutputStream()); // String content = "user_id:" + global.getUserId(); String content = "{\"user_id\":\"" + global.getUserId() + "\"}"; out.write(content.getBytes()); out.flush(); out.close(); if (con.getResponseCode() == 200) { JSONObject res = global.streamtoJson(con.getInputStream()); int code = res.optInt("code"); String msg = res.optString("msg"); if (code == 200) { JSONObject prize = res.getJSONArray("data").getJSONObject(0); plan=prize.getInt("prize_plan"); todo = prize.getInt("prize_todo"); } else { Toast.makeText(AchieveActivity.this, msg + res.getString("err"), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(AchieveActivity.this, "获取失败" + con.getErrorStream().toString(), Toast.LENGTH_SHORT).show(); } con.disconnect(); } catch (Exception e) { e.printStackTrace(); Toast.makeText(AchieveActivity.this, "连接错误", Toast.LENGTH_SHORT).show(); } } private void initData() { achieve_list = new ArrayList<Achieve>(); getInfo(); int maxi = Math.max(plan,todo); int mini = Math.min(plan,todo); for (int i = maxi; i >mini&&i>0; i-=2) { achieve_list.add(global.getAchieve().get(i-1)); } for (int i = mini; i >0; i--) { achieve_list.add(global.getAchieve().get(i-1)); } } private void initGv() { gv = (GridView) findViewById(R.id.achieve_gv); achieveAdapter = new AchieveAdapter(AchieveActivity.this, R.layout.item_achieve, achieve_list); gv.setAdapter(achieveAdapter); gv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(AchieveActivity.this, achieve_list.get(position).getNote(),Toast.LENGTH_SHORT).show(); } }); } }
Java
UTF-8
2,578
2.453125
2
[]
no_license
package com.sxzhongf.mscx.passbook.security; import com.sxzhongf.mscx.passbook.constant.Constants; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * AuthCheckInterceptor for 权限拦截器 * * @author <a href="mailto:magicianisaac@gmail.com">Isaac.Zhang</a> * @see HandlerInterceptor * @since 2019/5/24 */ @Component public class AuthCheckInterceptor implements HandlerInterceptor { /** * controller handle处理之前优先处理 * * 如果验证通过,添加token * @param request * @param response * @param handler * @return boolean * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader(Constants.TOKEN_KEY); if (StringUtils.isEmpty(token)) { throw new Exception("Http Header 中缺少" + Constants.TOKEN_KEY + "!"); } if (!token.equals(Constants.TOKEN_VALUE)) { throw new Exception("Http Header " + Constants.TOKEN_KEY + " 错误!"); } AccessContext.setToken(token); return true; } /** * 后处理回调方法,实现处理器的后处理(但在渲染视图之前), * 此时可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。 * * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 整个请求处理完毕回调方法,即在视图渲染完毕时回调, * 如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理, * 类似于try-catch-finally中的finally,但仅调用处理器执行链中 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { AccessContext.clearAccessKey(); } }
Java
UTF-8
1,328
3.828125
4
[]
no_license
package Offer; import org.junit.Test; import java.util.Stack; /** * 剑指 Offer 09. 用两个栈实现队列 * 用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 ) * */ public class LCFO09 { @Test public void test(){ CQueue obj = new CQueue(); System.out.println(obj.deleteHead()); obj.appendTail(5); obj.appendTail(2); System.out.println(obj.deleteHead()); System.out.println(obj.deleteHead()); } } class CQueue { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); public CQueue() { } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { // 如果第二个栈不为空,直接弹出 if (!stack2.isEmpty()){ return stack2.pop(); }else if (!stack1.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } return stack2.pop(); } return -1; } }
C
UTF-8
708
3.390625
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <float.h> #include <limits.h> #include "rand.h" int main(int argc, char *argv[]) { unsigned i, n = 30; double x; double sum0 = 0, sum1 = 0, sum2 = 0; double xmin = DBL_MAX; double xmax = -DBL_MAX; struct rand *rng = rand_new(); for (i = 0; i < n; i++) { x = rand_uniform(rng); sum0 += 1; sum1 += x; sum2 += x * x; xmin = x < xmin ? x : xmin; xmax = x > xmax ? x : xmax; printf("%f\n", x); } printf("MIN : %f\n", xmin); printf("MAX : %f\n", xmax); printf("MOM1 : %f\n", sum1 / sum0); printf("MOM2 : %f\n", sum2 / sum0); rand_free(rng); return 0; }
C++
UTF-8
5,233
3.34375
3
[]
no_license
#include <fstream> #include <string> #include <sstream> #include <iostream> #include <numeric> #define partOne False using namespace std; int get_size(string filename) { // Open the file ifstream file(filename); if(file.fail()) { cout << "No suck file.\n"; return 0; } // Read the file and store it in a string variable 'line' string line; getline(file, line); // Determine number of instructions int size = 0; string word; stringstream s(line); while (getline(s, word, ',')) { size++; } file.close(); return size; } int* get_deltas(string filename, int size) { ifstream file(filename); if(file.fail()) { cout << "No suck file.\n"; return 0; } string line; getline(file, line); // Read through the files and put the directions into the array // The directions are the first element of each CSV value int* deltas = new int[size]; int i = 0; string word; stringstream s(line); while (getline(s, word, ',')) { deltas[i] = stoi(word.substr(1, word.length() - 1)); i++; } file.close(); return deltas; } char* get_directions(string filename, int size) { ifstream file(filename); if(file.fail()) { cout << "No suck file.\n"; return 0; } string line; getline(file, line); // Read through the files and put the directions into the array // The directions are the first element of each CSV value char* directions = new char[size]; int i = 0; string word; stringstream s(line); while (getline(s, word, ',')) { directions[i] = word.at(0); i++; } file.close(); return directions; } int get_length(int deltas[], int size) { // Find total path length int length = 0; for(int i = 0; i < size; i++) { length += deltas[i]; } return length; } int** get_path(char directions[], int deltas[], int size) { // Create an array of pointers of size length int length = get_length(deltas, size); int** path = new int*[length]; // Iterate through directions and find all coordinates the wire passes through int delta; char direct; int X = 0; int Y = 0; int k = 0; for(int i = 0; i < size; i++) { // For each direction direct = directions[i]; delta = deltas[i]; for(int j = 0; j < delta; j++) { // Move the specified number of spaces in the specified direction switch (direct) { case 'R': { X += 1; break; } case 'L': { X -= 1; break; } case 'U': { Y += 1; break; } case 'D': { Y -= 1; break; } default: { cout << "Invalid direction: " << direct << "\n"; break; } } // And record it in the array path path[k] = new int[2]; path[k][0] = X; path[k][1] = Y; k++; } } return path; } bool is_same_point(int arr1[], int arr2[]) { if((arr1[0] == arr2[0]) && (arr1[1] == arr2[1])) { return true; } return false; } int main() { string filename1 = "wire_01_part1.csv"; string filename2 = "wire_02_part2.csv"; // Parse wiring diagrams to directions for wire 1 then get the path the wire takes int size1 = get_size(filename1); char* directions = get_directions(filename1, size1); int* deltas = get_deltas(filename1, size1); int** wire1 = get_path(directions, deltas, size1); int length1 = get_length(deltas, size1); // Do the same for wire 2 int size2 = get_size(filename2); directions = get_directions(filename2, size2); deltas = get_deltas(filename2, size2); int** wire2 = get_path(directions, deltas, size2); int length2 = get_length(deltas, size2); // Find closest crossover location int dist = 0; int minDist = INT_MAX; for(int i = 0; i < length1; i++) { for(int j = 0; j < length2; j++) { // Find common coordinates between the two wires if(is_same_point(wire1[i], wire2[j])) { // For each point calculate the length of the wire #if partOne dist = abs(wire1[i][0]) + abs(wire1[i][1]); #else // Additional plus two is to account for i and j starting at 0 dist = i + j + 2; #endif // If the new distance is less than the old min then update if(dist < minDist) { minDist = dist; } } } } cout << "\nMinimum distance is: " << minDist << "\n"; return 0; }
Markdown
UTF-8
915
3.859375
4
[]
no_license
# Intersection of Two Linked Lists ```java public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { int lenA = 0; ListNode iterA = headA; while (iterA != null) { lenA++; iterA = iterA.next; } int lenB = 0; ListNode iterB = headB; while (iterB != null) { lenB++; iterB = iterB.next; } iterA = headA; iterB = headB; while (lenA != lenB) { if (lenA > lenB) { iterA = iterA.next; lenA--; } else { iterB = iterB.next; lenB--; } } while (iterA != null && iterA != iterB) { iterA = iterA.next; iterB = iterB.next; } return iterA; } } ```
C++
UTF-8
708
2.859375
3
[]
no_license
// // Created by Ruud Andriessen on 13/05/2017. // #include "Midpoint.h" void Midpoint::simulateStep(System *system, float h) { // Get the initial state VectorXf oldState = system->getState(); // Evaluate a deriv step VectorXf deriv = system->derivEval(); // Compute the halfway point VectorXf midPointState = oldState + h * 0.5f * deriv; // Set the state to this midpoint system->setState(midPointState, system->getTime() + h); // Evaluate derivative at the midpoint deriv = system->derivEval(); // Update the state based on the computation from this midpoint VectorXf newState = oldState + h * deriv; system->setState(newState, system->getTime() + h); }
Java
UTF-8
785
1.929688
2
[]
no_license
package pt.isep.nsheets.server.lapr4.green.s1.ipc.n1160818.userAuthentication.persistence; import pt.isep.nsheets.server.lapr4.white.s1.core.n4567890.workbooks.persistence.PersistenceSettings; import java.util.Properties; /** * @author Rui Almeida<1160818> */ public class GetPropertiesService { /** * Gets the persistence settings * @return the settings */ public static PersistenceSettings getPersistenceSettings() { Properties props = new Properties(); props.put("persistence.repositoryFactory", "pt.isep.nsheets.server.lapr4.white.s1.core.n4567890.workbooks.persistence.jpa.JpaRepositoryFactory"); props.put("persistence.persistenceUnit", "lapr4.NSheetsPU"); return new PersistenceSettings(props); } }
PHP
UTF-8
558
2.765625
3
[ "MIT" ]
permissive
<?php namespace Poppy\System\Events; use Illuminate\Auth\SessionGuard; use Poppy\System\Models\PamAccount; /** * 登录成功事件 */ class LoginSuccessEvent { /** * @var PamAccount 用户账户 */ public $pam; /** * @var string 平台 */ public $platform; /** * @var SessionGuard|null */ public $guard; public function __construct(PamAccount $pam, $platform, $guard = null) { $this->pam = $pam; $this->platform = $platform; $this->guard = $guard; } }
PHP
UTF-8
657
2.84375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; class RolesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i=0; $i < 4; $i++) { $rec = new App\Role; if($i==0){ $rec->name = 'The highest authority'; } if($i==1){ $rec->name = 'Can register / edit / delete'; } if($i==2){ $rec->name = 'Only registered'; } if($i==3){ $rec->name = 'Only browsable'; } $rec->save(); } } }
Java
UTF-8
758
3.59375
4
[]
no_license
package p1sortandsearch.sortofcomparison; import java.util.Calendar; import java.util.Date; public class MainTest { public static void integerInner(Integer x) { x = new Integer(3); } public static void stringInner(String x) { x = new String("4"); } public static void dateInner(Date date) { date = new Date(1990, Calendar.AUGUST,15); } public static void main(String[] args) { Integer x = new Integer(4); integerInner(x); System.out.println(x); String x1 = new String("5"); stringInner(x1); System.out.println(x1); Date date = new Date(2021, Calendar.AUGUST,15); dateInner(date); System.out.println(date.getYear()); } }
SQL
UTF-8
1,138
3.546875
4
[]
no_license
/** This is the main script for `comment system` application @author : AQM Saiful Islam */ DROP DATABASE IF EXISTS commentSystem; CREATE DATABASE commentSystem; USE commentSystem; DROP TABLE IF EXISTS `posts`; CREATE TABLE `posts` ( `post_Id` int(11) NOT NULL AUTO_INCREMENT, `post_title` varchar(200) DEFAULT NULL, `post_email` varchar(100) NOT NULL, `post_description` text, `post_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`post_Id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `comments`; CREATE TABLE `comments` ( `comment_Id` int(11) NOT NULL AUTO_INCREMENT, `comment_name` varchar(100) DEFAULT NULL, `comment_email` varchar(100) DEFAULT NULL, `comment_description` text, `comment_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `post_id_fk` int(11) DEFAULT NULL, PRIMARY KEY (`comment_Id`), KEY `comments_fk_constrains` (`post_id_fk`), CONSTRAINT `comments_fk_constrains` FOREIGN KEY (`post_id_fk`) REFERENCES `posts` (`post_Id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SQL
UTF-8
4,458
3.1875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.0.10.10 -- http://www.phpmyadmin.net -- -- Máquina: 127.3.135.130:3306 -- Data de Criação: 14-Jul-2015 às 06:50 -- Versão do servidor: 5.5.41 -- versão do PHP: 5.3.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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 utf8 */; -- -- Base de Dados: `carettalb` -- -- -------------------------------------------------------- -- -- Estrutura da tabela `AccessToken` -- CREATE TABLE IF NOT EXISTS `AccessToken` ( `id` varchar(255) NOT NULL, `ttl` int(11) DEFAULT NULL, `created` datetime DEFAULT NULL, `userId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `ACL` -- CREATE TABLE IF NOT EXISTS `ACL` ( `id` int(11) NOT NULL AUTO_INCREMENT, `model` varchar(512) DEFAULT NULL, `property` varchar(512) DEFAULT NULL, `accessType` varchar(512) DEFAULT NULL, `permission` varchar(512) DEFAULT NULL, `principalType` varchar(512) DEFAULT NULL, `principalId` varchar(512) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estrutura da tabela `Complaint` -- CREATE TABLE IF NOT EXISTS `Complaint` ( `id` int(11) NOT NULL, `comment` varchar(512) DEFAULT NULL, `when` datetime NOT NULL, `addAt` datetime DEFAULT NULL, `location` point NOT NULL, `userName` varchar(512) NOT NULL, `imgUrl` varchar(512) DEFAULT NULL, `userId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `Nest` -- CREATE TABLE IF NOT EXISTS `Nest` ( `id` int(11) NOT NULL, `comment` varchar(512) DEFAULT NULL, `location` point NOT NULL, `userName` varchar(512) NOT NULL, `imgUrl` varchar(512) NOT NULL, `when` datetime NOT NULL, `addAt` datetime DEFAULT NULL, `userId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `Role` -- CREATE TABLE IF NOT EXISTS `Role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(512) NOT NULL, `description` varchar(512) DEFAULT NULL, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estrutura da tabela `RoleMapping` -- CREATE TABLE IF NOT EXISTS `RoleMapping` ( `id` int(11) NOT NULL AUTO_INCREMENT, `principalType` varchar(512) DEFAULT NULL, `principalId` varchar(512) DEFAULT NULL, `roleId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Estrutura da tabela `Turtle` -- CREATE TABLE IF NOT EXISTS `Turtle` ( `id` int(11) NOT NULL, `comment` varchar(512) DEFAULT NULL, `when` datetime NOT NULL, `addAt` datetime DEFAULT NULL, `location` point NOT NULL, `specieId` int(11) NOT NULL, `specie` varchar(512) NOT NULL, `userName` varchar(512) NOT NULL, `imgUrl` varchar(512) DEFAULT NULL, `userId` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estrutura da tabela `User` -- CREATE TABLE IF NOT EXISTS `User` ( `id` int(11) NOT NULL AUTO_INCREMENT, `realm` varchar(512) DEFAULT NULL, `username` varchar(512) DEFAULT NULL, `password` varchar(512) NOT NULL, `credentials` text, `challenges` text, `email` varchar(512) NOT NULL, `emailVerified` tinyint(1) DEFAULT NULL, `verificationToken` varchar(512) DEFAULT NULL, `status` varchar(512) DEFAULT NULL, `created` datetime DEFAULT NULL, `lastUpdated` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; /*!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 */;
Java
UTF-8
1,490
2.1875
2
[]
no_license
package com.example.intel.kospenmove02.db; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; /* | | Singleton Pattern - for Database instance | */ @Database(entities = {Kospenuser.class, Screening.class, KospenuserServer.class, KospenuserGlobal.class, OutRestReqKospenuser.class, InDBQueryKospenuser.class}, version=6) public abstract class AppDatabase extends RoomDatabase { private static AppDatabase INSTANCE; public abstract KospenuserDao kospenuserModel(); public abstract ScreeningDao screeningModel(); public abstract KospenuserServerDao kospenuserServerModel(); public abstract KospenuserGlobalDao kospenuserGlobalModel(); public abstract OutRestReqKospenuserDao outRestReqKospenuserModel(); public abstract InDBQueryKospenuserDao inDBQueryKospenuserModel(); public static AppDatabase getDatabase(Context context) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder( context.getApplicationContext(), AppDatabase.class, "kospendatabasev1") .allowMainThreadQueries() .fallbackToDestructiveMigration() .build(); } return INSTANCE; } public static void destroyInstance() { INSTANCE = null; } }
Ruby
UTF-8
1,342
4.84375
5
[]
no_license
#Exercise 1 # Create an emotions hash, where the keys are the names of different human emotions and the values are the degree to which the emotion is being felt on a scale from 1 to 3. emotions_hash = { :happy => 1, :sad => 3, :excited => 2, :angry => 1 } #Exercise 2 #Write a Person class with the following characteristics: class Person def initialize(name) # name (string) @name = name #emotions (hash) @emotions = {} end def add_emotions(emotions) @emotions = emotions # puts emotions end # Add an instance method to your class that displays a message describing how the person is feeling. Substitute the words "high", "medium", and "low" for the emotion levels 1, 2, and 3. def display_emotions @emotions.each do |k, v| if v == 3 puts "#{@name} is feeling a high amount of #{k}." elsif v == 2 puts "#{@name} is feeling a medium amount of #{k}." else puts "#{@name} is feeling a low amount of #{k}." end end end end #Initialize an instance of Person using your emotions hash from exercise 1. first_person = Person.new("Marlon") puts first_person.inspect first_person.add_emotions(emotions_hash) puts first_person.inspect # Exercise 3 puts "Displaying emotions for created instance" puts first_person.display_emotions
Java
UTF-8
8,113
1.851563
2
[ "Apache-2.0" ]
permissive
package com.chocozhao.wanandroid.mvp.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chocozhao.wanandroid.R; import com.chocozhao.wanandroid.di.component.DaggerknowledgeComponent; import com.chocozhao.wanandroid.mvp.contract.KnowledgeContract; import com.chocozhao.wanandroid.mvp.model.entity.GetTestData; import com.chocozhao.wanandroid.mvp.presenter.KnowledgePresenter; import com.chocozhao.wanandroid.mvp.ui.adapter.TestAdapter; import com.jess.arms.base.BaseFragment; import com.jess.arms.di.component.AppComponent; import com.jess.arms.utils.ArmsUtils; import com.jess.arms.utils.LogUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import timber.log.Timber; import static com.jess.arms.utils.Preconditions.checkNotNull; /** * ================================================ * Description: * <p> * Created by MVPArmsTemplate on 11/06/2019 00:21 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a> * <a href="https://github.com/JessYanCoding">Follow me</a> * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a> * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a> * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a> * ================================================ */ public class KnowledgeFragment extends BaseFragment<KnowledgePresenter> implements KnowledgeContract.View { @BindView(R.id.rv_test) RecyclerView mRvTest; // @Inject // GridLayoutManager mLayoutManager; @Inject TestAdapter mTestAdapter; @Inject List<GetTestData> mTestDataList; @BindView(R.id.tv_template) TextView mTvTemplate; @Inject Map<Integer, Boolean> map; public static KnowledgeFragment newInstance() { KnowledgeFragment fragment = new KnowledgeFragment(); return fragment; } @Override public void setupFragmentComponent(@NonNull AppComponent appComponent) { DaggerknowledgeComponent //如找不到该类,请编译一下项目 .builder() .appComponent(appComponent) .view(this) .build() .inject(this); } @Override public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_knowledge, container, false); } @Override public void initData(@Nullable Bundle savedInstanceState) { //初始化适配器 initRecyclerView(); CheckBox checkBox = getView().findViewById(R.id.cb_select); checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { for (int i = 0; i < mTestAdapter.getData().size(); i++) { //选中 map.put(i, true); } } else { for (int i = 0; i < mTestAdapter.getData().size(); i++) { //取消选中 map.put(i, false); } } mTestAdapter.setMap(map); } }); } /** * 通过此方法可以使 Fragment 能够与外界做一些交互和通信, 比如说外部的 Activity 想让自己持有的某个 Fragment 对象执行一些方法, * 建议在有多个需要与外界交互的方法时, 统一传 {@link Message}, 通过 what 字段来区分不同的方法, 在 {@link #setData(Object)} * 方法中就可以 {@code switch} 做不同的操作, 这样就可以用统一的入口方法做多个不同的操作, 可以起到分发的作用 * <p> * 调用此方法时请注意调用时 Fragment 的生命周期, 如果调用 {@link #setData(Object)} 方法时 {@link Fragment#onCreate(Bundle)} 还没执行 * 但在 {@link #setData(Object)} 里却调用了 Presenter 的方法, 是会报空的, 因为 Dagger 注入是在 {@link Fragment#onCreate(Bundle)} 方法中执行的 * 然后才创建的 Presenter, 如果要做一些初始化操作,可以不必让外部调用 {@link #setData(Object)}, 在 {@link #initData(Bundle)} 中初始化就可以了 * <p> * Example usage: * <pre> * public void setData(@Nullable Object data) { * if (data != null && data instanceof Message) { * switch (((Message) data).what) { * case 0: * loadData(((Message) data).arg1); * break; * case 1: * refreshUI(); * break; * default: * //do something * break; * } * } * } * * // call setData(Object): * Message data = new Message(); * data.what = 0; * data.arg1 = 1; * fragment.setData(data); * </pre> * * @param data 当不需要参数时 {@code data} 可以为 {@code null} */ @Override public void setData(@Nullable Object data) { } //初始化适配器 private void initRecyclerView() { ArmsUtils.configRecyclerView(mRvTest, new GridLayoutManager(mContext, 4)); for (int i = 0; i < 10; i++) { GetTestData data = new GetTestData(); data.setAmt("¥" + i + ".00/瓶/瓶"); data.setNumber(i + "ss"); data.setTitle(i + "--燕塘草莓味酸奶 250ml"); mTestDataList.add(data); } //初始化adatper数据 mRvTest.setAdapter(mTestAdapter); mTestAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { ImageView imageView = view.findViewById(R.id.iv_select); // for (Integer key : mTestAdapter.getMap().keySet()) { // LogUtils.debugInfo("booleanValue:"+mTestAdapter.getMap().get(key).booleanValue()); // imageView.setVisibility(mTestAdapter.getMap().get(key).booleanValue()?View.GONE:View.VISIBLE); // } if (imageView.getVisibility() == View.GONE) { //选中 imageView.setVisibility(View.VISIBLE); mTestAdapter.getMap().put(position, true); } else { //取消选中 imageView.setVisibility(View.GONE); mTestAdapter.getMap().put(position, false); } } }); } @Override public void showLoading() { } @Override public void hideLoading() { } @Override public void showMessage(@NonNull String message) { checkNotNull(message); ArmsUtils.snackbarText(message); } @Override public void launchActivity(@NonNull Intent intent) { checkNotNull(intent); ArmsUtils.startActivity(intent); } @Override public void killMyself() { } @OnClick({R.id.tv_template}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.tv_template: break; } } }
C++
UTF-8
1,310
3.359375
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; vector<int> GetNextArray(string str) { if(str.length() == 1) { vector<int> next = {-1}; return next; } vector<int> next(str.length(),0); next[0] = -1; next[1] = 0; int i = 2; int cn = 0; while(i < str.length()) { if(str[i] == str[cn]) { next[i++] = ++cn; } else if(cn > 0) { cn = next[cn]; } else { next[i++] = 0; } } return next; } int Kmp(string str1, string str2) { int i1 = 0; int i2 = 0; vector<int> next = GetNextArray(str2); while(i1 < str1.length() and i2 < str2.length()) { if(str1[i1] == str2[i2]) //相等向后移动 { i1++; i2++; } else if(next[i2] == -1) //str2已经没有办法再向前跳了,需要str1向后跳一个 { i1++; } else { i2 = next[i2];//i2跳到前缀的末尾处,继续找 } } return i2 == str2.length()?i1-i2:-1; //找到返回str1中当前的开头位置,找不到返回-1 } int main() { string a = "wumingpu"; string b = "ing"; cout<<Kmp(a,b)<<endl; }
Java
UTF-8
423
2.609375
3
[]
no_license
package com.twj.gfx; public class GeometryUtils { public static double pointToPlaneDistance(Vector4d point, Vector4d plane) { return plane.dotProduct(point); } public static Vector4d getPlaneFromPolygon(Polygon polygon) { double D = polygon.D(); Vector4d normal = polygon.getNormal(); return new Vector4d(normal.get(0), normal.get(1), normal.get(2), D); } }
Python
UTF-8
1,378
2.6875
3
[]
no_license
import cv2 import numpy as np from UserInterface.rescaleImageToUser import rescaleImageToUser from UserInterface.rescaleImageToUser import rescalePosToUser from UserInterface.rescaleImageToUser import rescaleCounur from Tracking.GetPositionFromContour import getPositionFromContour #Pre1: list of objects #Pre2: frame def getIDImage(listOfObjects,frame): szX = frame.xSz szY = frame.ySz numCol = 3 idImg = np.zeros((szX,szY, numCol), np.uint8) idImg = rescaleImageToUser(idImg) #Loop over the tracked objects for trackedCell in listOfObjects: #Draw both the ID of the object and the centroid idText = "ID " + str(trackedCell.getCellID()) (centerX,centerY) = trackedCell.getCentroid() #contour = trackedCell.getContour() #contour = rescaleCounur(contour,[szX,szY]) #(centerX,centerY) = getPositionFromContour(contour) (centerX,centerY) = rescalePosToUser((centerX,centerY),frame.getOptImage().shape) #Put Text and Cetroid #print(idText) #print((centerX,centerY)) cv2.putText(idImg, idText, (centerX-10,centerY-25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) cv2.circle(idImg, (centerX,centerY), 10, (0, 255, 0), -1) #cv2.circle(idImg, (centerX,centerY), 1, (0, 255, 0), -1) #idImg = rescaleImageToUser(idImg) #Return return(idImg)
Markdown
UTF-8
1,045
2.796875
3
[]
no_license
# 1.什么是DevOps ? 1.一组过程方法与系统的统称,用于促进开发、运维和质量保障部门之间的沟通、协作与整合 2.一种文化转变,或者说是一个鼓励很好的交流和协作,以便于更好的构建可靠性更高、质量 更好的软件的运动 3.一种能力,具备此能力的团队可以高质量,快速的交付软件产品 或服务 解决的主要问题:按时、快速、高质量的交付软件产品和服务 通过流程的自动化,节约成本 *答案请使用斜体* # 2.用原生JS实现传入CSS代码改变样式。 *答案请使用斜体* **题目来源是前端面试题,不强制写答案,大家自己对自己负责,希望大家去了解。请求合并信息写明姓名。** ```javascript //此处编写js代码 var div = document.getElmentById('div'); div.style.cssText="display:block;color:blue;background-color:#ccc"; //CSS传值样例 var style = { (多级)选择器:{ display:block; color:blue; background-color:#ccc; } } ```
JavaScript
UTF-8
1,238
4.5
4
[]
no_license
/* Couting Sort implementation in JavaScript */ function countingSort(arr) { var i, min = 0, index = 0, aux = [], sortedArray = []; var maxVal = Math.max.apply(null, arr); //If the max value of the array given, this line can be removed for (i = min; i <= maxVal; i++) { //initializing the auxiliary array with 0 aux[i] = 0; } for (i = 0; i < arr.length; i++) { //Counting the frequency of the elements aux[arr[i]]++; } for (i = min; i <= maxVal; i++) { //based on the frequency, building the new sorted array while (aux[i]-- > 0) { sortedArray[index++] = i; } } return sortedArray; } /******************* Testing Counting sort algorithm *********************/ /** * Returns a random integer between min (inclusive) and max (inclusive) * Using Math.round() will give you a non-uniform distribution! */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var arr = []; for (var i = 0; i < 10; i++) { //initialize a random integer unsorted array arr.push(getRandomInt(1, 100)); } console.log("Unsorted array: "); console.log(arr); //printing unsorted array arr = countingSort(arr); console.log("Sorted array: "); console.log(arr); //printing sorted array
Markdown
UTF-8
2,277
3.21875
3
[]
no_license
# Master Lock Speed Dial(r) lock simulation Master Lock's Speed Dial(r) combination lock is a readily available, affordable, and reasonably secure combination lock. I wanted to better understand the combination space of this lock (and just its functionality) a little better. This simulator exhausts the combination space and can give information about combinations that more or fewer conflicts and might give some hints on what good combination choices would be. Please see [this visualizer](https://toool.nl/images/e/e1/MhVisualizer_V2.0_p.swf) and [this paper](https://toool.nl/images/e/e5/The_New_Master_Lock_Combination_Padlock_V2.0.pdf) to help understand how the lock actually works. ## Basic use ``` cargo run --release ... For up to 10 moves 7396 Uniques 1390704 dups Best: (0|,2>,3<,3<) (1 target) (URRLLU) ``` The `--release` is important for performance. By default, the program will simulate all combinations up to 10 moves, print some statistics, and arbitrarily print information about the "best" combination. The information printed is first the state of the 4 wheels in the lock after applying this combination. Any sequence of moves resulting in this state would be able to open a lock set to this combination. To get more information, you can give arguments to the program, delimiting from the cargo command with two hyphens: ``` cargo run --release -- --help ``` ## Good combinations. Running with `--all` clearly shows that some combinations are better than others (there being four states that can be reached with 1,985 different up-to-10-move sequences. The lock is radially symmetric, so anything found can be applied to a different combination by rotating the lock a multiple on 90 degrees). However, if the attacker knows that the user has used this simulation to choose a combination, they might start with those combinations that result in the fewest collisions. It would seem, then, that the best choice would be to compromise between these, and choose a combination that has a small, but not too small, number of collisions, but whose shortest reaching sequence is as long as the user can tolerate memorizing. It would be silly to choose a 10-step combination if there is a 5-step combination that reaches the same target state.
Python
UTF-8
18,579
2.875
3
[]
no_license
import math import numpy as np import matplotlib.pyplot as plt import scipy.ndimage import SimpleITK as sitk ####################################################################################### # Visualizer class for ndimages ####################################################################################### class NdimageVisualizer(): def __init__(self): # Everything in sitk (W,H,D) format self.spacing = (1.0, 1.0, 3.0) self.suv_window = {'level':3, 'width':5} self.hu_window = {'level':0, 'width':300} self.cmap_dict = {'PET': 'gist_rainbow', 'CT': 'gray', 'labelmap': 'gray', 'normalized': 'gray'} self.dpi = 80 def set_suv_window(self, window): self.suv_window = window def set_hu_window(self, window): self.hu_window = window def _custom_imshow(self, ax, image, title, image_type): # Apply window if image_type == 'labelmap' or image_type == 'normalized': ax.imshow(image, cmap=self.cmap_dict[image_type]) else: if image_type == 'PET': window = self.suv_window elif image_type == 'CT': window = self.hu_window win_min = window['level'] - window['width'] // 2 win_max = window['level'] + window['width'] // 2 ax.imshow(image, cmap=self.cmap_dict[image_type], vmin=win_min, vmax=win_max) ax.set_title(title) ax.axis('off') def multi_image_strips(self, image_np_list, image_types, idx_range, view='axial', subtitles=[], title=""): array_size = image_np_list[0].shape phy_size = [int(array_size[i]*self.spacing[i]) for i in range(3)] n_images = len(image_np_list) figsize = (n_images*450)/self.dpi, ((idx_range[1]-idx_range[0])*450)/self.dpi fig, axs = plt.subplots(1, n_images, figsize=figsize) if len(subtitles) != n_images: subtitles = image_types if view == 'axial': for i, image_np in enumerate(image_np_list): slice_list = [] for j, s in enumerate(range(*idx_range)): axial_slice = image_np[:, :, s].T slice_list.append(axial_slice) strip = np.concatenate(slice_list, axis=0) self._custom_imshow(axs[i], strip, title=subtitles[i], image_type=image_types[i]) if view == 'coronal': for i, image_np in enumerate(image_np_list): slice_list = [] for j, s in enumerate(range(*idx_range)): coronal_slice = image_np[:, s, :] coronal_slice = scipy.ndimage.rotate(coronal_slice, 90) coronal_slice = np.flip(coronal_slice, axis=1) coronal_slice = scipy.ndimage.zoom(coronal_slice, [3,1], order=1) slice_list.append(coronal_slice) strip = np.concatenate(slice_list, axis=0) self._custom_imshow(axs[i], strip, title=subtitles[i], image_type=image_types[i]) if view == 'sagittal': for i, image_np in enumerate(image_np_list): slice_list = [] for s in range(*idx_range): sagittal_slice = image_np[s, :, :] sagittal_slice = scipy.ndimage.rotate(sagittal_slice, 90) sagittal_slice = scipy.ndimage.zoom(sagittal_slice, [3,1], order=1) slice_list.append(sagittal_slice) strip = np.concatenate(slice_list, axis=0) self._custom_imshow(axs[i], strip, title=subtitles[i], image_type=image_types[i]) # Display fig.suptitle(title, fontsize='x-large') plt.show() def grid(self, image_np, idx_range, view='axial', image_type='PET', title=''): array_size = image_np.shape phy_size = [int(array_size[i]*self.spacing[i]) for i in range(3)] w_phy, h_phy, d_phy = phy_size grid_size = ( 5, math.ceil((idx_range[1]-idx_range[0]) / 5) ) if view == 'axial': grid_image_shape = (h_phy * grid_size[0], w_phy * grid_size[1]) elif view == 'coronal': grid_image_shape = (d_phy * grid_size[0], w_phy* grid_size[1]) elif view == 'sagittal': grid_image_shape = (d_phy * grid_size[0], h_phy* grid_size[1]) grid_image = np.zeros(grid_image_shape) slice_list = [] if view == 'axial': for s in range(*idx_range): axial_slice = image_np[:, :, s].T slice_list.append(axial_slice) for gj in range(0, grid_size[1]): if gj != grid_size[1] - 1: strip = np.concatenate(slice_list[gj*5:gj*5+5], axis=0) else: strip = np.concatenate(slice_list[gj*5:], axis=0) grid_image[0:strip.shape[0], gj*w_phy : gj*w_phy+w_phy] = strip if view == 'coronal': for s in range(*idx_range): coronal_slice = image_np[:, s, :] coronal_slice = scipy.ndimage.rotate(coronal_slice, 90) coronal_slice = np.flip(coronal_slice, axis=1) coronal_slice = scipy.ndimage.zoom(coronal_slice, [3,1], order=1) slice_list.append(coronal_slice) for gj in range(0, grid_size[1]): if gj != grid_size[1] - 1: strip = np.concatenate(slice_list[gj*5:gj*5+5], axis=0) else: strip = np.concatenate(slice_list[gj*5:], axis=0) grid_image[0:strip.shape[0], gj*w_phy : gj*w_phy+w_phy] = strip if view == 'sagittal': for s in range(*idx_range): sagittal_slice = image_np[s, :, :] sagittal_slice = scipy.ndimage.rotate(sagittal_slice, 90) sagittal_slice = scipy.ndimage.zoom(sagittal_slice, [3,1], order=1) slice_list.append(sagittal_slice) for gj in range(0, grid_size[1]): if gj != grid_size[1] - 1: strip = np.concatenate(slice_list[gj*5:gj*5+5], axis=0) else: strip = np.concatenate(slice_list[gj*5:], axis=0) grid_image[0:strip.shape[0], gj*h_phy : gj*h_phy+h_phy] = strip # Display figsize = (5*400)/self.dpi, ((idx_range[1]-idx_range[0])/5*400)/self.dpi fig, ax = plt.subplots(figsize=figsize) self._custom_imshow(ax, grid_image, title=title, image_type=image_type) plt.show() ####################################################################################### # To display sitk images - either individually or with sitk overlay ####################################################################################### def display_image(sitk_image, axial_idxs=[], coronal_idxs=[], sagittal_idxs=[], window = None, title=None, cmap='gray'): spacing = sitk_image.GetSpacing() if window is not None: # Apply window and change scan image scale to 0-255 window_min = window['level'] - window['width']//2 window_max = window['level'] + window['width']//2 sitk_image = sitk.Cast(sitk.IntensityWindowing(sitk_image, windowMinimum=window_min, windowMaximum=window_max, outputMinimum=0.0, outputMaximum=255.0), sitk.sitkUInt8) ndarray = sitk.GetArrayFromImage(sitk_image) # Figure settings figsize = (20,10) fig, [ax1,ax2,ax3] = plt.subplots(3, figsize=figsize) # Extract axial slices -- axial_slices = [] for idx in axial_idxs: if ndarray.ndim == 3 : image2d = ndarray[idx, :, :] if ndarray.ndim == 4 : image2d = ndarray[idx, :, :, :] axial_slices.append(image2d) axial_slices = np.hstack(axial_slices) n_rows = image2d.shape[0] # #rows of the 2d array - corresponds to sitk image height n_cols = image2d.shape[1] # #columns of the 2d array - corresponds to sitk image width extent = (0, len(axial_idxs)*n_cols*spacing[0], n_rows*spacing[1], 0) ax1.imshow(axial_slices, extent=extent, interpolation=None, cmap=cmap) ax1.set_title(f"Axial slices: {axial_idxs}") ax1.axis('off') # Extract coronal slices -- coronal_slices = [] for idx in coronal_idxs: if ndarray.ndim == 3 : image2d = ndarray[:, idx, :] if ndarray.ndim == 4 : image2d = ndarray[:, idx, :, :] image2d = np.rot90(image2d, 2) coronal_slices.append(image2d) coronal_slices = np.hstack(coronal_slices) n_rows = image2d.shape[0] # #rows of the 2d array - corresponds to sitk image depth n_cols = image2d.shape[1] # #columns of the 2d array - corresponds to sitk image width extent = (0, len(coronal_idxs)*n_cols*spacing[0], n_rows*spacing[2], 0) ax2.imshow(coronal_slices, extent=extent, interpolation=None, cmap=cmap) ax2.set_title(f"Coronal slices: {coronal_idxs}") ax2.axis('off') # Extract sagittal slices -- sagittal_slices = [] for idx in sagittal_idxs: if ndarray.ndim == 3 : image2d = ndarray[:, :, idx] if ndarray.ndim == 4 : image2d = ndarray[:, :, idx, :] image2d = np.rot90(image2d, k=2) image2d = np.flip(image2d, axis=1) sagittal_slices.append(image2d) sagittal_slices = np.hstack(sagittal_slices) n_rows = image2d.shape[0] # #rows of the 2d array - corresponds to sitk image depth n_cols = image2d.shape[1] # #columns of the 2d array - corresponds to sitk image height extent = (0, len(sagittal_idxs)*n_cols*spacing[1], n_rows*spacing[2], 0) ax3.imshow(sagittal_slices, extent=extent, interpolation=None, cmap=cmap) ax3.set_title(f"Sagittal slices: {sagittal_idxs}") ax3.axis('off') if title: fig.suptitle(title, fontsize='x-large') plt.show() def display_image_np(np_array, spacing, is_label=False, axial_idxs=[], coronal_idxs=[], sagittal_idxs=[], window_level = None, window_width = None, title=None): """ Wrapper over our display_image() function Params: - spacing: (W,H,D) format """ sitk_image = sitk.GetImageFromArray(np_array.astype(np.int16)) sitk_image.SetSpacing(spacing) if is_label: sitk_image = sitk.LabelToRGB(sitk_image) # Get RGB color mapping display_image(sitk_image, axial_slice_idxs=axial_slice_idxs, coronal_slice_idxs=coronal_slice_idxs, sagittal_slice_idxs=sagittal_slice_idxs, window_level=window_level, window_width=window_width, title=title) def mask_image_multiply(mask, image): components_per_pixel = image.GetNumberOfComponentsPerPixel() if components_per_pixel == 1: return mask*image else: return sitk.Compose([mask*sitk.VectorIndexSelectionCast(image,channel) for channel in range(components_per_pixel)]) def alpha_blend(image1, image2, alpha = 0.5, mask1=None, mask2=None): ''' Alpha blend two images, pixels can be scalars or vectors. The alpha blending factor can be either a scalar or an image whose pixel type is sitkFloat32 and values are in [0,1]. The region that is alpha blended is controled by the given masks. ''' if not mask1: mask1 = sitk.Image(image1.GetSize(), sitk.sitkFloat32) + 1.0 mask1.CopyInformation(image1) else: mask1 = sitk.Cast(mask1, sitk.sitkFloat32) if not mask2: mask2 = sitk.Image(image2.GetSize(),sitk.sitkFloat32) + 1 mask2.CopyInformation(image2) else: mask2 = sitk.Cast(mask2, sitk.sitkFloat32) # if we received a scalar, convert it to an image if type(alpha) != sitk.SimpleITK.Image: alpha = sitk.Image(image1.GetSize(), sitk.sitkFloat32) + alpha alpha.CopyInformation(image1) components_per_pixel = image1.GetNumberOfComponentsPerPixel() if components_per_pixel>1: img1 = sitk.Cast(image1, sitk.sitkVectorFloat32) img2 = sitk.Cast(image2, sitk.sitkVectorFloat32) else: img1 = sitk.Cast(image1, sitk.sitkFloat32) img2 = sitk.Cast(image2, sitk.sitkFloat32) intersection_mask = mask1*mask2 intersection_image = mask_image_multiply(alpha*intersection_mask, img1) + \ mask_image_multiply((1-alpha)*intersection_mask, img2) return intersection_image + mask_image_multiply(mask2-intersection_mask, img2) + \ mask_image_multiply(mask1-intersection_mask, img1) def display_overlay_image(ct_sitk, pet_sitk=None, true_gtv_sitk=None, pred_gtv_sitk=None, axial_idxs=[], coronal_idxs=[], sagittal_idxs=[], ct_window_level=None, ct_window_width=None, pet_window_level=None, pet_window_width=None, gtv_as_contour=False, pet_ct_alpha=0.3, gtv_opacity=0.5, title=None): # Apply window and change scan image scale to 0-255 if ct_window_level != None and ct_window_width != None: ct_window_min = ct_window_level - ct_window_width//2 ct_window_max = ct_window_level + ct_window_width//2 ct_sitk = sitk.Cast(sitk.IntensityWindowing(ct_sitk, windowMinimum=ct_window_min, windowMaximum=ct_window_max, outputMinimum=0.0, outputMaximum=255.0), sitk.sitkUInt8) # Apply window and change scan image scale to 0-255 if pet_sitk != None: if pet_window_level != None and pet_window_width != None: pet_window_min = pet_window_level - pet_window_width//2 pet_window_max = pet_window_level + pet_window_width//2 pet_sitk = sitk.Cast(sitk.IntensityWindowing(pet_sitk, windowMinimum=pet_window_min, windowMaximum=pet_window_max, outputMinimum=0.0, outputMaximum=255.0), sitk.sitkUInt8) scan_sitk = alpha_blend(ct_sitk, pet_sitk, alpha=pet_ct_alpha) scan_sitk = sitk.Cast(scan_sitk, sitk.sitkUInt8) else: scan_sitk = ct_sitk # Overlay gtv mask over the scan -- if gtv_as_contour: true_gtv_contour = sitk.LabelContour(true_gtv_sitk, fullyConnected=True) # Convert segmentation to contour overlay_image = sitk.LabelOverlay(scan_sitk, true_gtv_contour, opacity=1) # Display the predicted GTV (along with true GTV) only if contour mode is enabled if pred_gtv_sitk: # Combine the 2 gtv masks into one true_gtv_np = sitk.GetArrayFromImage(true_gtv_sitk) pred_gtv_np = sitk.GetArrayFromImage(pred_gtv_sitk) combined_gtv_mask = pred_gtv_np * 2 # Change predicted GTV's label to 2 combined_gtv_mask[true_gtv_np == 1] = 1 # Keep true GTV's label as 1 combined_gtv_mask = sitk.GetImageFromArray(combined_gtv_mask) combined_gtv_mask.CopyInformation(true_gtv_sitk) combined_gtv_contour = sitk.LabelContour(combined_gtv_mask, fullyConnected=True) # Convert segmentation to contour overlay_image = sitk.LabelOverlay(scan_sitk, combined_gtv_contour, opacity=gtv_opacity) else: overlay_image = sitk.LabelOverlay(scan_sitk, true_gtv_sitk, opacity=gtv_opacity) # Display display_image(overlay_image, axial_idxs=axial_idxs, coronal_idxs=coronal_idxs, sagittal_idxs=sagittal_idxs, window_level=None, window_width=None, title=title) ####################################################################################### # To display single CT, PET and GTV slices side-by-side ####################################################################################### def display_slice(ct_slice_sitk, pet_slice_sitk, true_gtv_slice_sitk=None, pred_gtv_slice_sitk=None, title=None, dpi=100): """ Display corresponding slices of CT, PET and GTV side-by-side. Note: CT and PET need to have same size and spacing -- i.e. only resampled images should be used """ n_inputs = 2 ct_slice_sitk = sitk.Cast(sitk.IntensityWindowing(ct_slice_sitk, windowMinimum=-200, windowMaximum=600, outputMinimum=0.0, outputMaximum=255.0), sitk.sitkUInt8) pet_slice_sitk = sitk.Cast(sitk.IntensityWindowing(pet_slice_sitk, windowMinimum=0, windowMaximum=10, outputMinimum=0.0, outputMaximum=255.0), sitk.sitkUInt8) ct_slice_np = sitk.GetArrayFromImage(ct_slice_sitk) pet_slice_np = sitk.GetArrayFromImage(pet_slice_sitk) if true_gtv_slice_sitk: true_gtv_slice_sitk = true_gtv_slice_sitk * 255 true_gtv_slice_np = sitk.GetArrayFromImage(true_gtv_slice_sitk) n_inputs += 1 if pred_gtv_slice_sitk: pred_gtv_slice_sitk = pred_gtv_slice_sitk * 255 pred_gtv_slice_np = sitk.GetArrayFromImage(pred_gtv_slice_sitk) n_inputs += 1 spacing = ct_slice_sitk.GetSpacing() # Get pixel spacing of the slice extent = (0, ct_slice_np.shape[0]*spacing[1], ct_slice_np.shape[1]*spacing[0], 0) figsize = (n_inputs*5,5) #figsize = (n_inputs*ct_slice_np.shape[1]/dpi, n_images*ct_slice_np.shape[0]/dpi) fig, axs = plt.subplots(nrows=1, ncols=n_inputs, figsize=figsize) axs[0].imshow(ct_slice_np, extent=extent, interpolation=None, cmap='gray') axs[0].set_title("CT") axs[1].imshow(pet_slice_np, extent=extent, interpolation=None, cmap='gray') axs[1].set_title("PET") if true_gtv_slice_sitk: axs[2].imshow(true_gtv_slice_np, extent=extent, interpolation=None, cmap='gray') axs[2].set_title("Actual GTV") if pred_gtv_slice_sitk: axs[3].imshow(pred_gtv_slice_np, extent=extent, interpolation=None, cmap='gray') axs[3].set_title("Predicted GTV") for ax in axs: ax.axis('off') if title: fig.suptitle(title, fontsize='x-large') plt.show()
Java
UTF-8
629
1.773438
2
[]
no_license
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; /** * @Description: Hystrix可以用在消费端或客户端 * @Author: chenjun * @Date: 2020/10/19 10:47 */ @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker public class PaymentHystrixApplication { public static void main(String[] args) { SpringApplication.run(PaymentHystrixApplication.class,args); } }
Java
UTF-8
6,230
2.390625
2
[]
no_license
package com.laka.libnet.rx; import android.content.Context; import com.laka.libnet.constant.AppConstant; import com.laka.libnet.converter.JsonConverterFactory; import com.laka.libnet.intercepter.AuthorizationInterceptor; import com.laka.libnet.intercepter.LoggingInterceptor; import com.laka.libnet.intercepter.NetWorkInterceptor; import com.laka.libnet.utils.GsonUtils; import com.laka.libutils.app.ApplicationUtils; import java.io.File; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; /** * @Author:summer * @Date:2019/7/19 * @Description:Retrofit构建helper */ public class RetrofitHelper { private Context context; private Retrofit mRetrofit; private static ApiService mApiService; /** * description:常规参数配置 **/ private String HOST = ""; private boolean isAuthorRequest = false; private boolean isNetWorkInterceptor = false; private boolean isGlobalParamsInterceptor = false; public static ApiService getApiService() { if (mApiService == null) { synchronized (RetrofitHelper.class) { if (mApiService == null) { mApiService = createApiService(); } } } return mApiService; } private RetrofitHelper(Builder builder) { this.context = builder.context; this.isAuthorRequest = builder.isAuthorRequest; this.isNetWorkInterceptor = builder.isNetWorkInterceptor; this.isGlobalParamsInterceptor = builder.isGlobalParamsInterceptor; this.HOST = builder.requestHost; initRetrofit(); } /** * 配置Retrofit信息 */ private void initRetrofit() { // 指定缓存路径,缓存大小100Mb Cache cache = new Cache(new File(context.getCacheDir(), "HttpCache"), 1024 * 1024 * 100); OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); //拦截器 if (isGlobalParamsInterceptor) { builder.addInterceptor(new NetWorkInterceptor(context)); } if (isAuthorRequest) { builder.addInterceptor(new AuthorizationInterceptor(context)); } if (isNetWorkInterceptor) { builder.addInterceptor(new NetWorkInterceptor(context)); } builder.addNetworkInterceptor(new LoggingInterceptor()) .cache(cache) .retryOnConnectionFailure(true) .connectTimeout(AppConstant.MAX_CONNECT_TIME_OUT, TimeUnit.SECONDS) .readTimeout(AppConstant.MAX_READ_TIME_OUT, TimeUnit.SECONDS) .writeTimeout(AppConstant.MAX_WRITE_TIME_OUT, TimeUnit.SECONDS); // 创建OKHttp对象 OkHttpClient okHttpClient = builder.build(); Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(HOST) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(okHttpClient); //使用jsonConverter retrofitBuilder.addConverterFactory(JsonConverterFactory.create(GsonUtils.getDefaultGson())); mRetrofit = retrofitBuilder.build(); } /** * 创建ApiService对象 */ private static ApiService createApiService() { return new Builder(ApplicationUtils.getApplication()) .setAuthorRequest(true) .setNetWorkInterceptor(true) .setGlobalParamsInterceptor(true) .setRequestHost(AppConstant.BASE_HOST) .build() .create(ApiService.class); } /** * 通过create函数获取到具体的Service * * @param reqServer * @param <T> * @return */ public <T> T create(Class<T> reqServer) { return mRetrofit.create(reqServer); } public static class Builder { private boolean isAuthorRequest = false; private boolean isNetWorkInterceptor = false; private boolean isGlobalParamsInterceptor = true; private String requestHost = ""; private Context context; public Builder(Context context) { this.context = context; } public Builder setAuthorRequest(boolean tokenRequest) { isAuthorRequest = tokenRequest; return this; } public Builder setNetWorkInterceptor(boolean netWorkInterceptor) { isNetWorkInterceptor = netWorkInterceptor; return this; } public Builder setGlobalParamsInterceptor(boolean globalParamsInterceptor) { isGlobalParamsInterceptor = globalParamsInterceptor; return this; } public Builder setRequestHost(String requestHost) { this.requestHost = requestHost; return this; } public RetrofitHelper build() { return new RetrofitHelper(this); } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RetrofitHelper)) return false; RetrofitHelper that = (RetrofitHelper) o; if (isAuthorRequest != that.isAuthorRequest) return false; if (isNetWorkInterceptor != that.isNetWorkInterceptor) return false; if (isGlobalParamsInterceptor != that.isGlobalParamsInterceptor) return false; if (context != null ? !context.equals(that.context) : that.context != null) return false; if (mRetrofit != null ? !mRetrofit.equals(that.mRetrofit) : that.mRetrofit != null) return false; return HOST != null ? HOST.equals(that.HOST) : that.HOST == null; } @Override public int hashCode() { int result = context != null ? context.hashCode() : 0; result = 31 * result + (mRetrofit != null ? mRetrofit.hashCode() : 0); result = 31 * result + (HOST != null ? HOST.hashCode() : 0); result = 31 * result + (isAuthorRequest ? 1 : 0); result = 31 * result + (isNetWorkInterceptor ? 1 : 0); result = 31 * result + (isGlobalParamsInterceptor ? 1 : 0); return result; } }
Markdown
UTF-8
1,390
2.75
3
[]
no_license
## 0x17. Web stack debugging #3 ![](https://s3.amazonaws.com/intranet-projects-files/holbertonschool-sysadmin_devops/293/d42WuBh.png) When debugging, sometimes logs are not enough. Either because the software is breaking in a way that was not expected and is the error is not being logged, or because logs are not providing enough information. In this case, you will need to go down the stack, the good news is that this is something Holberton students can do :) Wordpress is a very popular tool, it allows to run blogs, portfolios, e-commerce and company websites… It actually powers 26% of the web, so there is a fair chance that you will end working with it at some point in your career. Wordpress is usually run on LAMP (Linux, Apache, MySQL, and PHP), which is a very widely used set of tools. The web stack you are debugging today is a Wordpress website running on a LAMP stack. **0. Strace is you friend** Using strace, find out why Apache is returning a 500 error. Once you find the issue, fix it and then automate it using Puppet (instead of using Bash as you were previously doing). Hint: * strace can attach to a current running process * You can use tmux to run strace in one windows and curl in another one Requirements: * Your 0-strace_is_your_friend.pp file must contain Puppet code * You can use whatever Puppet resource type you want for you fix
Markdown
UTF-8
3,342
3.046875
3
[]
no_license
### 技术 react全家桶(react react-router-dom redux antd) flex echarts ### 用户及用户功能 该系统用户分为两类: 管理员和标准用户(不是客户) 我们做的是该系统的管理员(其实以后两个都得做,需要根据请求添加各种权限),现在只需要做一个管理员即可。一个管理员手下可以有多个标准用户。 管理员可以进行所有信息的查看功能。 管理员可以管理普通用户,给普通用户分配任务。 管理员还可以管理活动信息,活动信息的添加、删除、编辑等。 ### 流程 #### 登录 管理员登陆 ---> 首页(展示该管理员的所有信息包括组员,以及管理的客户。) 简单介绍: 首页的导航三个按钮 只有客户管理能点。活动管理,和查看报表不能点。因为正常来说点击活动管理会展示一个所有活动的列表,但是这个例子就展示了DELL客户的活动,查看报告按钮也一样。所以首页导航的后面两个按钮就不能点击只负责显示(当前是否到了这页,到了就改变样式)。 #### 客户管理 首页点击客户管理 ---> 客户管理页(展示客户信息列表) 简单介绍: 客户信息里面的用户分配的意思可能是将这个客户分配给你的手下管理 该页功能可以实现对客户信息的添加编辑删除,点击列表中的客户编号和客户名称跳转到该客户的活动管理页。 #### 活动管理 一个活动是一个集合总称,里面有很多小活动(分为三类 网站 广告投放 电子杂志 )。 客户管理页点编号或者名称 ---> 活动管理列表页 该页功能可以实现对客户的活动信息的添加编辑删除,点击活动名称跳转到活动的详情信息页 该页功能可以实现对活动内的信息进行编辑等操作,点击查看报告跳转到对应活动的报告页面 #### 查看报告 该页的数据量有点多可以暂时不用做,简单的写点死数据就行(不需要关联)。还有报告页里面的小页面(或选项卡),每一项先做一两个展示剩下的后续再说。 ### 数据 除了查看报告相关的数据之外的数据都需要模拟,而且都是关联的。例如,点击了客户列表页面的客户 id ,跳转到客户活动列表页的时,展示数据要和点击的客户数据一致。 数据都写成本地数据不需要放到服务器(json-server)上。 数据的模拟自己看着模拟就行,因为少了报告一项所以没有太复杂。 ### 部分地址模拟 登录页 /login 首页 / 客户列表页 /customerlist 某个客户的某个活动(列表)管理页 /customer/客户id/activities 某个客户的某个活动详情页 /customer/客户id/activity/活动id 解释说明:地址栏信息要展现出是那个客户那个活动等等信息,方便以后的获取数据,以及对应页面的导航制作 ### 注意 所有的操作后面的编辑按钮和删除按钮默认是禁用状态,当你使用复选框选择了之后才可用。 虽然页面中的问号提示不需要大家做,但是做之前一定要点一下看看,会从中明白一些功能。 ### 最后 任何跳转流程,数据流程,以及我的解释说明,还有哪里做哪里不做不懂的及时问我。 技术问题自己要先好好研究实在不行问我。
Markdown
UTF-8
3,884
3.3125
3
[]
no_license
--- title: FATE category: administration order: 3 --- Accumulo must implement a number of distributed, multi-step operations to support the client API. Creating a new table is a simple example of an atomic client call which requires multiple steps in the implementation: get a unique table ID, configure default table permissions, populate information in ZooKeeper to record the table's existence, create directories in HDFS for the table's data, etc. Implementing these steps in a way that is tolerant to node failure and other concurrent operations is very difficult to achieve. Accumulo includes a Fault-Tolerant Executor (FATE) which is widely used server-side to implement the client API safely and correctly. Fault-Tolerant Executor (FATE) is the implementation detail which ensures that tables in creation when the Master dies will be successfully created when another Master process is started. This alleviates the need for any external tools to correct some bad state -- Accumulo can undo the failure and self-heal without any external intervention. ## Overview FATE consists of two primary components: a repeatable, persisted operation (REPO), a storage layer for REPOs and an execution system to run REPOs. Accumulo uses ZooKeeper as the storage layer for FATE and the Accumulo Master acts as the execution system to run REPOs. The important characteristic of REPOs are that they implemented in a way that is idempotent: every operation must be able to undo or replay a partial execution of itself. Requiring the implementation of the operation to support this functional greatly simplifies the execution of these operations. This property is also what guarantees safety in light of failure conditions. ## Administration Sometimes, it is useful to inspect the current FATE operations, both pending and executing. For example, a command that is not completing could be blocked on the execution of another operation. Accumulo provides an Accumulo shell command to interact with fate. The `fate` shell command accepts a number of arguments for different functionality: `list`/`print`, `fail`, `delete`, `dump`. ### List/Print Without any additional arguments, this command will print all operations that still exist in the FATE store (ZooKeeper). This will include active, pending, and completed operations (completed operations are lazily removed from the store). Each operation includes a unique "transaction ID", the state of the operation (e.g. `NEW`, `IN_PROGRESS`, `FAILED`), any locks the transaction actively holds and any locks it is waiting to acquire. This option can also accept transaction IDs which will restrict the list of transactions shown. ### Fail This command can be used to manually fail a FATE transaction and requires a transaction ID as an argument. Failing an operation is not a normal procedure and should only be performed by an administrator who understands the implications of why they are failing the operation. ### Delete This command requires a transaction ID and will delete any locks that the transaction holds. Like the fail command, this command should only be used in extreme circumstances by an administrator that understands the implications of the command they are about to invoke. It is not normal to invoke this command. ### Dump This command accepts zero more transaction IDs. If given no transaction IDs, it will dump all active transactions. A FATE operations is compromised as a sequence of REPOs. In order to start a FATE transaction, a REPO is pushed onto a per transaction REPO stack. The top of the stack always contains the next REPO the FATE transaction should execute. When a REPO is successful it may return another REPO which is pushed on the stack. The `dump` command will print all of the REPOs on each transactions stack. The REPOs are serialized to JSON in order to make them human readable.
Markdown
UTF-8
847
2.59375
3
[ "MIT" ]
permissive
# Aroma Video chatting with a dash of telecreativity. It is an exploration as to how to enable creativity in a virtual environment. ## Instructions Requires: nodejs and npm 1) npm install 2) npm run dev [developing] or npm start [production] 4) It will be available on locahost:5000 by default ## Planned feature set - 1-1 videocalls - Whiteboard functionality: Enable drawing on the screen without touch input (finger tracking using machine vision) - Emotion dependent style transfer: Use bio signals to classify the emotional state of the user. The output video will be styled using neural styling based on the emotion detected. ## Implementation Currently, it will be using WebRTC to enable 1-1 videochats, handled by a central NodeJS server. A Python server will run machine vision / neural styling algorithms on the WebRTC MediaStream.
Java
UTF-8
5,077
2.28125
2
[]
no_license
/* * Copyright (C) 2015 Arthur Gregorio, AG.Software * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package br.com.webbudget.domain.model.repository; import br.com.webbudget.domain.model.entity.IPersistentEntity; import java.util.List; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import javax.persistence.EntityManager; import javax.persistence.LockModeType; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import org.hibernate.Criteria; import org.hibernate.Session; /** * A implementacao padrao do repositorio generico, com esta classe habilitamos o * suporte as funcionalidades basicas de um repositorio de dados no banco * * @param <T> a classe persistente para este repositorio * @param <ID> o tipo de nossos ID * * @author Arthur Gregorio * * @version 1.1.0 * @since 1.0.0, 03/03/2013 */ public abstract class GenericRepository<T extends IPersistentEntity, ID extends Serializable> implements IGenericRepository<T, ID>, Serializable { @PersistenceContext private EntityManager entityManager; private final Class<T> persistentClass; /** * Inicia o repositorio identificando qual e a classe de nossa entidade, seu * tipo {@link Class<?>} */ @SuppressWarnings({"unchecked", "unsafe"}) public GenericRepository() { this.persistentClass = (Class< T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } /** * @return nosso entityManager, inicializado e configurado */ protected EntityManager getEntityManager() { if (this.entityManager == null) { throw new IllegalStateException("The entityManager is not initialized"); } return this.entityManager; } /** * @return a {@link Criteria} do hibernate setada para a classe do * repositorio */ protected Criteria createCriteria() { return this.getSession().createCriteria(this.getPersistentClass()); } /** * @return a {@link Session} do Hibernate para que possamos usar nossa * {@link Criteria} para buscas */ protected Session getSession() { return (Session) this.getEntityManager().getDelegate(); } /** * @return a classe de nossa entidade persistente */ public Class<T> getPersistentClass() { return this.persistentClass; } /** * {@inheritDoc} * * @param id * @param lock * @return */ @Override public T findById(ID id, boolean lock) { final T entity; if (lock) { entity = (T) this.getEntityManager().find( this.getPersistentClass(), id, LockModeType.OPTIMISTIC); } else { entity = (T) this.getEntityManager().find( this.getPersistentClass(), id); } return entity; } /** * {@inheritDoc} * * @return */ @Override public List<T> listAll() { final EntityManager manager = this.getEntityManager(); final CriteriaQuery<T> query = manager.getCriteriaBuilder() .createQuery(this.getPersistentClass()); final TypedQuery<T> selectAll = manager.createQuery(query.select( query.from(this.getPersistentClass()))); return selectAll.getResultList(); } /** * {@inheritDoc} * * @return */ @Override public Long count() { final EntityManager manager = this.getEntityManager(); final CriteriaBuilder builder = manager.getCriteriaBuilder(); final CriteriaQuery<Long> query = builder.createQuery(Long.class); query.select(builder.count(query.from(this.getPersistentClass()))); return manager.createQuery(query).getSingleResult(); } /** * {@inheritDoc} * * @param entity * @return */ @Override public T save(T entity) { return this.getEntityManager().merge(entity); } /** * {@inheritDoc} * * @param entity */ @Override public void delete(T entity) { final T persistentEntity = this.getEntityManager().getReference( this.getPersistentClass(), entity.getId()); this.getEntityManager().remove(persistentEntity); } }
Java
UTF-8
646
2.609375
3
[]
no_license
package cashless.vo; import cashless.domain.Product; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ProductVOMapper { public static List<ProductVO> map(Collection<Product> products) { ArrayList<ProductVO> vos = new ArrayList<>(); for (Product product : products) { vos.add(map(product)); } return vos; } private static ProductVO map(Product product) { ProductVO vo = new ProductVO(); vo.setId(product.getId()); vo.setName(product.getName()); vo.setCredits(product.getCredits()); return vo; } }
Java
UTF-8
1,273
1.929688
2
[]
no_license
package weixin.test; import weixin.popular.bean.EventMessage; import weixin.popular.util.XMLConverUtil; public class WeixinTest { public static void main(String[] args) { String xml = "<xml>" + " <ToUserName><![CDATA[]]></ToUserName>" + " <FromUserName><![CDATA[fromUser]]></FromUserName>" + " <CreateTime>1433332012</CreateTime>" + " <MsgType><![CDATA[event]]></MsgType>" + " <Event><![CDATA[ShakearoundUserShake]]></Event>" + " <ChosenBeacon>" + " <Uuid><![CDATA[uuid]]></Uuid>" + " <Major>major</Major>" + " <Minor>minor</Minor>" + " <Distance>0.057</Distance>" + " </ChosenBeacon>" + " <AroundBeacons>" + " <AroundBeacon>" + " <Uuid><![CDATA[uuid]]></Uuid>" + " <Major>major</Major>" + " <Minor>minor</Minor>" + " <Distance>166.816</Distance>" + " </AroundBeacon>" + " <AroundBeacon>" + " <Uuid><![CDATA[uuid]]></Uuid>" + " <Major>major</Major>" + " <Minor>minor</Minor>" + " <Distance>15.013</Distance>" + " </AroundBeacon>" + " </AroundBeacons>" + "</xml>"; EventMessage eventMessage = XMLConverUtil.convertToObject(EventMessage.class, xml); System.out.println("eventMessage === "+eventMessage); } }
Python
UTF-8
884
3.15625
3
[]
no_license
#-*- coding:utf-8-*- import jieba from collections import Counter #完整演示了制作一个词云的过程 #从文件中读取文本,并使用jieba类将文本序列化 def gettext(filename): text = '' with open(filename) as fin: for line in fin.readlines(): line = line.strip('\n') text += '//'.join(jieba.cut(line)) text += '//' return text #从词云来序列化文本 def getciyun(str): return jiba.cut(str) #计算序列化文化的词频 def getcountciyun(str): data = dict(Counter(str)) return data #按照词频排序 def sortdic(dict): s = dict.items() return sorted(s,key = lambda b:b[1]) #绘制词云 def draw(): pass def main(): text = gettext('lcs.txt') count_text = getcountciyun(text) sort_text = sortdic(count_text) print len(text),len(count_text),len(sort_text) if __name__ =="__main__": main()
Java
UTF-8
17,813
3.109375
3
[]
no_license
import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Set; public class BPlusTree extends StringTree { private Node root; private int minDegree; private ArrayList<String> leafNode = new ArrayList<>(); BPlusTree(int minDegree) { if (minDegree < 2) { System.out.print("minDegree must be at least 2"); System.exit(0); } this.minDegree = minDegree; root = new Node(true, true); } @Override public String get(Object key) { return root.get(key.toString()); } @Override public String put(String key, String value) { root.putElement(key, value); return "Key = " + key + ", Value = " + value + " has been put into the tree"; } @Override public String remove(Object key) { root.remove(key.toString(), this); return "Entry key = " + key + " has been removed"; } @Override void preOrderPrint() { preOrderPrint(0, root); } private void preOrderPrint(int level, @NotNull Node node) { int child = 0; if (!node.isRoot) for (Node parentChild : node.parent.children) if (parentChild != node) child++; else break; System.out.print("level=" + level + " child=" + child + " /"); int i = node.isLeaf ? 0 : 1; for (; i < node.entries.size(); i++) System.out.print(node.entries.get(i).getKey() + "/"); System.out.println(); if (!node.isLeaf) for (Node node1 : node.children) preOrderPrint(level + 1, node1); } void searchScope(String lowerBound, String upperBound) { leafNode.sort(null); for (String key : leafNode) if (key.compareTo(lowerBound) >= 0 && key.compareTo(upperBound) <= 0) System.out.println(key + " " + get(key)); } public Set<Entry<String, String>> entrySet() { return null; } public class Node { private boolean isLeaf; private boolean isRoot; private Node parent; private Node previous; private Node next; private ArrayList<SimpleEntry<String, String>> entries; private ArrayList<Node> children; private Node(boolean isLeaf) { this.isLeaf = isLeaf; entries = new ArrayList<>(); if (!isLeaf) children = new ArrayList<>(); } Node(boolean isLeaf, boolean isRoot) { this(isLeaf); this.isRoot = isRoot; } String get(String key) { if (isLeaf) { for (SimpleEntry<String, String> entry : entries) if (entry.getKey().compareTo(key) == 0) return entry.getValue(); return null; } else if (key.compareTo(entries.get(0).getKey()) <= 0) return children.get(0).get(key); else if (key.compareTo(entries.get(entries.size() - 1).getKey()) >= 0) return children.get(children.size() - 1).get(key); else for (int i = 0; i < entries.size(); i++) if (entries.get(i).getKey().compareTo(key) <= 0 && entries.get(i + 1).getKey().compareTo(key) > 0) return children.get(i).get(key); return null; } void putElement(String key, String obj) { if (!leafNode.contains(key)) leafNode.add(key); if (isLeaf) if (contains(key) || entries.size() < (2 * minDegree - 1)) { insertEntry(key, obj); if (parent != null) parent.fixAfterInsert(); } else { Node left = new Node(true); Node right = new Node(true); if (previous != null) { previous.next = left; left.previous = previous; } if (next != null) { next.previous = right; right.next = next; } left.next = right; right.previous = left; previous = null; next = null; int leftSize = minDegree + (2 * minDegree) % 2; int rightSize = minDegree; insertEntry(key, obj); for (int i = 0; i < leftSize; i++) left.entries.add(entries.get(i)); for (int i = 0; i < rightSize; i++) right.entries.add(entries.get(leftSize + i)); splitNode(left, right); } else { int i = 0; while (i < entries.size() && key.compareTo(entries.get(i).getKey()) >= 0) i++; children.get(i == 0 ? 0 : (i - 1)).putElement(key, obj); } } private void insertEntry(String key, String value) { SimpleEntry<String, String> entry = new SimpleEntry<>(key, value); if (entries.size() == 0) { entries.add(entry); return; } for (int i = 0; i < entries.size(); i++) if (entries.get(i).getKey().compareTo(key) == 0) { entries.get(i).setValue(value); return; } else if (entries.get(i).getKey().compareTo(key) > 0) if (i == 0) { entries.add(0, entry); return; } else { entries.add(i, entry); return; } entries.add(entries.size(), entry); } private void splitNode(Node left, Node right) { if (parent != null) { int index = parent.children.indexOf(this); parent.children.remove(this); left.parent = parent; right.parent = parent; parent.children.add(index, left); parent.children.add(index + 1, right); this.entries = null; this.children = null; parent.fixAfterInsert(); this.parent = null; } else { isRoot = false; Node parent = new Node(false, true); root = parent; left.parent = parent; right.parent = parent; parent.children.add(left); parent.children.add(right); this.entries = null; this.children = null; parent.fixAfterInsert(); } } private void fixAfterInsert() { fix(this); if (children.size() > (2 * minDegree - 1)) { Node left = new Node(false); Node right = new Node(false); int leftSize = minDegree + (2 * minDegree) % 2; int rightSize = minDegree; for (int i = 0; i < leftSize; i++) { left.children.add(children.get(i)); left.entries.add(new SimpleEntry<>(children.get(i).entries.get(0).getKey(), null)); children.get(i).parent = left; } for (int i = 0; i < rightSize; i++) { right.children.add(children.get(leftSize + i)); right.entries.add(new SimpleEntry<>(children.get(leftSize + i).entries.get(0).getKey(), null)); children.get(leftSize + i).parent = right; } splitNode(left, right); } } private void fix(@NotNull Node node) { if (node.entries.size() == node.children.size()) for (int i = 0; i < node.entries.size(); i++) { String key = node.children.get(i).entries.get(0).getKey(); if (!node.entries.get(i).getKey().equals(key)) { node.entries.remove(i); node.entries.add(i, new SimpleEntry<>(key, null)); if (!node.isRoot) fix(node.parent); i--; } } else if (node.isRoot && node.children.size() >= 2 || node.children.size() >= (2 * minDegree - 1) / 2 && node.children.size() <= (2 * minDegree - 1) && node.children.size() >= 2) { node.entries.clear(); for (int i = 0; i < node.children.size(); i++) { String key = node.children.get(i).entries.get(0).getKey(); node.entries.add(new SimpleEntry<>(key, null)); if (!node.isRoot) fix(node.parent); } } } private void updateRemove(@NotNull BPlusTree tree) { fix(this); if (children.size() < (2 * tree.minDegree - 1) / 2 || children.size() < 2) { if (isRoot) { if (children.size() < 2) { Node root = children.get(0); tree.root = root; root.parent = null; root.isRoot = true; this.entries = null; this.children = null; } } else { int currIdx = parent.children.indexOf(this); int prevIdx = currIdx - 1; int nextIdx = currIdx + 1; Node previous = null, next = null; if (prevIdx >= 0) previous = parent.children.get(prevIdx); if (nextIdx < parent.children.size()) next = parent.children.get(nextIdx); if (previous != null && previous.children.size() > (2 * tree.minDegree - 1) / 2 && previous.children.size() > 2) { int idx = previous.children.size() - 1; Node borrow = previous.children.get(idx); previous.children.remove(idx); borrow.parent = this; children.add(0, borrow); fix(previous); fix(this); parent.updateRemove(tree); } else if (next != null && next.children.size() > (2 * tree.minDegree - 1) / 2 && next.children.size() > 2) { Node borrow = next.children.get(0); next.children.remove(0); borrow.parent = this; children.add(borrow); fix(next); fix(this); parent.updateRemove(tree); } else { if (previous != null && (previous.children.size() <= (2 * tree.minDegree - 1) / 2 || previous.children.size() <= 2)) { for (int i = previous.children.size() - 1; i >= 0; i--) { Node child = previous.children.get(i); children.add(0, child); child.parent = this; } previous.children = null; previous.entries = null; previous.parent = null; parent.children.remove(previous); fix(this); parent.updateRemove(tree); } else if (next != null && (next.children.size() <= (2 * tree.minDegree - 1) / 2 || next.children.size() <= 2)) { for (int i = 0; i < next.children.size(); i++) { Node child = next.children.get(i); children.add(child); child.parent = this; } next.children = null; next.entries = null; next.parent = null; parent.children.remove(next); fix(this); parent.updateRemove(tree); } } } } } void remove(String key, BPlusTree tree) { leafNode.remove(key); if (isLeaf) { if (!contains(key)) return; if (isRoot) remove(key); else { if (entries.size() > (2 * tree.minDegree - 1) / 2 && entries.size() > 2) remove(key); else { if (previous != null && previous.entries.size() > (2 * tree.minDegree - 1) / 2 && previous.entries.size() > 2 && previous.parent == parent) { int size = previous.entries.size(); SimpleEntry<String, String> entry = previous.entries.get(size - 1); previous.entries.remove(entry); entries.add(0, entry); remove(key); } else if (next != null && next.entries.size() > (2 * tree.minDegree - 1) / 2 && next.entries.size() > 2 && next.parent == parent) { SimpleEntry<String, String> entry = next.entries.get(0); next.entries.remove(entry); entries.add(entry); remove(key); } else if (previous != null && (previous.entries.size() <= (2 * tree.minDegree - 1) / 2 || previous.entries.size() <= 2) && previous.parent == parent) { for (int i = previous.entries.size() - 1; i >= 0; i--) entries.add(0, previous.entries.get(i)); remove(key); previous.parent = null; previous.entries = null; parent.children.remove(previous); if (previous.previous != null) { Node temp = previous; temp.previous.next = this; previous = temp.previous; temp.previous = null; temp.next = null; } else { previous.next = null; previous = null; } } else if (next != null && (next.entries.size() <= (2 * tree.minDegree - 1) / 2 || next.entries.size() <= 2) && next.parent == parent) { entries.addAll(next.entries); remove(key); next.parent = null; next.entries = null; parent.children.remove(next); if (next.next != null) { Node temp = next; temp.next.previous = this; next = temp.next; temp.previous = null; temp.next = null; } else { next.previous = null; next = null; } } } parent.updateRemove(tree); } } else if (key.compareTo(entries.get(0).getKey()) <= 0) children.get(0).remove(key, tree); else if (key.compareTo(entries.get(entries.size() - 1).getKey()) >= 0) children.get(children.size() - 1).remove(key, tree); else for (int i = 0; i < entries.size(); i++) if (entries.get(i).getKey().compareTo(key) <= 0 && entries.get(i + 1).getKey().compareTo(key) > 0) { children.get(i).remove(key, tree); break; } } private boolean contains(String key) { for (SimpleEntry<String, String> entry : entries) if (entry.getKey().compareTo(key) == 0) return true; return false; } private void remove(String key) { int index = -1; for (int i = 0; i < entries.size(); i++) if (entries.get(i).getKey().compareTo(key) == 0) { index = i; break; } if (index != -1) entries.remove(index); } } }
C
UTF-8
795
2.75
3
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> /* * redis-cli del foo; gcc -o test test.c && ./test redis-cli set foo bar;echo $?;redis-cli get foo;rm -rf test */ int main(int argc, char *argv[]) { int r, child_status; pid_t child_pid = vfork(); char *prog_argv[5]; prog_argv[0] = "/usr/bin/redis-cli"; prog_argv[1] = "set"; prog_argv[2] = "foo"; prog_argv[3] = "bar"; prog_argv[4] = NULL; if (child_pid == 0) { execvp(prog_argv[0], prog_argv); printf("Unknown command\n"); _exit(1); } else { child_pid = waitpid(-1, &child_status, WUNTRACED); } if (WIFEXITED(child_status) || WIFSIGNALED(child_status)) _exit(EXIT_SUCCESS); _exit(1); }
C++
UTF-8
680
3.390625
3
[]
no_license
class Solution { public: int countNumbersWithUniqueDigits(int n) { if (n < 0) return 0; if (n == 0) return 1; if (n == 1) return 10; int cur = 9, k = 9, res = 10; //cur为位数为i的不含重复位的数字,res为总数 for (int i = 2; i <= n && k > 0; ++ i) { cur = cur * k; res += cur; k -= 1; } return res; } }; //[0, 10^n)内不含重复位的数字 //排列组合 time O(n) space O(1) //n = 1 --> 0 - 9 //n = 2 --> 10 12 13 ... 19 ... 91 92 ... 98 --> 9 * 9 //n = 3 -- > 9(不能为0) * 9(不能与第一位相同) * 8(不能与前两位相同) //so on
Markdown
UTF-8
3,213
3.015625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "Propri&#233;t&#233;s et arguments | Microsoft Docs" ms.custom: "" ms.date: "03/30/2017" ms.prod: ".net-framework" ms.reviewer: "" ms.suite: "" ms.tgt_pltfrm: "" ms.topic: "article" ms.assetid: 14651389-4a49-4cbb-9ddf-c83fdc155df1 caps.latest.revision: 3 author: "Erikre" ms.author: "erikre" manager: "erikre" caps.handback.revision: 3 --- # Propri&#233;t&#233;s et arguments Plusieurs options sont disponibles pour passer des données dans une activité.En plus d'utiliser <xref:System.Activities.InArgument>, il est également possible de développer des activités qui reçoivent des données à l'aide des propriétés CLR standard ou des propriétés <xref:System.Activities.ActivityAction> publiques.Cette rubrique explique comment sélectionner le type de méthode approprié. ## Utilisation des propriétés CLR Lors du passage des données dans une activité, les propriétés CLR \(c'est\-à\-dire, les méthodes publiques qui utilisent des routines Get et Set pour exposer des données\) sont l'option qui a le plus de restrictions.La valeur d'un paramètre passé dans une propriété CLR doit être connue lorsque la solution est compilée ; cette valeur sera la même pour chaque instance du workflow.Ainsi, une valeur passée dans une propriété CLR est semblable à une constante définie dans le code ; cette valeur ne peut pas changer pendant la durée de vie de l'activité, et ne peut pas être modifiée pour plusieurs instances de l'activité.<xref:System.Activities.Expressions.InvokeMethod%601.MethodName%2A> est un exemple de propriété CLR exposée par une activité ; le nom de méthode que l'activité appelle ne peut pas être modifié en fonction de conditions d'exécution, et sera identique pour toutes les instances de l'activité. ## Utilisation des arguments Les arguments doivent être utilisés lorsque les données ne sont évaluées qu'une fois pendant la durée de vie de l'activité ; c'est\-à\-dire que sa valeur ne changera pas pendant la durée de vie de l'activité, mais la valeur peut être différente pour différentes instances de l'activité.<xref:System.Activities.Statements.If.Condition%2A> est un exemple de valeur qui est évaluée une seule fois ; par conséquent, elle est définie comme argument.<xref:System.Activities.Statements.WriteLine.Text%2A> est un autre exemple d'une méthode qui doit être définie comme argument, car elle n'est évaluée qu'une seule fois pendant l'exécution de l'activité, mais elle peut être différent pour plusieurs instances de l'activité. ## Utilisation d'ActivityAction Lorsque des données doivent être évaluées plusieurs fois au cours de la durée de vie de l'exécution d'une activité, une <xref:System.Activities.ActivityAction> doit être utilisée.Par exemple, la propriété <xref:System.Activities.Statements.While.Condition%2A> est évaluée pour chaque itération de la boucle <xref:System.Activities.Statements.While> .Si un <xref:System.Activities.InArgument> était utilisé dans ce but, la boucle ne se terminerait jamais, puisque l'argument ne serait pas réévalué pour chaque itération et retournerait toujours le même résultat.
PHP
UTF-8
2,117
2.609375
3
[]
no_license
<?php /** * Smarty plugin * * Kept for XOOPS 2.0 backward compatibility only !!! * * Use the new xotpl: handler to access XOOPS templates * ------------------------------------------------------------- * File: resource.db.php * Type: resource * Name: db * Purpose: Fetches templates from a database * ------------------------------------------------------------- * @package xoops20 * @deprecated */ function smarty_resource_xotpl_source($tpl_name, &$tpl_source, &$smarty) { if ( $tplPath = smarty_resource_xotpl_getpath( $tpl_name, $smarty ) ) { if ( $tpl_source = file_get_contents( $tplPath ) ) { $smarty->realTemplatePath = $tplPath; return true; } } return false; } function smarty_resource_xotpl_timestamp($tpl_name, &$tpl_timestamp, &$smarty) { if ( $tplPath = smarty_resource_xotpl_getpath( $tpl_name, $smarty ) ) { if ( $tpl_timestamp = filemtime( $tplPath ) ) { return true; } } return false; } function smarty_resource_xotpl_secure($tpl_name, &$smarty) { return true; } function smarty_resource_xotpl_trusted($tpl_name, &$smarty) { return false; } function smarty_resource_xotpl_getpath( $tplName, &$smarty ) { global $xoops; if ( $smarty->currentTheme ) { $name = str_replace( '/templates/', '/', $tplName ); $themed = $smarty->currentTheme->resourcePath( $name ); if ( substr( $themed, 0, 7 ) == 'themes/' ) { $tplName = $themed; } else { if ( false !== ( $pos = strrpos( $tplName, '.' ) ) ) { $name = substr( $tplName, 0, $pos ); $ext = substr( $tplName, $pos ); $name = ( $ext == '.xotpl' ) ? "$name.html" : "$name.xotpl"; $name = str_replace( '/templates/', '/', $name ); // If the template is not in the theme folder, // check if it's not here, but with a different extension $themed = $smarty->currentTheme->resourcePath( $name ); if ( substr( $themed, 0, 7 ) == 'themes/' ) { $tplName = $themed; } } } } //echo $xoops->path( $tplName ) . "<br />\n"; return $xoops->path( $tplName ); } ?>
Ruby
UTF-8
2,928
3.078125
3
[]
no_license
require "rubygems" require "sequel" #require 'mysql2' #require 'data_objects' #================================= connect to an in-memory database DB = Sequel.sqlite # create an items table DB.create_table :items do primary_key :id String :name Float :price end # create a dataset from the items table items = DB[:items] # populate the table items.insert(:name => 'abc', :price => rand * 100) items.insert(:name => 'def', :price => rand * 100) items.insert(:name => 'ghi', :price => rand * 100) # print out the number of records puts "* Using sequel - SQLite => Item count: #{items.count}" # print out the average price #puts "The average price is: #{items.avg(:price)}" #================================== using Sequel DBmysql = Sequel.connect(:adapter=>'mysql2', :host=>'localhost', :database=>'whichs', :user=>'quantv', :password=>'xUqYEcsofvvB', :encoding=>'utf8') #=> OK #DBmysql = Sequel.connect('do:mysql://quantv:xUqYEcsofvvB@localhost/whichs') #=> can require data_objects, mysql2: chi lay duoc cau truc bang, ko lay duoc du lieu ??? puts "* Using Sequel - gem mysql2" ds = DBmysql.fetch("SELECT * FROM users where id in (1,2)") ds.each{|r| puts r} #ds.each{|r| puts "Username : " + r[:username].to_s} =begin DBmysql.fetch("SELECT * FROM users where id = 1") do |row| puts row.to_s end =end insert_ds = DBmysql["INSERT INTO users (username, email) VALUES (?, ?)", 'newUser' + Time.now.strftime("_%M_%S"), Time.now.strftime("_%H_%M_%S") + '@yahoo.com'] update_ds = DBmysql["UPDATE users SET email = ? WHERE id = ?", Time.now.strftime("_%H_%M_%S") + '@g.com', '1'] delete_ds = DBmysql["DELETE FROM users WHERE id >= ?", '14'] newId = insert_ds.insert count_affectRows_u = update_ds.update #count_affectRows_d = delete_ds.delete #puts "count_affectRows_d: " + count_affectRows_d.to_s puts "count_affectRows_u: " + count_affectRows_u.to_s puts "newId: " + newId.to_s #================================== using gem mysql2 # su dung api thuan cua mysql2 => OK puts "* Using gem mysql2" client = Mysql2::Client.new(:host=>'localhost', :database=>'whichs', :username=>'quantv', :password=>'xUqYEcsofvvB') results = client.query("SELECT * FROM users where id = 1") results.each do |row| puts "ID : " + row["id"].to_s if row["username"] puts "Username : " + row["username"].to_s end end =begin # USING SEQUEL WITH MODEL where{column =~ nil} Sequel.expr(:column1=>1) | {:column2=>2} Sequel.|({:column1=>1}, {:column2=>2}) Sequel.or(:column1=>1, :column2=>2) Sequel.negate(:column1=>1, :column2=>2) # (("column1" != 1) AND ("column2" != 2)) DB[:albums].exclude(:column1=>1, :column2=>2) # SELECT * FROM "albums" WHERE (("column" != 1) OR ("column2" != 2)) UserTable.find(:name=>'Bob') # SELECT * FROM artists WHERE (name = 'Bob') LIMIT 1 UserTable.find{name > 'M'} # SELECT * FROM artists WHERE (name > 'M') LIMIT 1 =end
Java
ISO-8859-1
816
3.703125
4
[]
no_license
package eins; public class ObjectSortieren implements Comparable{ /* * Bei Zahlen oder bei Strings ist es uns klar, wie sie sortiert werden * mssen * * Wie ist es bei z.B. Mitarbeitern oder Fahrzeugen? * Um solche Objekte vergleichen zu knnen mssen sie das * Comparable-Interface implementieren. * * Das Interface hat eine Methode: */ @Override public int compareTo(Object other) { /* * compareTo * - gibt 0 zurck, wenn beide Objekte gleich sind * - gibt einen Wert grer 0 zurck, wenn dieses Objekt * weiter hinten einsortiert werden soll (grer ist) * - gibt einen Wert kleiner 0 zurck, wenn dieses Objekt kleiner ist * * Den genauen Vergleichsmechanismus enthlt die compareTo()-Methode */ return 0; } }
Markdown
UTF-8
1,145
2.71875
3
[]
no_license
Welcome to the Top 20 practice project The project is a "Top 20" music voting application. The user will add artists, then add songs. Then the user will be asked to submit a vote for each song. The following "Tops" can be displayed: * The most popular song ever * the most popular artist ever * The most popular song and artist of the last week. A week is defined as a period from Monday to Sunday. The top will count the votes from the week that just ended. Constraints You need to use [Grails](http://grails.org), the Groovy language, the GSP language for the Web templates, and MySQL as the data store. Concerns that your solution must address: * Separation of concerns between model, view, controller, and service layer. * Tests * Validation * Ensuring data integrity * Database schema creation and migration Not a concern, i.e. don't worry about these: * Authentication and authorization * Preventing vote fraud Future concerns, not to be addressed right now, but intended to help you create a better design: * How would you add support for a mobile UI? * How big does your test suite need to be, to ensure maximum code coverage?
PHP
UTF-8
720
3.640625
4
[]
no_license
<?php namespace Brain\Games\Gcd; use Brain\Games\Engine; function gcd(int $num1, int $num2): int { $result = 1; $limit = $num1 < $num2 ? $num1 : $num2; for ($i = 2; $i <= $limit; $i++) { if ($num1 % $i === 0 && $num2 % $i === 0) { $result = $i; } } return $result; } function run(): void { $description = 'Find the greatest common divisor of given numbers.'; $data = function (): array { $randNum1 = rand(1, 10); $randNum2 = rand(1, 10); $question = "{$randNum1} {$randNum2}"; $answer = gcd($randNum1, $randNum2); return ['question' => $question, 'answer' => $answer]; }; Engine\render($description, $data); }
TypeScript
UTF-8
6,483
3.109375
3
[]
no_license
namespace Aufgabe05 { //Erstelle Interface interface Produkt { bild: string; preis: string; titel: string; beschreibung: string; } //Produkte erstellen >>> "Tische" const tisch1: Produkt = { bild: "images/Tische/Tisch1.png", preis: "100", titel: "Tisch 1", beschreibung: "Das ist eine Beschreibung." }; const tisch2: Produkt = { bild: "images/Tische/Tisch2.jpg", preis: "200", titel: "Tisch 2", beschreibung: "Das ist eine Beschreibung." }; const tisch3: Produkt = { bild: "images/Tische/Tisch3.jpg", preis: "300", titel: "Tisch 3", beschreibung: "Das ist eine Beschreibung." }; const tisch4: Produkt = { bild: "images/Tische/Tisch4.jpg", preis: "400", titel: "Tisch 4", beschreibung: "Das ist eine Beschreibung." }; const tisch5: Produkt = { bild: "images/Tische/Tisch5.png", preis: "500", titel: "Tisch 5", beschreibung: "Das ist eine Beschreibung." }; const tisch6: Produkt = { bild: "images/Tische/Tisch6.jpg", preis: "600", titel: "Tisch 6", beschreibung: "Das ist eine Beschreibung." }; //Produkte erstellen >>> "Stühle" const stuhl1: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "50", titel: "Stuhl 1", beschreibung: "Das ist eine Beschreibung." }; const stuhl2: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "100", titel: "Stuhl 2", beschreibung: "Das ist eine Beschreibung." }; const stuhl3: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "150", titel: "Stuhl 3", beschreibung: "Das ist eine Beschreibung." }; const stuhl4: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "200", titel: "Stuhl 4", beschreibung: "Das ist eine Beschreibung." }; const stuhl5: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "250", titel: "Stuhl 5", beschreibung: "Das ist eine Beschreibung." }; const stuhl6: Produkt = { bild: "images/Stühle/Stuhl1.png", preis: "300", titel: "Stuhl 6", beschreibung: "Das ist eine Beschreibung." }; // In Array speichern let artikelStühle: Produkt[] = [stuhl1, stuhl2, stuhl3, stuhl4, stuhl5, stuhl6]; let artikelTische: Produkt[] = [tisch1, tisch2, tisch3, tisch4, tisch5, tisch6]; //Klasse mit all Inhalt Tische let divinhalttisch: HTMLElement = document.createElement("div"); divinhalttisch.setAttribute("class", "main-tische"); //Klasse erschaffen let Tischediv: HTMLElement = document.createElement("div"); Tischediv.setAttribute("class", "flex-container"); divinhalttisch.appendChild(Tischediv); //Geht mit Schleife alle Produkte durch for (let i: number = 0; i < artikelTische.length; i++) { //Jeder neue Artikel wird in Klasse artikel gespeichern let divElement: HTMLElement = document.createElement("div"); divElement.setAttribute("class", "flex-item"); Tischediv.appendChild(divElement); //Bilder let bildElement: HTMLElement = document.createElement("img"); bildElement.setAttribute("src", artikelTische[i].bild); bildElement.setAttribute("class", "product-image"); divElement.appendChild(bildElement); //Preis let preiselement: HTMLElement = document.createElement("i"); divElement.appendChild(preiselement); preiselement.innerHTML = artikelTische[i].preis; //Titel let titelElement: HTMLElement = document.createElement("h3"); divElement.appendChild(titelElement); titelElement.innerHTML = artikelTische[i].titel; //Beschreibung let beschreibungElement: HTMLElement = document.createElement("p"); divElement.appendChild(beschreibungElement); beschreibungElement.innerHTML = artikelTische[i].beschreibung; //Kaufen Button let buttonElement: HTMLElement = document.createElement("button"); buttonElement.setAttribute("class", "KaufenButtonClass"); buttonElement.innerHTML = "Kaufen"; divElement.appendChild(buttonElement); } //Den ganzen Inhalt oben in den html main Tag hinzufügen document.getElementById("main-tische")?.appendChild(divinhalttisch); //Klasse mit all Inhalt Stühle let divinhaltstuhl: HTMLElement = document.createElement("div"); divinhaltstuhl.setAttribute("class", "main-stühle"); //Klasse erschaffen let Stühlediv: HTMLElement = document.createElement("div"); Stühlediv.setAttribute("class", "flex-container"); divinhaltstuhl.appendChild(Stühlediv); for (let i: number = 0; i < artikelStühle.length; i++) { //Jeder neue Artikel wird in Klasse artikel gespeichern let divElement: HTMLElement = document.createElement("div"); divElement.setAttribute("class", "flex-item"); Stühlediv.appendChild(divElement); //Bilder let bildElement: HTMLElement = document.createElement("img"); bildElement.setAttribute("src", artikelStühle[i].bild); bildElement.setAttribute("class", "product-image"); divElement.appendChild(bildElement); //Preis let preiselement: HTMLElement = document.createElement("i"); divElement.appendChild(preiselement); preiselement.innerHTML = artikelStühle[i].preis; //Titel let titelElement: HTMLElement = document.createElement("h3"); divElement.appendChild(titelElement); titelElement.innerHTML = artikelStühle[i].titel; //Beschreibung let beschreibungElement: HTMLElement = document.createElement("p"); divElement.appendChild(beschreibungElement); beschreibungElement.innerHTML = artikelStühle[i].beschreibung; //Kaufen Button let buttonElement: HTMLElement = document.createElement("button"); buttonElement.setAttribute("class", "KaufenButtonClass"); buttonElement.innerHTML = "Kaufen"; divElement.appendChild(buttonElement); } //Den ganzen Inhalt oben in den html main Tag hinzufügen document.getElementById("main-stühle")?.appendChild(divinhaltstuhl); }
C++
UTF-8
2,437
2.765625
3
[ "MIT" ]
permissive
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_COMMON_INIFILE_H #define VSNRAY_COMMON_INIFILE_H 1 #include <cstdint> #include <fstream> #include <map> #include <string> #include <utility> #include "export.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // Very basic ini file parser // class inifile { public: using key_type = std::string; struct value_type { std::string section; std::string value; }; enum error_code { Ok, ParseError, NonExistent, MultipleEntries }; public: VSNRAY_COMMON_EXPORT inifile(std::string filename); VSNRAY_COMMON_EXPORT bool good() const; VSNRAY_COMMON_EXPORT error_code get_bool(std::string key, bool& value); VSNRAY_COMMON_EXPORT error_code get_int8(std::string key, int8_t& value); VSNRAY_COMMON_EXPORT error_code get_int16(std::string key, int16_t& value); VSNRAY_COMMON_EXPORT error_code get_int32(std::string key, int32_t& value); VSNRAY_COMMON_EXPORT error_code get_int64(std::string key, int64_t& value); VSNRAY_COMMON_EXPORT error_code get_uint8(std::string key, uint8_t& value); VSNRAY_COMMON_EXPORT error_code get_uint16(std::string key, uint16_t& value); VSNRAY_COMMON_EXPORT error_code get_uint32(std::string key, uint32_t& value); VSNRAY_COMMON_EXPORT error_code get_uint64(std::string key, uint64_t& value); VSNRAY_COMMON_EXPORT error_code get_float(std::string key, float& value); VSNRAY_COMMON_EXPORT error_code get_double(std::string key, double& value); VSNRAY_COMMON_EXPORT error_code get_long_double(std::string key, long double& value); VSNRAY_COMMON_EXPORT error_code get_string(std::string key, std::string& value, bool remove_quotes = false); VSNRAY_COMMON_EXPORT error_code get_vec3i(std::string key, int32_t& x, int32_t& y, int32_t& z); VSNRAY_COMMON_EXPORT error_code get_vec3ui(std::string key, uint32_t& x, uint32_t& y, uint32_t& z); VSNRAY_COMMON_EXPORT error_code get_vec3f(std::string key, float& x, float& y, float& z); VSNRAY_COMMON_EXPORT error_code get_vec3d(std::string key, double& x, double& y, double& z); private: std::ifstream file_; std::multimap<key_type, value_type> entries_; bool good_ = false; }; } // visionaray #endif // VSNRAY_COMMON_INIFILE_H
Java
UTF-8
1,534
2.453125
2
[]
no_license
package com.mobile.pickup; import android.support.test.runner.AndroidJUnit4; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.mobile.pickup.Model.Customer; import org.junit.Test; import org.junit.runner.RunWith; /** * Created by Yanqing on 4/5/17. */ @RunWith(AndroidJUnit4.class) public class CustomerManagerTest { // test addCustomer function and getters of Customer class @Test public void addCustomer() throws Exception { CustomerManager tCustomerManager = new CustomerManager(); Customer tCustomer = tCustomerManager.addCustomer("tCustomer"); assert (tCustomer.getID() != null); assert (tCustomer.getCustomerName().equals("tCustomer")); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference customerRef = database.getReference("Customer"); customerRef.child(tCustomer.getID()).removeValue(); } // test removeCustomer function after addCustomer() with raw firebase query @Test public void removeCustomer() throws Exception { CustomerManager tCustomerManager = new CustomerManager(); Customer tCustomer = tCustomerManager.addCustomer("tCustomer"); tCustomerManager.removeCustomer(tCustomer.getID()); FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference customerRef = database.getReference("Customer"); assert (customerRef.child(tCustomer.getID()).equals(null)); } }
Ruby
UTF-8
134
3.15625
3
[]
no_license
=begin Unique Strings by Vladislav Trotsenko. =end def uniq_count(string) string.chars.permutation.map(&:join).uniq.size end uniq_count('aba')
C++
UTF-8
19,162
2.640625
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
/*======================================================================= Copyright (c) 2018-2019 Marcelo Kallmann. This software is distributed under the Apache License, Version 2.0. All copies must contain the full copyright notice licence.txt located at the base folder of the distribution. =======================================================================*/ # include <stdlib.h> # include <sig/gs_graph.h> # include <sig/gs_string.h> # include <sig/gs_heap.h> # include <sig/gs_queue.h> //# define GS_USE_TRACE1 // Node operations //# define GS_USE_TRACE2 // Shortest path search # include <sig/gs_trace.h> //============================== GsGraphNode ===================================== GsGraphNode::GsGraphNode () { _index=0; _graph=0; _blocked=0; } GsGraphNode::~GsGraphNode () { if ( _graph ) { GsManagerBase* lman = _graph->link_class_manager(); while ( _links.size()>0 ) lman->free ( _links.pop() ); } } GsGraphLink* GsGraphNode::linkto ( GsGraphNode* n, float cost ) { GsGraphLink* l = (GsGraphLink*) _graph->link_class_manager()->alloc(); l->_node = n; l->_index = 0; l->_cost = cost; _links.push () = l; return l; } void GsGraphNode::unlink () { GS_TRACE1 ( "GsGraphNode::unlink..." ); GsManagerBase* lman = _graph->link_class_manager(); while ( _links.size() ) { GsGraphNode* n = _links.top()->node(); // remove link this => n: lman->free ( _links.pop() ); // remove link n => this int lnt = n->search_link(this); if ( lnt>=0 ) { lman->free ( n->_links[lnt] ); n->_links[lnt] = n->_links.pop(); // fast remove } } GS_TRACE1 ( "Done." ); } void GsGraphNode::unlink ( int li ) { GsManagerBase* lman = _graph->link_class_manager(); lman->free ( _links[li] ); _links[li] = _links.pop(); } int GsGraphNode::search_link ( GsGraphNode* n ) const { int i; for ( i=_links.size()-1; i>=0; i-- ) if ( _links[i]->node()==n ) break; return i; } void GsGraphNode::output ( GsOutput& o ) const { float cost; int i, max; max = _links.size()-1; if ( max<0 ) return; GsManagerBase* lman = _graph->link_class_manager(); o<<'('; for ( i=0; i<=max; i++ ) { // output blocked status o << _links[i]->_blocked << gspc; // output index to target node o << _links[i]->_node->_index << gspc; // output link cost cost = _links[i]->_cost; if ( cost==GS_TRUNC(cost) ) o << int(cost); else o << cost; // output user data o << gspc; lman->output(o,_links[i]); if ( i<max ) o<<gspc; } o<<')'; } //============================== GsGraphPathTree =============================================== class GsGraphPathTree { public : struct Node { int parent; GsGraphNode* node; GsGraphLink* pnlink; }; struct Leaf { int l; int d; float hcost; }; // the leaf index in N, its depth, and dist to goal GsArray<Node> N; GsHeap<Leaf,float> Q; GsQueue<Leaf> B; GsGraphBase* graph; GsGraphNode* closest; int iclosest; float cdist; float (*hdfunc) ( const GsGraphNode*, const GsGraphNode*, void* udata ); float (*gdfunc) ( const GsGraphNode*, const GsGraphNode*, void* udata ); void *udata; bool bidirectional_block; public : GsGraphPathTree () { bidirectional_block = false; } void init ( GsGraphBase* g, GsGraphNode* s, GsGraphNode* t ) { N.size(1); N[0].parent = -1; N[0].pnlink = 0; N[0].node = s; cost(s) = 0; // cost to come g->mark ( s ); Leaf l; l.l = l.d = 0; l.hcost=hdfunc? hdfunc(s,t,udata):0; Q.init (); Q.insert ( l, 0 ); graph = g; hdfunc = 0; udata = 0; closest = 0; iclosest = 0; cdist = 0; } float& cost ( int i ) { return N[i].node->fparam; } float& cost ( GsGraphNode* n ) { return n->fparam; } bool expand_lowest_cost_leaf ( GsGraphNode* goalnode ) { int ui = Q.top().l; int nextd = Q.top().d+1; GsGraphNode* u = N[ui].node; if ( cost(u)+Q.top().hcost<Q.lowest_cost() ) // skip reduced nodes { GS_TRACE2 ( "reduced node: "<<cost(u)<<"<"<<(Q.lowest_cost()-Q.top().hcost)<<"..." ); Q.remove (); return false; } else { GS_TRACE2 ( "expanding node with cost "<<cost(u)<<"..." ); Q.remove (); } if ( u==goalnode ) { N.size(ui+1); return true; } Leaf leaf; float dg, newcost; const GsArray<GsGraphLink*>& ul = u->links(); for ( int i=0,s=ul.size(); i<s; i++ ) { //gsout<<a.size()<<gsnl; GsGraphLink* l = ul[i]; GsGraphNode* v = l->node(); if ( l->blocked() || v->blocked() ) continue; if ( bidirectional_block ) { GsGraphLink* vul=v->link(u); if(vul&&vul->blocked()) continue; } newcost = cost(u) + l->cost(); if ( graph->marked(v) && newcost>=cost(v) ) continue; // reached v with worse cost graph->mark ( v ); cost(v) = newcost; N.push(); N.top().parent = ui; N.top().pnlink = l; N.top().node = v; leaf.l = N.size()-1; leaf.d = nextd; if ( gdfunc ) { dg = gdfunc ( v, goalnode, udata ); if ( !closest || dg<cdist ) { closest=v; iclosest=N.size()-1; cdist=dg; } } if ( hdfunc ) { if ( hdfunc!=gdfunc ) dg = hdfunc ( v, goalnode, udata ); leaf.hcost = dg; Q.insert ( leaf, cost(v)+dg ); } else { leaf.hcost = 0; Q.insert ( leaf, cost(v) ); } } return false; } void bfs_init ( GsGraphBase* g, GsGraphNode* s, GsGraphNode* t ) { N.size(1); N[0].parent = -1; N[0].node = s; cost(s) = 0; // cost to come g->mark ( s ); Leaf l; l.l = l.d = 0; B.init (); B.insert ()=l; graph = g; } bool bfs_expand ( GsGraphNode* goalnode ) { int ui = B.first().l; int nextd = B.first().d+1; GsGraphNode* u = N[ui].node; B.remove (); Leaf leaf; const GsArray<GsGraphLink*>& ul = u->links(); for ( int i=0,s=ul.size(); i<s; i++ ) { //gsout<<a.size()<<gsnl; GsGraphLink* l = ul[i]; GsGraphNode* v = l->node(); if ( v==goalnode ) { N.size(ui+1); return true; } if ( graph->marked(v) || l->blocked() || v->blocked() ) continue; if ( bidirectional_block ) { GsGraphLink* vul=v->link(u); if(vul&&vul->blocked()) continue; } cost(v) = cost(u) + l->cost(); graph->mark ( v ); N.push(); N.top().parent = ui; N.top().node = v; leaf.l = N.size()-1; leaf.d = nextd; B.insert ()=leaf; } return false; } void make_path ( float* cost, int i, GsArray<GsGraphNode*>& path, GsArray<GsGraphLink*>* links ) { if ( cost ) *cost = N[i].node->fparam; path.size(0); if ( links ) links->size(0); while ( i>=0 ) { path.push() = N[i].node; if ( links ) links->push() = N[i].pnlink; i = N[i].parent; } path.reverse(); if ( links ) { links->pop(); links->reverse(); } } }; //============================== GsGraphBase =============================================== # define MARKFREE 0 # define MARKING 1 # define INDEXING 2 GsGraphBase::GsGraphBase ( GsManagerBase* nm, GsManagerBase* lm ) :_nodes(nm) { _curmark = 1; _mark_status = MARKFREE; _pt = 0; // allocated only if shortest path is called _lman = lm; _lman->ref(); // nm is managed by the list _nodes _leave_indices_after_save = 0; } GsGraphBase::~GsGraphBase () { _nodes.init (); // Important: this ensures that _lman is used before _lman->unref() delete _pt; _lman->unref(); } void GsGraphBase::init () { _nodes.init(); _curmark = 1; _mark_status = MARKFREE; } void GsGraphBase::compress () { if ( _nodes.empty() ) return; _nodes.gofirst(); do { _nodes.cur()->compress(); } while ( _nodes.notlast() ); } int GsGraphBase::num_links () const { if ( _nodes.empty() ) return 0; int n=0; GsGraphNode* first = _nodes.first(); GsGraphNode* cur = first; do { n += cur->num_links(); cur = cur->next(); } while ( cur!=first ); return n; } //----------------------------------- marking -------------------------------- static void _errormsg ( const char* s1, int code ) { const char* s2= code==0? "is locked" : code==1? "marking is not active" : code==2? "indexing is not active" : "error"; gsout.fatal ( "GsGraphBase::%s: %s!", s1, s2 ); } void GsGraphBase::begin_marking () const { if ( _mark_status!=MARKFREE ) _errormsg("begin_mark()",0); _mark_status = MARKING; if ( _curmark==gsuintmax ) _normalize_mark (); else _curmark++; } void GsGraphBase::end_marking () const { _mark_status=MARKFREE; } bool GsGraphBase::marked ( GsGraphNode* n ) const { if ( _mark_status!=MARKING ) _errormsg("marked(n)",1); return n->_index==_curmark; } void GsGraphBase::mark ( GsGraphNode* n ) const { if ( _mark_status!=MARKING ) _errormsg("mark(n)",1); n->_index = _curmark; } void GsGraphBase::unmark ( GsGraphNode* n ) const { if ( _mark_status!=MARKING ) _errormsg("unmark(n)",1); n->_index = _curmark-1; } bool GsGraphBase::marked ( GsGraphLink* l ) const { if ( _mark_status!=MARKING ) _errormsg("marked(l)",1); return l->_index==_curmark? true:false; } void GsGraphBase::mark ( GsGraphLink* l ) const { if ( _mark_status!=MARKING ) _errormsg("mark(l)",1); l->_index = _curmark; } void GsGraphBase::unmark ( GsGraphLink* l ) const { if ( _mark_status!=MARKING ) _errormsg("unmark(l)",1); l->_index = _curmark-1; } //----------------------------------- indexing -------------------------------- void GsGraphBase::begin_indexing () const { if ( _mark_status!=MARKFREE ) _errormsg("begin_indexing()",0); _mark_status = INDEXING; } void GsGraphBase::end_indexing () const { _normalize_mark(); _mark_status=MARKFREE; } gsuint GsGraphBase::index ( GsGraphNode* n ) const { if ( _mark_status!=INDEXING ) _errormsg("index(n)",2); return n->_index; } void GsGraphBase::index ( GsGraphNode* n, gsuint i ) const { if ( _mark_status!=INDEXING ) _errormsg("index(n,i)",2); n->_index = i; } gsuint GsGraphBase::index ( GsGraphLink* l ) const { if ( _mark_status!=INDEXING ) _errormsg("index(l)",2); return l->_index; } void GsGraphBase::index ( GsGraphLink* l, gsuint i ) const { if ( _mark_status!=INDEXING ) _errormsg("index(l,i)",2); l->_index = i; } //----------------------------------- construction -------------------------------- GsGraphNode* GsGraphBase::insert ( GsGraphNode* n ) { _nodes.insert_next ( n ); n->_graph = this; return n; } GsGraphNode* GsGraphBase::extract ( GsGraphNode* n ) { _nodes.cur(n); return _nodes.extract(); } void GsGraphBase::remove_node ( GsGraphNode* n ) { _nodes.cur(n); _nodes.remove(); } int GsGraphBase::remove_link ( GsGraphNode* n1, GsGraphNode* n2 ) { int i, n=0; while ( true ) { i = n1->search_link(n2); if ( i<0 ) break; n++; n1->unlink(i); } while ( true ) { i = n2->search_link(n1); if ( i<0 ) break; n++; n2->unlink(i); } return n; } void GsGraphBase::link ( GsGraphNode* n1, GsGraphNode* n2, float c ) { n1->linkto(n2,c); n2->linkto(n1,c); } //----------------------------------- get edges ---------------------------------- void GsGraphBase::get_directed_edges ( GsArray<GsGraphNode*>& edges, GsArray<GsGraphLink*>* links ) { edges.sizeres ( 0, num_nodes() ); if ( links ) links->sizeres ( 0, num_nodes() ); int i; GsGraphNode* n; GsListIterator<GsGraphNode> it(_nodes); for ( it.first(); it.inrange(); it.next() ) { n = it.get(); for ( i=0; i<n->num_links(); i++ ) { edges.push() = n; edges.push() = n->link(i)->node(); if ( links ) links->push() = n->link(i); } } } void GsGraphBase::get_undirected_edges ( GsArray<GsGraphNode*>& edges, GsArray<GsGraphLink*>* links ) { edges.sizeres ( 0, num_nodes() ); if ( links ) links->sizeres ( 0, num_nodes() ); int i, li; GsGraphNode* n; GsListIterator<GsGraphNode> it(_nodes); begin_marking(); for ( it.first(); it.inrange(); it.next() ) { n = it.get(); for ( i=0; i<n->links().size(); i++ ) { if ( !marked(n->link(i)) ) { edges.push() = n; edges.push() = n->link(i)->node(); mark ( n->link(i) ); if ( links ) links->push() = n->link(i); li = edges.top()->search_link(n); if ( li>=0 ) mark ( edges.top()->link(li) ); } } } end_marking(); } //----------------------------------- components ---------------------------------- static void _traverse ( GsGraphBase* graph, GsArray<GsGraphNode*>& stack, GsArray<GsGraphNode*>& nodes ) { int i; GsGraphNode *n, *ln; while ( stack.size()>0 ) { n = stack.pop(); graph->mark ( n ); nodes.push() = n; for ( i=0; i<n->num_links(); i++ ) { ln = n->link(i)->node(); if ( !graph->marked(ln) ) stack.push()=ln; } } } void GsGraphBase::get_connected_nodes ( GsGraphNode* source, GsArray<GsGraphNode*>& nodes ) { nodes.size ( num_nodes() ); nodes.size ( 0 ); GsArray<GsGraphNode*>& stack = _buffer; stack.size ( 0 ); begin_marking(); stack.push() = source; _traverse ( this, stack, nodes ); end_marking(); } void GsGraphBase::get_disconnected_components ( GsArray<int>& components, GsArray<GsGraphNode*>& nodes ) { nodes.size ( num_nodes() ); nodes.size ( 0 ); components.size ( 0 ); GsArray<GsGraphNode*>& stack = _buffer; stack.size ( 0 ); GsGraphNode* n; GsListIterator<GsGraphNode> it(_nodes); begin_marking(); for ( it.first(); it.inrange(); it.next() ) { n = it.get(); if ( !marked(n) ) { components.push() = nodes.size(); stack.push() = n; _traverse ( this, stack, nodes ); components.push() = nodes.size()-1; } } end_marking(); } //----------------------------------- shortest path ---------------------------------- bool GsGraphBase::shortest_path ( GsGraphNode* n1, GsGraphNode* n2, GsArray<GsGraphNode*>& path, GsArray<GsGraphLink*>* links, float* cost, float (*hdistf) ( const GsGraphNode*, const GsGraphNode*, void* udata ), float (*gdistf) ( const GsGraphNode*, const GsGraphNode*, void* udata ), void* udata ) { GS_TRACE2 ( "search_shortest_path starting..." ); path.size(0); if ( n1==n2 ) { GS_TRACE2 ( "n1==n2." ); path.push()=n1; return 0; } if ( !_pt ) _pt = new GsGraphPathTree; GS_TRACE2 ( "initializing..." ); begin_marking (); _pt->hdfunc=hdistf; _pt->gdfunc=hdistf; _pt->udata=udata; _pt->init ( this, n1, n2 ); GS_TRACE2 ( "searching..." ); while ( _pt->Q.size() ) { if ( _pt->expand_lowest_cost_leaf(n2) ) break; } end_marking (); if ( _pt->N.top().node==n2 ) // found { _pt->make_path ( cost, _pt->N.size()-1, path, links ); GS_TRACE2 ( "Found! size:"<<path.size()<<" cost:"<<cost ); return true; } else if ( gdistf ) // not found but closest goal available { GS_TRACE2 ( "Closest returned." ); _pt->make_path ( cost, _pt->iclosest, path, links ); return false; } else // not found { GS_TRACE2 ( "Not Found." ); cost = 0; return false; } } bool GsGraphBase::bfs ( GsGraphNode* n1, GsGraphNode* n2, GsArray<GsGraphNode*>& path, GsArray<GsGraphLink*>* links, float* cost, int maxdepth, float maxcost ) { if ( n1==n2 ) return true; begin_marking (); if ( !_pt ) _pt = new GsGraphPathTree; _pt->init ( this, n1, n2 ); bool found = true; bool end = false; while ( !end ) { if ( _pt->B.empty() ) { found=false; break; } // not found! int d = _pt->B.first().d; float c = _pt->cost ( _pt->B.first().l ); if ( maxdepth>0 && d>maxdepth ) break; // max depth reached if ( maxcost>0 && c>maxcost ) break; // max dist reached end = _pt->bfs_expand ( n2 ); } end_marking (); if ( found ) _pt->make_path ( cost, _pt->N.size()-1, path, links ); return found; } void GsGraphBase::bidirectional_block_test ( bool b ) { if ( !_pt ) _pt = new GsGraphPathTree; _pt->bidirectional_block = b; } //------------------------------------- I/O -------------------------------- void GsGraphBase::output ( GsOutput& o ) const { GsListIterator<GsGraphNode> it(_nodes); GsManagerBase* nman = node_class_manager(); // set indices if ( _mark_status!=MARKFREE ) gsout.fatal("GsGraphBase::operator<<(): begin_indexing() is locked!"); gsuint i=0; begin_indexing(); for ( it.first(); it.inrange(); it.next() ) index(it.get(),i++); // print o<<'['; for ( it.first(); it.inrange(); it.next() ) { o << it->index() << gspc; // output node index o << (it->_blocked?'b':'f') << gspc; // output node blocked status nman->output ( o, it.get() ); // output user data if ( it.get()->num_links()>0 ) // output node links (blocked, ids, cost, and udata) { o<<gspc; it->GsGraphNode::output ( o ); } if ( !it.inlast() ) o << gsnl; } o<<']'; if ( !_leave_indices_after_save ) end_indexing(); _leave_indices_after_save = 0; } static void set_blocked ( int& blocked, const char* ltoken ) { // accepts letters or 0/1 integer if ( ltoken[0]=='b' || ltoken[0]=='B' ) // blocked blocked = 1; else if ( ltoken[0]=='f' || ltoken[0]=='F' ) // free blocked = 0; else // should be an integer 0/1 blocked = atoi(ltoken); } void GsGraphBase::input ( GsInput& inp ) { GsArray<GsGraphNode*>& nodes = _buffer; nodes.size(128); nodes.size(0); GsManagerBase* nman = node_class_manager(); GsManagerBase* lman = link_class_manager(); init (); inp.get(); // [ inp.get(); // get node counter (which is not needed) while ( inp.ltoken()[0]!=']' ) { nodes.push() = _nodes.insert_next(); // allocate one node nodes.top()->_graph = this; inp.get(); // get node blocked status set_blocked ( nodes.top()->_blocked, inp.ltoken() ); nman->input ( inp, nodes.top() ); // read node user data inp.get(); // new node counter, or '(', or ']' if ( inp.ltoken()[0]=='(' ) while ( true ) { inp.get(); if ( inp.ltoken()[0]==')' ) { inp.get(); break; } GsArray<GsGraphLink*>& la = nodes.top()->_links; la.push() = (GsGraphLink*) lman->alloc(); set_blocked ( la.top()->_blocked, inp.ltoken() ); // get link blocked status inp.get(); // get id la.top()->_index = inp.ltoken().atoi(); // store id inp.get(); // get cost la.top()->_cost = inp.ltoken().atof(); // store cost lman->input ( inp, la.top() ); } } // now convert indices to pointers: int i, j; for ( i=0; i<nodes.size(); i++ ) { GsArray<GsGraphLink*>& la = nodes[i]->_links; for ( j=0; j<la.size(); j++ ) { la[j]->_node = nodes[ int(la[j]->_index) ]; } } } //---------------------------- private methods -------------------------------- // set all indices (nodes and links) to 0 and curmark to 1 void GsGraphBase::_normalize_mark() const { int i; GsGraphNode* n; if ( _nodes.empty() ) return; _nodes.gofirst(); do { n = _nodes.cur(); n->_index = 0; for ( i=0; i<n->num_links(); i++ ) n->link(i)->_index=0; } while ( _nodes.notlast() ); _curmark = 1; } //============================== end of file ===============================
C#
UTF-8
1,295
2.859375
3
[]
no_license
<Query Kind="Program" /> Dictionary<string, Dictionary<string, int>> graph = new Dictionary<string, Dictionary<string, int>> { {"start", new Dictionary<string, int> {{"a", 6}, {"b", 2}}}, {"a", new Dictionary<string, int> {{"end", 1}}}, {"b", new Dictionary<string, int> {{"a", 3}, {"end", 5}}}, {"end", new Dictionary<string, int>()} }; Dictionary<string, int> costs = new Dictionary<string, int>() {}; Dictionary<string, string> parents = new Dictionary<string, string>(){}; List<string> processed = new List<string>(); void Main() { var node = "start"; var neighbors = graph[node]; foreach (var n in neighbors.Keys) { costs[n] = graph[node][n]; parents[n] = node; } node = FindLowestCostNode(); while (node != null) { var cost = costs[node]; neighbors = graph[node]; foreach (var n in neighbors.Keys) { var newCost = cost + neighbors[n]; if (!costs.ContainsKey(n) || costs[n] > newCost) { costs[n] = newCost; parents[n] = node; } } processed.Add(node); node = FindLowestCostNode(); } costs.Dump(); parents.Dump(); } string FindLowestCostNode() { return costs .Where(x => !processed.Contains(x.Key)) .OrderBy(x => x.Value) .Select(x => x.Key) .FirstOrDefault(); } // Define other methods and classes here
Markdown
UTF-8
778
2.546875
3
[ "MIT" ]
permissive
--- ID: 1894 post_title: Common JavaScript “Gotchas” author: Shwuzzle post_date: 2013-01-20 18:48:31 post_excerpt: "" layout: post published: true aktt_notify_twitter: - 'yes' ratings_users: - "0" ratings_score: - "0" ratings_average: - "0" aktt_tweeted: - "1" --- If you are a beginner to JavaScript you might find this article quite useful. It mentions a few common JavaScript quirks that you may not understand at first, including: details on the global namespace, the <em>this</em> object, knowing the difference between ECMAScript 3 and ECMAScript 5, asynchronous operations, prototypes, and simple JavaScript inheritance. Full Article: <a href="http://www.jblotus.com/2013/01/13/common-javascript-gotchas/">Common JavaScript “Gotchas” (jblotus.com)</a>
Python
UTF-8
247
2.96875
3
[]
no_license
''' * File Name : utility.py * Language : Python * Creation Date : 05-01-2021 * Last Modified : Tue Jan 5 11:51:38 2021 * Created By : David Hanson ''' def multiply(num1, num2): return num1*num2 def divide(num1, num2): return num1/num2
C#
UTF-8
2,187
2.875
3
[ "MIT" ]
permissive
using System; using System.IO; using System.Net; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Updater; using System.Windows; using System.Web; namespace BackRunner { class BRDownloader { public static long currentFileLength = 0; public static long downloadedLength = 0; private MainWindow mainWindow = (MainWindow)Application.Current.MainWindow; public bool downloadFile(string localFilePath,string URL) { bool isSuccess = true; try { using (WebClient wc = new WebClient()) { wc.DownloadFile(new Uri(URL), localFilePath); } } catch (Exception e) { MessageBox.Show(e.ToString()); isSuccess = false; } return isSuccess; } public bool existFile(string URL) { int count = 0; bool isSuccess = true; while (!checkFileExist(URL)) { count++; if (count > 5) { isSuccess = false; break; } } return isSuccess; } private bool checkFileExist(string URL) { HttpWebRequest req = null; HttpWebResponse res = null; try { req = (HttpWebRequest)WebRequest.Create(URL); req.Method = "HEAD"; req.Timeout = 300; res = (HttpWebResponse)req.GetResponse(); return (res.StatusCode == HttpStatusCode.OK); } catch { return false; } finally { //回收资源 if (res != null) { res.Close(); res = null; } if (req != null) { req.Abort(); req = null; } } } } }
JavaScript
UTF-8
1,091
2.84375
3
[ "MIT" ]
permissive
var expect = require('expect.js'); var exclude = require('../util/exclude'); describe('exclude(obj, keys…):Object', function() { it('returns a new object', function() { var a = {}; var b = exclude(a); expect(b).to.be.an('object'); expect(Object.getPrototypeOf(b)).to.equal(Object.prototype); expect(b).to.not.equal(a); }); it('copies all non-excluded properties', function() { var a = {foo: 0, bar: 1, qux: 2, quux: 3}; var b = exclude(a); expect(b).to.eql(a); expect(b).to.not.equal(a); }); it('strips all excluded properties', function() { var a = {foo: 0, bar: 1, qux: 2, quux: 3}; var b = exclude(a, 'bar', 'quux'); expect(b).to.have.property('foo', a.foo); expect(b).to.have.property('qux', a.qux); expect(b).to.not.have.property('bar'); expect(b).to.not.have.property('quux'); }); it('does not modify the original object', function() { var a = {foo: 0, bar: 1, qux: 2, quux: 3}; exclude(a, 'bar', 'quux'); expect(a).to.have.property('bar', 1); expect(a).to.have.property('quux', 3); }); });
Java
UTF-8
3,727
2.796875
3
[]
no_license
/* * This code is part of the project "Audio Analyzer for the Android" * developed for the course CSE 599Y * "Mobile and Cloud Applications for Emerging Regions" * at the University of Washington Computer Science & Engineering * * The goal of this project is to create an audio analyzer that * allows the user to record, play and analyze audio files. * The program plot the waveform of the recording, the spectrogram, * and plot several audio descriptors. * * At the current state the audio descriptors are: * - Spectral Centroid * - Spectral Centroid Variation * - Energy * - Energy Variation * - Zero Crossing * - Zero Crossing Variation * * In addition to this temporal descriptors the total average of them * is presented in numeral format with the duration of the recording, and * the number of samples. * * Otherwise noticed, the code was created by Hugo Solis * hugosg@uw.edu, feel free to contact me if you have any questions. * Dec 16, 2009 * hugosg */ package net.hugo.audioAnalyzer; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; /** * @author hugosg * * This code is an extension and variation of the code in * http://emeadev.blogspot.com/2009/09/raw-audio-manipulation-in-android.html * */ public class Player extends AsyncTask<AudioAnalyzer, Void, Void>{ PlayerListener pl; /** * @param pl * * This class waits for only one listener */ public void addPlayerListener(PlayerListener pl){ this.pl = pl; } @Override protected void onPostExecute(Void result) { //super.onPostExecute(result); synchronized(this){ pl.postPlayer(); } } @Override protected void onPreExecute() { //super.onPreExecute(); synchronized(this){ pl.prePlayer(); } } @Override protected Void doInBackground(AudioAnalyzer... params) { // Get the file we want to playback. File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.pcm"); // Get the length of the audio stored in the file (16 bit so 2 bytes per short) // and create a short array to store the recorded audio. int musicLength = (int)(file.length()/2); short[] music = new short[musicLength]; try { // Create a DataInputStream to read the audio data back from the saved file. InputStream is = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(is); DataInputStream dis = new DataInputStream(bis); // Read the file into the music array. int i = 0; while (dis.available() > 0) { music[i] = dis.readShort(); i++; } // Close the input streams. dis.close(); // Create a new AudioTrack object using the same parameters as the AudioRecord // object used to create the file. AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, //hard coded! not ideal AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, musicLength, AudioTrack.MODE_STREAM); //There is a minor issue. This audio Track player will play the file //until the end without a way to track the location of the reading or the end of playing :-( //at least as we use it here // Start playback audioTrack.play(); // Write the music buffer to the AudioTrack object audioTrack.write(music, 0, musicLength); } catch (Throwable t) { Log.e("AudioTrack","Playback Failed"); } //Log.i("HUGO", "DONE PLAYING"); return null; } }
Java
UTF-8
1,134
3.53125
4
[]
no_license
package thread.concurrent; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * Created by jhui on 2018/3/23. */ public class ThreadFactoryTest { public static void main(String[] args) { MyThreadFactory factory = MyThreadFactory.getInstance(); for (int i = 0; i < 20; i++) { factory.newThread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()); } }).start(); } } static class MyThreadFactory implements ThreadFactory{ private static MyThreadFactory factory = new MyThreadFactory(); private AtomicInteger count = new AtomicInteger(0); private MyThreadFactory(){} public static MyThreadFactory getInstance(){ return factory; } @Override public Thread newThread(Runnable r) { System.out.println("current thread:" + count.intValue()); count.incrementAndGet(); return new Thread(r); } } }
Java
UTF-8
1,247
2.03125
2
[]
no_license
package org.nacos.server.one; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; import com.alibaba.nacos.api.annotation.NacosInjected; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; @SpringBootApplication @EnableDiscoveryClient public class App { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @NacosInjected private NamingService nsamingService; @Value("${server.port}") private int serverPort; @Value("${spring.application.name}") private String applicationName; @PostConstruct public void registerInstance() throws NacosException { nsamingService.registerInstance(applicationName, "127.0.0.1", serverPort); } public static void main( String[] args ) { SpringApplication.run(App.class, args); } }
Java
UTF-8
1,917
2.8125
3
[]
no_license
package com.superfast.cache.main; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import com.superfast.cache.KVStore; import com.superfast.cache.exception.CacheException; import com.superfast.cache.impl.KVStoreFactory; import com.superfast.cache.store.DiskAsyncWriter; import com.superfast.cache.store.DiskStore; import com.superfast.cache.store.DiskStoreFactory; /** * Main method for running a demo of cache operations * @author Shailendra.Kumar2 * */ public class Main { public static void main(String[] args) throws InterruptedException { String mainConfigFilePath = null; if (args.length == 1) mainConfigFilePath = args[0]; else mainConfigFilePath = "D:/cache-store-config.properties"; // externalize the properties Properties props = new Properties(); try { props.load(new FileInputStream(mainConfigFilePath)); } catch (IOException e) { e.printStackTrace(); } String rootFolder = props.getProperty("rootFolder"); DiskStore diskStore = DiskStoreFactory.getDiskStore(rootFolder); String initialCapacity = props.getProperty("initialCapacity"); Integer initCapacity = new Integer(initialCapacity); String loadFactor = props.getProperty("loadFactor"); Float lf = Float.valueOf(loadFactor); KVStore kvStore = KVStoreFactory.getKVStore(initCapacity,lf,diskStore); for( int i=0 ; i< 200;i++){ try { kvStore.put("Shailendra"+i, "My String "+i); } catch (CacheException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // wait for sometime to let all the IO happen before the main program exits. //In a typical non terminating cache server, this will not be needed as the cache //process is supposed to be running infinitely listening for requests for CRUD operation DiskAsyncWriter.awaitTermination(); } }
Java
UTF-8
4,866
2.4375
2
[]
no_license
/* ===================================================================== SortHeaderRenderer.java Created by Claude Duguay Copyright (c) 2002 Taken freely from: http://www.fawcette.com/javapro/2002_08/magazine/columns/visualcomponents/ at the 'download code' link. Heavily modified to use the header's default renderer, but add icons. Also modified to have a bevelled 'pressed' look. ===================================================================== */ package com.limegroup.gnutella.gui.tables; import java.awt.Component; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import com.limegroup.gnutella.gui.themes.ThemeMediator; import com.limegroup.gnutella.gui.themes.ThemeObserver; import com.limegroup.gnutella.gui.themes.ThemeSettings; import com.limegroup.gnutella.util.CommonUtils; public final class SortHeaderRenderer extends DefaultTableCellRenderer implements ThemeObserver { public static Icon ASCENDING; public static Icon DESCENDING; static { updateIcons(); } private static void updateIcons() { if(CommonUtils.isMacOSX() || ThemeSettings.isWindowsTheme()) { ASCENDING = AquaSortArrowIcon.getAscendingIcon(); DESCENDING = AquaSortArrowIcon.getDescendingIcon(); } else { ASCENDING = SortArrowIcon.getAscendingIcon(); DESCENDING = SortArrowIcon.getDescendingIcon(); } } private boolean allowIcon = true; public SortHeaderRenderer() { setHorizontalAlignment(CENTER); setIconTextGap(2); // reduce from the default of 4 pixels setHorizontalTextPosition(LEFT); ThemeMediator.addThemeObserver(this); } public void updateTheme() { updateIcons(); } public void setAllowIcon(boolean allow) { allowIcon = allow; } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { int index = -1; boolean ascending = true; boolean isPressed = false; if (allowIcon && table instanceof JSortTable) { JSortTable sortTable = (JSortTable)table; index = sortTable.getSortedColumnIndex(); ascending = sortTable.isSortedColumnAscending(); isPressed = (sortTable.getPressedColumnIndex() == col); } JLabel renderer = this; if (table != null) { JTableHeader header = table.getTableHeader(); try { if (header != null) { TableCellRenderer tcr = header.getDefaultRenderer(); Component c = tcr.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, col); if(c instanceof JLabel) { renderer = (JLabel)c; renderer.setFont(header.getFont()); renderer.setBackground(header.getBackground()); renderer.setForeground(header.getForeground()); } } } catch(NullPointerException ignored) { // happens occasionally, ignore. } } if(value instanceof Icon) { renderer.setIcon((Icon)value); renderer.setText(null); } else { Icon icon = (col == index) ? (ascending ? ASCENDING : DESCENDING) : null; renderer.setIcon(icon); renderer.setText((value == null) ? null : value.toString()); } if(renderer != this) { renderer.setHorizontalAlignment(CENTER); renderer.setIconTextGap(2); // reduce from the default of 4 pixels renderer.setHorizontalTextPosition(LEFT); } // Update the borders to simulate pressing, but only if the actual // renderer didn't put its own borders on. Border pressed, normal, active; pressed = UIManager.getBorder("TableHeader.cellPressedBorder"); normal = UIManager.getBorder("TableHeader.cellBorder"); active = renderer.getBorder(); if(active == pressed || active == normal || active == null) { if ( isPressed ) { // need to explicitly check for null since some laf's // [osx] might not have it. all will have cellBorder tho. renderer.setBorder(pressed == null ? normal : pressed); } else { renderer.setBorder(normal); } } return renderer; } }
C++
UTF-8
4,653
3
3
[]
no_license
#include<iostream> #include<math.h> typedef long long int lld; using namespace std; struct Coordinate { lld x,y; }; int slopecheckifptinbet(Coordinate c1 ,Coordinate c2 , Coordinate c3) { // c1 c3 same slop c3 c2 // if ( (float)((c3.y-c1.y )/(c3.x-c1.x)) == (float)((c2.y-c3.y )/(c2.x-c3.x)) ) // { // return 1; // } // return 0; // if ( (c3.y-c1.y )*(c2.x-c3.x) == (c2.y-c3.y )*(c3.x-c1.x) ) // { // return 1; // } // return 0; if (c2.x <= max(c1.x, c3.x) && c2.x >= min(c1.x, c3.x) && c2.y <= max(c1.y, c3.y) && c2.y >= min(c1.y, c3.y)) return true; return false; } int orientation(Coordinate p,Coordinate q,Coordinate r) { lld ore = (q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y); if(ore==0) { return 0; //same line } else if(ore>0) { return 1 ;//clock } else { return 2; } } int insertect(Coordinate p1,Coordinate q1 ,Coordinate p2,Coordinate q2) { //p1 ,q1 one line lld firsore = orientation(p1,q1,q2); lld secore = orientation(p1,q1,p2); lld thirdsore = orientation(p2,q2,q1); lld fourtsore = orientation(p2,q2,p1); if (thirdsore!=fourtsore && firsore != secore ) { return true ;//intersect } // check linearity if (firsore==0 &&(slopecheckifptinbet(p1,q2,q1)) ) { return true;//intersect } if (secore==0 &&(slopecheckifptinbet(p1,p2,q1)) ) { return true;//intersect } if (thirdsore==0 &&(slopecheckifptinbet(p2,q1,q2))) { return true;//intersect } if (fourtsore==0&&(slopecheckifptinbet(p2,p1,q2)) ) { return true;//intersect } return false; } int main(int argc, char const *argv[]) { Coordinate c1,c2,l1,l2; lld testcaes; cin>>testcaes; while (testcaes--) { cin>>c1.x>>c1.y>>c2.x>>c2.y>>l1.x>>l1.y>>l2.x>>l2.y; if (insertect(c1,c2,l1,l2)) { cout<<1<<endl; } else { cout<<0<<endl; } } return 0; } // // A C++ program to check if two given line segments intersect // #include <iostream> // using namespace std; // struct Point // { // int x; // int y; // }; // // Given three colinear points p, q, r, the function checks if // // point q lies on line segment 'pr' // bool onSegment(Point p, Point q, Point r) // { // if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && // q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) // return true; // return false; // } // // To find orientation of ordered triplet (p, q, r). // // The function returns following values // // 0 --> p, q and r are colinear // // 1 --> Clockwise // // 2 --> Counterclockwise // int orientation(Point p, Point q, Point r) // { // // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // // for details of below formula. // int val = (q.y - p.y) * (r.x - q.x) - // (q.x - p.x) * (r.y - q.y); // if (val == 0) return 0; // colinear // return (val > 0)? 1: 2; // clock or counterclock wise // } // // The main function that returns true if line segment 'p1q1' // // and 'p2q2' intersect. // bool doIntersect(Point p1, Point q1, Point p2, Point q2) // { // // Find the four orientations needed for general and // // special cases // int o1 = orientation(p1, q1, p2); // int o2 = orientation(p1, q1, q2); // int o3 = orientation(p2, q2, p1); // int o4 = orientation(p2, q2, q1); // // General case // if (o1 != o2 && o3 != o4) // return true; // // Special Cases // // p1, q1 and p2 are colinear and p2 lies on segment p1q1 // if (o1 == 0 && onSegment(p1, p2, q1)) return true; // // p1, q1 and q2 are colinear and q2 lies on segment p1q1 // if (o2 == 0 && onSegment(p1, q2, q1)) return true; // // p2, q2 and p1 are colinear and p1 lies on segment p2q2 // if (o3 == 0 && onSegment(p2, p1, q2)) return true; // // p2, q2 and q1 are colinear and q1 lies on segment p2q2 // if (o4 == 0 && onSegment(p2, q1, q2)) return true; // return false; // Doesn't fall in any of the above cases // } // int main(int argc, char const *argv[]) // { // Point c1,c2,l1,l2; // lld testcaes; // cin>>testcaes; // while (testcaes--) // { // cin>>c1.x>>c1.y>>c2.x>>c2.y>>l1.x>>l1.y>>l2.x>>l2.y; // if (doIntersect(c1,c2,l1,l2)) // { // cout<<1<<endl; // } // else // { // cout<<0<<endl; // } // } // return 0; // }
PHP
UTF-8
1,299
2.578125
3
[]
no_license
<?php /** * Note 1: Replace the popup ID used below ('#popmake-123') with the * value '#popmake-{integer} used with your popup. From the WP Admin, refer * to 'Popup Maker' -> 'All Popups' -> 'CSS Classes (column)' -> to find * the popup ID. * * Note 2: Use the cookie ID ('pum-{integer}' linked to the popup ID above * for the code used on your site. * * Add the following code to your theme (or child-theme) * 'functions.php' file starting with 'add_action()'. * -------------------------------------------------------------------------- */ add_action( 'wp_footer', 'my_custom_popup_scripts', 500 ); /** * Set a cookie to close a popup on form submit. * * @since 1.0.0 * * @return void */ function my_custom_popup_scripts() { ?> <script type="text/javascript"> (function ($, document, undefined) { jQuery('#popmake-123 form').on('submit', function () { jQuery.pm_cookie( 'pum-123', // The cookie name that is checked prior to auto opening. true, // Setting a cookie value of true. '10 years', // Plain english time frame. '/' // Cookie path of '/' means site wide. ); }); }(jQuery, document)) </script><?php }
Markdown
UTF-8
3,739
2.953125
3
[ "MIT" ]
permissive
# SSSSBC - Single Seven Segment Serial Binary Clock There's lots of LED clocks out there. There's lots of binary clocks out there. This is a mix of them both. On a single seven segment display, you can get to within about five minutes accuracy of what time of day it is. ## Hardware My first cut at this was to use an Adafruit BLE Feather and update my cruddy RTC with a BLE message once a month. But I got a DS3231 instead and it's much better accuracy, so you can run this most any Arduino-ish thingy you have. - ![Adafruit](https://www.adafruit.com/product/2829) Feather or Metro or Arduino. The choice is yours...the choice is yours. - ![Realtime clock](https://www.adafruit.com/product/3028) The DS3231 is good or go with DS1307. DS3231 is 3V happy. - ![Shift register](https://www.digikey.com/en/products/filter/logic-shift-registers/712) Ye olde 74HC595 for me. - ![Seven segment LED](https://www.digikey.com/en/products/filter/display-modules-led-character-and-numeric) Pick a LED. - Resistors - You'll need eight and still get the right mA through your LED. Do the math. A 100 ohm @ 3.3V with a red LED is usually fine. - Trim pot - A trim pot can be used to choose which of the bit patterns you'd like to see. - Switch - A single-pole single-throw switch to turn on/off daylight savings time (optional). ## Layout This sketch accomodates either common anode or common cathode LED. Just change one variable. The breadboard layout is simple but always tricky with so many wires. Here's the high level setup. ``` | Arduino Pin 12 -|- SRCLK 74HC595 Q0 -|- DP(5) LED (3 or 8) -+- 3.3V (common anode from Feather) | 11 -|- RCLK Q1 -|- C(4) | 10 -|- SER Q2 -|- B(6) | A1 6 -|-+ Q3 -|- E(1) +------+--------+++ \ Q4 -|- F(10) | || \ Q5 -|- D(2) trim pot DS3231 SPST Q6 -|- G(9) Q7 -|- A(7) ``` The clock just goes on the I2C SDA/SCL lines. Pick any open port for your switch. ![Block diagram](ssssbc1.pdf) The Fritzing diagram shows the basic layout. Be sure to calculate the right resistor for your LED. The typical 74HC595 doesn't like lots of current through it so get the specs for your LED and use the right resistors. ![Single Seven Segment Binary Clock](ssssbc_demo.gif) ### Possible configurations You can also wire this directly if you have enough pinouts. My first draft was built that way and I simulated an RTC with a simple accumulator. ## Usage There are a few settings you should look at in the code. The first is the type of LED, common anode or cathode. Look at what display pattern you want to use. The bits can flip in a few different patterns, so pick the one you like. I like to keep the decimal point as either the "mid-quarter" blinker or as the high "16 o'clock" bit. It's also most aesthetically pleasing to keep the two quarter hour bits in some kind of harmony, either together or mirrored. Then it's up to you to choose how the hours will light. Some patterns have a great "finale" at the midnight switch. Others are easy to decipher at a quick glance. ## Code requirements This sketch requires few libraries, especially if you don't put the Arduino to sleep or use BLE. - Wire.h - for communication between the Arduino and the RTC (probably) - LowPower.h - for reducing power consumption (optional) ## Next steps The final build will incorporate a few additions. - BLE communication: get time from UART. Show the name of the current pattern and time. - Dimmer: global PWM from a photosensor. (?) - DST: Set your offsets settings, and you'll be set. (DONE)
C#
UTF-8
4,308
3.109375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; namespace Lib.Office { public static class ConvertHelper { #region IEnumerable<T>转换DataTable /// <summary> /// /// Description:IEnumerable<T>转换DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="array"></param> /// <returns></returns> public static DataTable ConvertIEnumerableToDataTable<T>(this IEnumerable<T> array) { var dt = new DataTable(); var pro = TypeDescriptor.GetProperties(typeof(T)); foreach (PropertyDescriptor dp in pro) { if ((dp.PropertyType).IsGenericType && (dp.PropertyType).IsConstructedGenericType) continue; dt.Columns.Add(dp.Name, dp.PropertyType); } foreach (T item in array) { var Row = dt.NewRow(); foreach (PropertyDescriptor dp in pro) { if ((dp.PropertyType).IsGenericType && (dp.PropertyType).IsConstructedGenericType) continue; Row[dp.Name] = dp.GetValue(item); } dt.Rows.Add(Row); } return dt; } #endregion #region DataTable转换IEnumerable<T> /// <summary> /// /// Description: DataTable转换IEnumerable<T> /// </summary> /// <typeparam name="T">实体</typeparam> /// <param name="dt">数据表</param> /// <returns>返回实体集合</returns> public static IEnumerable<T> ConvertDataTableToIEnumerable<T>(this DataTable dt) where T : class, new() { var pros = typeof(T).GetProperties(); T entity = null; foreach (DataRow dr in dt.Rows) { entity = new T(); foreach (var pr in pros) { if (dt.Columns.Contains(pr.Name)) { var value = dr[pr.Name]; if (pr.CanWrite) { if (value != DBNull.Value && !string.IsNullOrEmpty(value.ToString())) { pr.SetValue(entity, TypeConvert(value, pr.PropertyType), null); } else { if (pr.PropertyType.Equals(typeof(DateTime))) pr.SetValue(entity, System.Data.SqlTypes.SqlDateTime.MinValue.Value, null); else pr.SetValue(entity, pr.PropertyType.IsValueType ? Activator.CreateInstance(pr.PropertyType) : "", null); } } } else { if (pr.PropertyType.Equals(typeof(DateTime))) { pr.SetValue(entity, System.Data.SqlTypes.SqlDateTime.MinValue.Value, null); } else if (pr.PropertyType.Equals(typeof(string))) { pr.SetValue(entity, "", null); } } } yield return (entity); } } #endregion #region 类型强转 (可判断泛型Nullable值) /// <summary> /// /// Description :类型强转 /// </summary> /// <param name="obj"></param> /// <param name="t"></param> /// <returns></returns> public static object TypeConvert(object obj, Type t) { if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { if (obj == null) { return null; } t = Nullable.GetUnderlyingType(t); } return Convert.ChangeType(obj, t); } #endregion } }
Java
UTF-8
2,665
2.515625
3
[]
no_license
package br.com.etorcedor.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; @Entity public class Time implements Serializable { private static final long serialVersionUID = 4947351929869437331L; private Long id; private String nome; private List<Torcida> torcidas; private List<Jogo> jogos; public Time() { } public Time(String nome) { this.nome = nome; } public Time(Long id, String nome, List<Torcida> torcidas, List<Jogo> jogos) { this.id = id; this.nome = nome; this.torcidas = torcidas; this.jogos = jogos; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @OneToMany(mappedBy = "time", fetch = FetchType.EAGER) public List<Torcida> getTorcidas() { return torcidas; } public void setTorcidas(List<Torcida> torcidas) { this.torcidas = torcidas; } @ManyToMany(fetch = FetchType.EAGER) public List<Jogo> getJogos() { return jogos; } public void setJogos(List<Jogo> jogos) { this.jogos = jogos; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((jogos == null) ? 0 : jogos.hashCode()); result = prime * result + ((nome == null) ? 0 : nome.hashCode()); result = prime * result + ((torcidas == null) ? 0 : torcidas.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Time other = (Time) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (jogos == null) { if (other.jogos != null) return false; } else if (!jogos.equals(other.jogos)) return false; if (nome == null) { if (other.nome != null) return false; } else if (!nome.equals(other.nome)) return false; if (torcidas == null) { if (other.torcidas != null) return false; } else if (!torcidas.equals(other.torcidas)) return false; return true; } @Override public String toString() { return "Time [id=" + id + ", nome=" + nome + ", torcidas=" + torcidas + ", jogos=" + jogos + "]"; } }
Markdown
UTF-8
2,181
2.65625
3
[]
no_license
![](http://ivansun123.b0.upaiyun.com/chaz/picCZPull1.gif!bac) --- # CZPullToRefresh These `UIScrollView` categories makes it super easy to add pull-to-refresh to any UIScrollView (or any of its subclass). Instead of relying on delegates and/or subclassing `UIViewController`, CZPullToRefresh uses the Objective-C runtime to add the following methods to` UIScrollView`: ```swift public func addpullToRefreshScrollWithHandler(topInsert: CGFloat ,indicatorType: IndicatorType, actionHandler: handler) ``` ## Installation * Drag the CZPullToRefresh floder in your project * that's all, so easy isn't it?! ### Usage: * add func "addpullToRefreshScrollWithHandler" in viewDidLoad() * add func "stopPullRefreshAnimation" when update view forData * parameter handler: doing network request in handler * parameter topInsert: insert of tableview top. * parameter indicatorType: "SystemIndicator" : use system default indicator animate; "CustomIndicator(indicatorParh: UIBezierPath)" : input a CGPath parameter ### Adding pull to refresh ```swift $yourtableView.addpullToRefreshScrollWithHandler(topInsert, indicatorType: indicatorType) { // prepend data to dataSource, insert cells at top of table view // call [tableView.pullToRefreshView stopAnimating] when done } ``` ### Stop animating when done ```swift $yourtableView.pullRefreshView?.stopPullRefreshAnimation() ``` ###IndicatorType * SystemIndicator > use system animation indicator when loading data. * CustomIndicator(indicatorPath: UIBezierPath) > input a UIBezierPath indicator, which you hope indicator present. ### other changeable property in code ```swift /** after addpullToRefreshScrollWithHandler function modified this prperty, use for transform the indicator centerY offset:(if needed) - default : 0 - parameter +: move down indicator - parameter -: move up indicator */ public var indicatorPositionYOffset: CGFloat = 0 //MARK: - define refresh view height - private let PullRefreshViewHeight: CGFloat = 70 //MARK: - define lineWidth - let lineWidth: CGFloat = 2 ``` --- __个人博客[http://lukastong.github.io/](http://lukastong.github.io/)__
Shell
UTF-8
256
3.484375
3
[]
no_license
#!/bin/bash read -p "Enter number of elements: " count a=1 sum=0 while [ $a -le $count ] do read -p "Enter number $a:" n sum=`expr $sum + $n` a=`expr $a + 1` done avg=`expr $sum / $count` echo "Avergae of given $count numbers: $avg"
C++
UTF-8
624
2.625
3
[]
no_license
#include<iostream> #include<fstream> using namespace std; int main() { ifstream infile("A1P2in1.txt"); //ofstream outfile("A1P2out1.txt"); unsigned long int m; unsigned long int n; while(infile >> n >> m) { if(n==0 && m==0) break; double val1; double val2; double result = 1.0; val1=min(n,m); val2=n+m; while(val1 > 0) { result = result * val2/val1; val2--; val1--; } //outfile << result << endl; cout << result << endl; } system("pause"); return 0; }
C
UTF-8
1,968
2.671875
3
[]
no_license
/* NAME: Keyu Ji EMAIL: g.jikeyu@gmail.com ID: 704966744 */ #include <stdio.h> #include <stdlib.h> //#include <sys/stat.h> //#include <sys/types.h> #include <sys/wait.h> //#include <sys/time.h> //#include <sys/resource.h> #include <time.h> #include <ctype.h> #include <fcntl.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <signal.h> #include <errno.h> #include <pthread.h> #include "SortedList.h" void SortedList_insert(SortedList_t *list, SortedListElement_t *element) { SortedListElement_t *tracker = list->next; while((tracker != list) && (strcmp(tracker->key, element->key) <0)) tracker = tracker->next; if (opt_yield & INSERT_YIELD) sched_yield(); tracker->prev->next = element; element->prev = tracker->prev; element->next = tracker; tracker->prev = element; } int SortedList_delete(SortedListElement_t *element) { if (element->next->prev != element || element->prev->next != element) return 1; if (opt_yield & DELETE_YIELD) sched_yield(); element->next->prev = element->prev; element->prev->next = element->next; return 0; } SortedListElement_t *SortedList_lookup(SortedList_t *list, const char *key) { if (list->next->key == NULL) return NULL; SortedListElement_t *tracker = list->next; while (tracker->key != NULL) { if (opt_yield & LOOKUP_YIELD) sched_yield(); if ((strcmp(tracker->key, key)) == 0) return tracker; tracker = tracker->next; } return NULL; } int SortedList_length(SortedList_t *list) { if (list == NULL || list->next->key == NULL) { if (list->prev->key != NULL) return -1; else return 0; } int counter = 0; SortedListElement_t *tracker = list->next; while (tracker != list) { if (opt_yield & LOOKUP_YIELD) sched_yield(); if (tracker->next->prev != tracker || tracker->prev->next != tracker) return -1; counter++; tracker = tracker->next; } return counter; }