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
C
UTF-8
2,055
2.859375
3
[]
no_license
#define NOTE_C4 1911 // 계이름들의 반주기 #define NOTE_D4 1702 #define NOTE_E4 1516 #define NOTE_F4 1431 #define NOTE_G4 1275 #define NOTE_A4 1136 #define NOTE_B4 1012 #define C 1911 // 계이름들의 반주기 #define D 1702 #define E 1516 #define F 1431 #define G 1275 #define A 1136 #define B 1012 int note_arr[8] = {NOTE_C4, NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4}; //솔 솔 라 라 솔 솔 미 int school_tang_tang[7] = {G,G,A,A,G,G,E}; int school_tang_tang_play[7] = {250,250,250,250,250,250,500}; int school_tang_tang_delay[7] = {75,75,75,75,75,75,75}; unsigned long c_micros = 0; unsigned long p_micros = 0; unsigned long c_millis = 0; unsigned long p_millis = 0; unsigned long p_millis1 = 0; int toggle = 0; int note_index = 0; int play_on = 1; void setup() { pinMode(5, OUTPUT); } void loop() { c_micros = micros(); c_millis = millis(); if(play_on == 1) // 우리가 가변적으로 키고 끄는것을 만듦 { if(c_micros - p_micros > school_tang_tang[note_index]) // micros 구조의 것으로 소리만 내는것 { p_micros = c_micros; if(toggle == 0) { toggle = 1; digitalWrite(5, HIGH); } else { toggle = 0; digitalWrite(5, LOW); } } } if(c_millis - p_millis > school_tang_tang_play[note_index] + school_tang_tang_delay[note_index]) // 끝날때 다시 시작 || 1 { p_millis = c_millis; play_on = 1; // 위의 것을 실행시킴 p_millis1 = c_millis; // 시작을 시킬때 부터 시간을 세기 위해 만듦 note_index++; if(note_index == 7) { note_index = 0; } } if(play_on == 1) // 부저가 울리기 시작할때 같이 시작하기 위해 만듦 || 2 { if(c_millis - p_millis1 > school_tang_tang_play[note_index]) // 250을 가변으로 넣을 수 있다 { play_on = 0; digitalWrite(5, LOW); toggle = 0; } } } // 울리는것을 250 millis, 꺼져있는것을 75millis로 맞춘다는 가정하에 저 위의 1번은 처음 시작할떄의 초기화, 2번은 1번과 함께 시작하게 만든다
C++
UTF-8
5,750
2.859375
3
[]
no_license
#include "mpi.h" #include <iostream> #include "math.h" #include <time.h> // incluye "time" #include <unistd.h> // incluye "usleep" #include <stdlib.h> // incluye "rand" y "srand" /* mpicxx PROD.cpp -o prod mpirun -np 6 INTERSINCRO Procesos pares mejor */ #define Productor 0 //identificador de la etiqueta #define Buffer 5 //el proceso nº5 es el buffer #define Consumidor 1 //identificador de la etiqueta #define ITERS 20 #define TAM 5 using namespace std; //////////////////////////////////PRODUCTOR///////////////////////////////////////////// void productor(int elemento) { int dato; for( unsigned int i = 0 ; i < ITERS/5; i++) //divido entre 5 pk tengo 20 iteraciones y 5 productores { dato=elemento*10+i; cout << "Productor ["<<elemento<<"]"<< "produce valor "<< dato << endl ; MPI_Ssend( &dato, 1, MPI_INT, Buffer, Productor, MPI_COMM_WORLD );//Yo quiero enviar al Buffer y su etiqueta=productor // espera bloqueado durante un intervalo de tiempo aleatorio // (entre una décima de segundo y un segundo) usleep( 1000U * (100U+(rand()%900U)) ); } int rank; MPI_Comm_rank( MPI_COMM_WORLD, &rank ); //se introduce el id del proceso en la variable rank cout<< ".........Productor "<<rank<<" ha terminado..."<<endl<<flush; } //////////////////////////////////CONSUMIDOR///////////////////////////////////////////// void consumidor(int elemento) { int value, peticion=1; float raiz; MPI_Status status; int nombre=elemento % 4;//Los consumidores son el proceso 5,6,7,8 digamos que hago que si es el primero consumidor es el 5, 5%4=1 for( unsigned int i = 0 ; i < ITERS/4 ; i++ )//Al ser solo 4 consumidores, divido entre 5 pk tengo 20 iteraciones { MPI_Ssend( &peticion, 1, MPI_INT, Buffer, Consumidor, MPI_COMM_WORLD ); MPI_Recv ( &value,1, MPI_INT, Buffer, Consumidor, MPI_COMM_WORLD, &status);//El Consumidor guarda el dato cout << "Consumidor ["<<nombre<<"] recibe valor "<<value<<" de Buffer "<<endl ; // espera bloqueado durante un intervalo de tiempo aleatorio // (entre una décima de segundo y un segundo) usleep( 1000U * (100U+(rand()%900U)) ); raiz = sqrt(value); } int rank; MPI_Comm_rank( MPI_COMM_WORLD, &rank ); cout<< "........Consumidor "<<rank<<" ha terminado..."<<endl<<flush; } //////////////////////////////////BUFFER//////////////////////////////////////////////// void buffer() { int value[TAM]; int peticion; MPI_Status status; int pos=0; int rama; int num=0; int task=0; for( unsigned int i = 0 ; i < ITERS*2 ; i++ ) //SON 40 20--->productor y 20---->consumidor { if(pos==0) { rama=0; //El consumidor no puede consumir, buffer vacio PRODUCIRA EL productor } else { if(pos==TAM)//El productor no puede producir, el buffer esta lleno { rama=1; } else { /*Retorna sólo cuando hay algún mensaje que encaje con los argumentos. ▸ Permite esperar la llegada de un mensaje sin conocer su procedencia, etiqueta o tamaño.*/ MPI_Probe( MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status );//status, almacena la etiqueta entera del mensaje(quien la enviado,etiqueta, etc) if (status.MPI_SOURCE < Buffer) rama =0; //como los procesos productores son los del 0 al 4 llevarán en rama = 0 (tag) else rama=1; /* otra manera es: if (status.MPI_TAG == Productor) //AQUI ES CON LA ETIQUETA rama =0; else rama=1; */ } } // std::cout << "RAMA" << rama<<endl; switch(rama) { case 0://PRODUCTOR Uso el tag=productor //El buffer recive al productor MPI_Recv( &value[pos], 1, MPI_INT, MPI_ANY_SOURCE, Productor, MPI_COMM_WORLD, &status );//El id del proceso me da igual--> MPI_ANY_SOURCE task=status.MPI_SOURCE ; //saco quien lo ha enviado al buffer osea el id del proceso cout << "BUFFER recibe " << value[pos] << " de Productor [" << task <<"]" <<endl; pos++; break; case 1://CONSUMIDOR uso el tag=consumidor MPI_Recv( &peticion, 1, MPI_INT, MPI_ANY_SOURCE, Consumidor, MPI_COMM_WORLD, &status );//eTIQUETA-->> Consumidor,, id de cualquiera // En vez de poner MPI_ANY_SOURCE y luego calcular task = status.MPI_SOURCE ;---> directamente me ahorro hacer eso task=status.MPI_SOURCE; num = status.MPI_SOURCE % 4 ; //como los consumidores van a tener ei id 6,7,8,9, pues le hago el modulo, el 5 es el buffer y de 0...4 son los productores // envíamos al tag del que recibimos. pos--; MPI_Ssend( &value[pos], 1, MPI_INT, task, Consumidor , MPI_COMM_WORLD);//el buffer envia el dato al consumidor cout << "Buffer envía " << value[pos] << " a Consumidor " << num << endl; break; } } } /////////////////////////////////////MAIN///////////////////////////////////////////////// int main(int argc, char *argv[]) { int rank,size; // inicializar MPI, leer identif. de proceso y número de procesos MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ) ; MPI_Comm_size( MPI_COMM_WORLD, &size ) ; //srand ( time(NULL) ); // comprobar el número de procesos con el que el programa // ha sido puesto en marcha (debe ser 10) if(size!=10) { cerr<<"error numero de procesos incorrecto, debe de ser 10"<<endl; return 1; } if ( rank < 5 /*bufer*/) // Procesos 0,1,2,3 y 4 productor(rank) ; //LE PASO COMO PARAMETRO EL RANK por hacer cosas diferente else { if ( rank == Buffer ) // Proceso 5 buffer() ; else consumidor(rank) ; // Procesos 6,7,8 y 9 //LE PASO COMO PARAMETRO EL RANK } MPI_Finalize( ) ; return 0; }
C++
UTF-8
3,522
3.09375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oel-bour <oel-bour@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/22 17:26:29 by oel-bour #+# #+# */ /* Updated: 2020/02/22 17:26:29 by oel-bour ### ########.fr */ /* */ /* ************************************************************************** */ #include "Intern.hpp" #include "Bureaucrat.hpp" #include "Form.hpp" #include "PresidentialPardonForm.hpp" #include "RobotomyRequestForm.hpp" #include "ShrubberyCreationForm.hpp" // int main() // { // Bureaucrat staff1("max",1); // Bureaucrat staff2("jack",150); // std::cout << "creation of two bureaucrats" << std::endl; // std::cout << staff1 << std::endl; // std::cout << staff1 << std::endl; // Intern intern; // Form *form1; // std::cout << "creating a form" << std::endl; // form1 = intern.makeForm("shrubbery creation","old man"); // std::cout << "signing the form by max should work" << std::endl; // std::cout << "signing the form by jack should fail" << std::endl; // form1->beSigned(staff1); // staff2.executeForm(*form1); // return 0; // } int main() { Bureaucrat test("Arta", 1); Bureaucrat test2("Lydeka", 150); std::cout << "** Created Bureaucrat Arta, grade 1 **" << std::endl << test << std::endl << "** Created Bureaucrat Lydeka, grade 150 **" << std::endl << test2 << std::endl; Intern intern; std::cout << "** Created new Intern, will now proceed to make forms with intern **" << std::endl << std::endl; Form *ftest; std::cout << "** Creating Shrubbery Creation form with target Mary_Jane with Intern **" << std::endl; ftest = intern.makeForm("Shrubbery Creation", "Mary_Jane"); std::cout << "** Now having Arta signed the form (should succeed), and Lydeka execute form (should fail) **" << std::endl; ftest->beSigned(test); test2.executeForm(*ftest); Form *ftest2; std::cout << std::endl << "** Creating Robotomy Request form with target Gundam with Intern **" << std::endl; ftest2 = intern.makeForm("Robotomy Request", "Gundam"); std::cout << "** Now having Arta signed the form (should succeed), and Lydeka execute form (should fail) **" << std::endl; ftest2->beSigned(test); test2.executeForm(*ftest2); Form *ftest3; std::cout << std::endl << "** Creating Presidential Pardon form with target Obama with Intern **" << std::endl; ftest3 = intern.makeForm("Presidential Pardon", "Obama"); std::cout << "** Now having Arta signed the form (should succeed), and Lydeka execute form (should fail) **" << std::endl; ftest3->beSigned(test); test2.executeForm(*ftest3); Form *ftest4; std::cout << std::endl << "** Creating Non Existent form with target Whatever with Intern, should fail **" << std::endl; ftest4 = intern.makeForm("Non Existent", "Whatever"); delete ftest; delete ftest2; delete ftest3; delete ftest4; return (0); }
Shell
UTF-8
1,093
3.09375
3
[]
no_license
#!/bin/bash echo "================================================================================" echo "============================== FT_CONTAINERS TEST ==============================" echo "================================================================================" mkdir -p obj mkdir -p results clang++ -Wall -Wextra -Werror -std=c++98 -g3 -fsanitize=address src/main.cpp -o ./obj/test_std if [[ $? -ne 0 ]]; then echo -e "\033[31mCOMPILATION ERROR\033[0m" exit fi clang++ -Wall -Wextra -Werror -std=c++98 -g3 -fsanitize=address -D TFT src/main.cpp -o ./obj/test_ft if [[ $? -ne 0 ]]; then echo -e "\033[31mCOMPILATION ERROR\033[0m" exit fi echo "Testing STD" echo "Timings :" time ./obj/test_std > ./results/tstd.results echo "STD test done" echo "" echo "Testing FT" echo "Timings :" time ./obj/test_ft > ./results/tft.results echo "FT test done" diff ./results/tstd.results ./results/tft.results > ./results/results.diff if [[ $? -ne 0 ]]; then echo -e "\033[31mERROR\nsee results.diff\033[0m" exit else echo -e "\033[32mEverything is working as intended\033[0m" fi
Java
UTF-8
1,721
1.976563
2
[]
no_license
package kr.co.gugu.service; import java.util.List; import javax.inject.Inject; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import kr.co.gugu.dao.RoomDAO; import kr.co.gugu.domain.RoomDTO; import kr.co.gugu.domain.SearchPaging; import kr.co.gugu.domain.Paging; @Service public class RoomServiceImpl implements RoomService { @Inject RoomDAO roomDAO; @Override public List<RoomDTO>RoomList() throws Exception { // TODO Auto-generated method stub return roomDAO.RoomList(); } //강의실 등록 @Override public int AddRoom(RoomDTO rDTO) throws Exception { // TODO Auto-generated method stub return roomDAO.AddRoom(rDTO); } @Override public List<RoomDTO> Paging(Paging paging) throws Exception { // TODO Auto-generated method stub return roomDAO.Paging(paging); } @Override public int CountPaging(Paging paging) throws Exception { // TODO Auto-generated method stub return roomDAO.CountPaging(paging); } @Override public List<RoomDTO> Search(SearchPaging searchPaging) throws Exception { // TODO Auto-generated method stub return roomDAO.Search(searchPaging); } //수정 @Override public int RoomUpdate(RoomDTO roomDTO) throws Exception { // TODO Auto-generated method stub return roomDAO.RoomUpdate(roomDTO); } //삭제 @Override public int RoomDelete(int roomno) throws Exception { // TODO Auto-generated method stub return roomDAO.RoomDelete(roomno); } @Override public RoomDTO RoomDetail(int roomno) throws Exception { // TODO Auto-generated method stub return roomDAO.RoomDetail(roomno); } }
Java
UTF-8
888
3.0625
3
[]
no_license
import java.util.Arrays; public class Phonelist { public static boolean checkList(String[] str) { for(int i = 0; i < str.length-1; i++) { int k = 0; //try { while ((k < str[i].length()) && (str[i].charAt(k) == str[i+1].charAt(k))) { k++; } //} catch(StringIndexOutOfBoundsException exception) { //return false; //} if (k == str[i].length()) { return false; } } return true; } public static void main(String[] args) { Kattio io = new Kattio(System.in); int cases = io.getInt(); int numbers; String[] nrs = null; for(int i = 0; i < cases; i++) { numbers = io.getInt(); nrs = new String[numbers]; for(int j = 0; j < numbers; j++) { nrs[j] = io.getWord(); } Arrays.sort(nrs); if (checkList(nrs)) { System.out.println("YES"); } else { System.out.println("NO"); } } io.close(); } }
Java
UTF-8
1,125
2.65625
3
[]
no_license
package harrisonwall.phase3; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class SectionModAdapter extends ArrayAdapter<Section> { public SectionModAdapter(Context context, ArrayList<Section> sections) { super(context, 0, sections); } @Override public View getView(int position, View convertView, ViewGroup parent) { View sectionView = convertView; if( sectionView == null ) sectionView = LayoutInflater.from(getContext()).inflate(R.layout.mod_section, parent, false); // Fill section info Section currSec = getItem(position); TextView secName = sectionView.findViewById(R.id.mod_section_name); TextView secMod = sectionView.findViewById(R.id.mod_section_moderator); secName.setText( currSec.getSecName() ); secMod.setText( currSec.getSecModerator() ); return sectionView; } }
Java
UTF-8
415
1.859375
2
[]
no_license
package com.jishijiyu.takeadvantage.entity.request; import com.jishijiyu.takeadvantage.utils.Constant; /** * 邀请好友二维码 * * @author sunaoyang */ public class InviteCodeAddressRequest { public String c = Constant.INVITE_CODE_ADDRESS; public Pramater p; public InviteCodeAddressRequest() { p = new Pramater(); } public class Pramater { public String userId; public String tokenId; } }
Shell
UTF-8
397
3.796875
4
[ "MIT" ]
permissive
#! /bin/bash for i in $* do case $i in 3) Python=/opt/rh/rh-python34/root/usr/bin/python ;; 2) Python=/opt/rh/python27/root/usr/bin/python ;; 0) Python=python ;; 4) Python=python3.4 ;; *) echo "Need a python version: 3 for python 3, 2 for python 2 or 0 to use the system default"; exit 1 ;; esac done echo "Installing Python module for $Python" $Python setup.py install
Java
UTF-8
597
2.015625
2
[ "MIT" ]
permissive
package er.modern.movies.demo.components; import com.webobjects.appserver.WOContext; import com.webobjects.directtoweb.D2WContext; import com.webobjects.directtoweb.D2WPage; import er.extensions.components.ERXComponent; public class PageWrapper extends ERXComponent { public PageWrapper(WOContext context) { super(context); } public D2WContext d2wContext() { if (context().page() instanceof D2WPage) { D2WPage d2wPage = (D2WPage) context().page(); return d2wPage.d2wContext(); } return null; } public String bodyClass() { return "Body"; } }
Java
UTF-8
1,027
2.28125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package header1; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.Date; import javax.faces.bean.ManagedBean; /** * * @author Rabiul */ @ManagedBean public class DateandTime { private Date d1=new Date(); private SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); private String ds=sdf.format(d1); public DateandTime() { } public Date getD1() { return d1; } public void setD1(Date d1) { this.d1 = d1; } public SimpleDateFormat getSdf() { return sdf; } public void setSdf(SimpleDateFormat sdf) { this.sdf = sdf; } public String getDs() { return ds; } public void setDs(String ds) { this.ds = ds; } }
SQL
UTF-8
3,029
4.125
4
[]
no_license
CREATE VIEW ExtendedOrganization AS SELECT O.OID, O.Organization, O.Product, O.Last_Update, O.SourceID, F.Field, O.HasBranch, O.ParentID, M.Description, M.Department, JP.JobPosition, A.Name FROM Organization O LEFT JOIN OFields Fs ON (Fs.OID = O.OID) LEFT JOIN Field F ON (Fs.FieldID = F.FieldID) LEFT JOIN AOMAP M ON (M.OID=O.OID) LEFT JOIN Alumni A ON (M.AID=A.AID) LEFT JOIN JobPosition JP ON (M.JobPositionID=JP.JobPositionID) ; CREATE VIEW FullCommunityName (AID, Community) AS SELECT Cs.AID, CASE WHEN (Cs.Khusus IS NOT NULL) THEN C.Community || ' - ' || Cs.Khusus WHEN (Cs.Angkatan IS NOT NULL) THEN C.Community || ' - ' || Cs.Angkatan ELSE C.Community END AS Community FROM ACommunities Cs INNER JOIN Community C ON (Cs.CID = C.CID); CREATE VIEW ExtendedCommunity (AID, Community, Angkatan, Program, Department, ProgramID, DepartmentID) AS SELECT Cs.AID, Cs.Community, Cs.Angkatan, P.Program, D.Department, C.ProgramID, C.DepartmentID FROM ACommunities Cs LEFT JOIN Community C ON (Cs.CID = C.CID) LEFT JOIN Program P ON (C.ProgramID = P.ProgramID) LEFT JOIN Department D ON (C.DepartmentID = D.DepartmentID); CREATE VIEW FullName (AID, FullName) AS SELECT AID, CASE WHEN (Prefix IS NOT NULL) AND (Suffix IS NOT NULL) THEN Prefix || ' ' || Name || ', ' || Suffix WHEN (Prefix IS NOT NULL) THEN Prefix || ' ' || Name WHEN (Suffix IS NOT NULL) THEN Name || ', ' || Suffix ELSE Name END AS FullName FROM Alumni; CREATE VIEW ExtendedAlumni AS SELECT A.AID, A.Name, Fn.FullName, A.Last_Update, A.SourceID, R.Religion, C.Angkatan, C.Community, C.Program, C.Department, C.ProgramID, C.DepartmentID, ACe.Certification, ACe.Institution, Co.Competency, M.Description, JT.JobType, JP.JobPosition, O.Organization FROM Alumni A LEFT JOIN Religion R ON A.ReligionID = R.ReligionID INNER JOIN FullName Fn ON (A.AID=Fn.AID) LEFT JOIN ExtendedCommunity C ON (C.AID = A.AID) LEFT JOIN ACertifications ACe ON (ACe.AID = A.AID) LEFT JOIN ACompetencies ACo ON (ACo.AID = A.AID) LEFT JOIN Competency Co ON (Co.CompetencyID = ACo.CompetencyID) LEFT JOIN AOMAP M ON (M.AID=A.AID) LEFT JOIN Organization O ON (M.OID=O.OID) LEFT JOIN JobType JT ON M.JobTypeID = JT.JobTypeID LEFT JOIN JobPosition JP ON (M.JobPositionID=JP.JobPositionID) ; CREATE VIEW Lahir (AID, Name, SourceID, BirthDate, Tanggal, Bulan, Tahun, Hari, Lahir) AS SELECT AID, Name, SourceID, BirthDate, EXTRACT(day FROM BirthDate) as Tanggal, EXTRACT(month FROM BirthDate) as Bulan, EXTRACT(year FROM BirthDate) as Tahun, CASE EXTRACT(weekday FROM BirthDate) WHEN 0 THEN 'Minggu' WHEN 1 THEN 'Senin' WHEN 2 THEN 'Selasa' WHEN 3 THEN 'Rabu' WHEN 4 THEN 'Kamis' WHEN 5 THEN 'Jumat' WHEN 6 THEN 'Sabtu' END AS Hari, CAST(Birthdate AS char(15)) as Lahir FROM Alumni WHERE BirthDate IS NOT NULL;
PHP
UTF-8
784
2.78125
3
[]
no_license
<?php namespace SergiuParaschiv\Config; class Config { private $cache; public function __construct() { $this->cache = []; } public function get($name) { $name = $this->parseName($name); $this->loadFile($name['file']); return $this->getKey($name['file'], $name['key']); } private function getKey($file, $key) { return $this->cache[$file][$key]; } private function loadFile($name) { $this->cache[$name] = include PATH_CONFIG . '/' . $name . '.php'; } private function parseName($name) { $parts = explode('.', $name); return [ 'file' => $parts[0], 'key' => $parts[1] ]; } }
Python
UTF-8
3,797
2.765625
3
[]
no_license
from __future__ import print_function import dependency import grpc import grpc_iiwa_pb2 import grpc_iiwa_pb2_grpc class lbr_grpc_client: def __init__(self, ip="172.31.1.147", port=30009): self.ip = ip self.port = str(port) self.channel = grpc.insecure_channel(self.ip + ":" + self.port) self.stub = grpc_iiwa_pb2_grpc.iiwaServiceStub(self.channel) def run(self): # print(self.ask_home()) self.move([550, 0, 500]) print("Current joint Position: " + str(self.ask_joint_position())) print("Current Cartesian Position: " + str(self.ask_cartesian_position())) def ask_joint_position(self): response = self.stub.askJointPosition(grpc_iiwa_pb2.python_request()) robot_cartesian_position = [response.A1, response.A2, response.A3, response.A4, response.A5, response.A6, response.A7] return robot_cartesian_position def ask_cartesian_position(self): response = self.stub.askCartesianPosition(grpc_iiwa_pb2.python_request()) robot_cartesian_position = [response.X, response.Y, response.Z, response.A, response.B, response.C] return robot_cartesian_position def auto_down(self, force, z_distance, velocity): response = self.stub.auto_down( grpc_iiwa_pb2.force_condition(force=force, z_distance=z_distance, velocity=velocity)) return response.success def hold_position(self, cartesian_position, cartesian_orientation, velocity=0.25, mode='lin'): if mode == 'lin': mode = True elif mode == 'ptp': mode = False else: print('mode error,only lin and ptp') return x = cartesian_position[0] y = cartesian_position[1] z = cartesian_position[2] a = cartesian_orientation[0] b = cartesian_orientation[1] c = cartesian_orientation[2] response = self.stub.hold_position( grpc_iiwa_pb2.python_cartesian_pose_request(X=x, Y=y, Z=z, A=a, B=b, C=c, velocity=velocity, mode=mode)) return response.success def move(self, cartesian_position, cartesian_orientation=None, velocity=0.25, mode='lin'): if mode == 'lin': mode = True elif mode == 'ptp': mode = False else: print('mode error,only lin or ptp') return if cartesian_orientation is None: x = cartesian_position[0] y = cartesian_position[1] z = cartesian_position[2] response = self.stub.move( grpc_iiwa_pb2.python_cartesian_position_request(X=x, Y=y, Z=z, velocity=velocity, mode=mode)) else: x = cartesian_position[0] y = cartesian_position[1] z = cartesian_position[2] a = cartesian_orientation[0] b = cartesian_orientation[1] c = cartesian_orientation[2] response = self.stub.move_with_orientation( grpc_iiwa_pb2.python_cartesian_pose_request(X=x, Y=y, Z=z, A=a, B=b, C=c, velocity=velocity, mode=mode)) return response.success def to_home(self): return self.move([550, 0, 500], [-3.141592654, 0, 3.141592654]) if __name__ == '__main__': lbr = lbr_grpc_client() print(lbr.ask_cartesian_position()) # lbr.to_home() # # lbr.move([500, 100, 300]) # # lbr.to_home() # # lbr.move([500, 100, 300],mode='ptp', velocity=0.5) # # lbr.to_home() # # lbr.move(([500, 100, 300]),[-2.5,0,2.5]) # # lbr.to_home() lbr.move([550, 0, 300]) print(lbr.auto_down(force=4, z_distance=250, velocity=0.1)) lbr.hold_position(([650, 0, 400]), [-3.141592654, 0, 3.141592654])
TypeScript
UTF-8
4,371
2.546875
3
[ "MIT" ]
permissive
import { IHandleCommand, ICommand } from "./command-handler"; import { AzRunner } from "./az-runner"; import { Step, StepFrom } from "./command-pipeline-step"; import { injectable, inject } from "inversify"; import { Then } from "./command-pipeline-then"; import { TerraformInterfaces, ILogger } from "./terraform"; declare module "./command-pipeline-step" { interface Step<TResult> { azStorageAccountCreate<TPreviousResult>(this: Step<TPreviousResult>, command: AzStorageAccountCreate): StepFrom<TPreviousResult, AzStorageAccountCreateResult>; } } Step.prototype.azStorageAccountCreate = function<TPreviousResult>(this: Step<TPreviousResult>, command: AzStorageAccountCreate): StepFrom<TPreviousResult, AzStorageAccountCreateResult>{ return new Then<TPreviousResult, AzStorageAccountCreate, AzStorageAccountCreateResult>(this, command); } export class AzStorageAccountCreateResult { id: string; location: string; name: string; constructor(id: string, location: string, name: string) { this.id = id; this.location = location; this.name = name; } } export class AzStorageAccountCreate implements ICommand<AzStorageAccountCreateResult> { readonly name: string; readonly resourceGroup: string; readonly sku: string; readonly kind: string; readonly encryptionServices: string; readonly accessTier: string; constructor(name: string, resourceGroup: string, sku: string, kind: string = "StorageV2", encryptionServices: string = "blob", accessTier: string = "hot") { this.name = name; this.resourceGroup = resourceGroup; this.sku = sku; this.kind = kind; this.encryptionServices = encryptionServices; this.accessTier = accessTier; } toString() : string { return `storage account create --name ${this.name} --resource-group ${this.resourceGroup} --sku ${this.sku} --kind ${this.kind} --encryption-services ${this.encryptionServices} --access-tier ${this.accessTier}` } } export class AzStorageAccountShowResult { id: string; location: string; name: string; constructor(id: string, location: string, name: string) { this.id = id; this.location = location; this.name = name; } } export class AzStorageAccountShow implements ICommand<AzStorageAccountShowResult> { readonly name: string; readonly resourceGroup: string; constructor(name: string, resourceGroup: string) { this.name = name; this.resourceGroup = resourceGroup; } toString() : string { return `storage account show --name ${this.name} --resource-group ${this.resourceGroup}` } } @injectable() export class AzStorageAccountCreateHandler implements IHandleCommand<AzStorageAccountCreate, AzStorageAccountCreateResult>{ private readonly cli: AzRunner; private readonly log: ILogger; constructor( @inject(AzRunner) cli: AzRunner, @inject(TerraformInterfaces.ILogger) log: ILogger) { this.cli = cli; this.log = log; } execute(command: AzStorageAccountCreate): AzStorageAccountCreateResult { let azStorageAccountShow: AzStorageAccountShow = new AzStorageAccountShow(command.name, command.resourceGroup) let result: AzStorageAccountShowResult | undefined = undefined; try{ result = this.cli.execJson<AzStorageAccountShowResult>(azStorageAccountShow.toString()); } catch(e){ let expectedError: string = `The Resource 'Microsoft.Storage/storageAccounts/${command.name}' under resource group '${command.resourceGroup}' was not found`; if(e.message.includes(expectedError)){ this.log.debug("az storage account create: storage account not found, creating..."); } else throw e; } if(result){ this.log.debug("az storage account create: storage account already exists"); return new AzStorageAccountCreateResult(result.id, result.location, result.name); } else return this.cli.execJson<AzStorageAccountCreateResult>(command.toString()); } }
Java
UTF-8
1,859
3.34375
3
[]
no_license
package crawley.james.stringutils; import org.junit.Test; import static org.junit.Assert.*; /** * Created by jamescrawley on 10/11/16. */ public class MyStringUtilsTest { MyStringUtils utils = new MyStringUtils(); @Test public void combineCharsTest () { String actual = utils.combine(new char[] {'A', 'B', 'Z'}); assertEquals("The string should be \"A,B,Z\".", "A,B,Z", actual); } @Test public void combineStringTest () { String[] ehbeezee = {"eh", "bee", "zee"}; String actual = utils.combine(ehbeezee); assertEquals("The string should be \"eh,bee,zee\".", "eh,bee,zee", actual); } @Test public void breakByLineTest () { String[] actual = utils.breakByLine("This\nis\na\nstring"); assertArrayEquals("The string array should be \"[This, is, a, string].",new String[] {"This", "is", "a", "string"} , actual); } @Test public void reverseCapitalizeTest () { assertEquals("The string should be \"tHIS iS a sTRING\"", "tHIS iS a sTRING",utils.reverseCapitalize("This is a string")); } @Test public void reverseAllTest () { assertEquals("The string should be \"sihT si a gnirts\"", "sihT si a gnirts", utils.reverseAll("This is a string")); } @Test public void whitespaceToNewlineTest () { assertEquals("The string should be \"This\nis\na\nstring\"", "This\nis\na\nstring", utils.whitespaceToNewline("This is a string")); } @Test public void substringArrayTest () { String[] expected = {"a", "s", "st", "str", "stri", "strin", "string", "t", "tr", "tri", "trin", "tring", "r", "ri", "rin", "ring", "i", "in", "ing", "n", "ng", "g"}; assertArrayEquals("The string should be \"[" + expected + "]\"", expected, utils.substringArray("a string")); } }
C
UTF-8
1,147
3.421875
3
[]
no_license
#include <stdio.h> #include <string.h> #include <time.h> // #define LOCAL static int maxnum = 3000; int f[maxnum]; // delete leading zero int delzero(int x) { while (x>=0 && !f[x]) --x; return x; } int main(void) { // #ifdef LOCAL // freopen("output.txt","a+",stdout); // #endif int i,j,n; printf(" Enter an integer n (e.g.20) : \n"); scanf(" %d\n", &n); memset( f, 0, sizeof(f)); f[0]=1; clock_t beg,end; beg = clock(); /* modify following codes */ for (i = 2; i <= n; ++i){ int c = 0; int multiplyCnt = delzero(maxnum - 1) + 3;// note, here for (j=0; j<=multiplyCnt; ++j){ int s=f[j]*i+c;// mutiply i f[j]=s%10; c=s/10; } } for (j=maxnum-1; j>=0; --j){ // ignore the leading zero if (f[j]) break; } end=clock(); // print the result for (i=j; i>=0; --i) printf("%d",f[i]); printf("\n"); printf(" time used: %.5lf\n",(double)(end-beg)/CLOCKS_PER_SEC); return 0; }
PHP
UTF-8
4,198
2.75
3
[]
no_license
<?php require_once '../CONTROLADOR/tipo_doc.control.php'; require_once '../MODELO/tipo_doc.model.php'; require_once '../MODELO/database.php'; //logica $tipo_doc = new TipoDoc(); $model = new TipoDocModel(); $db = database::conectar(); if(isset($_REQUEST['action'])){ switch ($_REQUEST['action']) { case 'actualizar': $tipo_doc->__SET('tipo_doc2', $_REQUEST['tipo_doc2']); $tipo_doc->__SET('estado_tipo_doc', $_REQUEST['estado_tipo_doc']); $tipo_doc->__SET('tipo_doc', $_REQUEST['tipo_doc']); $model->Actualizar_tipo_doc($tipo_doc); print "<script>alert(\"Registro Actualizado exitosamente.\");window.location='tipo_doc.vista.php';</script>"; break; case 'registrar': $tipo_doc->__SET('tipo_doc', $_REQUEST['tipo_doc']); $tipo_doc->__SET('estado_tipo_doc', $_REQUEST['estado_tipo_doc']); $model->Registrar_tipo_doc($tipo_doc); print "<script>alert(\"Registro Agregado exitosamente.\");window.location='tipo_doc.vista.php';</script>"; break; // Instancia la clase a eliminar que se encuentra al final de cada registro// case 'eliminar': $model->Eliminar_tipo_doc($_REQUEST['tipo_doc']); print "<script>alert(\"Registro Eliminado exitosamente.\");window.location='tipo_doc.vista.php';</script>"; break; // Instancia la clase editar que se encuentra al final de cada registro// case 'editar': $tipo_doc = $model->Obtener_tipo_doc($_REQUEST['tipo_doc']); break; } } ?> <!DOCTYPE html> <html lang="es"> <head> <title>CRUD tipo_doc</title> <link rel="stylesheet" href="../css/style_form.css"> </head> <body> <!-- FORMULARIO NUEVO REGISTRO --> <br><a href="?action=ver&m=1">NUEVO REGISTRO</a><br><br> <div id="div_form"> <?php if( !empty($_GET['m']) && !empty($_GET['action']) ){ ?> <form action="#" method="post"> <label for="tipo prod">Tipo Documento</label> <input type="text" name="tipo_doc" placeholder="Tipo Documento" required> <br><br><label for="Estado Documento">Estado Tipo Documento</label> <input type="number" name="estado_tipo_doc" placeholder="Estado Documento" required> <br><br><input type="submit" value= "Guardar" onclick = "this.form.action = '?action=registrar';" /> </form> </div> <?php } ?> <div id="div_form"> <?php if(!empty($_GET['tipo_doc']) && !empty($_GET['action']) ){ ?> <form action="#" method="post"> <!--LABEL USUARIO FINAL --> <label>Tipo de documento por Modificar: <?php echo $tipo_doc->__GET('tipo_doc'); ?> </label> <input type="text" name="tipo_doc" value="<?php echo $tipo_doc->__GET('tipo_doc'); ?>" style="display:none" placeholder="Numero Documento" required> <br><br><label>TIPO DOCUMENTO</label> <input type="text" name="tipo_doc2" id="tipo_doc2" value="<?php echo $tipo_doc->__GET('tipo_doc'); ?>" placeholder="Tipo Documento" required> <br><br><label>ESTADO TIPO DOCUMENTO</label> <input type="number" name="estado_tipo_doc" id="estado_tipo_doc" value="<?php echo $tipo_doc->__GET('estado_tipo_doc'); ?>" placeholder="Estado tipo Documento" required> <!-- <br> <input type="text" name="rol_Rol" id="rol_Rol" value="<?php echo $tipo_doc->__GET('rol_Rol'); ?>" placeholder="Rol" required> --> <br><br><input type="submit" value= "Actualizar" onclick = "this.form.action = '?action=actualizar';" /> </form> </div> <?php } $sq11= "CALL Listar_tipo_doc"; $query= $db->query($sq11); if($query->rowCount()>0):?> <br><h1>Consulta - Registros</h1><br> <table id="customers"> <thead> <tr> <th>Tipo Documento</th> <th>Estado Tipo Documento</th> <th>Editar</th> <th>Eliminar</th> </tr> </thead> <?php foreach ($model->Listar_tipo_doc() as $r): ?> <tr> <td><?php echo $r->__GET('tipo_doc'); ?></td> <td><?php echo $r->__GET('estado_tipo_doc'); ?></td> <td> <a href="?action=editar&tipo_doc=<?php echo $r->tipo_doc; ?>">Editar</a> </td> <td> <a href="?action=eliminar&tipo_doc=<?php echo $r->tipo_doc; ?>" onclick="return confirm('¿Esta seguro de eliminar este Usuario?')">Eliminar</a> </td> </tr> <?php endforeach; ?> </table> <?php else:?> <h4 class="alert-danger">Señor Usuario No se Encuentran Registros!!!</h4> <?php endif;?> </body> </html>
Java
UTF-8
173
2.140625
2
[ "MIT" ]
permissive
package app.domain.shared.exceptions; public class SexException extends IllegalArgumentException{ public SexException(String message){ super(message); } }
Java
UTF-8
2,785
2.125
2
[]
no_license
package org.webrtc; public interface Predicate<T> { Predicate<T> and(Predicate<? super T> predicate); Predicate<T> negate(); Predicate<T> or(Predicate<? super T> predicate); boolean test(T t); /* renamed from: org.webrtc.Predicate$-CC reason: invalid class name */ public final /* synthetic */ class CC { public static Predicate $default$or(Predicate _this, Predicate predicate) { return new Predicate<T>(predicate) { final /* synthetic */ Predicate val$other; public /* synthetic */ Predicate and(Predicate predicate) { return CC.$default$and(this, predicate); } public /* synthetic */ Predicate negate() { return CC.$default$negate(this); } public /* synthetic */ Predicate or(Predicate predicate) { return CC.$default$or(this, predicate); } { this.val$other = r2; } public boolean test(T t) { return Predicate.this.test(t) || this.val$other.test(t); } }; } public static Predicate $default$and(Predicate _this, Predicate predicate) { return new Predicate<T>(predicate) { final /* synthetic */ Predicate val$other; public /* synthetic */ Predicate and(Predicate predicate) { return CC.$default$and(this, predicate); } public /* synthetic */ Predicate negate() { return CC.$default$negate(this); } public /* synthetic */ Predicate or(Predicate predicate) { return CC.$default$or(this, predicate); } { this.val$other = r2; } public boolean test(T t) { return Predicate.this.test(t) && this.val$other.test(t); } }; } public static Predicate $default$negate(Predicate _this) { return new Predicate<T>() { public /* synthetic */ Predicate and(Predicate predicate) { return CC.$default$and(this, predicate); } public /* synthetic */ Predicate negate() { return CC.$default$negate(this); } public /* synthetic */ Predicate or(Predicate predicate) { return CC.$default$or(this, predicate); } public boolean test(T t) { return !Predicate.this.test(t); } }; } } }
Markdown
UTF-8
1,169
3.3125
3
[ "MIT" ]
permissive
## Functions ### Built-in functions * `abs` * `all` * `any` * `bin` * `bool` * `chr` * `dict` * `dir` * `divmod` * `enumerate` * `filter` * `float` * `hex` * `int` * `isinstance` * `issubclass` * `len` * `list` * `long` * `map` * `max` * `min` * `oct` * `ord` * `pow` * `print` * `range` * `raw_input` * `reduce` * `repr` * `reversed` * `round` * `set` * `slice` * `sorted` * `str` * `sum` * `tuple` * `xrange` * `zip` For how to use above functions, check [built-in functions on Python official documentation](https://docs.python.org/3/library/functions.html). #### Example ```python print(bin(3)) # 0b11 print(hex(255)) # 0xff print(abs(-5)) # 5 print(pow(3, 2)) # 9 print(round(3.5)) # 4.0 print(round(3.2)) # 3.0 print(oct(8)) # 010 print(ord('A')) # 65 print(chr(97)) # a a = [1,4,5,2,3] print(sorted(a)) # [1, 2, 3, 4, 5] ``` ### User-defined functions You can define your own function by using `def`. Example: ```python def my_add(a, b): c = a + b return c print(my_add(1, 2)) # 3 ``` ### Reference * [Built-in function - docs.python.org](https://docs.python.org/3/library/functions.html)
Java
UTF-8
261
2.546875
3
[]
no_license
package DecoratorPattern; public class Client { public static void main(String[] args){ Component component=new ConcreateComponent(); component=new ConcreteDecotator1(component); component=new ConcreteDecorator2(component); component.operate(); } }
JavaScript
UTF-8
902
2.65625
3
[]
no_license
import React, { Component } from "react"; class KeyPad extends Component { constructor(props) { super(props); } keyPress(e, value) { e.preventDefault(); this.props.onSubmit(value); } render() { let keyVals = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 'reset'] ]; let remaining = this.props.remaining; return ( <table> <tbody> {keyVals.map(values => <tr key={values}> {values.map(val => <td key={val}> {(val <= remaining || val === 'reset') && <button onClick={(e) => this.keyPress(e, val)}>{val}</button> } {val > remaining && <button disabled>{val}</button>} </td> )} </tr> )} </tbody> </table> ) } } export default KeyPad;
Java
UTF-8
1,435
1.921875
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package org.sdo.iotplatformsdk.common.protocol.types; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.sdo.iotplatformsdk.common.protocol.types.To2OwnerServiceInfo; class To2OwnerServiceInfoTest { To2OwnerServiceInfo to2OwnerServiceInfo; @BeforeEach void beforeEach() { to2OwnerServiceInfo = new To2OwnerServiceInfo(0, "Test"); } @Test void test_Bean() { assertEquals(Integer.valueOf(0), to2OwnerServiceInfo.getNn()); assertEquals("Test", to2OwnerServiceInfo.getSv()); to2OwnerServiceInfo.getType(); to2OwnerServiceInfo.getVersion(); } }
JavaScript
UTF-8
1,928
2.625
3
[]
no_license
const express = require('express') const cors = require('cors') const request = require('request') const app = express() const config = { app: { port: 80, restricted: false, whitelist: [ // if restricted is enabled will only // allow any request with a whitelisted // origin to use the CORS proxy. // // example: 'https://example.com' // // NOTE: the Origin header can be set // manually so this is only a very // basic means to prevent unwanted use // you would probably want to use a more // secure method to enforce this in a // production environment ], passthrough: [ // Any headers you want to allow // too be passed through to the // proxied request // // example: 'Authorization' ] }, cors: { // Any property/value accepted by // https://www.npmjs.com/package/cors origin: '*', methods: [ 'GET' ] } } function passthrough (headers) { let result = {} config.app.passthrough.forEach(passthrough => { let header = headers[passthrough.toLowerCase()] if (header) { result[passthrough] = header } }) return result } app.route('*') .options(cors(config.cors)) .all(cors(config.cors), (req, res, next) => { let targetURL = req.url.slice(1) if (config.app.restricted && !config.app.whitelist.includes(req.headers['origin'])) { return res.status(401).json({ error: 'unauthorized' }) } else if (!config.cors.methods.includes(req.method)) { return res.status(400).json({ error: 'invalid request type' }) } else if (!targetURL || !targetURL.startsWith('http')) { return res.status(400).json({ error: 'missing valid url' }) } return request({ url: targetURL, method: req.method, headers: passthrough(req.headers) }) .pipe(res) }) app.listen(config.app.port, () => { console.log('CORS proxy started') })
Markdown
UTF-8
5,799
2.71875
3
[]
no_license
# Article Annexe 1. SPÉCIFICATIONS TECHNIQUES 1.1. Description La croix lumineuse est constituée d'un ensemble de feux lumineux jaunes à éclats disposés sur un support en forme de croix dite de Saint-André. Le support des feux est constitué de deux branches de même longueur se coupant perpendiculairement en leur milieu. Chaque branche a une longueur d'environ 6 mètres (voir figure 1, schéma 1). 1.2. Conception Le dispositif est conçu pour permettre le positionnement de l'ensemble dans un plan perpendiculaire à la trajectoire des aéronefs en courte finale. La croix lumineuse est frangible. Elle résiste à des vents d'au moins 60 km/h. Des valeurs supérieures à cette vitesse peuvent être spécifiées localement en fonction des caractéristiques aérologiques du site. 1.3. Feux 1.3.1. Disposition des feux Un feu est installé au centre de la croix et trois autres régulièrement espacés d'environ 1 mètre sur chaque demi-branche (voir figure 1, schéma 1). 1.3.2. Caractéristiques 1.3.2.1. Couleur Les feux sont de couleur jaune conformément aux spécifications de l'appendice I de la présente annexe. 1.3.2.2. Photométrie La répartition spatiale en intensité lumineuse des feux est similaire à celle des feux de ligne axiale d'approche mais avec une intensité moyenne minimale de 5 000 Cd dans le faisceau principal, conformément aux spécifications de l'appendice II de la présente annexe. En cas de besoin opérationnel, les intensités lumineuses des feux peuvent être ajustées en fonction des conditions extérieures (position jour/nuit). 1.3.2.3. Clignotement Les feux clignotent en mode synchrone avec une fréquence de battement comprise entre 30 et 80 éclats par minute. La durée d'absence du signal ne doit en aucun cas être supérieure à la seconde. (Schémas non reproduits, voir JO du 14/09/2003 page 15790). Figure 1 : disposition de la croix lumineuse sur la piste 1.4. Alimentation électrique Le circuit électrique est conçu de telle sorte que la panne d'un feu n'entraîne pas l'extinction de l'ensemble. L'alimentation électrique de la croix est secourue avec un temps d'absence de signal lumineux inférieur ou égal à 15 secondes. En outre, si le système dispose de son alimentation propre, la durée maximale d'autonomie en utilisation normale et secourue est spécifiée afin qu'il en soit tenu compte dans les consignes locales d'utilisation de la croix prévues dans l'article 5 du présent arrêté. Tout autre disposition est validée par le service technique de la navigation aérienne. 1.5. Signalisation de l'ensemble La croix est signalée comme obstacle mobile et équipée de deux feux d'obstacle basse intensité de type C (jaune à éclats) disposés de telle manière que la croix soit repérée dans la direction opposée à celle de l'approche par des véhicules amenés à circuler sur la piste fermée. 2. PROCÉDURES D'EXPLOITATION 2.1. Emploi La croix lumineuse est un dispositif de balisage utilisé pour signaler une piste fermée en totalité, visible en direction de l'approche de la piste fermée. 2.2. Disposition Le dispositif est installé sur l'axe de piste en aval du seuil à une distance de celui-ci n'excédant pas 75 mètres. En cas d'impossibilité physique, la distance peut être modifiée conformément à l'article 6 du présent arrêté si la perception visuelle de la croix lumineuse est maintenue dans les mêmes conditions. L'ensemble est disposé dans un plan perpendiculaire à la trajectoire des aéronefs en courte finale (voir figure 1, schéma 2). 2.3. Situation dégradée Une croix lumineuse ne peut pas être utilisée si elle présente plus d'un feu hors-service par branche. APPENDICE I : SPÉCIFICATIONS DE LA COULEUR JAUNE DES FEUX DE LA CROIX LUMINEUSE Nota - Les spécifications de cet appendice sont extraites de l'annexe 14 à la convention internationale de l'aviation civile, OACI, volume I, appendice 1, paragraphe 2 "Couleurs des feux aéronautiques à la surface " et figure 1.1. Les couleurs des feux aéronautiques sont telles que leurs coordonnées colorimétriques, exprimées dans le système de coordonnées (x, y, Y) adopté par la Commission internationale de l'éclairage en 1931, respectent les limites définies par la zone "jaune" de la figure 2 et par les équations suivantes : (Tableau et schéma non reproduits, voir JO du 14/09/2003 page 15790). Figure 2 APPENDICE II : DIAGRAMME ISOCANDÉLA DES FEUX DE LA CROIX LUMINEUSE Nota - La répartition lumineuse du faisceau lumineux (diagramme isocandéla) de cet appendice est similaire à celle des feux de ligne axiale d'approche de l'annexe 14 à la convention internationale de l'aviation civile, OACI, volume I, appendice 2, figure 2.1 (avec un minimum d'intensité lumineuse plus faible). Figure 3 : diagramme isocandéla des feux de la croix lumineuse (Schéma non reproduit, voir JO du 14/09/2003 page 15791). Notes - 1. Les courbes sont calculées d'après la formule : (x2/a2) + (y2/b2) = 1 : Avec a = 10° b = 5,5° ; a = 14° b = 6,5° ; a = 15° b = 8,5° ; Angles x mesurés par rapport au plan vertical passant par l'axe de piste ; Angles y mesurés par rapport au plan horizontal. 2. Les intensités spécifiées s'appliquent à la lumière jaune. 3. Si le feu est doté de lampes incandescentes, l'intensité lumineuse minimale à respecter est l'intensité spécifiée. Dans le cas de lampes à éclats très brefs, l'intensité lumineuse effective du feu est à considérer. 4. L'angle de calage en site du feu est tel que le faisceau principal ait une ouverture verticale entre 0° et 11°. 5. Le feu est installé de manière que le faisceau principal soit aligné en respectant le calage spécifié à un demi-degré près.
Java
UTF-8
1,133
2.546875
3
[ "MIT" ]
permissive
package _06FootballBettingDatabase; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * Created by IntelliJ IDEA. * User: LAPD * Date: 28.3.2018 г. * Time: 21:18 ч. */ @Entity @Table(name = "bets") public class Bet { private int id; private BigDecimal betMoney; private Date dateTimeOfBet; private User user; public Bet() { } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "bet_money") public BigDecimal getBetMoney() { return betMoney; } public void setBetMoney(BigDecimal betMoney) { this.betMoney = betMoney; } @Column(name = "date_and_time_of_bet") public Date getDateTimeOfBet() { return dateTimeOfBet; } public void setDateTimeOfBet(Date dateTimeOfBet) { this.dateTimeOfBet = dateTimeOfBet; } @ManyToOne public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
Java
UTF-8
439
2.375
2
[]
no_license
package com.personal.oyl.stateMachine.handler; import com.personal.oyl.stateMachine.AbstractStateHandler; import com.personal.oyl.stateMachine.Event; import com.personal.oyl.stateMachine.Order; public class DeliverHandler extends AbstractStateHandler { @Override protected void doHandler(Order order) { System.out.println("发货"); } @Override public Event event() { return Event.deliver; } }
Markdown
UTF-8
4,336
2.84375
3
[ "MIT" ]
permissive
# Netplay Networking abstraction layer for GameMaker Studio 2 which introduces formatted packets and offloaded packet handling ## Usage Netplay uses the concept of a `session` to manage your networking. You create a `session` by calling `netplay_create_session`, and using this in all future Netplay functions. A session can be either a client session or a server session, but not both. Once you have created your session, use `netplay_connect` or `netplay_open` to either connect to an existing server, or start a new server. ```javascript var session = netplay_create_session(); var socket = netplay_connect(session, "localhost", 5000); // Connect to a server on localhost:5000 var socket = netplay_open(session, 5000, 32); // Start a new server on localhost:5000 ``` ### Packets Packets are formatted chunks of data, making use of GameMaker's `buffer` functions, and allowing for strict typing in your packets. This allows you to define the structure for your packet once and have Netplay handle the formatting of the data. > In the examples that follow, treat `ECHO_PACKET_ID` as `1` ```javascript netplay_add_packet(session, ECHO_PACKET_ID, buffer_string); ``` When defining a packet via `netplay_add_packet`, you must supply a `session` and `packet_id`, and the remaining arguments specify the structure of the packet. In this case, a single string value. To send a packet, you would use `netplay_send`. ```javascript netplay_send(session, socket, ECHO_PACKET_ID, "Hello World!"); ``` > Packets are prefixed with a particular type, which is used to identify which packet is being sent and received. This defaults to `buffer_u8`, but can be changed via `netplay_set_header_type` ### Packet Handlers Netplay allows you to assign scripts that will be invoked when a certain packet is received by the session. You can assign any number of scripts for a single packet type. ```javascript /// scr_echo_callback(session, socket, ip, port, packet_id, values); netplay_add_packet_handler(session, ECHO_PACKET_ID, scr_echo_callback); ``` For more information on handlers, see the [Event Handlers](#event-handlers) section below ### Event Handlers When working packets, you need to assign handlers for them, but you can also assign handlers that are invoked on *every* data event. You can assign any number of handlers to events, just like packet handlers, and they will be invoked in the order they were added. ```javascript event_connect_handler(session, socket, ip, port, success); event_data_handler(session, socket, ip, port, buffer) event_disconnect_handler(session, socket, ip, port, success); ``` > If you return `false` from a handler, it will stop execution of further handlers in the sequence ### Asynchronous handling and cleanup To enable Netplay to work, you *must* call `netplay_async` in the `Async - Networking` event of an instance, and supply it with your `session`. When you are finished with the `session`, you should clean up all resources used by it via `netplay_destroy`. ### Function List ```javascript netplay_create_session() netplay_connect(session, host, port) netplay_open(session, port, maxclients) netplay_send(session, socket, packet_id, values...) netplay_async(session) netplay_destroy(session) netplay_add_event_handler(session, event, handler) netplay_remove_event_handler(session, event, handler) netplay_get_event_handlers(session, event) netplay_add_packet_handler(session, packet_id, handler) netplay_remove_packet_handler(session, packet_id, handler) netplay_get_packet_handlers(session, packet_id) netplay_add_packet(session, packet_id, types...) netplay_remove_packet(session, packet_id) netplay_get_packets(session) netplay_set_header_type(session, type) netplay_get_header_type(session) netplay_is_remote(session) netplay_get_remote_sockets(session) netplay_get_host(session) netplay_get_port(session) netplay_get_socket(session) netplay_get_buffer(session) ``` ## Built With * [GameMaker Studio 2](http://www.yoyogames.com/gamemaker/studio2) ## Authors * **Andrew Bennett** - *GML implementation* - [AndrewBGM](https://github.com/AndrewBGM) See also the list of [contributors](https://github.com/AndrewBGM/netplay/contributors) who participated in this project ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE) file for details
Shell
UTF-8
1,444
2.671875
3
[]
no_license
# $Id$ # Maintainer: Sergej Pupykin <pupykin.s+arch@gmail.com> # Contributor: ice-man <icemanf@gmail.com> pkgname=sisctrl pkgver=0.0.20051202 pkgrel=7 arch=(i686 x86_64) pkgdesc="Display Control Panel for XFree86/X.org SiS driver" makedepends=('pkgconfig') depends=('gtk2' 'libxxf86vm' 'libxv') url="http://www.winischhofer.eu/linuxsisvga.shtml" license=("GPL") source=(https://arch.p5n.pp.ru/~sergej/dl/2016/sisctrl-$pkgver.tar.gz) sha256sums=('76855a8ff4631418374261613a273b082e0f56f29aa083a2197c5350688611f1') build() { cd "$srcdir"/$pkgname-$pkgver if [ -e /usr/lib/libXv.so ]; then LDFLAGS=-lm ./configure --with-xv-path=/usr/lib else LDFLAGS=-lm ./configure fi make } package() { cd "$srcdir"/$pkgname-$pkgver mkdir -p "$pkgdir"/usr/bin mkdir -p "$pkgdir"/usr/man/man1/ mkdir -p "$pkgdir"/usr/share/pixmaps mkdir -p "$pkgdir"/usr/share/applications install -m 755 sisctrl "$pkgdir"/usr/bin cp sisctrl.1x sisctrl.1; gzip sisctrl.1 install -m 644 sisctrl.1.gz "$pkgdir"/usr/man/man1/ install -m 644 icons/32x32/sisctrl.xpm "$pkgdir"/usr/share/pixmaps install -m 644 icons/16x16/sisctrl.png "$pkgdir"/usr/share/pixmaps/sisctrl_16x16.png install -m 644 icons/32x32/sisctrl.png "$pkgdir"/usr/share/pixmaps/sisctrl_32x32.png install -m 644 icons/48x48/sisctrl.png "$pkgdir"/usr/share/pixmaps/sisctrl_48x48.png install -m 644 extra/sisctrl.desktop "$pkgdir"/usr/share/applications mv "$pkgdir"/usr/man "$pkgdir"/usr/share/ }
Python
UTF-8
948
3.234375
3
[]
no_license
"""This module is used to measure the drones hieght with the VL53L0X. It uses a python library called 'VL53L0X'.""" import time import VL53L0X class HeightMeasurer: def __init__(self, posdata): self.positiondata = posdata # Create a VL53L0X object self.tof = VL53L0X.VL53L0X() # Start ranging self.tof.start_ranging(VL53L0X.VL53L0X_LONG_RANGE_MODE) self.timing = self.tof.get_timing() if self.timing < 20000: self.timing = 20000 # print ("Timing %d ms" % (timing/1000)) def measure_height(self): while True: distance = self.tof.get_distance() if 3000 > distance > 20: #TODO 50 instellen op treshhold waarde = waarde dat gemeten wordt wanneer drone op grond staat. self.positiondata.Z = distance time.sleep(self.timing/1000000.00) self.tof.stop_ranging() #unreachable with while true
Shell
UTF-8
2,353
3.9375
4
[]
no_license
#!/usr/bin/env bash # SPDX-License-Identifier: LGPL-2.1-or-later # Copyright © 2019 ANSSI. All rights reserved. # Safety settings: do not remove! set -o errexit -o nounset -o pipefail # Do not run as root if [[ "${EUID}" == 0 ]]; then >&2 echo "[*] Do not run as root!" exit 1 fi main() { if [[ -z "$(command -v cosmk)" ]]; then >&2 echo "[!] Could not find \"cosmk\". Aborting." exit 1 fi # Figure out which one of minisign or rsign2 is installed local sign="" if [[ -n "$(command -v minisign)" ]]; then sign="minisign -S -m" elif [[ -n "$(command -v rsign)" ]]; then sign="rsign sign" else >&2 echo "[!] Please install 'minisign' or 'rsign2'. Aborting." exit 1 fi local -r repo_root="$(cosmk repo-root-path)" local -r product="$(cosmk product-name)" local -r current_version="$(cosmk product-version)" # Figure out current and next minor version local minor_version="${current_version##*.}" local next_version=$((minor_version+1)) next_version="${current_version/%${minor_version}/${next_version}}" echo "[+] Preparing update from ${current_version} to ${next_version}..." # Setup update webroot for nginx running in ipsec-gw echo "[+] Setting up nginx webroot..." local webroot="synced_folders/ipsec-gw/update/" local dist="${webroot}/dist/${next_version}" mkdir -p "${webroot}/update/v1/${product}" mkdir -p "${dist}" echo "version = \"${next_version}\"" > "${webroot}/update/v1/${product}/version" # Copy ${product}-core & ${product}-efiboot echo "[+] Getting new ${product}-core & ${product}-efiboot..." local out="../out/${product}/${current_version}" cp "${out}/core/bundle/core.next.squashfs.verity.bundled" "${dist}/${product}-core" cp "${out}/efiboot/configure/linux.next.efi" "${dist}/${product}-efiboot" echo "[+] Signing ${product}-core & ${product}-efiboot..." local pubkey="../src/platform/updater/test/keys/pub" local privkey="../src/platform/updater/test/keys/priv" for f in "${product}-core" "${product}-efiboot"; do echo "" | ${sign} \ "${dist}/${f}" \ -p "${pubkey}" \ -s "${privkey}" \ -x "${dist}/${f}.sig" \ -t "${next_version}" done echo "[+] Done" } main
Java
UTF-8
663
2.078125
2
[]
no_license
package com.example.android.bakingapplication.dagger.module; import com.example.android.bakingapplication.presentation.DetailListFragmentPresenter; import com.example.android.bakingapplication.presentation.DetailListFragmentPresenterImpl; import com.example.android.bakingapplication.repository.RecipeRepository; import dagger.Module; import dagger.Provides; @Module(includes = RecipeRepositoryModule.class) public class DetailListFragmentPresenterModule { @Provides static DetailListFragmentPresenter provideDetailListFragmentPresenter(RecipeRepository recipeRepository) { return new DetailListFragmentPresenterImpl(recipeRepository); } }
Markdown
UTF-8
1,246
2.625
3
[ "MIT" ]
permissive
# whiskybook An app to manage the documentation of your whisky tastings ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. You will need the following tool installed an setted up on your computer - Node.js 8 - git - ssh ``` git clone git@github.com:Paquan/whiskybook.git cd whiskybook npm install npm start ``` ### Using Docker in VS Code When using VS Code you can install the [Remote Development Extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack). With it installed simply run the command Remote-Containers: Reopen in Container. VS Code will then build a Container with all the system dependencies of the programm (like node, git, parcel) installed. Start your browser at: http://localhost:1234 ### Fake-Backend If you want to work with real backend: ``` npm start --env=local-real-backend ``` ## Versioning We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags). ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
C++
UTF-8
2,008
3.1875
3
[ "Apache-2.0" ]
permissive
/** * AddressInfo.h * * Utility wrapper arround "getAddressInfo()" * * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * @copyright 2015 Copernica BV */ #pragma once namespace AMQP { /** * Class definition */ class AddressInfo { private: /** * The addresses * @var struct AddressInfo */ struct addrinfo *_info = nullptr; /** * Vector of addrinfo pointers * @var std::vector<struct addrinfo *> */ std::vector<struct addrinfo *> _v; public: /** * Constructor * @param hostname * @param port */ AddressInfo(const char *hostname, uint16_t port = 5672) { // store portnumber in buffer auto portnumber = std::to_string(port); // info about the lookup struct addrinfo hints; // set everything to zero memset(&hints, 0, sizeof(struct addrinfo)); // set hints hints.ai_family = AF_UNSPEC; // allow IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // datagram socket/ // get address of the server auto code = getaddrinfo(hostname, portnumber.data(), &hints, &_info); // was there an error if (code != 0) throw std::runtime_error(gai_strerror(code)); // keep looping for (auto *current = _info; current; current = current->ai_next) { // store in vector _v.push_back(current); } } /** * Destructor */ virtual ~AddressInfo() { // free address info freeaddrinfo(_info); } /** * Size of the array * @return size_t */ size_t size() const { return _v.size(); } /** * Get reference to struct * @param index * @return struct addrinfo* */ const struct addrinfo *operator[](int index) const { // expose vector return _v[index]; } }; /** * End of namespace */ }
Java
UTF-8
1,146
2.234375
2
[ "BSD-3-Clause" ]
permissive
package com.socialmanager; import android.os.Bundle; import com.socialmanager.SocialManager.Action; import com.socialmanager.SocialManager.Platform; public interface SocialActionListener { /** * Callback for completion, note that this method is called in sub-thread * @param platform Platform for the callback * @param action Action for the callback * @param bundle Bundle value containing completion data, please refer to {@link Constant} for the keys */ public void onActionCompleted(Platform platform, Action action, Bundle bundle); /** * Callback for failure, note that this method is called in sub-thread * @param platform Platform for the callback * @param action Action for the callback * @param bundle Bundle value containing failure data, please refer to {@link Constants} for the keys */ public void onActionFailed(Platform platform, Action action, Exception e); /** * Callback for canceling, note that this method is called in sub-thread * @param platform Platform for this callback * @param action Action for this callback */ public void onActionCanceled(Platform platform, Action action); }
Python
UTF-8
714
3.21875
3
[]
no_license
# Consume all memory import os from datetime import datetime import psutil memory_usage_limit_megabytes = 1000 def memory_usage_megabytes(): process = psutil.Process(pid) mem = process.memory_info().rss / 1_048_576 return mem print("Start eating memory...") print("Memory limit (MB): ", memory_usage_limit_megabytes) big_list = [] last_memory_usage = 0 pid = os.getpid() print("PID: ", pid) while last_memory_usage < memory_usage_limit_megabytes: big_list.append(datetime.now()) if len(big_list) % 1000000 == 0: last_memory_usage = memory_usage_megabytes() print("Element count: ", len(big_list), ". Memory usage (MB): ", last_memory_usage) print("The limit is exceeded")
Markdown
UTF-8
1,512
3.265625
3
[]
no_license
# Personnel-Management-System Project that uses binary search trees to arrange a list of names received from a text file, it can arrange the names in ascending or descending order. For this project, I used past notes from my data structures class, on the logic on how binary search trees work. I used online references to understand and implement the logic of binary search trees in c, i used https://www.tutorialspoint.com/c_standard_library/ and also http://stackoverflow.com/questions/7109964/creating-your-own-header-file-in-c to learn about header file for my program. When working on the program, Francisco Gallegos, Aaron Santellanes and myself talked about the struture of the insert Node method, we talked about how the algorithm worked and what ways it could be implemented. The command required to run my when in the directory where all my files are located are, $ make clean $ make all $ make demo This command will clean all .o files not required, create new .o files and then run the demo of my program. My program apparently arranges names in the binary search tree appropriately when hardcoded names are input into the tree, but when trying to enter names manually, it has a problem with some names due to the stringcmp() method. “This assignment was prepared in a manner consistent with the instructor’s requirements. Clear documentation must be provided for all significant collaboration or guidance from external sources (including algorithms or code presented in the textbook or this web site).
PHP
UTF-8
1,649
3.140625
3
[]
no_license
<?php require_once "Autoloader.php"; Autoloader :: register(); class Loger extends Etudiant{ private $batiment; private $chambre; public function __construct($matricule="",$nom = "", $prenom = "",$email="", $telephone="",$dat_naissance="",$batiment="",$chambre="") { parent::__construct($matricule,$nom , $prenom ,$email, $telephone,$dat_naissance); $this->batiment = $batiment; $this->chambre = $chambre; } public function getBatiment(){ return $this->batiment; } public function setBatiment($batiment){ $this->batiment = $batiment; } public function getChambre(){ return $this->chambre; } public function setChambre($chambre){ $this->chambre = $chambre; } public function addPersonnel(Personne $unePersonne ) { $this->personnes[] = $unePersonne; } public function findPersonnel($nom){ foreach ($this->personnes as $key => $value) { if($value->nom==$nom) return $value; } return null; } public function getListPersonne($type){ $tabperso=[]; for($i=0;$i<=count($this->personnes);$i++){ if(get_class($this->personnes[$i])==$type){ $tabperso[] =$this->personnes[$i]; } } return $tabperso; } //trouver un element dans une tableau a partir de // sa position public function find($i) { if($i>=0 && $i<count($this->personnes) ) return $this->personnes[$i]; return null; } }
Java
UTF-8
1,343
2.328125
2
[ "Apache-2.0" ]
permissive
package com.phodu.tambola.ticket.manage; import org.junit.Test; import com.phodu.tambola.board.FullBoardException; import com.phodu.tambola.board.InvalidGameException; import com.phodu.tambola.board.TambolaBoard; import com.phodu.tambola.board.manage.BoardManagementService; import com.phodu.tambola.profile.Profile; import com.phodu.tambola.profile.manage.ProfileManagementService; import com.phodu.tambola.ticket.TambolaTicket; public class TicketManagementTest { @Test public void test() { long gameId = BoardManagementService.createNewBoard(); TambolaBoard board = BoardManagementService.loadBoard(gameId); ProfileManagementService profileManagementService = new ProfileManagementService(); long profileId = profileManagementService.createProfile(); Profile profile = profileManagementService.loadProfile(profileId); long ticketId = TicketManagementService.createTicket(board, profile); TambolaTicket ticket = TicketManagementService.loadTicket(ticketId); for (int i = 0; i < 100; i++) { int drawnNumber = 0; try { drawnNumber = BoardManagementService.drawNextNumber(gameId); } catch (FullBoardException | InvalidGameException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (ticket.claimNumber(drawnNumber)) { System.out.println(drawnNumber); } } } }
Java
UTF-8
877
1.96875
2
[ "Apache-2.0" ]
permissive
package com.classic.clearprocesses; import android.content.Context; import com.classic.adapter.BaseAdapterHelper; import com.classic.adapter.CommonRecyclerAdapter; import org.github.yippee.notifytools.R; import java.util.List; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; /** * 应用名称: ClearProcesses * 包 名 称: com.classic.clearprocesses * * 文件描述: TODO * 创 建 人: 续写经典 * 创建时间: 2016/7/25 18:05 */ public class PackageAdapter extends CommonRecyclerAdapter<String> { public PackageAdapter(Context context) { super(context, R.layout.item_app_info); } @Override public void onUpdate(BaseAdapterHelper helper, String item, int position) { helper.setText(R.id.item_pkg, item); } }
Java
UTF-8
628
3.15625
3
[]
no_license
import java.applet.Applet; import java.awt.Font; import java.awt.Graphics; //write a program to move banner between two borders. public class MoveBanner extends Applet implements Runnable { Thread th; Font f; int c; public void init() { th=new Thread(this); c=1; f=new Font("Arial",Font.BOLD,30); setFont(f); th.start(); } public void run() { while(c<=900) { c++; try { Thread.sleep(5); } catch(Exception e) {} if(c>=900) { c=-200; } repaint(); } } public void paint(Graphics g) { g.drawString("Compact",c, 200); } }
Python
UTF-8
5,665
2.59375
3
[ "MIT" ]
permissive
import operator from collections import namedtuple from typing import List import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD num_workers = comm.Get_size() rank = comm.Get_rank() Transition = namedtuple( "Transition", [ "observation", "action", "extrinsic_return", "advantage", "agac_advantage", "value", "log_pi", "adv_log_pi", "logits_pi", "adv_logits_pi", "done", ], ) Batch = namedtuple( "Batch", [ "observations", "actions", "extrinsic_returns", "advantages", "agac_advantages", "values", "log_pis", "adv_log_pis", "logits_pi", "adv_logits_pi", "dones", ], ) class Memory(object): def __init__(self, max_size=1e6): self._storage = [] self._max_size = max_size self._pointer_position = 0 @property def num_elements(self): return len(self._storage) def add(self, transition: Transition): if len(self._storage) == self._max_size: self._storage[int(self._pointer_position)] = transition self._pointer_position = (self._pointer_position + 1) % self._max_size else: self._storage.append(transition) def reset(self): self._storage = [] self._pointer_position = 0 def sample(self, batch_size: int) -> Batch: if len(self._storage) < batch_size: raise ValueError("Not enough data in replay buffer to sample a batch.") else: ind = np.random.randint(0, len(self._storage), size=batch_size) op = operator.itemgetter(*ind) ( observation, action, extrinsic_return, advantage, agac_advantage, value, log_pi, adv_log_pi, logits_pi, adv_logits_pi, done, ) = list(zip(*op(self._storage))) batch = Batch( observations=np.array(observation).copy(), actions=np.array(action).copy(), extrinsic_returns=np.array(extrinsic_return).copy(), advantages=np.array(advantage).copy(), agac_advantages=np.array(agac_advantage).copy(), values=np.array(value).copy(), log_pis=np.array(log_pi).copy(), adv_log_pis=np.array(adv_log_pi).copy(), logits_pi=np.array(logits_pi).copy(), adv_logits_pi=np.array(adv_logits_pi).copy(), dones=np.array(done).copy(), ) return batch def get_advantages_stats(self): _, _, _, advantages, agac_advantages, _, _, _, _, _, _ = list( zip(*self._storage) ) advantages = np.array(advantages).copy() agac_advantages = np.array(agac_advantages).copy() # Share advantages between processes to get more accurate stats advantages = comm.allgather(advantages) advantages = np.concatenate(tuple(advantages)) agac_advantages = comm.allgather(agac_advantages) agac_advantages = np.concatenate(tuple(agac_advantages)) return ( advantages.mean(), advantages.std(), agac_advantages.mean(), agac_advantages.std(), ) def get_epoch_batches(self, batch_size: int) -> List[Batch]: if len(self._storage) < batch_size: raise ValueError("Not enough data in replay buffer to sample a batch.") else: idxes = np.arange(len(self._storage)) np.random.shuffle(idxes) num_batches = len(self._storage) // batch_size if len(self._storage) > num_batches * batch_size: num_batches += 1 num_batches = np.min(comm.allgather(num_batches)) idxes = idxes[: (num_batches * batch_size)] adv_mean, adv_std, agac_adv_mean, agac_adv_std = self.get_advantages_stats() batches = [] for i in range(num_batches): ind = idxes[i::num_batches] op = operator.itemgetter(*ind) ( observation, action, extrinsic_return, advantage, agac_advantage, value, log_pi, adv_log_pi, logits_pi, adv_logits_pi, done, ) = list(zip(*op(self._storage))) batch = Batch( observations=np.array(observation).copy(), actions=np.array(action).copy(), extrinsic_returns=np.array(extrinsic_return).copy(), advantages=np.array(advantage).copy(), # unnormalized agac_advantages=(np.array(agac_advantage).copy() - agac_adv_mean) / agac_adv_std, values=np.array(value).copy(), log_pis=np.array(log_pi).copy(), adv_log_pis=np.array(adv_log_pi).copy(), logits_pi=np.array(logits_pi).copy(), adv_logits_pi=np.array(adv_logits_pi).copy(), dones=np.array(done).copy(), ) batches.append(batch) return batches def save(self, outfile): np.save(outfile, self._storage) print(f"* {outfile} succesfully saved..")
C++
UTF-8
1,029
2.75
3
[]
no_license
#include <iostream> using namespace std; int n, m, cnt = 0; char a[55][55], b[55][55]; void changeMatrix(int x, int y){ cnt++; for(int i=x; i<x+3; i++) for(int j=y; j<y+3; j++) a[i][j] = (a[i][j] - '0') ? '0' : '1'; return; } int main(){ ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for(int i=0; i<n; i++) for(int j=0; j<m; j++) cin >> a[i][j]; for(int i=0; i<n; i++) for(int j=0; j<m; j++) cin >> b[i][j]; for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(a[i][j] != b[i][j] && (i+3 <= n && j+3 <= m)) changeMatrix(i, j); else if(a[i][j] != b[i][j] && (i+3 > n || j+3 > m)){ cout << -1 << "\n"; return 0; } for(int i=0; i<n; i++) for(int j=0; j<m; j++) if(a[i][j] != b[i][j]){ cout << -1 << "\n"; return 0; } cout << cnt << "\n"; return 0; }
Markdown
UTF-8
6,587
2.90625
3
[ "MIT" ]
permissive
--- layout: post title: Machine Learning 101 - Workshops & More at NIT Warangal --- <link rel="stylesheet" type="text/css" href="{{ site.baseurl }}/post.css" /> In my final year of Undergraduate studies, I wanted to start an active machine learning group in our college where like-minded people would come together, ideate, learn and publish. Not that such groups were a radically new idea of mine, it had been attempted in past but couldn't sustain. When I asked around, to my surprise, I found that many people were interested in the idea and were enthusiastic to join the group. But they wanted to join the group to simply learn ML because of the lack of a sound understanding of the theoretical and applied knowledge of the subject. That's when I realised that almost everyone is talking about ML and AI and they are excited by the possibilities that it has to offer. People also have all sorts of ideas that they want to approach using ML, be it in the field of computer science, circuit design, biotechnology or mechanical engineering, but they lack the requisite knowledge to realise these ideas. That’s when I decided to organize workshops for people to help them develop the skill set that will allow them to work on their on ML projects. Now, Tz (Tz...technozion is the annual flagship technical festival organized by NITW) preparation was also going on at full swing around the same time. So, I along with [Ashish Rai](https://www.linkedin.com/in/raishish/) and [Protik Biswas](https://www.linkedin.com/in/protik-biswas-293605109/) came together to organize the workshops in collaboration with Tz-17 and CSEA (Computer Science and Engineering Association). Tz-17 provided us the opportunity to serve a larger target audience and we also decided to organize a ML contest as a Full-Fledged online event. The event also served as an incentive for people to learn and work on a practical ML problem to test their skills. CSEA at the same time took care of logistics for the workshops and later for contest. The team was formed! ![ML Workshop Team]({{site.baseurl}}/images/ml1.jpg "ML Workshop Team") As enthusiastic as I was to deliver the sessions, Now came the hardest part - preparing the content for the first ever ML workshop for a diverse audience with varying knowledge of the pre-requisites in calculus, linear algebra and computer programming etc. Ashish, Protik and I decided to keep the content completely separate from the programming. Because Many first year students were still writing their first c++ program. That doesn’t mean that we didn’t encourage them to get their hands dirty and dive right in to understand the implementation challenges which are as intriguing as the theory backing it, But we kept the programming exercises optional for all. Preparation took-off on other fronts as well. Posters were designed and shared across platforms. Below is the poster we came up with for our workshops. ![ML Series Poster]({{site.baseurl}}/images/ml-series.jpg "ML Series Poster") About 360 people from different engineering specializations and courses including B.Tech, M.Tech and MCA registered for the first workshop out of which 250 showed up. I was overwhelmed by the huge response we had received. The content delivery was a big challenge for addressing such a large audience but thanks to Ashish and Protik who filled in whenever I missed some point and also took over to suggest alternate views and helped in giving personalized support to the audience, we were able to manage well. The first workshop lasted for about 5 hours in 2 sessions, one before lunch 10-1 and next post lunch from 2-4. It was a huge success. This further motivated us to organize such sessions in future. ![ML Workshop Session]({{site.baseurl}}/images/ml3.jpg "ML Workshop Session") We organized three workshops as part of the series and covered a wide spectrum of algorithms including linear regression, logistic regression, neural networks, support vector machines, k-means, decision trees etc, along with some techniques and practical issues around them including L1 norm, L2 norm, tree-pruning, class imbalance, one-hot encoding, gaussian noise, underfitting, overfitting, bias and variance, vectorization, effects of outliers, cross-validation, K-fold-cross-validation, batch, mini-batch and stochastic methods etc. We also discussed some mathematics here and there to help us provide solid foundational support for formulas and some intuitive justification around them including linear algebra, calculus, partial derivatives, optimizations, convex and concave functions etc. We focussed on the programming exercises for people who wanted to work on their implementation skills. We asked them to write their own logic for algorithms as well as introduced libraries for the same. We created elaborate assignments for people on Jupyter notebooks and used scipy, numpy, scikit-learn, matplotlib and some other open-source tools. ![ML Workshop Session]({{site.baseurl}}/images/ml4.png "ML Workshop Session") We organized a special coding session where we discussed 2017’s Goldman Sachs GS-Quantify ML problem statement and built several solutions around it. The session was organized specifically to introduce how multiple algorithms can be used together, to demonstrate the importance of data cleaning and pre-processing and gathering useful insights by doing simple statistical analysis on the data. It was a very interesting problem statement and dataset I had encountered recently. We discussed how handling class imbalance and hyper-parameter tuning could affect the model performance among few other practical insights. Next, we organized Tz ML contest on kaggle which was open to public and allowed people to put the skills they had learnt to use. We saw good participations and innovative solutions to the problems. ![ML TZ Session]({{site.baseurl}}/images/tz-ml.jpg "ML TZ Session") We also later organized a deep learning session where we discussed CNNs, Auto-Encoders, RNNs, RBMs etc and focussed on some other projects we had been working on, to give our audience an idea of the kind of research work that goes on in the field. Around that time I was working on Discriminatory Scatternets for my UG thesis. You can read more about my work in [this blog post](https://architkansal.github.io/Discriminatory-Scatternet). ![ML Workshop Session]({{site.baseurl}}/images/ml2.jpg "ML Workshop Session") Overall, I must say it was an awesome experience for me. I learnt a lot out of these sessions and exercises both on the technical and non-technical fronts.
JavaScript
UTF-8
3,086
3.75
4
[]
no_license
/** * @author Essmaker, Jo'Anne (joannessmaker@gmail.com) * @summary Project 4 || created: 10/15/2017 */ "use strict"; const PROMPT = require('readline-sync'); let continueResponse; let movieRating1, movieRating2, movieRating3, totalRatingSum, averageRating; let movieTitle; function main() { process.stdout.write('\x1Bc'); setContinueResponse(); while (continueResponse === 1) { setMovieTitle(); setMovieRating1(); setMovieRating2(); setMovieRating3(); setTotalRatingSum(); setAverageRating(); printAverageRating(); setContinueResponse(); } return main(); } main(); /** * @method setContinueResponse * @desc Continue Response */ function setContinueResponse() { if (continueResponse = null) { continueResponse = 1; while (continueResponse !== 0 && continueResponse !== 1) { continueResponse = Number(PROMPT.question(`\nDo you want to continue? [0=no, 1=yes]: `)) } } else { continueResponse = 1; } } /** * @method setMovieTitle * @desc Input Movie Title */ function setMovieTitle() { movieTitle = PROMPT.question(`\nPLEASE ENTER MOVIE TITLE: `); } /** * @method setMovieRating1 * @desc Rating of Action Sequences */ function setMovieRating1() { movieRating1 = Number(PROMPT.question(`\tHow Many Stars Would You Rate the Action Sequences in ${movieTitle}? `)); if (movieRating1 < 0 || movieRating1 > 5) { console.log(`\tI'M SORRY, PLEASE RATE THIS MOVIE FROM 1-5 STARS. PLEASE TRY AGAIN. `); return setMovieRating1(); } } /** * @method setMovieRating2 * @desc Rating of Plot */ function setMovieRating2() { movieRating2 = Number(PROMPT.question(`\tHow Many Stars Would You Rate the Plot for ${movieTitle}? `)); if (movieRating2 < 0 || movieRating2 > 5) { console.log(`\tI'M SORRY, PLEASE RATE THIS MOVIE FROM 1-5 STARS. PLEASE TRY AGAIN. `); return setMovieRating2(); } } /** * @method setMovieRating3 * @desc Rating of Main Character */ function setMovieRating3() { movieRating3 = Number(PROMPT.question(`\tHow Many Stars Would You rate the Main Character in ${movieTitle}? `)); if (movieRating3 < 0 || movieRating3 > 5) { console.log(`\tI'M SORRY, PLEASE RATE THIS MOVIE FROM 1-5 STARS. PLEASE TRY AGAIN. `); return setMovieRating3(); } } /** * @method setTotalRatingSum * @desc Sum of all three ratings */ function setTotalRatingSum() { totalRatingSum = (movieRating1 + movieRating2 + movieRating3); } /** * @method setAverageRating * @desc Average of all three ratings */ function setAverageRating() { averageRating = totalRatingSum / 3; } /** * @method printAverageRating * @desc Print Average Rating To Screen */ function printAverageRating() { console.log(`\t${movieTitle} = ${averageRating} STARS `) } /* Movie Kiosk: Re-factor your code to run a kiosk at a movie theater. Program should loop infinitely to allow user to either see average rating of previous user entries or enter their own review. */
Shell
UTF-8
2,041
4.09375
4
[]
no_license
#!/bin/bash ## # script simply # - installs postgres, psql (client) and psycopg2 (client driver). # - also adds a superuser, because permissioning was a bit awkward in python driver # # # usage # while getopts ":h" opt; do # n.b. getopts starts at 1st argument ($1) and stops at the 1st non-option argument case ${opt} in h) echo "Usage:" echo " setup-db -h " echo " setup-db setup [-u user] Install postgres, postgres client and driver. Include user other than current user as a superuser. Additional configuration will be required for anyone but current user whoami." exit 0 ;; \?) echo "Invalid Option: -$OPTARG" 1>&2 exit 1 ;; esac done shift $((OPTIND -1)) # # install # user=$(whoami) # default subcommand=$1; shift 1; # shift to ignore 1st non-option arg case "$subcommand" in setup) # see if user is specified while getopts ":u:" opt; do case ${opt} in u ) user=$OPTARG ;; \? ) echo "Invalid Option: -$OPTARG" 1>&2 exit 1 ;; :) echo "-$OPTARG requires an argument." exit 1 ;; esac done # finally go ahead with install... # dependencies sudo apt update; sudo apt install postgresql postgresql-contrib postgresql-client postgresql-client-common libpq-dev; python3 -m pip install psycopg2; # TODO virtualenv? # TODO rebuild http://initd.org/psycopg/articles/2018/02/08/psycopg-274-released/ # user # postgres permissions are slightly annoying, couldn't set up with python client (which is why this script is not just a few `apt installs`) sudo -u postgres psql -c "CREATE USER $user WITH PASSWORD '';" sudo -u postgres psql -c "ALTER USER $user WITH SUPERUSER;" ;; esac
Markdown
UTF-8
23,932
3.046875
3
[ "MIT" ]
permissive
--- layout: post title: Financial Statement Insights date: 2020-09-25 summary: categories: biz --- * 主題:從財報數字看懂經營本質 * 目標:能夠從財報中,真的看出一些 insights 而不是只會算 * 緣起:上學期修完初等會計一已經會看三種財報、但還是不知道怎樣的數字才合理、怎樣的數字是有危機的 ### 讀財報 1. 了解資產負債表,現金流量表,損益表的意涵 2. 了解表上面數字隱含的意思,數字落在哪個區間才健康 ### 稻盛荷夫:財報的四步驟 - 財報須呈現真實經營情況 - 不要修飾帳面數字,例如內帳、外帳差很多 - 經營者須對數字有敏銳度 - 資產縮水:一堆呆滯存貨不清掉,一堆收不回來的 account receivable - 獲利停滯:張忠謀說,revenue growth (5%) < earning growth (7%) 才好,不可讓 revenue growth (5%) > earning growth (3%) → 這代表失去成長動力 - 產品被迫降價,造成獲利(earning)成長變差,損害毛利 - 成本的增長吃掉 earning growth - 對數字追根究底,問為什麼 - 「今年 Q1 提列較多呆帳,導致獲利受影響」 → 為什麼提列呆帳?不能就這樣帶過 - 阿米巴(變形蟲)管理法 - 「利潤中心」把公司切成各種利潤中心來管理 - 讓每個員工都是某個利潤中心的一個角色。所有同一個利潤中心的人們都要共同拼此利潤中心的業績。 - 例如一條航線是一個利潤中心,空姐機長地勤都要想辦法讓這條航線賺錢,衝績效表現。 - 日航的案例 ### 股本、股數 - 每一股面額都是 10 元 - 發行股數 * 10 = 股本 - 例如:台積電帳上股本 = 2593 億元,所以他有 259.3 億股流通在外 ### EPS v.s. ROE v.s. ROA - ROE 簡單來說,就是「公司用自有資本賺錢的能力」,反應了「運用資源的效率」。 - 若說 EPS 是用來評估企業賺了多少獲利的指標,那麼 ROE 便是用來評鑑企業「賺得多有效率的指標」 - 一間公司若是 EPS 高但 ROE 卻很低,則代表公司雖然有賺錢,卻賺的沒有效率 - 累積了許多保留盈餘(Retained Earnings,屬於 Owner's Equity 的一種)卻無法有效利用。 ROE = Net Income / Owner's Equity = Net Income / (Assets - Liability) - 依據公式,ROE可以靠 Liability 來提升,因為負債高、分母小、ROE 就大。 - 所以在「負債比高」的產業 (如: 銀行業、金控業) 則不適合用 ROE 來判斷。 - ROE 數值愈高,獲利能力愈佳 → 公司能有效利用股東資金,所以股東就可能享受到公司所給予的獲利愈多。 - ROE 的計算是不包含股價的,所以無法單獨使用於選擇股票。 ROA = Net Income / Assets - ROA 適合作為負債比例高的行業(銀行業、金控業) 的指標,他是公司「用所有的資產賺錢的能力」。 - ROA 越高表示資產利用率越好,資產大多為了營運所需,沒有虛資產 - 一般而言我們會「希望 ROA 高於銀行利率和長期公債利率」 - 需要注意的是**「若公司的 ROE 高,但 ROA 卻很低」**,這代表公司主要獲利多是來自**高財務槓桿、負債很高(例如銀行)。**相對的投資風險會因此提高。 ### 張忠謀:「無法量化就無法管理」三原則 - 高品質的資產負債 - 具有結構性獲利能力 - 現金流穩定流入 ### 高品質的資產負債 - 沒有高估的資產 → 不要有存貨、應收帳款一堆、沒用的設備 - 借殼上市:一家僵屍公司 A 在做化纖的,他已經沒用了,現在有一家 LED 公司 B來借殼這家 A公司上市 - 化纖的廠房,對於 LED 的生產一點用都沒有 - 照理說要把A的設備淘汰,但都掛著當資產沒使用 → 資產高估 - 沒有低估的負債 → 負債再怎麼可怕都要詳細說明,不要刻意低估給股東看 - 健康的負債比例 → 負債比率=負債總額/資產總額 x 100% - 波動越小的產業,可以承受越高的負債比 - 銀行 90%,製造業 60%,科技公司只能 40% - 台積電 2018 年的負債比是 23%,表現比同業好很多(同樣是科技公司) - 沒什麼「虛資產」 - 商譽就是虛資產 - 總言之,資產大多為了營運所需,同時沒有重大負債 → GOOD ### 具有結構性獲利能力 - 獲利成長率,需大於營收成長率 → 這才是附加價值有成長 - how? 掌握市場定價權,蘋果走在前端就可做到 - 大立光的技術優勢也是 - 營業費用與獲利結構平衡 - 營業費用(operating expense)分為「固定費用」與「變動費用」跟 COGS 是不同的東西 - 營業費用包含管理、銷售、研發 - 銷售費用成長太快,代表產品不夠有力,才需要一直打廣吿,撐不久 - 管理費用成長太快,代表公司管理不夠有力 - 研發費用是投資未來,但要考量現有股東利益。有時候為了存活只能管現在 - 損益平衡點,必須控制在低點 - 營業費用分為固定費用與變動費用 - 固定費用比例越少越好,變動費用比例越大越好 - 這樣景氣不好、賺不到錢時,費用可快速下調 - 如何減低固定費用?車商去談說把設備費用攤提給全體供應商去分擔,減少自身的固定費用 - 良好的獲利能力、內部籌資能力 - 獲利能力不可只看 EPS,也要看 ROE 才是對大股東負責 - EPS = earning per share,稅後淨利 / 股本。 - 對投資人重要 - 與股價關係密切 - ROE = Return of Earnings,稅後淨利 / 股東權益。 - 對大的股東、董事會重要 - 代表股東權益有被充分利用 - 內部籌資能力 → 能產出企業投資、發放股利的這些現金流量 ### 現金流穩定流入 - 虧損不可怕,不管賺或賠,產出良好現金流就都沒事 - 現金流 = 企業投資、發放股利的來源 - 現金流 = 營業活動、投資活動、籌資活動 - 目標是「讓營業活動產出的現金,能適時支援投資+籌資活動需要的現金」 - 台積電 2018 年投入 3000 億買設備(投資活動)、而且發放股東 2000 億股利(籌資活動) → 營業活動必須賺到 > 5000 億現金才夠 - 營業賺錢 → 支撐買設備 + 發股利 ### 宏觀的資產負債表 - 資產總額,越大越具有影響力,但須注意主要業務是否集中 - 正向例子:台積電(大到不能倒、業務又集中) - 反面例子:大同、美國 GE(什麼產業都想碰,結果樣樣不精) - 由資產比重高的項目(科目)去判斷在該產業的競爭強度 - 銀行業:貼現、放款 - 零售業:現金、存貨 - 電玩產業:現金、應收帳款、其他應收款 - 晶圓代工業(資本與技術密集):「不動產、產房及設備」、現金 - 台積電不動產 51% 現金 28%,幾乎是 80% 資產 - 其實公司手上持有較多的現金,在景氣佳時可投資技術與規模 - 不佳時也較有利渡過,故現金為一重要指標 - 「設備」→「現金」→「應收」→「存貨」可為一循環,為製造業日常營運必備的資產 - 有設備才能研發,有現金才能調度,有應收帳款代表銷貨後客戶還沒給錢,有存貨代表有材料或是有做好的產品的庫存。 - 台積電此四項佔了 90% → 資產大多用於營運所需 - 除了這四類以外的資產,則是要越少越好,如:商譽、客戶關係等虛資產 - 資產運用效能:年營收 / 平均資產總額([年初+年末]/2) - 台積電的是 0.51 元營收/每一元的資產,其他同業只有 0.41 ### 與同業比:資產負債表 - 流動比率:流動資產 / 流動負債 - 基本上超過120%,過150%較佳;低於100%就不好了,像是只有 23 % 這種就穩倒的 - 負債比率 - 過高過低都不好,景氣波動大的產業低於四成為佳 - 波動小者五成以內為佳。例外:電廠、港灣、電信,可到七成 - 台電甚至可到九成 - 通常銀行看到負債比率> 70% 就不會給你貸款,銀行會希望你趕快跟股東增資 - 在算負債比率時,有時會把無形資產(商譽、客戶關係)扣掉,因為快倒掉的公司、這兩項根本沒意義 - e.g., 如興,121 / 263 億 = 46%,但是扣掉無形資產 80 億,只剩 121 / 183 = 66% 就蠻危險的 ### 微觀角度的資產負債表 - 一個月的現金及約當現金 ~= 日常開銷+資本支出+股息 = 年度支出 / 12 - 此值要大於兩個月,即保持兩個月的現金「安全水位」 - 故投資人有時不該只看現金多寡,而是需細算出現金安全水位 - 不要把現金都放在借款銀行 - 有些人覺得現金保留很少,因為覺得一拿到現金就該去還銀行貸款 → 但這樣出事情就破產了 - 抽掉銀根(Monetary Situation):市場上貨幣周轉流通的情況(央行負債 → 信用貨幣) - 大多好公司現金水位都很高,兩個月到半年。 - 應收帳款天數約在兩個月左右,不宜超過三個月 - 太多天數很奇怪,代表說你有一堆客戶收到貨都不給錢 - 太少也很怪,代表你沒啥客戶、或是客戶都是一收到貨就給錢,不太合理 - 應收帳款週轉天數 = (期末應收帳款) / (全年銷售額) * 365 - c.f., Account Receivable Turnover Ratio: 應收帳款率 - 台積電的是 1292e/10315e * 365 = 46 天的應收帳款週轉天數,意思是:台積電出貨後,平均 46 天能收到錢。同業大概是 58 天,比較慢。 但是仍然在 60 天(兩個月)還不錯 - 存貨周轉天期約在兩個月左右 - Inventory Turnover Ratio: 存貨週轉率 - 存貨週轉天數 = (期末存貨金額) / 全年 COGS * 365 - 正常公司的存貨大約是二個月,但也不能太低,以免造成沒有原料生產或無貨可賣的情況 - 台積電的是 71 天,略差於兩個月 - 超過三個月也很奇怪,代表可能呆帳或作假帳(太多應收帳款卻不去收)或者經營弱、收不回錢。你一次買原材料(COGS),買三個月的份真的都用得光嗎? - 當公司存貨天數不合理的低,例如5 天、8天的,通常表示假交易做的太火熱所致。 ### 宏觀角度的損益表 - 企業競爭力看營收的「成長性」及「穩定性」 - 毛利出現顯著變動時,應去想是短、中、還是長期現象 - ROE 比 EPS 更能反映經營能力,聰明的股東應該看這個 ### 現金流量表 - 分為營業、投資、籌資活動 - 若無法從營業上獲得現金,基本上獲利就是不健康的(太多存貨或者應收帳款) - 自由現金流量=營業活動現金 – 資本支出 – 利息 - 自由現金流量代表可以增加現金股利的空間 ## 企業做假帳的六個特徵 ### 特徵1:過高的應收帳款天數 - 獲利 = 營收 - 成本 - 費用 - 可以增加營收、或是減少成本 or 費用來達到看起來更高的獲利 - 同時增加營收+成本,就能有合理的正常獲利 - 同時,營收一直增加、感覺也更像公司未來很好,會帶動股票上漲 - 創造營收的方式通常是先找一批不存在或是呆滯的存貨,然後安排幾個人頭公司來交易這批貨 - 比如甲公司先以100萬元向B公司購入一批空貨 - 然後將這批貨以120萬元賣給A公司 - A公司接著再以120萬轉回給B公司 - 從完成營收增加120萬、利潤增加20萬 - 接著甲公司再以120萬元向B公司買回這批貨,再以140萬元賣給A公司。如此這般不斷重複,就可以創造出要多少營收與利潤就有多少營收與利潤的財務數據。 - 第一次偽交易會為它創造120萬元的營業收入,同時也為它創造出100萬元的營業成本。 - 有20萬(120萬-100萬)的獲利(利潤) - 除非老闆拿錢來填利潤這個缺口,否則這個利潤會永遠留在應收帳款裡銷不掉。 - **Debit: 120w Account Receivable** - **Credit: 100w COGS** - **20w ???? → 需要有錢來填上** - 做假帳的目的通常是炒股票,如果老闆真的因此賺到錢,他從賺的錢中拿一部份出來把洞補就好 - 所以怎麼抓假帳?觀察他「利潤沖不掉」或者「應收帳款被挪用」 - 老闆若沒有即時拿錢來填虛假利潤這個洞,藏在應收帳款裡的虛假利潤金額,就會愈來愈高 → 利潤沖不掉 - 當老闆資金不足、卻想要炒股時,最簡單的方法就是在假交易中,「早付應付帳款、晚收應收帳款」,就可以挪用公司的資金去炒股。因為一堆被晚收的應收帳款,所以應收帳款金額就愈高。 - 公司的整體帳齡超過三個月(90 天),除非有特殊原因,不然有可能是有巨額呆帳未承認或是存有假帳 - 博達案:平均收款天數達到 347 天 ### 特徵2:過低的存貨天數 - 企業通常不會為了做假帳而去買一大批不需要的存貨進來 - 所以公司帳上的存貨,通常還是真正可以出售的存貨 - 以致期末存貨與銷貨成本比起來期末存貨就會變得很小 - 將「(期末存貨 / 銷貨成本)X 365 天」所得出來的天數就會比同業低很多。 如果一家公司與同業相較,同時有「應收帳款天數過高」與「存貨天數過低」這兩個指標,做假帳的機率高達九成。 ### 特徵3:過高的不動產、廠房及設備 - 比較精明的假帳,會將應收帳款轉成「不動產、廠房及設備」、「長期投資」、「現金」及雜項資產。我們先講轉入「不動產、廠房及設備」。 - 如果一家公司的應收帳款不合理,但應收帳款突然在某一個時點消失不見,而「不動產、廠房及設備」卻大幅增加,有可能是該企業以高於市價方式購入資產(例如設備) - 跟其他同業比較此項就看得出來是否造假 ### 特徵4:過高的長期投資 - 也可能藉由高價投資股票方式大筆買進,來消化「應收帳款」或掏空公司的資產 - 根據 MGMT 1A 所教的,如果買一個股票後,佔那家被投資公司的 50% 以上的股權 → 這家被投資公司就會被編入我們的合併報表 - 其過高的價格就會反應在商譽上 - 土地、廠房或設備大多有市價可參考或推算,要追查價格是否太高比較容易 - 未上市櫃公司的合理股價就比較不容易推算,尤其電子、遊戲、生醫等企業的合理股價 ### 特徵5:過高的現金 - 博達案怎麼做到的? - 博達為了消化應收帳款金額,將幾十億元的應收帳款「賣」給國外銀行 - MGMT 1A 有教「之後客戶會還錢啦,你那時候就可以把應收帳款領回來了」於是當成商品賣給別人 - 博達與銀行協議,在銀行尚未收到應收帳款的錢時,銀行為了買這筆帳款所付給博達的現金,博達不能領出來。 - 超怪的,我賣了產品給別人(銀行),然後別人把產品收走了,也說要給我錢。但那筆錢我去不能用。為什麼博達還同意這種條件? - 換句話說,搞了半天這個交易有做等於沒做。 - 博達因此在交易帳上大砍應收帳款、大增現金。 - 財報上顯示,該公司有92億元的借款,而手上現金卻高達53億元。 - 明明借款的利息高、存銀行的利息低,你為什麼不把手上現金去還掉借款? - **如果一家公司的現金不合理的高,尤其「現金與銀行借款兩者都很高」,就是不合理的現象** ### 特徵6:過高的雜項資產 - 為了抵銷應收帳款,公司會用很多雜項來抵銷 - 同業沒有這些雜項或是金額很少,投資人就該小心 ### 製造假帳錢的非財務警訊 - 老闆的誠信被質疑 - 經營階層變動,尤其財務長調職 - 財務長通常不能馬上離職,需要先調職一個月到其他部門、才能離職。職務調整與離職,通常被劃上等號 - 一開始財務長都知情,但他會相信董事長能用應收帳款填平開缺。但發現不行時就會逃了 - 獨立董事通常最晚發現,被矇在谷底 - 負債比偏高+財會經理離職 → 不正常。 - 市場上利多消息不斷,但是公司一直出來澄清 - 炒股票的手段,這樣波動大 - 企業處於被借殼後的初期階段 - 有些殭屍公司股票脫不了手,就會自願被別人借殼,讓這些股東能脫手這些爛股 - 借殼的公司也能重新活化。但通常借殼公司都是因為自身財務不好,才需要活化資產,已辦理現金增資之類的 - 才剛借殼,就看到營收大幅成長,同時營業活動的現金流卻沒什麼漲 → 很可能是炒股 - 營收增加,照理說應該是有現金 or 應收帳款增加 - 結果大多都是應收帳款,現金沒多少。那就是同樣問題。 - 處於低潮的產業,卻獲利特高 ### 七個產業特性 #### 電子組裝業 - 台灣電子組裝業因為毛利率極低,而常被媒體及投資人批評。 - 毛利率低固然不好,但是其低毛利的原因,其實大部分可歸因於產業特性。 - 鴻海毛利率雖低,但一年好歹也為投資人賺了約1,300 億元,是台灣 IC 設計業龍頭聯發科的6倍。 - 營收數字是電子組裝業獲利的關鍵。 #### IC 設計業 - IC 設計業是半導體業的最上游,也是台灣最具國際競爭力的產業之一。 - 近來在AI、5G、車用、高速傳輸等用途帶領下,很多股價大漲的個股,如譜瑞、祥碩,都是IC 設計業中的佼佼者。I - C 設計業是投資人討論最多,也最愛投資的產業之一。 - 簡單說,毛利率和研發費用率是IC 設計業成功的關鍵。 #### 實體通路業 - 實體通路業是毛利率及獲利率最穩定的產業,也是最不受景氣影響的產業 - 也因此成了股價最牛皮的產業,另一方面,則是不景氣時最好的投資去處 - 一個具經濟規模的通路商,即使有「極高的負債比率」與「較低的流動比率」,也依然能夠自在逍遙 #### 餐飲業 - 採直營店與採加盟店方式經營的餐飲業,其成本與費用結構有很大的差異 - 受新冠肺炎疫情或其他因素影響的衝擊,反映在財報上,也會有很大的不同 - 此外,經營精緻餐飲與經營庶民餐飲的餐飲業,受疫情或其他因素影響的衝擊,反映在財報上,也會呈現截然不同的樣貌 #### 生技業 - 最容易造成股民虧損的股票就是生技股 - 被不懂生技業的立委或學者批評不應准許其上市的產業,經常就是針對生技業 - 這是一個容易被誤解的產業,投資生技業可能會大賺,也可能會虧得一文不剩 - 通常來說,生技業的高股價與財報無關;但是從它們的財務狀況,卻可以幫助我們判斷何時應該逃命。 #### 銀行業 - 即使是學過會計的人,也大多看不懂銀行業的財報 - 看不懂的原因,首先是不瞭解銀行業的獲利模式 - 其次是銀行業的財報編製準則、從來也不曾站在投資人的立場去思考如何才能讓人看得懂 - 一般投資人要搞懂這個章節,確實很難 #### 壽險業 - 壽險業是所有產業中業務最特殊、最難懂、會計準則也最奇怪的產業 - 往往大家認為它應該賺了大錢時,它虧了; 當大家認為它應該會虧時,它反而賺了 - 可是,如果讓看得懂壽險業財報的人去研究財報內容,又會得出與財報損益數不同的結論 - 如果說銀行業的財報很難懂的話,那麼可以說,壽險業的財報就像天書一般 ### 舉例:IC 設計業(聯發科、瑞昱、聯詠)─資產負債表的 5 大特色 #### 不動產、廠房及設備比重低 - 同屬於半導體業,晶圓代工跟 IC 設計不一樣。台積電是前者,聯發科是後者 - 因為沒有生產設備及無塵室的投資,IC設計業在「不動產、廠房及設備」以及「使用權資產」的金額普遍較低 - 如2019年聯發科、瑞昱及聯詠,這方面的金額都只佔總資產的7%到9%之間 - 相較之下,從事晶圓代工的台積電,2019年上述兩個科目即高達總資產的61% #### 現金及長短期投資多 - IC設計業只要經營不差,極容易累積現金。原因有兩個 - IC設計業不需像晶圓代工業一樣須花費巨資在價格昂貴的無塵室及設備上,所以賺到錢就真的賺到錢,不用再掏出來 - 其次是配合政府政策賺取利差所致 - 首先要從我們的外貿和匯率政策說起。由於臺灣外貿長期一直處於順差,政府為了避免台幣大幅升值,就採取了兩個「不能說的政策」 - 一是個人國外所得大致在670萬元之內(實際數要視個人情況)免稅,二是維持台幣偏低的利率。 - 雖然第一項與企業無關(只有自然人能享受到670萬元免稅這個好處)但大公司可以借 1%多的低利台幣,轉投資到利率3%~8%的海外債券或特別股 - 於是我們可以看到聯發科及瑞昱賺取10億乃至數十億元的利率差 #### 存貨是罩門所在 - IC設計業的客戶大多是製造業大廠,或是大聯大 之類的電子流通業大廠 → 所以發生倒帳的機會不大 - 但如果產品賣不出去呢?遇到這種情形通常就要降價求售了 - IC設計業的毛利率通常在 40% 左右,甚至更高,如果一家公司的毛利率和以前比起來大跌10%,就暗指其產品不佳,這時存貨週轉天數也會出現異常,天數會暴增 #### 無形資產佔比高 - IC設計業的無形資產大約可分為兩種 - 一類是為了設計而買入的專利權或專門技術 - 另一類是因合併所帶進來的專利權、專門技術及商譽。 - 什麼是專利、專門技術、商譽? - 假設今天聯發科想要以新台幣1,100億元買下聯詠,但聯詠截至2019年底的帳面淨值只有約330億元 - 這中間的差額770億元在財報上必須有個去處,於是大家需要找出聯詠帳上「被低估的財產」 - 假設發現聯詠的矽智財有許多專利,而且其IC設計技術有獨到之處,其中專利權值70億元,專門技術值200億元,就可以被拿來補差額 - 最後還有其他500億元不知擺哪裡,那麼這500億元通常就會被歸類為商譽。 - 在大公司裡,商譽金額通常都很大,例如 Qualcomm 在2019年帳上約有63億美元的商譽,佔股東權益的128%;Broadcom(博通) 在2019年帳上約有367億美元的商譽,佔股東權益的147%。 - 在IC設計業新功能或新種類IC不斷出現,讓每家IC設計公司的核心獲利能力不斷改變的情形下,這些商譽到底還有多少是存在的呢? #### 負債比率低 - 大型IC設計業錢多、設備少,不太需要負債 - 除了 Qualcomm 及 Broadcom 的負債比較高,其他大型IC設計公司的負債比率通常都不高。 - 小型 IC 設計公司,因為產品線比較單薄,為了預防新產品接不上來時,還要繼續投資在研發費用上,通常也會保持在50%以下的負債比率。 ### References - [PTT: 大會計師教你從財報數字看懂經營本質](https://www.ptt.cc/bbs/book/M.1573889769.A.459.html) - [《大會計師教你從財報數字看懂經營本質》:預先看出財報地雷——企業做假帳的六特徵](https://www.thenewslens.com/article/121472) - [博客來:大會計師教你從財報數字看懂產業本質](https://www.books.com.tw/web/sys_serialtext/?item=0010864916)
C#
UTF-8
1,339
3.0625
3
[ "MIT" ]
permissive
using System; namespace Duracion { class Duracion{ private int Hr; private int Mi; private int Seg; private int mit; public Duracion(int H, int M, int S,int mt ){ Hr = H; Mi = M; Seg = S; mit =mt; } public void print(){ Console.WriteLine("Horas :"+Hr+" Minutos : "+Mi+" Segundos :"+Seg ); Console.WriteLine("Minutos totales :" +((Hr*60)+Mi) ); } } class Program { static void Main(string[] args) { Duracion Cancion = new Duracion(0,02,52,00); Duracion Clases = new Duracion(0,50,59,00); Duracion Concierto = new Duracion(3,40,40,00); Duracion Partido = new Duracion(1,30,00,00); Duracion Caricatura = new Duracion(0,40,40,00); Duracion Peliculas = new Duracion(2,10,00,00); Console.WriteLine("Cancion"); Cancion.print(); Console.WriteLine("Clases"); Clases.print(); Console.WriteLine("Concierto"); Concierto.print(); Console.WriteLine("Partido de futbol"); Partido.print(); Console.WriteLine("Caricatura"); Caricatura.print(); Console.WriteLine("Pelicula"); Peliculas.print(); } } }
Java
UTF-8
4,958
1.734375
2
[]
no_license
package com.banry.pscm.persist.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.type.JdbcType; import com.banry.pscm.persist.mapper.TenderPlanSQLBuilder; import com.banry.pscm.service.tender.SupplierBidItemRate; public interface SupplierBidItemRateMapper { @SelectProvider(type = TenderPlanSQLBuilder.class,method = "findRateBySqlWhere") List<SupplierBidItemRate> findRateBySqlWhere(String sqlWhere); @Select({"select * from supplier_bid_item_rate where division_sn_code = #{divisionSnCode,jdbcType=VARCHAR}"}) @Results({@Result(column = "item_bid_code", property = "itemBidCode", jdbcType = JdbcType.VARCHAR, id = true), // @Result(column = "division_sn_code", property = "divisionSnCode", jdbcType = JdbcType.VARCHAR), @Result(column = "supplier_credit_code", property = "supplierCreditCode", jdbcType = JdbcType.VARCHAR), @Result(column = "name", property = "name", jdbcType = JdbcType.VARCHAR), @Result(column = "first_bid_unit_rate", property = "firstBidUnitRate", jdbcType = JdbcType.DOUBLE), @Result(column = "end_bid_unit_rate", property = "endBidUnitRate", jdbcType = JdbcType.DOUBLE)}) SupplierBidItemRate findSupplierBidItemRateByDivCode(String divisionSnCode); @Select({"select * from supplier_bid_item_rate"}) @Results({@Result(column = "item_bid_code", property = "itemBidCode", jdbcType = JdbcType.VARCHAR, id = true), // @Result(column = "division_sn_code", property = "divisionSnCode", jdbcType = JdbcType.VARCHAR), @Result(column = "supplier_credit_code", property = "supplierCreditCode", jdbcType = JdbcType.VARCHAR), @Result(column = "name", property = "name", jdbcType = JdbcType.VARCHAR), @Result(column = "first_bid_unit_rate", property = "firstBidUnitRate", jdbcType = JdbcType.DOUBLE), @Result(column = "end_bid_unit_rate", property = "endBidUnitRate", jdbcType = JdbcType.DOUBLE)}) List<SupplierBidItemRate> findAllSupplierBidItemRate(); @Select({"select * from supplier_bid_item_rate where division_sn_code = #{divisionSnCode,jdbcType=VARCHAR}", " and supplier_credit_code = #{supplierCreditCode,jdbcType=VARCHAR}"}) @Results({@Result(column = "item_bid_code", property = "itemBidCode", jdbcType = JdbcType.VARCHAR, id = true), // @Result(column = "division_sn_code", property = "divisionSnCode", jdbcType = JdbcType.VARCHAR), @Result(column = "supplier_credit_code", property = "supplierCreditCode", jdbcType = JdbcType.VARCHAR), @Result(column = "name", property = "name", jdbcType = JdbcType.VARCHAR), @Result(column = "first_bid_unit_rate", property = "firstBidUnitRate", jdbcType = JdbcType.DOUBLE), @Result(column = "end_bid_unit_rate", property = "endBidUnitRate", jdbcType = JdbcType.DOUBLE)}) SupplierBidItemRate findSupplierBidItemRateByDivCodeAndSupplierCode(@Param("divisionSnCode") String divisionSnCode, @Param("supplierCreditCode") String supplierCreditCode); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ int deleteByPrimaryKey(String itemBidCode); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ int insert(SupplierBidItemRate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ int insertSelective(SupplierBidItemRate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ SupplierBidItemRate selectByPrimaryKey(String itemBidCode); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ int updateByPrimaryKeySelective(SupplierBidItemRate record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table supplier_bid_item_rate * * @mbg.generated Fri May 25 16:21:28 CST 2018 */ int updateByPrimaryKey(SupplierBidItemRate record); List<SupplierBidItemRate> getSupBidItemRateByTpCodeAndSupCode(Map map); List<SupplierBidItemRate> getMoveInOrChangeSupplierSupBidItemRateByChangeCode(Map map); List<SupplierBidItemRate> findSupplierBidItemRateByTenderPlanCode(String tenderPlanCode); }
Python
UTF-8
439
3.3125
3
[]
no_license
import math def is_prime(n): if n % 2 == 0 and n != 2 or n % 1 != 0 or n <= 1: return False for i in range(2, int(math.sqrt(n) + 1)): if n % i == 0: return False return True def gcd(a, b): while (b): (a, b) = (b, a % b) return abs(a) def lcm(a, b): try: lcm = int(abs(a * b) / gcd(a, b)) except ZeroDivisionError: return "Undefined" return abs(lcm)
Java
UTF-8
4,154
2.40625
2
[]
no_license
package mchehab.com.javafirebaseauthentication; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private FirebaseAuth firebaseAuth = FirebaseAuth.getInstance(); private TextView textViewResetPassword; private Button buttonSignUp; private Button buttonLogin; private ProgressBar progressBar; private EditText editTextEmail; private EditText editTextPassword; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupUI(); setupButtonLoginListener(); setupButtonSignUp(); setupTextViewReset(); } private void setupUI(){ textViewResetPassword = findViewById(R.id.textViewResetPassword); buttonSignUp = findViewById(R.id.buttonSignUp); buttonLogin = findViewById(R.id.buttonLogin); progressBar = findViewById(R.id.progressBar); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); } private void setupTextViewReset() { textViewResetPassword.setOnClickListener(e -> new ResetPasswordDialogFragment().show(getSupportFragmentManager(), "")); } private void setupButtonSignUp() { buttonSignUp.setOnClickListener(e -> { Intent intent = new Intent(MainActivity.this, SignUpActivity.class); startActivity(intent); }); } private void setupButtonLoginListener() { buttonLogin.setOnClickListener(e -> { if (!canSubmit()) { displaySubmitErrorDialog(); return; } buttonLogin.setClickable(false); progressBar.setVisibility(View.VISIBLE); signIn(); }); } private boolean canSubmit(){ if(editTextEmail.getText().length() == 0 || editTextPassword.getText().length() == 0) return false; return true; } private void displaySubmitErrorDialog(){ new AlertDialog.Builder(this) .setTitle("Error") .setMessage("Please fill email and password fields") .setPositiveButton("Ok", null) .create() .show(); } private void signIn(){ String email = editTextEmail.getText().toString(); String password = editTextPassword.getText().toString(); firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> { buttonLogin.setClickable(true); progressBar.setVisibility(View.GONE); if (task.isSuccessful()) { if(isUserVerified()){ goToHomeScreen(); }else{ Toast.makeText(MainActivity.this, "You must verify your " + "mail in order to login", Toast.LENGTH_LONG).show(); } } else { displaySignInError(); } }); } private void displaySignInError(){ new AlertDialog.Builder(this) .setTitle("Error") .setMessage("Invalid credentials") .setPositiveButton("Ok", null) .create() .show(); } private boolean isUserVerified(){ if(firebaseAuth.getCurrentUser() == null) return false; return firebaseAuth.getCurrentUser().isEmailVerified(); } private void goToHomeScreen(){ Intent intent = new Intent(getApplicationContext(), HomeScreen.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }
Python
UTF-8
22,343
2.765625
3
[]
no_license
import codecs import os import nltk import re import spacy nlp_tool = spacy.load('en') import xml.sax import zipfile # all text follow word2vec and fasttext format # lower cased # number normalized to 0 # utf-8 pattern = re.compile(r'[-_/]+') def my_split(s): text = [] iter = re.finditer(pattern, s) start = 0 for i in iter: if start != i.start(): text.append(s[start: i.start()]) text.append(s[i.start(): i.end()]) start = i.end() if start != len(s): text.append(s[start: ]) return text def my_tokenize(txt): # tokens1 = nltk.word_tokenize(txt.replace('"', " ")) # replace due to nltk transfer " to other character, see https://github.com/nltk/nltk/issues/1630 # tokens2 = [] # for token1 in tokens1: # token2 = my_split(token1) # tokens2.extend(token2) # return tokens2 document = nlp_tool(txt) sentences = [] for span in document.sents: sentence = [document[i] for i in range(span.start, span.end)] tokens = [] for t in sentence: token1 = t.text.strip() if token1 == '': continue token2 = my_split(token1) tokens.extend(token2) sentences.append(tokens) return sentences def normalize_word_digit(word): new_word = "" for char in word: if char.isdigit(): new_word += '0' else: new_word += char return new_word def nlp_process(data): sentences = my_tokenize(data) sentences_normed = [] for sent in sentences: tokens_normed = [] for token in sent: token = token.lower() token = normalize_word_digit(token) tokens_normed.append(token) sentences_normed.append(tokens_normed) return sentences_normed def ehr_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) print("total: {}".format(len(list_dir))) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue print("processing {}".format(file_name)) with codecs.open(os.path.join(dir_path, file_name), 'r', 'UTF-8') as fp: data = fp.read() sentences = nlp_process(data) for sent in sentences: for token in sent: output_fp.write(token+' ') output_fp.write('\n') output_fp.close() def faers_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) print("total: {}".format(len(list_dir))) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue print("processing {}".format(file_name)) with codecs.open(os.path.join(dir_path, file_name), 'r', 'LATIN_1') as fp: count = 1 data = '' for line in fp: if count != 1: data += line count += 1 sentences = nlp_process(data) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') output_fp.close() def cdr_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue if file_name.find('.PubTator.txt') == -1: continue with codecs.open(os.path.join(dir_path, file_name), 'r', 'UTF-8') as fp: for line in fp: _t_position = line.find('|t|') if _t_position != -1: id = line[0 : _t_position] print("processing {}".format(id)) title = line[_t_position+len('|t|'):] sentences = nlp_process(title) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') _a_position = line.find('|a|') if _a_position != -1: abstract = line[_a_position+len('|a|'):] sentences = nlp_process(abstract) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') output_fp.close() def ncbi_disease_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue if file_name.find('.txt') == -1: continue with codecs.open(os.path.join(dir_path, file_name), 'r', 'UTF-8') as fp: for line in fp: _t_position = line.find('|t|') if _t_position != -1: id = line[0 : _t_position] print("processing {}".format(id)) title = line[_t_position+len('|t|'):] sentences = nlp_process(title) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') _a_position = line.find('|a|') if _a_position != -1: abstract = line[_a_position+len('|a|'):] sentences = nlp_process(abstract) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') output_fp.close() def ade_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') with codecs.open(os.path.join(dir_path, "ADE-NEG.txt"), 'r', 'UTF-8') as fp: for line in fp: _t_position = line.find(' NEG ') if _t_position != -1: id = line[0 : _t_position] print("processing {}".format(id)) title = line[_t_position+len(' NEG '):] sentences = nlp_process(title) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') with codecs.open(os.path.join(dir_path, "DRUG-AE.rel"), 'r', 'UTF-8') as fp: for line in fp: spliteed = line.split('|') print("processing {}".format(spliteed[0])) sentences = nlp_process(spliteed[1]) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') output_fp.close() def clef_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) print("total: {}".format(len(list_dir))) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue if file_name.find(".pipe.txt") != -1: continue print("processing {}".format(file_name)) with codecs.open(os.path.join(dir_path, file_name), 'r', 'UTF-8') as fp: data = fp.read() sentences = nlp_process(data) for sent in sentences: for token in sent: output_fp.write(token+' ') output_fp.write('\n') output_fp.close() def pubmed_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') list_dir = os.listdir(dir_path) for file_name in list_dir: if file_name.find("DS_Store") != -1: continue with codecs.open(os.path.join(dir_path, file_name), 'r', 'UTF-8') as fp: for line in fp: _t_position = line.find('|t|') if _t_position != -1: id = line[0 : _t_position] print("processing {}".format(id)) title = line[_t_position+len('|t|'):] sentences = nlp_process(title) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') _a_position = line.find('|a|') if _a_position != -1: abstract = line[_a_position+len('|a|'):] sentences = nlp_process(abstract) for sent in sentences: for token in sent: output_fp.write(token + ' ') output_fp.write('\n') output_fp.close() class DrugBankHandler( xml.sax.ContentHandler ): def __init__(self, output_file_path, append): self.currentTag = "" self.parentTag = [] self.currentData = '' self.append = append self.output_file_path = output_file_path def startDocument(self): if self.append: self.output_fp = codecs.open(self.output_file_path, 'a', 'UTF-8') else: self.output_fp = codecs.open(self.output_file_path, 'w', 'UTF-8') def endDocument(self): self.output_fp.close() def startElement(self, tag, attributes): if self.currentTag != '': self.parentTag.append(self.currentTag) self.currentTag = tag def endElement(self, tag): if len(self.parentTag) != 0: self.currentTag = self.parentTag[-1] self.parentTag.pop() else: self.currentTag = '' def characters(self, content): if len(self.parentTag) == 2 and self.parentTag[-1] == 'drug' and self.currentTag == 'name': print("processing {}".format(content)) elif len(self.parentTag)>0 and self.parentTag[-1] == 'drug' and self.currentTag == 'description': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>0 and self.parentTag[-1] == 'drug' and self.currentTag == 'indication': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>0 and self.parentTag[-1] == 'drug' and self.currentTag == 'pharmacodynamics': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>0 and self.parentTag[-1] == 'drug' and self.currentTag == 'mechanism-of-action': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>0 and self.parentTag[-1] == 'drug' and self.currentTag == 'toxicity': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>1 and self.parentTag[-2] == 'drug-interactions' and self.parentTag[-1] == 'drug-interaction' and self.currentTag == 'description': if content.strip() == '': return sentences = nlp_process(content) for sent in sentences: for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') class DailyMedHandler( xml.sax.ContentHandler ): def __init__(self, output_fp): self.output_fp = output_fp self.currentTag = "" self.parentTag = [] def startDocument(self): pass def endDocument(self): pass def startElement(self, tag, attributes): if self.currentTag != '': self.parentTag.append(self.currentTag) self.currentTag = tag def endElement(self, tag): if len(self.parentTag) != 0: self.currentTag = self.parentTag[-1] self.parentTag.pop() else: self.currentTag = '' def characters(self, content): if len(self.parentTag)>0 and self.parentTag[-1] == 'text' and self.currentTag == 'paragraph': if content.strip() == '': return if re.search(r'[a-zA-Z]+', content) == None: return sentences = nlp_process(content) for sent in sentences: has_alpha = False for token in sent: if re.search(r'[a-zA-Z]+', token) != None: has_alpha = True break if has_alpha == False: continue for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') elif len(self.parentTag)>1 and self.parentTag[-2] == 'text' and self.parentTag[-1] == 'list' and self.currentTag == 'item': if content.strip() == '': return if re.search(r'[a-zA-Z]+', content) == None: return sentences = nlp_process(content) for sent in sentences: has_alpha = False for token in sent: if re.search(r'[a-zA-Z]+', token) != None: has_alpha = True break if has_alpha == False: continue for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') def dailymed_parse_one_xml(file_path, output_file_path, parser): output_fp = codecs.open(output_file_path, 'w', 'UTF-8') Handler = DailyMedHandler(output_fp) parser.setContentHandler(Handler) parser.parse(os.path.join(file_path)) output_fp.close() def dailymed_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') Handler = DailyMedHandler(output_fp) list_dir = os.listdir(dir_path) print("total: {}".format(len(list_dir))) for file_name in list_dir: if file_name.find('.zip') == -1: continue print("processing {}".format(file_name)) z = zipfile.ZipFile(os.path.join(dir_path, file_name), "r") for zip_filename in z.namelist(): if zip_filename.find('.xml') != -1: xml_content = z.read(zip_filename).decode('utf-8') xml.sax.parseString(xml_content, Handler) output_fp.close() class FdaXmlHandler( xml.sax.ContentHandler ): def __init__(self, output_fp): self.currentTag = "" self.parentTag = [] self.output_fp = output_fp def startDocument(self): pass def endDocument(self): self.currentTag = "" self.parentTag = [] def startElement(self, tag, attributes): if self.currentTag != '': self.parentTag.append(self.currentTag) self.currentTag = tag def endElement(self, tag): if len(self.parentTag) != 0: self.currentTag = self.parentTag[-1] self.parentTag.pop() else: self.currentTag = '' def characters(self, content): if self.currentTag == 'Section': if content.strip() == '': return if re.search(r'[a-zA-Z]+', content) == None: return sentences = nlp_process(content) for sent in sentences: has_alpha = False for token in sent: if re.search(r'[a-zA-Z]+', token) != None: has_alpha = True break if has_alpha == False: continue for token in sent: self.output_fp.write(token + ' ') self.output_fp.write('\n') def tac2017_to_text(dir_path, output_file_path, append): if append: output_fp = codecs.open(output_file_path, 'a', 'UTF-8') else: output_fp = codecs.open(output_file_path, 'w', 'UTF-8') Handler = FdaXmlHandler(output_fp) list_dir = os.listdir(dir_path) print("total: {}".format(len(list_dir))) for file_name in list_dir: if file_name.find('.xml') == -1: continue print("processing {}".format(file_name)) xml.sax.parse(os.path.join(dir_path, file_name), Handler) output_fp.close() if __name__ == '__main__': # ehr: made, cardio, hypoglecimia # output_file = '/Users/feili/resource/data_to_train_emb/ehr.txt' # ehr_to_text('/Users/feili/Desktop/umass/MADE/MADE-1.0/corpus', output_file, False) # ehr_to_text('/Users/feili/Desktop/umass/MADE/made_test_data/corpus', output_file, True) # ehr_to_text('/Users/feili/Desktop/umass/bioC_data/Cardio_train/corpus', output_file, True) # ehr_to_text('/Users/feili/Desktop/umass/bioC_data/Cardio_test/corpus', output_file, True) # ehr_to_text('/Users/feili/Desktop/umass/hypoglycemia/ehost_annotations_hypoglycemia_201807/ehost_annotations_hypoglycemia_201807/corpus', # output_file, True) # FAERS # output_file = '/Users/feili/resource/data_to_train_emb/faers.txt' # faers_to_text('/Users/feili/Desktop/umass/FAERS_122_Reports/Nadya_51/aers51', output_file, False) # faers_to_text('/Users/feili/Desktop/umass/FAERS_122_Reports/Nadya-11/aers11', output_file, True) # faers_to_text('/Users/feili/Desktop/umass/FAERS_122_Reports/Nadya-48/aers48', output_file, True) # cdr # output_file = '/Users/feili/resource/data_to_train_emb/cdr.txt' # cdr_to_text('/Users/feili/old_file/v/cdr/CDR_Data/CDR.Corpus.v010516' ,output_file, False) # ncbi disease # output_file = '/Users/feili/resource/data_to_train_emb/ncbi_disease.txt' # ncbi_disease_to_text('/Users/feili/old_file/NCBI disease corpus', output_file, False) # ade # output_file = '/Users/feili/resource/data_to_train_emb/ade.txt' # ade_to_text('/Users/feili/old_file/ADE-Corpus-V2', output_file, False) # clef 2013 # output_file = '/Users/feili/resource/data_to_train_emb/clef.txt' # clef_to_text('/Users/feili/old_file/clef/2013/clef2013/task1train/ALLREPORTS', output_file, False) # clef_to_text('/Users/feili/old_file/clef/2013/clef2013/task1test/ALLREPORTS', output_file, True) # pubmed # output_file = '/Users/feili/resource/data_to_train_emb/pubmed.txt' # pubmed_to_text('/Users/feili/resource/data_to_train_emb/pubmed_ade', output_file, False) # drugbank # output_file = '/Users/feili/resource/data_to_train_emb/drugbank.txt' # parser = xml.sax.make_parser() # parser.setFeature(xml.sax.handler.feature_namespaces, 0) # Handler = DrugBankHandler(output_file, False) # parser.setContentHandler(Handler) # parser.parse("/Users/feili/resource/drugbank_database.xml") # dailymed # output_file = '/Users/feili/resource/data_to_train_emb/dailymed.txt' # dailymed_to_text("/Users/feili/resource/dm_spl_monthly_update_oct2018/prescription", output_file, False) # dailymed_to_text("/Users/feili/resource/dm_spl_monthly_update_oct2018/otc", output_file, True) # dailymed_parse_one_xml('/Users/feili/Downloads/AFINITOR11232018/beceb18a-7957-4a80-bcc1-b4a0b05ef106.xml', output_file, parser) # tac 2017 # output_file = '/Users/feili/resource/data_to_train_emb/tac2017.txt' # tac2017_to_text("/Users/feili/dataset/tac_2017_ade/train_xml", output_file, False) # tac2017_to_text("/Users/feili/dataset/tac_2017_ade/unannotated_xml", output_file, True) # training set # output_file = '/Users/feili/resource/data_to_train_emb/fda2018.txt' # tac2017_to_text("/Users/feili/dataset/ADE Eval Shared Resources/ose_xml_training_20181101", output_file, False) # pubmed meddra # output_file = '/Users/feili/resource/data_to_train_emb/pubmed_meddra.txt' # pubmed_to_text('/Users/feili/resource/pubmed_meddra', output_file, False) # pubmed snomed # output_file = '/Users/feili/resource/data_to_train_emb/pubmed_snomed.txt' # pubmed_to_text('/Users/feili/resource/pubmed_snomed', output_file, False) # test set output_file = '/Users/feili/resource/data_to_train_emb/fda2018_test.txt' tac2017_to_text("/Users/feili/dataset/ADE Eval Shared Resources/UnannotatedTestCorpus", output_file, False) pass
PHP
UTF-8
395
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Services; use App\Models\HelloBarClick; use App\Contracts\HelloBarClicksServiceInterface; class HelloBarClicksService implements HelloBarClicksServiceInterface { public function __construct(HelloBarClick $hello_bar_click) { $this->hello_bar_click = $hello_bar_click; } public function addClick($inputs) { return $this->hello_bar_click->create($inputs); } }
Python
UTF-8
964
4
4
[]
no_license
class Solution: def countSubstrings(self, S: str) -> int: N = len(S) ans = 0 for center in range(2*N - 1): left = int(center / 2) right = int(left + center % 2) while left >= 0 and right < N and S[left] == S[right]: ans += 1 left -= 1 right += 1 return ans """ 647. Palindromic Substrings Medium 1971 96 Add to List Share Given a string, your task is to count how many palindromic substrings in this string. The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. Example 1: Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c". Example 2: Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". input = "abc" output = 3 center, left, right, ans 0 0 0 0 1 0 1 1 2 1 1 1 3 1 2 2 4 2 2 2 """
C#
UTF-8
9,883
2.984375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace CSharpDateConverter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public static string FileLoad = ""; private void button1_Click(object sender, EventArgs e) { // Displays an OpenFileDialog so the user can select a File OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "CSV Files|*.csv|Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; openFileDialog1.Title = "Select a Source File"; openFileDialog1.InitialDirectory = @"C:\...Desktop\"; openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { labelFileName.Text = openFileDialog1.FileName; FileLoad = openFileDialog1.FileName; } } private void buttonLoadFile_Click(object sender, EventArgs e) { try { DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dataGridViewMembers); dataGridViewMembers.ColumnCount = 6; dataGridViewMembers.Columns[0].Name = "First Name"; dataGridViewMembers.Columns[1].Name = "Last Name"; dataGridViewMembers.Columns[2].Name = "Birth Date"; dataGridViewMembers.Columns[3].Name = "City"; dataGridViewMembers.Columns[4].Name = "State"; dataGridViewMembers.Columns[5].Name = "Join Date"; StreamReader inputFile; //to read the file string line; //to hold a line from the file int count = 0; //line counter //create a delimiter array char[] delim = { ',' }; //open the csv file inputFile = File.OpenText(FileLoad); while (!inputFile.EndOfStream) { //read a line from the file. line = inputFile.ReadLine(); //get the test scores as tokens string[] tokens = line.Split(delim); //dataGridViewMembers.DataSource = tokens; dataGridViewMembers.Rows.Add(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]); //increment the line counter count++; } //close the file inputFile.Close(); labelFileName.Text = count + " lines processed."; } catch (Exception ex) { //display an error message MessageBox.Show(ex.Message); } } private void Form1_Load(object sender, EventArgs e) { labelFileName.Text = "Please select a file to format."; } private void buttonFixDates_Click(object sender, EventArgs e) { labelFileName.Text = "Fixing.... Please wait."; try { dataGridViewMembers.Rows.Clear(); DataGridViewRow row = new DataGridViewRow(); row.CreateCells(dataGridViewMembers); dataGridViewMembers.ColumnCount = 6; dataGridViewMembers.Columns[0].Name = "First Name"; dataGridViewMembers.Columns[1].Name = "Last Name"; dataGridViewMembers.Columns[2].Name = "Birth Date"; dataGridViewMembers.Columns[3].Name = "City"; dataGridViewMembers.Columns[4].Name = "State"; dataGridViewMembers.Columns[5].Name = "Join Date"; StreamReader inputFile; //to read the file string line; //to hold a line from the file int count = 0; //line counter //create a delimiter array char[] delim = { ',' }; //open the csv file inputFile = File.OpenText(FileLoad); StreamWriter OutputFile = new StreamWriter("ConvertedDates.CSV"); while (!inputFile.EndOfStream) { //read a line from the file. line = inputFile.ReadLine(); line = line.Replace(".", "/"); line = line.Replace("-", "/"); //heres where we change stuff. tokens[2] and tokens[5] are the birthdates and join dates. //so we're gonna turn them into variables, then their own arrays. //get the columns as tokens string[] tokens = line.Split(delim); //splits the birthdate into 3 parts: MM DD & YY or YYYY string date = tokens[2]; date = date.Replace("Jan", "1"); date = date.Replace("Feb", "2"); date = date.Replace("Mar", "3"); date = date.Replace("Apr", "4"); date = date.Replace("May", "5"); date = date.Replace("Jun", "6"); date = date.Replace("Jul", "7"); date = date.Replace("Aug", "8"); date = date.Replace("Sep", "9"); date = date.Replace("Oct", "10"); date = date.Replace("Nov", "11"); date = date.Replace("Dec", "12"); string temp = ""; string[] dateparts = date.Split('/'); //if month is abbreviated, switch with numeric value if (int.Parse(dateparts[0]) > 12) { //switch the dates around temp = dateparts[1]; dateparts[1] = dateparts[0]; dateparts[0] = temp; } if (int.Parse(dateparts[2]) < 1000) { dateparts[2] = "19" + dateparts[2]; } if (dateparts[0].Contains("0")) { if (int.Parse(dateparts[0]) < 10) { dateparts[0].Replace("0", ""); } } tokens[2] = dateparts[0] + "/" + dateparts[1] + "/" + dateparts[2]; //next comes the join date //splits the joindate into 3 parts: MM DD & YY or YYYY string date2 = tokens[5]; date2 = date2.Replace("Jan", "1"); date2 = date2.Replace("Feb", "2"); date2 = date2.Replace("Mar", "3"); date2 = date2.Replace("Apr", "4"); date2 = date2.Replace("May", "5"); date2 = date2.Replace("Jun", "6"); date2 = date2.Replace("Jul", "7"); date2 = date2.Replace("Aug", "8"); date2 = date2.Replace("Sep", "9"); date2 = date2.Replace("Oct", "10"); date2 = date2.Replace("Nov", "11"); date2 = date2.Replace("Dec", "12"); string temp2 = ""; string[] dateparts2 = date2.Split('/'); //if month is abbreviated, switch with numeric value if (int.Parse(dateparts2[0]) > 12) { //switch the dates around temp2 = dateparts2[1]; dateparts2[1] = dateparts2[0]; dateparts2[0] = temp2; } if (int.Parse(dateparts2[2]) < 1000) { dateparts2[2] = "19" + dateparts2[2]; } if (dateparts2[0].Contains("0")) { if (int.Parse(dateparts2[0]) < 10) { dateparts2[0] = dateparts2[0].Replace(@"0", ""); } } if (dateparts2[1].Contains("0")) { if (int.Parse(dateparts2[1]) < 10) { dateparts2[1] = dateparts2[1].Replace(@"0", ""); } } tokens[5] = dateparts2[0] + "/" + dateparts2[1] + "/" + dateparts2[2]; dataGridViewMembers.Rows.Add(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]); OutputFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2] + "," + tokens[3] + "," + tokens[4] + "," + tokens[5]); //increment the line counter count++; } //close the file inputFile.Close(); labelFileName.Text = "Processing Complete!"; } catch (Exception ex) { //display an error message MessageBox.Show(ex.Message); } } private void buttonOutput_Click(object sender, EventArgs e) { //copy the code from the fix button but tweak it so it outputs to a seperate CSV file } } }
Python
UTF-8
1,132
3.96875
4
[]
no_license
# ==================================================== # # # # Created By: Darhil Aslaliya - GitHub :- darsh-22 # # # # ==================================================== # # required module import random # generate random number from 1 to 10 randon_number = random.randint(1, 10) userGuess = None guesses = 0 # main loop while(userGuess != randon_number): userGuess = int(input("Enter your guess: ")) guesses += 1 if(userGuess==randon_number): print("You guessed it right!") else: if(userGuess>randon_number): print("You guessed it wrong! Enter a smaller number") else: print("You guessed it wrong! Enter a larger number") print(f"You guessed the number in {guesses} guesses") # saving high score in file with open("highscore.txt", "r") as f: highscore = int(f.read()) # check if high score is break or not if(guesses<highscore): print("You have just broken the high score!") with open("highscore.txt", "w") as f: f.write(str(guesses))
Java
UTF-8
875
3.171875
3
[]
no_license
package layouts; import java.awt.Frame; import java.awt.BorderLayout; import java.awt.Panel; import java.awt.Button; class S extends Frame{ Button btn1,btn2; S(){ setLayout(new BorderLayout()); btn1=new Button("File"); btn2=new Button("Edit"); add(new M(),BorderLayout.WEST); setBounds(10,10,1000,1000); setVisible(true); } } class K extends Panel{ Button btn1,btn2; K(){ add(new Button("New")); add(new Button("Open")); add(new Button("Save")); add(new Button("Save as")); } } class M extends Panel{ M(){ add(new Button("New")); add(new Button("Open")); add(new Button("Save")); add(new Button("Save as")); } } public class Program_3_BorderLayout_with_panel { public static void main(String[] args) { new S(); } }
Java
UTF-8
2,666
2.9375
3
[]
no_license
package api; public class NodeData implements node_data { private class location implements geo_location{ private double x, y, z, dis; public location(double x, double y, double z, double dis){ this.x = x; this.y = y; this.z = z; this.dis = dis; } public location(geo_location loc){ this.x = loc.x(); this.y = loc.y(); this.z = loc.z(); this.dis = distance(loc); } @Override public double x() { return x; } @Override public double y() { return y; } @Override public double z() { return z; } @Override public double distance(geo_location g) { double pow_x = this.x - g.x(); pow_x = Math.pow(pow_x, 2); double pow_y = this.y - g.y(); pow_y = Math.pow(pow_y, 2); double pow_z = this.z - g.z(); pow_z = Math.pow(pow_z, 2); double res = pow_x + pow_y + pow_z; res = Math.sqrt(res); return res; } } ////private variables//// private static int keyCount = 0; private int key, tag; private geo_location loc; private double weight; private String info; ///////////////////////// public NodeData(int key){ this.key = key; this.tag = 0; this.loc = new location(loc); this.weight = weight; this.info = ""; } public NodeData(geo_location loc, double weight){ this.key = keyCount; keyCount++; this.tag = 0; this.loc = new location(loc); this.weight = weight; this.info = ""; } @Override public int getKey() { return this.key; } @Override public geo_location getLocation() { return this.loc; } @Override public void setLocation(geo_location p) { // this.loc = new location(p); this.loc = p; } @Override public double getWeight() { return weight; } @Override public void setWeight(double w) { this.weight = w; } @Override public String getInfo() { return this.info; } @Override public void setInfo(String s) { this.info = s; } @Override public int getTag() { return this.tag; } @Override public void setTag(int t) { this.tag = t; } }
C
UTF-8
954
2.65625
3
[]
no_license
#include <stdio.h> #include "advstat.h" #include "dangerous.h" #include "four_three.h" enum { DEBUG_DANGER = 0 }; /** * returns 0 if (x,y) is not dangerous * 1 if is four danger * 2 if is active three danger * 3 if is 4+3 danger */ int isDangerous(Configuration v, int x, int y, PEBBLE_COLOR p){ int idx=(p==BLACK)?0:1; /* printBoardNonBlock(v); printf("%d %d %d\n", x, y, idx);*/ if (getColor(v, x, y)==NONE){ if (v->statistics[x][y][AFOUR][idx] || v->statistics[x][y][ACTIVE_FOUR][idx]){ if (DEBUG_DANGER){ printf("hazard four %d %d\n", x, y); // getchar(); } return 1; } else if (v->statistics[x][y][ACTIVE_THREE][idx]){ if (DEBUG_DANGER){ printf("hazard active three %d %d\n", x, y); // getchar(); } return 2; } else if (four_three(v, x, y, p)){ if (DEBUG_DANGER){ printf("hazard %d %d\n", x, y); // getchar(); } return 3; } else return 0; } else return 0; }
C#
UTF-8
1,165
2.828125
3
[]
no_license
//return full data public UserFull GetUser(Guid userId) { using (var c = ConnectionToDataBase()) { var user = c.Users .Where(u => u.Id==userId) .Select(u => new UserFull { Id = u.Id, Name = u.Name, Company = u.Company //force execution }).FirstOrDefault(); return user; } } //return partial data public dynamic GetUser(Guid userId) { using (var c = ConnectionToDataBase()) { var user = c.Users .Where(u => u.Id==userId) .Select(u => new { Id = u.Id, Name = u.Name, }).FirstOrDefault(); return user; } } [HttpGet, Route("api/users/{userId:guid}")] public IHttpActionResult User(Guid userId) { try { var res = GetUser(Guid userId); return Ok(res); } catch { return InternalServerError(); } }
Java
UTF-8
1,797
3.203125
3
[]
no_license
import java.util.*; public class Cuenta { private double balance; private Usuario userAccount; private List<Gasto> expenses; private List<Ingreso>income; public Cuenta(Usuario usuarioCuenta) { this.userAccount=usuarioCuenta; this.balance=0; this.expenses=new ArrayList<Gasto>(); this.income=new ArrayList<Ingreso>(); } public void setUsuarioCuenta(Usuario usuarioCuenta) { this.userAccount = usuarioCuenta; } public void setSaldo(double saldo) { this.balance = saldo; } public double getSaldo() { return balance; } public Usuario getUsuarioCuenta() { return userAccount; } public List<Gasto> getGastos() { return expenses; } public List<Ingreso> getIngresos() { return income; } public double addIngresos(String description, double cantidad){ Ingreso nuevoIngreso = new Ingreso(cantidad,description); this.income.add(nuevoIngreso); this.balance=this.balance+cantidad; return balance; } public double addGastos(String description, double cantidad){ try{ this.balance = this.balance-cantidad; if(this.getSaldo()<0){ throw new GastoException(); } }catch(GastoException e){ return -1; } Gasto nuevoGasto=new Gasto(cantidad,description); expenses.add(nuevoGasto); return balance; } @Override public String toString(){ return "Bienvenido " + this.userAccount.getNombre() + ", el saldo de tu cuenta es " + this.balance; } }
Java
UTF-8
4,799
2.28125
2
[]
no_license
/****************************************************************************** * Copyright (C) 2016 * ShenZhen ComTop Information Technology Co.,Ltd * All Rights Reserved. * 本软件为深圳康拓普开发研制。 * 未经本公司正式书面同意,其他任何个人、团体不得使用、 * 复制、修改或发布本软件. *****************************************************************************/ package com.comtop.meeting.model; import com.comtop.cap.runtime.base.model.CapBaseVO; import comtop.org.directwebremoting.annotations.DataTransferObject; import javax.persistence.Table; import javax.persistence.Column; import com.comtop.cap.runtime.base.annotation.DefaultValue; import javax.persistence.Id; import java.sql.Timestamp; /** * 个人(测试表) * * @author CAP超级管理员 * @since 1.0 * @version 2016-5-30 CAP超级管理员 */ @Table(name = "TEST_PERSON") @DataTransferObject public class TestPersonVO extends CapBaseVO { /** 序列化ID */ private static final long serialVersionUID = 1L; /** 主键Id */ @Id @Column(name = "ID",length=36,precision=0) private String id; /** 姓名 */ @Column(name = "NAME",length=30,precision=0) private String name; /** 地址 */ @Column(name = "ADRESS",length=100,precision=0) private String adress; /** 性别 */ @Column(name = "SEX",precision=0) private Integer sex; /** 电话 */ @Column(name = "PHONE",length=20,precision=0) private String phone; /** 生日 */ @Column(name = "BIRTHDAY",precision=6) @DefaultValue(value="SYSDATE") private Timestamp birthday; /** 薪水 */ @Column(name = "SALARY",precision=10) private Double salary; /** 流程状态 */ @Column(name = "FLOW_STATE",precision=0) @DefaultValue(value="0") private Integer flowState; /** 流程实例Id */ @Column(name = "PROCESS_INS_ID",length=64,precision=0) private String processInsId; /** * @return 获取 主键Id 属性值 */ public String getId() { return id; } /** * @param id 设置 主键Id 属性值为参数值 id */ public void setId(String id) { this.id = id; } /** * @return 获取 姓名 属性值 */ public String getName() { return name; } /** * @param name 设置 姓名 属性值为参数值 name */ public void setName(String name) { this.name = name; } /** * @return 获取 地址 属性值 */ public String getAdress() { return adress; } /** * @param adress 设置 地址 属性值为参数值 adress */ public void setAdress(String adress) { this.adress = adress; } /** * @return 获取 性别 属性值 */ public Integer getSex() { return sex; } /** * @param sex 设置 性别 属性值为参数值 sex */ public void setSex(Integer sex) { this.sex = sex; } /** * @return 获取 电话 属性值 */ public String getPhone() { return phone; } /** * @param phone 设置 电话 属性值为参数值 phone */ public void setPhone(String phone) { this.phone = phone; } /** * @return 获取 生日 属性值 */ public Timestamp getBirthday() { return birthday; } /** * @param birthday 设置 生日 属性值为参数值 birthday */ public void setBirthday(Timestamp birthday) { this.birthday = birthday; } /** * @return 获取 薪水 属性值 */ public Double getSalary() { return salary; } /** * @param salary 设置 薪水 属性值为参数值 salary */ public void setSalary(Double salary) { this.salary = salary; } /** * @return 获取 流程状态 属性值 */ public Integer getFlowState() { return flowState; } /** * @param flowState 设置 流程状态 属性值为参数值 flowState */ public void setFlowState(Integer flowState) { this.flowState = flowState; } /** * @return 获取 流程实例Id 属性值 */ public String getProcessInsId() { return processInsId; } /** * @param processInsId 设置 流程实例Id 属性值为参数值 processInsId */ public void setProcessInsId(String processInsId) { this.processInsId = processInsId; } /** * 获取主键值 * @return 主键值 */ @Override public String getPrimaryValue(){ return this.id; } }
Java
UTF-8
1,328
2.078125
2
[]
no_license
package br.com.jg.loucademia.interfaces.aluno.web; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import br.com.jg.loucademia.application.service.AlunoService; import br.com.jg.loucademia.domain.aluno.Aluno; @Named @RequestScoped public class PesquisaBean implements Serializable { private String matricula; private String nome; private Integer rg; private Integer telefone; private List<Aluno> alunos; @EJB private AlunoService as; @Inject private AlunoBean ab; public String pesquisar() { alunos = as.listAlunos(matricula, nome, rg, telefone); return null; } public String excluir(String matricula) { as.excluir(matricula); return null; } public String getMatricula() { return matricula; } public void setMatricula(String matricula) { this.matricula = matricula; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Integer getRg() { return rg; } public void setRg(Integer rg) { this.rg = rg; } public Integer getTelefone() { return telefone; } public void setTelefone(Integer telefone) { this.telefone = telefone; } public List<Aluno> getAlunos() { return alunos; } }
Markdown
UTF-8
1,918
2.78125
3
[]
no_license
# Aufgaben ## Aufgabe 1 Formulieren Sie einen Algorithmus (in einfachen Sätzen oder Pseudocode), der es ermöglicht, in dem unten gezeigten Buchstabenarray eines der Wörter: **sein**, **tat**, **kann** oder **ist** zu finden. Die Leserichtung für die Wörter kann dabei horizontal, vertikal oder diagonal und jeweils vorwärts und rückwärts sein. Sobald ein Wort gefunden wurde, terminiert der Algorithmus. | n | w | b | m | t | | ---- | ---- | ---- | ---- | ---- | | n | i | s | t | a | | a | e | e | p | t | | k | f | x | s | e | ## Aufgabe 2- Collatz Implementieren Sie den Algorithmus zum Collatz‐Problem und testen Sie ihn für verschiedene Eingaben. * Finden Sie eine Eingabe, für die der Algorithmus nicht terminiert. ## Aufgabe 3- GGT Informieren Sie sich über die Möglichkeiten zur algorithmischen Berechnung des GGT. Formulieren Sie eine rekursive Vorschrift zur Berechnung Euklid und Stein ("steinscher Algorithmus"). Schreiben Sie je ein C‐ oder Java‐Programm, das diese beiden Algorithmen umsetzt und eine Trace‐Tabelle produziert. Durch eine solche Tabelle wird jeder Schritt des Ablaufs durch Ausgaben der Variablenwerte nachvollziehbar gemacht. Testen Sie Ihr Programm für verschiedene Eingaben. ## Aufgabe 4- Fibonacci Die Folge der Fibonacci‐Zahlen ist folgendermaßen definiert: $$ F_0 = 0 $$ $$ F_1 = 1 $$ $$ F_n = F_{n - 1} + F_{n - 2} $$ Somit ist der Wert der Fibonacci‐Zahlen mit den Indizes 0 und 1 genau ihr Index und jede weitere Fibonacci‐Zahl entspricht der Summe ihrer beiden Vorgänger. Die direkte Implementierung zur Berechnung der Fibonacci‐Zahlen mittels Rekursion ist leider sehr ineffizient – warum? Implementieren Sie die rekursive Variante und entwerfen Sie einen weiteren Algorithmus zur iterativen Berechnung der Folge bis zu einem (vom Benutzer einzugebenden) *݊n*.
Markdown
UTF-8
1,921
2.515625
3
[ "MIT" ]
permissive
# "The" Build This repository contains project setup templates and reusable phing build targets for Drupal projects. _Note: If you are starting a new a project, you may be looking for the [drupal-skeleton](https://github.com/palantirnet/drupal-skeleton)._ ## Adding the-build with composer ```sh $> composer require palantirnet/the-build ``` Composer 2.2.2 or greater is required for the-build. ## Setting up Install the default templates and phing targets to your project: ```sh $> vendor/bin/the-build-installer ``` This will trigger an interactive prompt to configure your basic build properties, adding the following templated files and directories: * `.circleci/` * `.the-build/` * `behat.yml` * `build.xml` * `drush/drushrc.php` * `drush/*.aliases.drushrc.php` * `config/` * `(web|docroot)/sites/default/settings.php` * `(web|docroot)/sites/default/settings.(host).php` These files should be checked in to your project. Configure your build by editing `.the-build/build.yml`. You can find more properties in [defaults.yml](defaults.yml), and override the defaults by copying them into your project's properties files. ## Using the-build ### Everyday commands Reinstall the Drupal site from config: ```sh $> vendor/bin/phing install ``` Rebuild the `settings.build.php` configuration, and the styleguide if it's available (run automatically when you call `install`): ```sh $> vendor/bin/phing build ``` Run code reviews and tests: ```sh $> vendor/bin/phing test ``` ### Other commands View a list of other available targets with: ```sh $> vendor/bin/phing -l ``` ## Additional documentation * [Configuring the-build](docs/configuration.md) * [Building an artifact](docs/artifacts.md) * [Using Drupal multisites](docs/drupal_multisite.md) * [Custom Phing tasks provided by the-build](docs/tasks.md) * [Developing on the-build](docs/development.md) ---- Copyright 2016-2020 Palantir.net, Inc.
JavaScript
UTF-8
3,347
3.171875
3
[]
no_license
var products=[] ; // نجيب الداتا من الداتا بيز ونعرضها عند عملية الريفريش if(localStorage.getItem("products")==null){ products=[] }else{ products=JSON.parse(localStorage.getItem("products")) // parse convert string to object displayData(); } // نجيب الداتا من حقول الادخال function getData(){ var ProductName= document.getElementById("ProductName").value; var ProductCategory= document.getElementById("ProductCategory").value; var ProductPrice= document.getElementById("ProductPrice").value; var ProductDescription= document.getElementById("ProductDescription").value; var product={ name:ProductName, category:ProductCategory, price:ProductPrice, description:ProductDescription } products.push(product); localStorage.setItem('products',JSON.stringify(products)); displayData(); document.getElementById("ProductName").value=""; document.getElementById("ProductCategory").value=""; document.getElementById("ProductPrice").value=""; document.getElementById("ProductDescription").value=""; } // عرض الداتا فى الجدول function displayData(){ var copaya=""; for(var i=0;i<products.length;i++){ copaya +=` <tr > <td>${i}</td> <td>${products[i].name}</td> <td>${products[i].category}</td> <td>${products[i].price}</td> <td>${products[i].description}</td> <td><button onclick=Delete(${i}) class="btn btn-danger">Delete</button></td> <td><button onclick=Updaate(${i}) class="btn btn-info" >Update</button></td> </tr> ` } document.getElementById("demo").innerHTML=copaya; console.log(products); } // delete operation function Delete(idex){ products.splice(idex,1); displayData(); localStorage.setItem('products',JSON.stringify(products)); } // search function search(){ var search=document.getElementById("search").value; for(var i=0;i<products.length;i++){ if(products[i].name.toLowerCase().includes(search.toLowerCase())){ console.log("yes"+i); } } } // update operation var selectedRow=""; function Updaate(index){ selectedRow=index; document.getElementById("ProductName").value=products[index].name; document.getElementById("ProductCategory").value=products[index].category; document.getElementById("ProductPrice").value=products[index].price; document.getElementById("ProductDescription").value=products[index].description; document.getElementById("updateProd").style.display='block'; document.getElementById("Addpro").style.display='none'; } function updateProduct(){ products[selectedRow].name=document.getElementById("ProductName").value; products[selectedRow].category=document.getElementById("ProductCategory").value; products[selectedRow].price=document.getElementById("ProductPrice").value; products[selectedRow].description=document.getElementById("ProductDescription").value; Delete(selectedRow); getData(); document.getElementById("Addpro").style.display='block'; document.getElementById("updateProd").style.display='none'; }
Java
UTF-8
475
1.992188
2
[]
no_license
package com.example.app.spring3; import com.example.app.spring3.context.PhoneBookApplicationContext; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * Hello world! * */ public class Main { public static void main( String[] args ) { ApplicationContext context = new AnnotationConfigApplicationContext(PhoneBookApplicationContext.class); } }
Java
UTF-8
129
2.015625
2
[ "MIT" ]
permissive
package sdt; public class SDTException extends RuntimeException { public SDTException(String message) { super(message); } }
C
UTF-8
4,544
2.703125
3
[ "BSD-3-Clause" ]
permissive
#include <xc.h> /* XC8 General Include File */ #include "i2c.h" // --------------------------------------------------------------------------- // Init MSSP module in master mode // --------------------------------------------------------------------------- void I2cInitMaster(void) { SCL_PIN = 1; // SCL/SDA lines as input SDA_PIN = 1; SSP1CON1 = 0b00101000; // Master mode: Clock=Fosc/(4*(SSPADD+1)) SSP1CON2 = 0; SSP1STATbits.CKE = 0; // SMbus compatible mode off SSP1ADD = BAUD; // calculated baudrate in i2c.h SSP1STATbits.SMP = SLEWRATE; // slewrate PIR1bits.SSP1IF = 0; // reset flag interrupt serial port PIR2bits.BCL1IF = 0; // reset flag interrupt bus collision } // --------------------------------------------------------------------------- // Init MSSP module in slave mode // address = 7bit address // --------------------------------------------------------------------------- void I2cInitSlave(const unsigned char address) { SCL_PIN = 1; // SCL/SDA lines as inputs SDA_PIN = 1; SSP1CON1 = 0x36; // slave mode, 7bit address SSP1CON2 = 0; SSP1ADD = address; // address, bits A7-A1 SSP1STATbits.CKE = 0; // SMbus compatible mode off SSP1STATbits.SMP=SLEWRATE; // slewrate PIR1bits.SSP1IF = 0; // Reset flag interrupt serial port PIR2bits.BCL1IF = 0; // Reset flag interrupt bus collision } // --------------------------------------------------------------------------- // wait current operation finish // --------------------------------------------------------------------------- void I2cWait(void) { while (!PIR1bits.SSP1IF) { continue; } PIR1bits.SSP1IF=0; } // --------------------------------------------------------------------------- // wait bus in idle status or no transmission // --------------------------------------------------------------------------- void I2cWaitForIdle(void) { while ((SSP1CON2 & 0x1F) | SSP1STATbits.R_nW) { continue; } } // --------------------------------------------------------------------------- // start i2c bus // --------------------------------------------------------------------------- void I2cStart(void) { I2cWaitForIdle(); PIR1bits.SSP1IF = 0; SSP1CON2bits.SEN = 1; // start sequence I2cWait(); } // --------------------------------------------------------------------------- // repeated start // --------------------------------------------------------------------------- void I2cRepStart(void) { I2cWaitForIdle(); PIR1bits.SSP1IF = 0; SSP1CON2bits.RSEN = 1; // repeated start sequence I2cWait(); } // --------------------------------------------------------------------------- // stop i2c bus // --------------------------------------------------------------------------- void I2cStop(void) { I2cWaitForIdle(); PIR1bits.SSP1IF = 0; SSP1CON2bits.PEN = 1; // stop sequence SSP1CON2bits.ACKEN = 1; // acknowledge sequence I2cWait(); } // --------------------------------------------------------------------------- // slave writes // --------------------------------------------------------------------------- void I2cWriteSlave(unsigned char data) { SSP1CON1bits.CKP = 0; // clock lock SSP1BUF = data; // transfer data in the buffer PIR1bits.SSP1IF = 0; // interrupt flag reset SSP1CON1bits.CKP = 1; // clock unlock I2cWait(); } // --------------------------------------------------------------------------- // slave reads // --------------------------------------------------------------------------- unsigned char I2cReadSlave(void) { char temp; I2cWait(); temp = SSP1BUF; return temp; } // --------------------------------------------------------------------------- // master writes // returns true when slave send ACK // --------------------------------------------------------------------------- unsigned char I2cWriteMaster(unsigned char data) { I2cWaitForIdle(); SSP1BUF = data; I2cWait(); return !SSP1CON2bits.ACKSTAT; } // --------------------------------------------------------------------------- // master reads // returns the byte. if ack=1, sends acknowledge // --------------------------------------------------------------------------- unsigned char I2cReadMaster(unsigned char ack) { unsigned char data; I2cWaitForIdle(); SSP1CON2bits.RCEN = 1; PIR1bits.SSP1IF = 0; I2cWait(); data = SSP1BUF; if (ack) { SSP1CON2bits.ACKDT = 0; // sends ACK } else { SSP1CON2bits.ACKDT = 1; // no ACK } SSP1CON2bits.ACKEN = 1; // starts ACK routine I2cWait(); return data; } #undef CLOCK #undef FOSC #undef BAUD #undef SLEWRATE
Python
UTF-8
19,360
2.671875
3
[]
no_license
import serial import textwrap import time import threading import ast ''' This protocol can operate with action codes up to 255 The first 32 is used by the protocol. The others defined by the interfaces. First 32 code: 1 - Basic text 2 - Bundle header code 3 - Apply new timeout multiplier ''' # <----------------------------------------------------------------------------------> # Constans BIT_PER_SEC = 300 BUFFER_SIZE = 512 PROTOCOL_CODES_NUM = 32 BUNDLE_HEADER_CODE = 2 BASIC_TEXT_CODE = 1 DEVICE_ID = 255 TIMEOUT_MULTIPLIER = 1.5 # Logger function log = print # <----------------------------------------------------------------------------------> # Classes class Queue(object): # Basic queue def __init__(self, type, initData=None): self._type = type self._data = [] if initData != None: for element in initData: self.insert(element) def __str__(self): return "<" + self.__class__.__name__ + " of {} with size {}>".format(self.type.__name__, self.size) def __repr__(self): return self.__class__.__name__ + "(type={}, initData={})".format(self.type.__name__, self._data) @property def size(self): return len(self._data) @property def type(self): return self._type @property def data(self): return self._data.copy() def insert(self, element): if not issubclass(type(element), self.type): raise TypeError("Expected {}, but got {}".format(self.type, type(element))) self._data.append(element) def peek(self): if self.size == 0: raise QueueIsEmpty() return self._data[0] def pop(self): if self.size == 0: raise QueueIsEmpty() element = self._data.pop() return element def isEmpty(self): return self.size == 0 # <----------------------------------------------------------------------------------> class Dequeue(Queue): # It's a double-ended queue # It is capable to add element to front of the queue and # remove last from queue def insertFirst(self, element): if not issubclass(type(element), self.type): raise TypeError("Expected {}, but got {}".format(self.type, type(element))) self._data.insert(0, element) def peekLast(self): if self.size == 0: raise QueueIsEmpty() return self._data[self.size - 1] def popLast(self): if self.size == 0: raise QueueIsEmpty() element = self._data.pop(self.size - 1) return element # <----------------------------------------------------------------------------------> class Buffer(Dequeue): # Buffer only takes Sendable objects or it's children def __init__(self, initData=None): super().__init__(Sendable) if initData != None: for element in initData: self.insert(element) def __repr__(self): return self.__class__.__name__ + "(initData={})".format(self._data) # <----------------------------------------------------------------------------------> class TransparentBuffer(Buffer): def peekCode(self, code): if self.hasCode(code): filtered = filter(lambda elem: elem.header.code == code, self.data) return next(filtered) else: raise TransparentBufferNotContainsError() def hasCode(self, code): filtered = filter(lambda elem: elem.header.code == code, self.data) try: element = next(filtered) return True except StopIteration as e: return False def popCode(self, code): if self.hasCode(code): element = self._data.pop(self._data.index(self.peekCode(code))) return element else: raise TransparentBufferNotContainsError() # <----------------------------------------------------------------------------------> class Sendable(object): # Connection handler can send only Sendable objects # Sendable has no message def __init__(self, sender, target, actionCode): self._header = Header(0, sender, target, actionCode) self._body = "" self._encodedBody = b"" def __str__(self): return "<" + self.__class__.__name__ + " [{}]{}".format(str(self._header), self._body) def __repr__(self): return self.__class__.__name__ + "(sender={}, target={}, actionCode={})".format( self._header.value[1], self._header.value[2], self._header.value[3] ) @property def header(self): return self._header def encode(self): return b"" + self.header.value + self._encodedBody @property def byteSize(self): return len(self.encode("ascii", "replace")) @property def code(self): return self.header.code @property def length(self): return self.header.length @property def target(self): return self.header.target @property def sender(self): return self.header.sender # <----------------------------------------------------------------------------------> class Message(Sendable): def __init__(self, sender, target, actionCode, message, messageLength=None): message = str(message) if len(message) > 255: raise OversizedMessageError("Message can contain only 255 characters") try: length = len(message) if messageLength == None else int(messageLength) except ValueError as e: raise ValueError("Message length must be convertable to int") self._header = Header(length, sender, target, actionCode) self._body = message self._encodedBody = message.encode("ascii", "replace") def __repr__(self): return self.__class__.__name__ + "(sender={}, target={}, actionCode={}, message=\"{}\")".format( self._header.value[1], self._header.value[2], self._header.value[3], self.body ) @property def header(self): return self._header @property def body(self): # Body stored as string, not bytestring return self._body @classmethod def joinHeaderWithBody(cls, header, body): return cls(header.value[1], header.value[2], header.value[3], body, header.value[0]) # <----------------------------------------------------------------------------------> class BrokenMessage(Message): @property def brokenLength(self): return len(self._body) @property def body(self): return super().body + ("%" * (self.length - self.brokenLength)) # <----------------------------------------------------------------------------------> class Bundle(Sendable): def __init__(self, sender, target, code, message): self._data = Queue(Message) messages = textwrap.wrap(message, 255) if len(messages) > 255: raise OversizedMessageError("Bundle can contain only 65025 characters") header = Message(sender, target, BUNDLE_HEADER_CODE, len(messages)) self._data.insert(header) for line in messages: element = Message(sender, target, code, line) self._data.insert(element) def __str__(self): return "<" + self.__class__.__name__ + " [{}]".format(str(self.header)) def __repr__(self): return self.__class__.__name__ + "(sender={}, target={}, actionCode={}, message=\"{}\")".format( self.header.header.value[1], self.header.header.value[2], self.header.header.value[3], self.body ) @property def data(self): # self._data is queue return self._data.data @property def code(self): return self.data[1].code @property def header(self): return self.data[0] @property def body(self): string = "" for element in self.data[1:]: string += element.body return string @property def size(self): return len(self.data) def encode(self): string = b"" for element in self.data: string += element.encode() return string @classmethod def joinMessages(cls, headerMessage, bodyMessages): code = bodyMessages[0].code sender = bodyMessages[0].sender target = bodyMessages[0].target bundle = cls(sender, target, code, bodyMessages[0].body) # WARNING This classmethod manipulates the object's private # data directly [bundle._data.insert(msg) for msg in bodyMessages[1:]] return bundle # <----------------------------------------------------------------------------------> class Header(object): # Header of Sendables def __init__(self, length, sender, target, actionCode): self._data = bytearray(4) try: self._data[0] = length self._data[1] = sender self._data[2] = target self._data[3] = actionCode except TypeError as e: raise ValueNotInteger() except ValueError as e: raise ValueOutOfByteRange() def __str__(self): return "<" + self.__class__.__name__ + " {}>".format(list(self._data)) def __repr__(self): return self.__class__.__name__ + "(length={}, sender={}, target={}, actionCode={})".format( self._data[0], self._data[1], self._data[2], self._data[3]) @property def value(self): return self._data @property def length(self): return self.value[0] @property def sender(self): return self.value[1] @property def target(self): return self.value[2] @property def code(self): return self.value[3] @classmethod def unpack(cls, data): return cls(data[0], data[1], data[2], data[3]) # <----------------------------------------------------------------------------------> class Serial(serial.Serial): pass # <----------------------------------------------------------------------------------> class FlowControlledSerial(Serial): def write(self, data): counter = 0 splitted = self.splitByteString(data) for current in splitted: wTime = len(current) * 8 / BIT_PER_SEC log("FlowControlledSerial Writing {} bytes to the serial".format(len(current))) counter += super().write(current) log("FlowControlledSerial Waiting {} sec to send the written data".format(wTime)) time.sleep(wTime) return counter def splitByteString(self, input): data = [] for index in range(0, len(input), BUFFER_SIZE): data.append(input[index: index + BUFFER_SIZE]) return data # <----------------------------------------------------------------------------------> class Connection(object): def __init__(self, con): if not issubclass(type(con), Serial): raise NotSerialError("Excepted a Serial object from this library") self._serial = con log("Connection Using serial: " + str(con)) self._serialWriteLock = threading.Lock() self._slotmanager = SlotManager() # self._received = TransparentBuffer() self.receiverThread = threading.Thread( target=self._continousReadGate, name="Receiver thread reading from {}".format(self._serial.port), daemon=True) self.receiverThread.start() log("Connection Initialization done") def _continousReadGate(self): log("Connection Starting continous read from serial") try: self._continousRead() except Exception as e: log("Connection An error occured in continous read. Receiving stopped.", e) def _continousRead(self): while True: msg = self._readMessage(1)[0] log("Connection Received a new message: " + str(msg)) if msg.code == BUNDLE_HEADER_CODE: messages = self._readBundleBody(msg) # Make bundle from mesages sendable = Bundle.joinMessages(msg, messages) log("Connection Received a new bundle (body not displayed)") else: sendable = msg if (sendable.target == DEVICE_ID) or (sendable.target == 0): self._slotmanager(sendable.code, sendable, self) else: log("Connection Ignore message because it's not sended for this device") def _readBundleBody(self, headerMessage): log("Connection Reading bundle body") data = self._readMessage(int(headerMessage.body)) log("Connection Bundle body received") return data def _readMessage(self, num): messages = [] log("Connection Waiting for {} message(s)".format(num)) while num: header = self._readHeader() body = self._readBody(header) if len(body) < header.length: msg = BrokenMessage.joinHeaderWithBody(header, body) log("Connection Message is broken: " + str(msg)) else: msg = Message.joinHeaderWithBody(header, body) log("Connection Message arrived correctly: " + str(msg)) messages.append(msg) num -= 1 return messages def _readHeader(self): self._serial.timeout = None rawHeader = self._serial.read(4) header = Header.unpack(rawHeader) return header def _readBody(self, header): length = header.length timeout = (length * 8 / BIT_PER_SEC) * TIMEOUT_MULTIPLIER self._serial.timeout = timeout rawBody = self._serial.read(length) body = rawBody.decode("ascii", "replace") return body @property def slots(self): return self._slotmanager def send(self, sendable): if not issubclass(type(sendable), Sendable): raise TypeError("Expected Sendable, got {}".format(type(sendable))) with self._serialWriteLock: byteString = sendable.encode() log("Connection Writing {} to the serial".format(byteString)) self._serial.write(byteString) def join(self): log("Connection Waiting for receiver thread to die") self.receiverThread.join() @property def deviceID(self): return DEVICE_ID @deviceID.setter def deviceID(self, num): if type(num) != int: raise TypeError("Excepted int, got {}".format(type(num))) if not (num in range(256)): ValueError("Excepted int in [0-255], got {}".format(num)) log("Connection New device id is {}".format(num)) global DEVICE_ID DEVICE_ID = num # <----------------------------------------------------------------------------------> class SlotManager(object): def __init__(self): self._placeholder = lambda msg, conn: None self._slots = [self._placeholder for x in range(255)] # Bind underhood functions self._slots[1] = _1_BasicText self._slots[3] = _3_ApplyTimeOut self._slots[5] = _5_Exit def __call__(self, slotnum, arg, connection): if not (slotnum in range(255)): raise IndexError("Slots are available from 0-254") try: self._slots[slotnum](arg, connection) log("SlotManager Slot {} excuted".format(slotnum)) except Exception as e: log("SlotManager Error happend while executing slot {}".format(slotnum), e) def bind(self, slotnum, func): if not (slotnum in range(PROTOCOL_CODES_NUM, 255)): raise IndexError("Slots are available from {}-254".format(PROTOCOL_CODES_NUM)) if not callable(func): raise TaskNotCallableError("{} is not callable".format(func)) if self._slots[slotnum] == self._placeholder: self._slots[slotnum] = func log("SlotManager Binded {} to slot {}".format(func, slotnum)) else: raise SlotAlreadyUsedError("{} is already in slot {}".format(self._slots[slotnum], slotnum)) def unbind(self, slotnum): if not (slotnum in range(PROTOCOL_CODES_NUM, 255)): raise IndexError("Slots are available from {}-254".format(PROTOCOL_CODES_NUM)) if self._slots[slotnum] == self._placeholder: raise EmptySlotErrorr("Slot {} is already empty".format(slotnum)) else: logText = self._slots[slotnum] self._slots[slotnum] = self._placeholder log("SlotManager Unbinded {} from slot {}".format(logText, slotnum)) def isUsed(self, slotnum): if not (slotnum in range(255)): raise IndexError("Slots are available from {}-254".format(PROTOCOL_CODES_NUM)) return not (self._slots[slotnum] == self._placeholder) def __str__(self): return "<" + self.__class__.__name__ + ">" def __repr__(self): return self.__class__.__name__ + "()" # <----------------------------------------------------------------------------------> # Underhood functions (the first 32 action code) def _1_BasicText(msg, conn): log("BASIC_TEXT Text Received:", msg.body) def _3_ApplyTimeOut(msg, conn): tm = ast.literal_eval(msg.body) if (tm == None) or (type(tm) == float) or (type(tm) == int): TIMEOUT_MULTIPLIER = tm logText = "None"if tm == None else 100 * tm log("APPLY_TIME_OUT_MULTIPLIER New timeout is {}%".format(logText)) else: log("APPLY_TIME_OUT_MULTIPLIER Can't set new multiplier: " + str(tm)) raise TypeError("TIMEOUT_MULTIPLIER excepcted None, float or int, got {}".format(type(tm))) def _5_Exit(msg, conn): log("EXIT Got an exit call (msg 5)") exit(5) # <----------------------------------------------------------------------------------> def wrapText(text, sender, target): # Wrap any string into sendable log("Wrapper Wrapping text: " + text) s = Message(sender, target, BASIC_TEXT_CODE, text)\ if len(text) <= 255 else Bundle(sender, target, BASIC_TEXT_CODE, text) log("Wrapper Text wrapped: " + str(s)) return s # <----------------------------------------------------------------------------------> # Exceptions class QueueIsEmpty(Exception): pass # <----------------------------------------------------------------------------------> class ValueNotInteger(Exception): pass class ValueOutOfByteRange(Exception): pass # <----------------------------------------------------------------------------------> class OversizedMessageError(Exception): pass # <----------------------------------------------------------------------------------> class TransparentBufferNotContainsError(Exception): pass # <----------------------------------------------------------------------------------> class NotSerialError(Exception): pass # <----------------------------------------------------------------------------------> class TaskNotCallableError(Exception): pass class SlotAlreadyUsedError(Exception): pass class EmptySlotError(Exception): pass
C
UTF-8
946
3.78125
4
[]
no_license
#include <stdio.h> #include <string.h> int palindrome(int num){ char str[40]; sprintf(str, "%d", num); int len=strlen(str); int end=len-1; int start=0; for (start=0; start<end; start++){ if(str[start]!=str[end]) return 0; end--; } return 1; } int findMaxPalindrome(){ int firstN=100; int secondN=100; int max=0; for(firstN=100; firstN<1000; firstN++){ for(secondN=100; secondN<1000; secondN++){ int sum=firstN*secondN; if (palindrome(sum) && sum>max){ printf("%d x %d = %d \n", firstN, secondN, sum); max=sum; } } } return max; } int main(void) { // your code goes here int result=palindrome(12345); printf("%d\n", result); result=palindrome(9009); printf("%d\n", result); result=palindrome(909); printf("%d\n", result); int max=findMaxPalindrome(); printf("max palindrome: %d\n", max); return 0; }
C++
UTF-8
333
2.84375
3
[]
no_license
class Solution { public: int nthUglyNumber(int n) { set<long long> s; n--; long long x = 1; while(n--) { s.insert(x*2); s.insert(x*3); s.insert(x*5); x = *(s.begin()); s.erase(s.begin()); } return (int)x; } };
JavaScript
UTF-8
1,879
2.578125
3
[]
no_license
import React, { Component } from "react"; import { bindActionCreators } from "redux"; import { connect } from "react-redux"; import { createBoard, changeCellState, randomizeBoard } from "../../actions/index"; import "./Board.css"; class Board extends Component { renderBoard = () => { if (!this.props.board.cells) return; return this.props.board.cells.map((row, rowId) => row.map((cell, colId) => { if (cell === 0) return ( <div key={rowId + colId} className="board__cell board__cell--dead" onClick={() => this.props.changeCellState(rowId, colId)} /> ); if (cell === 1) return ( <div key={rowId + colId} className="board__cell board__cell--alive" onClick={() => this.props.changeCellState(rowId, colId)} /> ); return ( <div key={rowId + colId} className="board__cell board__cell--alive-old" onClick={() => this.props.changeCellState(rowId, colId)} /> ); }) ); }; componentWillMount() { this.props.createBoard(30, 55); this.props.randomizeBoard(); } render() { let gridSetings = { gridTemplateRows: `repeat(${this.props.board.height}, ${ this.props.board.cellSize })`, gridTemplateColumns: `repeat(${this.props.board.width}, ${ this.props.board.cellSize })` }; return ( <div className="board" style={gridSetings}> {this.renderBoard()} </div> ); } } const mapStateToProps = ({ board }) => ({ board }); const mapDispatchToProps = dispatch => bindActionCreators({ createBoard, changeCellState, randomizeBoard }, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(Board);
Java
UTF-8
3,518
2.21875
2
[ "Apache-2.0" ]
permissive
package de.tfsw.accounting.io.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for xmlClient complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="xmlClient"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="clientNumber" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="address" type="{}xmlAddress" minOccurs="0"/> * &lt;element name="defaultPaymentTerms" type="{}xmlPaymentTerms" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "xmlClient", propOrder = { "clientNumber", "address", "defaultPaymentTerms" }) public class XmlClient { protected String clientNumber; protected XmlAddress address; protected XmlPaymentTerms defaultPaymentTerms; @XmlAttribute(name = "name", required = true) protected String name; /** * Gets the value of the clientNumber property. * * @return * possible object is * {@link String } * */ public String getClientNumber() { return clientNumber; } /** * Sets the value of the clientNumber property. * * @param value * allowed object is * {@link String } * */ public void setClientNumber(String value) { this.clientNumber = value; } /** * Gets the value of the address property. * * @return * possible object is * {@link XmlAddress } * */ public XmlAddress getAddress() { return address; } /** * Sets the value of the address property. * * @param value * allowed object is * {@link XmlAddress } * */ public void setAddress(XmlAddress value) { this.address = value; } /** * Gets the value of the defaultPaymentTerms property. * * @return * possible object is * {@link XmlPaymentTerms } * */ public XmlPaymentTerms getDefaultPaymentTerms() { return defaultPaymentTerms; } /** * Sets the value of the defaultPaymentTerms property. * * @param value * allowed object is * {@link XmlPaymentTerms } * */ public void setDefaultPaymentTerms(XmlPaymentTerms value) { this.defaultPaymentTerms = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } }
C++
UTF-8
445
3.296875
3
[]
no_license
#include <iostream> #include <string> using namespace std; void letras(string str){ int voc=0; for(unsigned int i=0; i<str.length(); i++){ if(str[i]=='a' || str[i]=='A' || str[i]=='e' || str[i]=='E' || str[i]=='i' || str[i]=='I' || str[i]=='o' || str[i]=='O' || str[i]=='u' || str[i]=='U'){ voc++; } } cout << voc << "/" << str.length() << endl; } int main(){ string str; while(getline (cin,str)){ letras(str); } return 0; }
C#
UTF-8
1,263
3.15625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Study { /// <summary> /// 约瑟夫环[有死循环未解决] /// </summary> public class JosephRing : MonoBehaviour { private readonly List<int> people = new List<int>(); private void Start() { for (int i = 0; i < 41; i++) { people.Add(i + 1); } Compute(people, 3); } private void Compute(List<int> list, int circle = 3) { int index = 0, step = 0; while (true) { if (list.Count < 3) { break; } if (++step == circle) { step = 1; Debug.LogError("移除:" + list[index]); list.RemoveAt(index); } if (index >= list.Count) { index = 0; } if (++index >= list.Count) { index = 0; } } Debug.LogError("剩余:" + list[0] + " and " + list[1]); } } }
C
UTF-8
751
2.625
3
[ "MIT" ]
permissive
#include "stride.h" int OutSeq(CHAIN **Chain, int NChain, COMMAND *Cmd) { int Cn, Res; FILE *Seq; if( (int)strlen(Cmd->SeqFile) == 0 ) Seq = stdout; else if( (Seq = fopen(Cmd->SeqFile,"a")) == NULL ) die("Error writing sequence file %s\n",Cmd->SeqFile); for( Cn=0; Cn<NChain; Cn++ ) { if( !Chain[Cn]->Valid ) continue; fprintf(Seq,">%s %c %d %7.3f\n", Chain[Cn]->File,SpaceToDash(Chain[Cn]->Id),Chain[Cn]->NRes, Chain[Cn]->Resolution); for( Res=0; Res<Chain[Cn]->NRes; Res++ ) { if( Res%60 == 0 && Res != 0 ) fprintf(Seq,"\n"); fprintf(Seq,"%c",ThreeToOne(Chain[Cn]->Rsd[Res]->ResType)); } fprintf(Seq,"\n"); } fclose(Seq); exit(0); return(SUCCESS); }
Java
UTF-8
1,005
2.078125
2
[]
no_license
package com.didu.serviceImpl; import com.didu.dao.Carouseldao; import com.didu.dao.Navigationdao; import com.didu.domain.Navigation; import com.didu.service.NavigationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by Administrator on 2017/10/27. */ @Service @Transactional public class NavigationServiceImpl implements NavigationService { @Autowired private Navigationdao idao; @Override public boolean addImage(Navigation navigation) { return idao.addImage(navigation)>0?true:false; } @Override public Navigation queryI(int id) { return idao.queryI(id); } @Override public boolean updateImage(Navigation picture) { return idao.updateImage(picture)>0?true:false; } @Override public List<Navigation> query() { return idao.query(); } }
Shell
UTF-8
179
2.703125
3
[]
no_license
#!/bin/bash DEPLOY_DIR=`dirname $0`/listen_deploy echo "DEPLOYING to $DEPLOY_DIR" ant -Ddeploy.dir=$DEPLOY_DIR test deploy JRET=$? if [ $JRET == "0" ]; then ant clean rpm fi
Java
UTF-8
1,168
3.078125
3
[]
no_license
package withattribute; import java.util.ArrayList; import java.util.List; public class Route { private long id; private String name; List<BusRoute> busRouteList = new ArrayList<>(); public Route(long id, String name) { this.id = id; this.setName(name); } public void addBusRoute(BusRoute busRoute) { if (busRoute == null) { throw new IllegalArgumentException("BusRoute shouldn't be null!"); } if (!busRouteList.contains(busRoute)) { busRouteList.add(busRoute); } } public void removeBusRoute(BusRoute busRoute) { busRouteList.remove(busRoute); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { if (name == null) { throw new IllegalArgumentException("Route isn't named!"); } this.name = name; } public List<BusRoute> getBusRouteList() { return busRouteList; } public String toString() { return getName(); } }
JavaScript
UTF-8
1,736
2.546875
3
[]
no_license
import React from 'react'; import './Rate.css'; import Calc from '../Calc/Calc' class Rate extends React.Component { constructor(props) { super(props); this.state = { 'date': '', 'currencyRate': {} } this.getRate(); this.currency = ["USD", "RUB", "CAD", "PHP", "BRL"]; } getRate = () => { fetch("https://api.exchangeratesapi.io/latest") .then(data => { return data.json(); }) .then(data => { console.log(data); this.setState({ date: data.date }); let result = {}; for (let i = 0; i < this.currency.length; i++) { result[this.currency[i]] = data.rates[this.currency[i]] } console.log(result); this.setState({ currencyRate: result }); }); } render() { return (<div className="rate"> <div className="blockmoney"> {Object.keys(this.state.currencyRate).map((keyName, i) => ( <div className="WAR" key={keyName}> <div className="flex-block">{keyName}</div> <div className="flex-block">{this.state.currencyRate[keyName].toFixed(2) } </div> <p className="par"> *You can buy for one euro</p> <img src="European-union-icon.png" className="iconeur"></img> </div> ) )} </div> <Calc rate={this.state.currencyRate}/> <div className="soc"> <ul> <li claaName="soc_item"> </li> <li claaName="soc_item"></li> <li claaName="soc_item"></li> <li></li> </ul> </div> </div> ); } } export default Rate;
Markdown
UTF-8
3,110
3.25
3
[ "MIT" ]
permissive
# stripe-cohort Create [Stripe](https://stripe.com) customer cohorts for a useful business overview. ### Overview If you're interested in getting a cohort based overview of your Stripe customers, then this library might be of help. It currently supports the following stats (by cohort): - Total number of customers - Monthly recurring revenue - Number of subscriptions - Subscriptions by plan ## Installation $ npm install stripe-cohort ## Example Create a new Stripe cohort (by the customer's `created` date): ```js cohort(new Date('1/1/2014'), new Date('2/1/2014'), function (err, customers) { console.log(customers.count() + ' created in January!'); }); ``` And the returned `customers` object lets you dive deeper into the cohort. #### Options You can include options as the second param when initializing a cohort. * `ignoreStripeFees` (default:false) If `true`, this will include the Stripe fees in your MRR. #### Number of Customers You can query the total amount of customers returned: ```js customers.count(); ``` or filter further inside the cohort by the customers' `created` date: ```js customers.count(new Date('1/15/2014'), new Date('1/24/2014')); ``` #### Customer List ```js customers.list() ``` ```js [ { id: 'cus_2983jd92d2d', name: 'Patrick Collison', .. }, ] ``` or filter further by the customers' `created` date: ```js customers.list(new Date('1/15/2014'), new Date('1/24/2014')); ``` or get all the `delinquent` customers: ```js customers.delinquent().count(); ``` #### Subscriptions You can learn about your active subscriptions too: ```js customers.subscriptions().count(); ``` Or the ones created between the date provided: ```js customers.subscriptions(new Date('1/15/2014'), new Date('1/24/2014')).count(); ``` Or just get the list of Stripe subscription objects: ```js var objects = customers.subscriptions().list(); ``` #### Monthly Recurring Revenue You can get the monthly recurring revenue from the active subscriptions on the customers: ```js customers.subscriptions().active().mrr(); ``` And for the trialing accounts: ```js customers.subscriptions().trialing().mrr(); ``` And for any status really: ```js customers.subscriptions().status('unpaid').mrr(); ``` And you can query the monthly recurring revenue by subscription `start` within a cohort: ```js customers.subscriptions().active().mrr(new Date('1/15/2014'), new Date('1/16/2014')); ``` Remember that the montly recurring revenue does not equal charges. For example, if a customer upgrades from a $29 plan to a $79 plan today, they will pro-rated for the rest of their billing period. That means you did not make the $79 yet, but you'll make the difference next month. For hard cash, use [stripe-charges](https://github.com/segmentio/stripe-charges). #### Plans It's also interesting to know what plans the subscriptions are being set at. You can select the subscriptions that fall under that plan: ```js var mrr = customers.subscriptions().active().plan('startup').mrr(); console.log('We made $' + mrr + ' off the startup plan!'); ``` ## License MIT
C#
UTF-8
687
2.515625
3
[]
no_license
using System; using Xamarin.Forms; namespace XFormsDrawer { public class BoxView : View { public static readonly BindableProperty BorderColorProperty = BindableProperty.Create<EllipseView, Color>(p => p.Color, Color.Accent); public static readonly BindableProperty FillColorProperty = BindableProperty.Create<EllipseView, Color>(p => p.Color, Color.Accent); public BoxView () { } public Color BorderColor { get { return (Color)GetValue(BorderColorProperty); } set { SetValue(BorderColorProperty, value); } } public Color FillColor { get { return (Color)GetValue(FillColorProperty); } set { SetValue(FillColorProperty, value); } } } }
Python
UTF-8
721
2.953125
3
[]
no_license
# import math import Queue import copy def solve(name, n): start = 0 i = 0 r = 0 result = 0 while i < len(name): if name[i] not in 'aeiou': r += 1 if r >= n: # print i+1,n,start,(i+1-n-start+1),(len(name)-i) result += (i+1-n-start+1)*(len(name)-i) start = i-n+2 else: r = 0 i += 1 return result def main(): # fp = open('a.in') # fp = open('A-small-attempt2.in') fp = open('A-large.in') # fp = open('A-small-practice.in') # fp = open('A-large-practice.in') for case in xrange(int(fp.readline())): name, n = fp.readline().split() n = int(n) # print name, n result = solve(name, n) print 'Case #{0}: {1}'.format(case+1, result) if __name__ == "__main__": main()
JavaScript
UTF-8
2,125
2.65625
3
[]
no_license
/* Created by and property of: Aidan Harney Free use provided to: Perth's Allied Costumers Said use can by revoked by said owner at any time */ (function ($) { // Define the AHyoutube button $.cleditor.buttons.AHyoutube = { name: "AHyoutube", image: "youtube.gif", title: "Insert YouTube Video", command: "inserthtml", popupName: "AHyoutube", popupClass: "cleditorPrompt", popupContent: '<label>Enter YouTube Id:<br /><input type="text" style="width:200px"></label><br/>' + '<label>Height (px):<br /><input type="text" style="width:200px"></label><br/>' + '<label>Width (px):<br /><input type="text" style="width:200px"></label><br/>' + '<br /><input type="button" value="Submit">', buttonClick: youtubeButtonClick }; // AHyoutube button click event handler function youtubeButtonClick(e, data) { // Wire up the submit button click event handler $(data.popup).children(":button") .unbind("click") .bind("click", function (e) { // Get the editor var editor = data.editor; // Get the input content var $text = $(data.popup).find(":text"), id = $text[0].value, height = parseInt($text[1].value), width = parseInt($text[2].value); // Build the html var html; if (id != null && id != "") { html = '[youtube id="' + id + '"'; if(height > 0) { html = html + ' height="' + height; } if(width > 0) { html = html + ' width="' + width; } html = html + '/]'; } // Insert the html if (html) editor.execCommand(data.command, html, null, data.button); // Reset the text, hide the popup and set focus $text.val(""); editor.hidePopups(); editor.focus(); }); } })(jQuery);
Java
UTF-8
4,938
3
3
[]
no_license
package sintatico.execucao; import sintatico.armazenamento.htmltojava; import java.io.IOException; import java.util.ArrayList; import java.util.Stack; import lexico.conceito.armazenamento.Token; import lexico.conceito.processamento.ErroLexico; import lexico.conceito.processamento.Lexico; import sintatico.armazenamento.Log; import sintatico.armazenamento.Node; import sintatico.armazenamento.Tree; public class Sintatico { private Lexico lex; private String[][] Tabela; private String[][] Exprecoes; private Log log; private Tree<Token> tree; ArrayList<Token> lista_token; String msgerro = ""; public Sintatico(String caminho) throws ErroSintatico, ErroLexico { lex = new Lexico(caminho); Tabela = new String[36][40]; Exprecoes = new String[66][2]; try { htmltojava table = new htmltojava("Tabela Sintatica.html", 0); Tabela = table.getCampos(); table = new htmltojava("Tabela Sintatica.html", 1); Exprecoes = table.getCampos(); } catch (IOException ex) { System.out.println("Erro ao acessar a tabela sintatica." + ex.toString()); System.exit(0); } Token aux_token = new Token(); aux_token.setToken("$"); aux_token.setLexema(""); lista_token = lex.getTokens(); lista_token.add(aux_token); pilha.push("$"); pilha.push("principal"); aux_token = new Token(); aux_token.setToken("programa_inicio"); aux_token.setLexema("programa_inicio"); aux_token.setLinha(-1); aux_token.setColuna(-1); Node<Token> root = new Node<Token>(aux_token); tree = new Tree<Token>(root); log = new Log("Sintatico"); processar(root); if(!(msgerro.isEmpty())){ throw new ErroSintatico(msgerro); } } int x = 0; Stack pilha = new Stack(); Node<Token> aux_no2 = null; private void processar(Node<Token> pai) { int y = 0; String temp[] = null; String aux = (String) pilha.pop(); log.setTexto("(PILHA) Desempilhado :" + aux); Token aux_token = new Token(); aux_token.setToken(aux); aux_token.setLexema(aux); aux_token.setLinha(-1); aux_token.setColuna(-1); aux_no2 = new Node<Token>(aux_token); pai.addChild(aux_no2); log.setTexto("(ARVORE) Inserido no :" + aux_no2.toString()); pai = aux_no2; if (aux.equals((lista_token.get(x)).getToken())) { pai.addChild(new Node<Token> (lista_token.get(x))); log.setTexto("(ARVORE) Inserido no :" + (lista_token.get(x)).getLexema()); if (aux.equals("$")) { return; } x++; } else if (aux.equals("î")) { } else { aux = verificarTabela(aux, (lista_token.get(x).getToken())); if (aux.equals("-")) { msgerro = " (Linha "+(lista_token.get(x).getLinha()+1)+") Arquivo fonte não reconhecido.\n"; } else { temp = this.verificarExprecoes(aux); y = temp.length - 1; while (y >= 0) { pilha.push(temp[y]); log.setTexto("(PILHA) Empilhado :" + temp[y]); y--; } y = 0; while (y < temp.length) { processar(pai); y++; } } } } private String verificarTabela(String pilha, String token) { String saida; int aux = 1; int aux2 = 1; for (int i = 0; i < 36; i++) { if (Tabela[i][0].equals(pilha)) { aux = i; } } for (int i = 0; i < 40; i++) { if (Tabela[0][i].equals(token)) { aux2 = i; } } saida = Tabela[aux][aux2]; return saida; } private String[] verificarExprecoes(String aux) { int z; for (z = 0; z < 66; z++) { if (aux.equals(Exprecoes[z][0])) { break; } } String[] saida = new String[Exprecoes[z].length - 1]; int w = 1; while (w < Exprecoes[z].length) { saida[w - 1] = Exprecoes[z][w]; w++; } return saida; } public String getLog() { return log.getTexto(); } public String imprimirArvore() { tree.imprimirArvore((tree.getRoot()), 6, 0); return(tree.getSaida()); } public Tree<Token> getTree() { return tree; } }
Shell
UTF-8
110
2.671875
3
[]
no_license
#! /bin/bash for i in $(seq 1 16); do port=$((8000 + $i)) python ../src/webapp.py --port $port& done
C++
UTF-8
3,410
3.703125
4
[]
no_license
#include <iostream> #include <math.h> #define MAX 2 using namespace std; struct Fraction { float numerator; float denominator; }; void InputFraction(Fraction *F) { do { cout << "Input numerator: "; cin >> F->numerator; cout << "Input denominator: "; cin >> F->denominator; } while (F->denominator == 0); } void ReduceFraction(Fraction *F) { int a = F->numerator; int b = F->denominator; if (a < 0) { a = abs(a); } while (a != b) //tìm UCLN của 2 số { a > b ? a -= b : b -= a; //nếu a>b thì a=a-b ngược lại a<b thì b=b-a; } F->numerator = F->numerator / a; //lấy tử chia UCLN = a = b bởi vì khi thoát khỏi vòng lặp while thì điều kiện phải là a = b F->denominator = F->denominator / a; //lấy mẫu chia UCLN =a = b nên lấy =a là được cout << F->numerator << "/" << F->denominator << endl; //in ra phân số vừa rút gọn } void Compare(Fraction F1, Fraction F2) { float a,b; a = (F1.numerator / F1.denominator); b = (F2.numerator / F2.denominator); if (a==b) { cout << "the first fraction is equal to the second fraction" << endl; } else if (a > b) { cout << "The first fraction ( " << F1.numerator << "/" << F1.denominator << " ) is bigger than the second fraction." << endl; } else { cout << "The second fraction ( " << F2.numerator << "/" << F2.denominator << " ) is bigger than the first fraction." << endl; } } void ReduceToTheSameDenominator(Fraction *F1, Fraction *F2) { int SameDenominator; SameDenominator = (F1->denominator) * (F2->denominator); F1->numerator = F1->numerator * F2->denominator; F2->numerator = F2->numerator * F1->denominator; F1->denominator = SameDenominator; F2->denominator = SameDenominator; } void Calculate(Fraction F1, Fraction F2) { Fraction Sum, Subtract, Multiply, Divide; Sum.numerator = F1.numerator + F2.numerator; Sum.denominator = F1.denominator; cout << " Sum: "; ReduceFraction(&Sum); Subtract.numerator = F1.numerator - F2.numerator; Subtract.denominator = F1.denominator; cout << " Subtract: "; ReduceFraction(&Subtract); Multiply.numerator = F1.numerator * F2.numerator; Multiply.denominator = F1.denominator * F2.denominator; cout << " Multiply: "; ReduceFraction(&Multiply); Divide.numerator = F1.numerator * F2.denominator; Divide.denominator = F1.denominator * F2.numerator; cout << " Divide: "; ReduceFraction(&Divide); } int main() { Fraction F[MAX]; int i, n = 1; cout << "1. Reduce a fraction: " << endl; for (i = 0; i <= n; i++) { InputFraction(&F[i]); cout << "The fraction after reduce is: " << endl; cout << "\nF["<< i <<"]= "; ReduceFraction(&F[i]); cout << endl; } cout << "\n2. Compare two fractions: " << endl; Compare(F[0],F[1]); ReduceToTheSameDenominator(&F[0], &F[1]); cout << "\n3. Calculate: " << endl; Calculate(F[0], F[1]); system("pause"); } //---------giải thích hàm ReduceFraction ----------\\ //Tại mỗi bước lặp nó sẽ kiểm tra giá trị hiện tại của a và b xem thằng nào lớn hơn /*Ví dụ với hai số a = 7, b = 5 bên trong vòng lặp while(a != b) L1: a > b = > a = 2, b = 5 L2: b > a = > a = 2, b = 3 L3: b > a = > a = 2, b = 1 L4: a > b = > a = 1, b = 1 L5: a == b = > trả về a hoặc b đều được = > KQ là 1 */
SQL
UTF-8
1,630
3.25
3
[ "MIT" ]
permissive
/* SQLyog Ultimate v12.4.1 (64 bit) MySQL - 10.1.21-MariaDB : Database - db_parkir ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`db_parkir` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `db_parkir`; /*Table structure for table `tbl_transaksi` */ DROP TABLE IF EXISTS `tbl_transaksi`; CREATE TABLE `tbl_transaksi` ( `id` int(3) NOT NULL AUTO_INCREMENT, `plat_nomor` varchar(20) DEFAULT NULL, `warna` varchar(20) DEFAULT NULL, `tipe` varchar(3) DEFAULT NULL, `tanggal_masuk` datetime DEFAULT NULL, `tanggal_keluar` datetime DEFAULT NULL, `parkir_lot` varchar(4) DEFAULT NULL, `jumlah_bayar` int(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1; /*Data for the table `tbl_transaksi` */ insert into `tbl_transaksi`(`id`,`plat_nomor`,`warna`,`tipe`,`tanggal_masuk`,`tanggal_keluar`,`parkir_lot`,`jumlah_bayar`) values (15,'D 1993 PE','Hitam','MPV','2019-07-26 11:24:42',NULL,'A15',NULL), (16,' B 123 34','Hitam','SUV','2019-07-26 11:25:04',NULL,'A16',NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
Markdown
UTF-8
965
2.515625
3
[]
no_license
# Codevember Codevember is a challenge for developers to sharpen their creativity and improve their skills. The goal is to build a creative piece of code every day of November. We give you daily hints to inspire you but you can do unrelated sketches. * [Day 01 - Infinity](https://codepen.io/H0tFudge/full/pQzpoq/) * [Day 02 - Time](https://codepen.io/H0tFudge/full/gQORVm/) * [Day 03 - Carrot](https://codepen.io/H0tFudge/full/wQBaqZ/) * [Day 04 - Sky](https://codepen.io/H0tFudge/full/XyJoBL/) * [Day 05 - Music](https://codepen.io/H0tFudge/full/XybvPO/) * [Day 06 - Web](https://codepen.io/H0tFudge/full/aQvMMq/) * [Day 07 - Sea](https://codepen.io/H0tFudge/full/GwoKor/) * [Day 08 - Cat](https://codepen.io/H0tFudge/full/WYxZxR/) * [Day 09 - Green](https://codepen.io/H0tFudge/full/OaXYvX/) * [Day 10 - Apple](https://codepen.io/H0tFudge/full/eQBgJj/) * [Day 11 - RGB](/) * [Day 12 - Bread](/) * [Day 13 - Black Hole](https://codepen.io/H0tFudge/full/Gwrjwd/)
Java
UTF-8
3,279
2.359375
2
[]
no_license
package com.br.smartzoo.ui.adapter; import android.app.Activity; import android.content.res.Resources; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.br.smartzoo.R; import com.br.smartzoo.SmartZooApplication; import com.br.smartzoo.model.entity.Employee; import com.br.smartzoo.model.interfaces.OnHireListener; import com.bumptech.glide.Glide; import java.util.List; /** * Created by adenilson on 22/05/16. */ public class HireEmployeeListAdapter extends RecyclerView.Adapter<HireEmployeeListAdapter.ViewHolder> { private Activity mContext; private List<Employee> mEmployeeList; private OnHireListener mOnHireListener; public HireEmployeeListAdapter(Activity context, List<Employee> employeeList){ this.mContext = context; this.mEmployeeList = employeeList; } public void addOnHireListener(OnHireListener onHireListener){ this.mOnHireListener = onHireListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Log.i("onCreateViewHolder", ""); View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_hire_employee_list, parent, false); return new ViewHolder(itemView); } public void onBindViewHolder(ViewHolder holder, int position) { final Employee employee = mEmployeeList.get(position); Resources resources = mContext.getResources(); Glide.with(mContext).load(resources.getIdentifier(employee.getImage(), "drawable", SmartZooApplication.NAME_PACKAGE)).into(holder.mImageViewIcon); holder.mTextViewName.setText(employee.getName()); holder.mTextViewProfession.setText(employee.getProfession()); holder.mTextViewPrice.setText("$" + String.valueOf(employee.getSalary())); holder.mButtonEmployee.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOnHireListener.onHire(employee); } }); } @Override public int getItemCount() { return mEmployeeList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private ImageView mImageViewIcon; private TextView mTextViewName; private TextView mTextViewProfession; private TextView mTextViewPrice; private Button mButtonEmployee; public ViewHolder(View itemView) { super(itemView); mImageViewIcon = (ImageView) itemView.findViewById(R.id.image_view_employee); mTextViewName = (TextView) itemView.findViewById(R.id.text_view_name_employee); mTextViewProfession = (TextView) itemView.findViewById(R.id.text_view_profession); mTextViewPrice = (TextView) itemView.findViewById(R.id.text_view_price_employee); mButtonEmployee = (Button) itemView.findViewById(R.id.button_hire_employee); } } public List<Employee> getEmployeeList() { return mEmployeeList; } }
Java
UTF-8
7,747
2.96875
3
[]
no_license
package data.mappers; import data.DatabaseConnector; import data.ExceptionLogger; import data.exceptions.UsersException; import data.interfaces.MapperInterface; import data.models.LoggerEnum; import data.models.RoleEnum; import data.models.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; /** * * @author Martin Frederiksen */ public class UserMapper implements MapperInterface<User, String> { DatabaseConnector dbc = new DatabaseConnector(); public UserMapper(DataSource ds) { dbc.setDataSource(ds); } /** * Gets all Users from the database * @return List of User * @throws UsersException UsersException */ @Override public List getAll() throws UsersException { try (Connection con = dbc.open()) { List<User> users = new ArrayList(); String qry = "SELECT * FROM accounts;"; Statement stm = con.createStatement(); ResultSet rs = stm.executeQuery(qry); while (rs.next()) { users.add(new User(rs.getString("email"), rs.getString("password"), RoleEnum.valueOf(rs.getString("role")), rs.getString("name"), rs.getString("address"), rs.getString("zipCity"), rs.getString("phone"))); } return users; } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in getAll Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while getting data from database"); } } /** * Gets single user from the database * @param email email of user * @return Single User * @throws UsersException UsersException */ @Override public User getSingle(String email) throws UsersException { try (Connection con = dbc.open()) { String qry = "SELECT * FROM accounts WHERE email = ?;"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, email); ResultSet rs = ps.executeQuery(); while (rs.next()) { return new User(rs.getString("email"), rs.getString("password"), RoleEnum.valueOf(rs.getString("role")), rs.getString("name"), rs.getString("address"), rs.getString("zipCity"), rs.getString("phone")); } return null; } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in getSingle Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while getting data from database"); } } /** * Adds new user to the database * @param user User to be added * @throws UsersException UsersException */ @Override public void add(User user) throws UsersException { try (Connection con = dbc.open()) { String qry = "INSERT INTO accounts " + "VALUES (?,?,?,?,?,?,?);"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, user.getEmail()); ps.setString(2, user.getPassword()); ps.setString(3, user.getRole().toString()); ps.setString(4, user.getName()); ps.setString(5, user.getAddress()); ps.setString(6, user.getZipCity()); ps.setString(7, user.getPhone()); ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in add Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while adding data to database"); } } /** * Validates user by email and password * @param email Email of user * @param password Password of user * @return true/false * @throws UsersException UsersException */ public boolean validateUser(String email, String password) throws UsersException { try (Connection con = dbc.open()) { String qry = "SELECT email FROM accounts WHERE (email = ?) AND password = ?;"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, email); ps.setString(2, password); ResultSet rs = ps.executeQuery(); boolean valid = false; while (rs.next()) { valid = true; } return valid; } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in validateUser Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while validating user"); } } /** * Changes password of specific user * @param email Email of user * @param password New password for user * @return -1/0/1 * @throws UsersException UsersException */ public int changePassword(String email, String password) throws UsersException { try (Connection con = dbc.open()) { String qry = "UPDATE accounts SET password = ? WHERE email = ?;"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, password); ps.setString(2, email); int result = ps.executeUpdate(); return result; } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in changePassword Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while updating user"); } } /** * Changes role of specific user * @param email Email of user * @param role New role of user * @return -1/0/1 * @throws UsersException UsersException */ public int changeUserRole(String email, RoleEnum role) throws UsersException { try (Connection con = dbc.open()) { String qry = "UPDATE accounts SET role = ? WHERE email = ?;"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, role.toString()); ps.setString(2, email); return ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in changeUserRole Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error occoured while updating user"); } } /** * Removes user from the database * @param email Email of user * @throws UsersException UsersException */ public void remove(String email) throws UsersException { try (Connection con = dbc.open()) { String qry = "DELETE FROM accounts WHERE email = ?;"; PreparedStatement ps = con.prepareStatement(qry); ps.setString(1, email); ps.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); ExceptionLogger.log(LoggerEnum.USERMAPPER, "Error in remove Method: \n" + ex.getMessage(), ex.getStackTrace()); throw new UsersException("Error while removing request from database"); } } }
Java
UTF-8
323
2.015625
2
[]
no_license
package com.lunatech.assignment.imdb.client.dao; import java.util.List; public interface ImdbDao { List<String> readTopRatedMovieByGenre(String genre); List<String> getGenresForActor(String name); List<String> getTitlesForPerson(String name); List<String> getCharactersByTitles(List<String> titles); }
Go
UTF-8
431
3.0625
3
[ "BSD-3-Clause" ]
permissive
package main import ( "net" "fmt" "log" "bufio" ) func main(){ li,err:=net.Listen("tcp",":8080") if err!=nil{ fmt.Println("error1") } defer li.Close() for{ conn,err:=li.Accept() if err!=nil{ log.Println("error") } go handle(conn) } } func handle(conn net.Conn){ scanner:=bufio.NewScanner(conn) for scanner.Scan(){ ln:=scanner.Text() fmt.Println(ln) fmt.Fprintln(conn,ln) } defer conn.Close() }
Python
UTF-8
7,625
2.71875
3
[ "BSD-3-Clause" ]
permissive
import refMaps import context import match def hasTags(node): return "tags" in node def matchNodes(node1, node2, conf): #print("matching nodes", node1["tags"], "and", node2["tags"]) node1["matched"] = True node2["matched"] = True node1["match"] = match.Match(node2, conf) node2["match"] = match.Match(node1, conf) def unMatchNode(node): node["match"] = None node["matched"] = False def findMultTags(tags): multTags = [] for tag in tags: if tag == None: continue if tag[0] == "+" and len(tag) > 1: multTags.append(tag[1:]) return multTags def findDenyTags(tags): denyTags = [] for tag in tags: if tag == None: continue if tag[0] == "!": denyTags.append(tag[1:]) return denyTags ''' Given two nodes, check if any tags are equal ''' def tagsMatch(node1, node2, parent1, parent2, lang, rec, index1=0, index2=0): tags1 = node1["tags"] tags2 = node2["tags"] #deny = findDenyTags(tags1) + findDenyTags(tags2) mult = findMultTags(tags1) + findMultTags(tags2) multCount1 = 0 multCount2 = 0 #check if the tags are naively equal for tag in tags1: if tag == "\*": return 1 #if tag in deny: return -1 if tag in mult: multCount1 += 1 for tag_ in tags2: if tag_ == "\*": return 1 #if tag_ in deny: return -1 if tag_ in mult: mult2Count += 1 if tag.lower() == tag_.lower() and len(mult) == 0: return 1 #if len(deny) > 0: return 1 if len(mult) > 0 and multCount1 > 1 or multCount2 > 1: return 1 elif len(mult) > 0: return -1 if rec: confidence1 = equalTags(node1, node2, parent1, parent2, lang, index1, index2) if not confidence1 == -1: return confidence1 return equalTags(node2, node1, parent2, parent1, lang, index2, index2) else: confidence2 = equalTagsNotRec(node1, node2, parent1, parent2, lang) if not confidence2 == -1: return confidence2 return equalTagsNotRec(node2, node1, parent2, parent1, lang) def cntxtInsensitiveCheck(eqObj, tags2): tags2 = [tag.lower() for tag in tags2] for tag_ in eqObj.tags: if not tag_.lower() in tags2: return False return True def confidenceOfMatch(node, node2, parent, parent2, lang, rec, index1, index2): if hasTags(node) and hasTags(node2): #and not node2["matched"]: confidence1 = tagsMatch(node, node2, parent, parent2, lang, rec, index1, index2) if not confidence1 == -1: return confidence1 elif not hasTags(node) and not hasTags(node2) and typesMatch(node, node2) and datasMatch(node, node2): return 1 return -1 def getAllPotentialMatches(node, t2Nodes,lang, index1, rec=True): potentialMatches = [] unmatchedNodes = [] for node2 in t2Nodes: if not node2["matched"]: unmatchedNodes.append(node2) adlStrNodes = (node2 for node2 in t2Nodes if additionalStructure(node2,lang)) for adlStrNode in adlStrNodes: #print("adding children of", adlStrNode["tags"]) if not "children" in adlStrNode: continue editChildren(adlStrNode) unmatchedChildren = (child for child in adlStrNode["children"] if not child["matched"]) unmatchedNodes += unmatchedChildren index2 = 0 for node2 in unmatchedNodes: confidence = confidenceOfMatch(node, node2, node["parent"], node2["parent"], lang, rec, index1, index2) if not confidence == -1: potentialMatches.append(match.Match(node2, confidence)) index2 += 1 return potentialMatches def additionalDetail(node, lang): if not "tags" in node: return True for tag in node["tags"]: if tag.lower() in refMaps.adlDetailMap: for cntxt in refMaps.adlDetailMap[tag.lower()]: if cntxt == createContext(node,lang): return True return False ''' Given a node and its parent, see if it exists in the structEql map ''' def additionalStructure(node,lang): if not hasTags(node): return False for tag in node["tags"]: if tag.lower() in refMaps.adlStructMap: for cntxt in refMaps.adlStructMap[tag.lower()]: if createContext(node,lang) == cntxt: return True return False def editChildren(node): for child in node["children"]: if not "parent" in child: child["parent"] = node if not "matched" in child: child["matched"] = False def getBestMatch(potentialMatches): #print("potentialMatches:") #for match in potentialMatches: # print(match[0]["tags"]) bestConfValue = -1 bestMatch = None for match in potentialMatches: if match.confidence > bestConfValue: bestMatch = match bestConfValue = match.confidence return bestMatch def calculateConfidence(node1, node2, level, lang, index1, index2): numMatch = 0 if "children" in node1 and "children" in node2: editChildren(node1) editChildren(node2) for child in node1["children"]: child["parent"] = node1 if len(getAllPotentialMatches(child, node2["children"], lang, index1, False)) >= 1: numMatch += 1 numUnmatchable = 0 unmatchable = (_child for _child in node2["children"] if additionalStructure(_child,lang) or additionalDetail(_child, lang)) for unmatch in unmatchable: numUnmatchable += 1 totalChildren = (len(node2["children"]) - numUnmatchable)+ len(node1["children"]) if totalChildren == 0: return 1 #part1 = number of children if (len(node2["children"]) - numUnmatchable) - len(node1["children"]) == 0: part1 = .33 else: part1 = 0 #part2 = matches in the children part2 = (numMatch / totalChildren) / 3 #part3 = differences in indicies part3 = (1 - abs(index1 - index2)) / 3 return part1 + part2 + part3 return 1 ''' Checks if two tags are equal using the equality map ''' def equalTags(node1, node2, parent1, parent2, lang, index1, index2): tags1 = node1["tags"] tags2 = node2["tags"] #if it is a key in the equality map with an empty context for tag in tags1: if tag.lower() in refMaps.tagEqlMap: for eqObj in refMaps.tagEqlMap[tag.lower()]: if eqObj.context == context.Context(lang) and cntxtInsensitiveCheck(eqObj, tags2): return calculateConfidence(node1, node2, 1, lang, index1, index2) elif cntxtInsensitiveCheck(eqObj, tags2) and contextSensitiveCheck(eqObj, node1, lang): return calculateConfidence(node1, node2, 1,lang, index1, index2) return -1 def equalTagsNotRec(node1, node2, parent1, parent2, lang): tags1 = node1["tags"] tags2 = node2["tags"] #if it is a key in the equality map with an empty context for tag in tags1: if tag.lower() in refMaps.tagEqlMap: for eqObj in refMaps.tagEqlMap[tag.lower()]: if eqObj.context == context.Context(lang) and cntxtInsensitiveCheck(eqObj, tags2): return 1 elif cntxtInsensitiveCheck(eqObj, tags2) and contextSensitiveCheck(eqObj, node1, lang): return 1 return -1 def createContext(node,lang): lookaheadTags = None siblingTags = None parentTags = None gpTags = None if "children" in node: lookaheadTags = [] for child in node["children"]: if "tags" in child: lookaheadTags += child["tags"] if not lookaheadTags == None and len(lookaheadTags) == 0: lookaheadTags = None if "parent" in node and "children" in node["parent"]: siblingTags = [] for child in node["parent"]["children"]: if "tags" in child and not tagsMatch(child, node, node["parent"], node["parent"], lang, False, 0, 0): siblingTags += child["tags"] if not siblingTags == None and len(siblingTags) == 0: siblingTags = None if "parent" in node and "tags" in node["parent"]: parentTags = node["parent"]["tags"] if "parent" in node and "parent" in node["parent"] and "tags" in node["parent"]["parent"]: gpTags = node["parent"]["parent"]["tags"] return context.Context(lang, lookaheadTags, siblingTags, parentTags, gpTags) def contextSensitiveCheck(eqObj, node1, lang): return eqObj.context == createContext(node1, lang)
Java
UTF-8
334
1.773438
2
[]
no_license
package njust.service; import njust.model.User; public interface UserService extends BaseService<User> { public boolean isRegisted(String email); public User validateLoginInfo(String email, String md5); public void clearAuthorize(Integer userId); public void updateAuthorize(User model, Integer[] ownRoleIds); }
TypeScript
UTF-8
1,662
3.140625
3
[]
no_license
const solve09 = (matrix: string[][]) => { const MINE = "x"; for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == MINE) continue; let counter = 0; // right if (matrix[i][j + 1] && matrix[i][j + 1] == MINE) { counter++; } // left if (matrix[i][j - 1] && matrix[i][j - 1] == MINE) { counter++; } // top if (matrix[i - 1] && matrix[i - 1][j] == MINE) { counter++; } // bottom if (matrix[i + 1] && matrix[i + 1][j] == MINE) { counter++; } // top-right if ( matrix[i - 1] && matrix[i - 1][j + 1] && matrix[i - 1][j + 1] == MINE ) { counter++; } // top-left if ( matrix[i - 1] && matrix[i - 1][j - 1] && matrix[i - 1][j - 1] == MINE ) { counter++; } // bottom-right if ( matrix[i + 1] && matrix[i + 1][j + 1] && matrix[i + 1][j + 1] == MINE ) { counter++; } // bottom-left if ( matrix[i + 1] && matrix[i + 1][j - 1] && matrix[i + 1][j - 1] == MINE ) { counter++; } matrix[i][j] = counter.toString(); } } return matrix; }; console.log( solve09([ ["", "", "", "x", "", "", "", "x", "", ""], ["", "", "x", "", "", "x", "", "", "", "x"], ["", "x", "", "", "", "x", "x", "x", "x", ""], ["", "", "", "x", "", "x", "", "x", "", ""], ["", "", "", "", "", "x", "x", "x", "", "x"], ["", "x", "", "", "x", "x", "x", "", "", ""], ]) );
JavaScript
UTF-8
701
3.3125
3
[]
no_license
function createBoxes(num) { let card = document.querySelector('#root'); let acc = ''; for(let i = 0; i < num; i++){ acc += '<div></div>'; } card.innerHTML += acc; console.log(card.children); let height = 30; let width = 30; for(let el of card.children) { let r = Math.floor(Math.random() * (256)); let g = Math.floor(Math.random() * (256)); let b = Math.floor(Math.random() * (256)); let c='#' + r.toString(16) + g.toString(16) + b.toString(16); el.style.backgroundColor = c; el.style.display = 'block'; el.style.height = `${height}px`; el.style.width = `${width}px`; height += 10; width += 10; } console.log(card); } createBoxes(7);
Java
UTF-8
1,923
3.40625
3
[]
no_license
package Modelos; import java.util.ArrayList; import java.util.List; /* Clase Padre de personas ya que las personas pueden ser veterinarios o duenios de mascotas */ public class PersonaImpl{ //Constructor protected Integer cedula; protected String nombre; protected String ap1; protected String ap2; protected String direccion; protected String telefono; public PersonaImpl(Integer cedula, String nombre, String ap1, String ap2, String direccion, String telefono) { this.cedula = cedula; this.nombre = nombre; this.ap1 = ap1; this.ap2 = ap2; this.direccion = direccion; this.telefono = telefono; } // Sets y gets public Integer getCedula() { return cedula; } public void setCedula(Integer cedula) { this.cedula = cedula; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getAp1() { return ap1; } public void setAp1(String ap1) { this.ap1 = ap1; } public String getAp2() { return ap2; } public void setAp2(String ap2) { this.ap2 = ap2; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public List<String> getInformacionPersonal(){ List<String> informacion = new ArrayList<>(); informacion.add("Nombre: "+nombre+" "+ap1+" "+ap2+"\n"); informacion.add("Cedula: "+cedula+"\n"); informacion.add("Direccion: "+direccion+"\n"); informacion.add("Telefono: "+telefono+"\n"); return informacion; } }