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
Markdown
UTF-8
902
2.609375
3
[ "MIT" ]
permissive
# AOI Proxy 青いプロキシ A simple proxy for switching between blue and green environments. The proxy is configured with an address to a blue environment and the address of a green environment. The proxy will listen on a specified port and send all requests to the blue environment. Using a web api, you can toggle the environment to green. Then the proxy will start sending all requests to the green environment. ## Roadmap - [x] Add test handler to test the "s-out" environment on a different port - [ ] Do I need to lock the ENVIRONMENT flag with a mutex or something?? - [ ] Find a better way to toggle/check the ENVIRONMENT flag (something like an enum) - [ ] Command Line flags to change the ports - [ ] use Environment variables so its easy to put in Docker - [ ] Improve the admin api - [ ] json-ify the output - [ ] check status api - [ ] specify environment instead of toggle
C
UTF-8
4,219
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "pilotos.h" #include "vuelos.h" #include "controller.h" #include "parser.h" #include "validaciones.h" int Parser_generarListaVuelos(FILE* pFile, LinkedList* listaDeVuelos) { eVuelo* auxVuelo; char titulos[100]; char idVuelo[51]; char idAvion[51]; char idPiloto[51]; char fecha[51]; char destino[51]; char cantPasajeros[51]; char horaDespegue[51]; char horaLlegada[51]; int flag = 0; if(pFile!=NULL) { while(!feof(pFile)) { if(flag == 0) { fscanf(pFile, "%[^\n]\n", titulos); flag = 1; } fscanf(pFile, "%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^,],%[^\n]\n", idVuelo, idAvion, idPiloto, fecha, destino, cantPasajeros, horaDespegue, horaLlegada); auxVuelo = constructorParametrizadoVuelo(idVuelo, idAvion, idPiloto, fecha, destino, cantPasajeros, horaDespegue, horaLlegada); ll_add(listaDeVuelos, auxVuelo); } printf("*Se cargaron los Vuelos desde el archivo .csv\n\n"); fclose(pFile); }else{ printf("*Imposible cargar los Vuelos\n\n"); } return 1; } int Parser_guardarVuelosCortosEnArchivo(FILE* pFile, LinkedList* listaDeVuelos) { LinkedList* listaDeVuelosCortos = ll_filter(listaDeVuelos, Controller_Tellechea_vuelosCortos); eVuelo* auxVuelo; int idVuelo; int idAvion; int idPiloto; char fecha[51]; char destino[51]; int cantPasajeros; int horaDespegue; int horaLlegada; int i; if(listaDeVuelosCortos != NULL) { if(!ll_isEmpty(listaDeVuelosCortos)) { if(pFile!=NULL) { for(i=0; i<ll_len(listaDeVuelosCortos); i++) { if(i == 0) { fprintf(pFile, "idVuelo,idAvion,idPiloto,fecha,destino,cantPasajeros,horaDespegue,horaLlegada\n"); } auxVuelo =(eVuelo*) ll_get(listaDeVuelosCortos, i); if(auxVuelo!=NULL) { vueloGetHoraDespegue(auxVuelo, &horaDespegue); vueloGetHoraLlegada(auxVuelo, &horaLlegada); vueloGetIdVuelo(auxVuelo, &idVuelo); vueloGetIdAvion(auxVuelo, &idAvion); vueloGetIdPiloto(auxVuelo, &idPiloto); vueloGetFecha(auxVuelo, fecha); vueloGetDestino(auxVuelo, destino); vueloGetCantPasajeros(auxVuelo, &cantPasajeros); fprintf(pFile, "%d,%d,%d,%s,%s,%d,%d,%d\n", idVuelo, idAvion, idPiloto, fecha, destino, cantPasajeros, horaDespegue, horaLlegada); } } } printf("*Se guardo la lista correctamente en el archivo VuelosCortos.csv (Modo Texto)\n\n"); }else{ printf("\n*Imposible cargar el archivo"); } fclose(pFile); }else if(ll_isEmpty(listaDeVuelos)){ printf("*No hay Vuelos cargados, ingrese 1 para cargarlos\n\n"); } return 1; } int Parser_generarListaPilotos(FILE* pFile, LinkedList* listaDePilotos) { ePiloto* auxPiloto; char idPiloto[51]; char nombre[51]; if(pFile!=NULL) { while(!feof(pFile)) { fscanf(pFile, "%[^,],%[^\n]\n", idPiloto, nombre); auxPiloto = constructorParametrizadoPiloto(idPiloto, nombre); ll_add(listaDePilotos, auxPiloto); } fclose(pFile); }else{ printf("*Imposible cargar los Pilotos\n\n"); } return 1; }
C
UTF-8
1,648
3.015625
3
[]
no_license
#include <stdint.h> #include <stdio.h> #include <string.h> #include "my_include.h" #if 0 { char ip[16]={0}; // allochiamo un array di 16 char perche' nel caso peggiore 192.156.111.222 char ip_1[4]={0}; // parte piu' significativa del'ip int i=0; while(1) { if((ip[i]=='.')||(i>15)) break; ip_1[i]=ip[i]; i++; } } #endif #if 0 queste sono le maschere per determinare i valori associati ai relativi bit.... attraverso l'utilizzo dell'operatore & and #endif #define MASK_CLASS_A 0x80 // 1000_0000 #define MASK_CLASS_B 0xC0 // 1100_0000 #define MASK_CLASS_C 0xE0 // 1110_0000 #define MASK_CLASS_D_E 0xF0 // 1111_0000 #define CLASS_A 0x01 #define CLASS_B 0x02 #define CLASS_C 0x03 #define CLASS_D 0x04 #define CLASS_E 0x05 uint8_t get_ip_class(uint8_t ip_class) { uint8_t retv=0; ip_class=get_ip_class("192.168.3.1"); // in ip_class c'e' un numero ad 8 bit if(ip_class&MASK_CLASS_A==0x00) { retv=CLASS_A; } if(ip_class&MASK_CLASS_B==0x80) { retv=CLASS_B; } if(ip_class&MASK_CLASS_C==0xC0) { retv=CLASS_C; } if(ip_class&MASK_CLASS_D_E==0xE0) { retv=CLASS_D; } if(ip_class&MASK_CLASS_D_E==0xF0) { retv=CLASS_E; } return retv; }//uint8_t get_ip_class(uint8_t ip_class) #define _DEBUG_ 1 #define TRACE (_DEBUG_ == 0) ? (void) 0 : printf #define EOL "\r\n" #ifdef _MAIN_ int main (int argc ,char *argv[]) { int retv=0; TRACE("run %s"EOL,argv[0]); switch(argc) { case 1: //exit(0); break; case 2: break; default: break; }//switch(argc) return retv; } #endif
Python
UTF-8
2,154
3.046875
3
[]
no_license
import os import unittest from Hyde import Hyde from TestUtility import TestUtility class JekyllPageTest(unittest.TestCase): def test_handle_add_new_page(self): """ Tests adding a page and ensures the file is created. Then cleans up the file and the directory. """ page_name = 'TestPage' actual_file_name = 'index.md' Hyde._handle_add_page(page_name) actual_file = page_name + '/' + actual_file_name self.assertTrue(os.path.exists(page_name)) self.assertTrue(os.path.isfile(actual_file)) expected_page_contents = JekyllPageTest.get_expected_page_contents(page_name) actual_page_contents = JekyllPageTest.get_actual_page_contents(actual_file) self.assertEqual(expected_page_contents, actual_page_contents) TestUtility.remove_file(actual_file) self.assertFalse(os.path.isfile(actual_file)) TestUtility.remove_directory(page_name) self.assertFalse(os.path.exists(page_name)) def test_handle_add_existing_page(self): """ Tests adding a page that already exists. Ensures a sub-page is created correctly and that the existing page remains unchanged. """ page_name = 'TestPage' actual_file_name = 'index.md' Hyde._handle_add_page(page_name) actual_file = page_name + '/' + actual_file_name self.assertTrue(os.path.exists(page_name)) self.assertTrue(os.path.isfile(actual_file)) Hyde._handle_add_page(page_name) self.assertTrue(os.path.exists(page_name)) self.assertTrue(os.path.isfile(actual_file)) @staticmethod def get_expected_page_contents(page_name): """ Creates a post template list for testing. @param page_name: the name of the page. @return: the expected post template list. """ expected_page = ['---\n', 'layout: page\n', 'title: ' + page_name + '\n', '---\n'] return expected_page @staticmethod def get_actual_page_contents(page_file): """ Reads and returns the contents of a post file. @param page_file: the page file to read. @return: post file contents as a list of lines. """ with open(page_file) as post_file: actual_file = post_file.readlines() return actual_file if __name__ == '__main__':# pragma: no cover unittest.main()
C++
UTF-8
532
3.328125
3
[]
no_license
#include "circle.hpp" #include <cassert> #include <cmath> Circle::Circle(const point_t &center, const double &radius) : center_(center), radius_(radius) { assert(radius_ >= 0); } double Circle::getArea() const { return M_PI * radius_ * radius_; } rectangle_t Circle::getFrameRect() const { return {2 * radius_, 2 * radius_, center_}; } void Circle::move(const point_t &position) { center_ = position; } void Circle::move(const double &move_x, const double &move_y) { center_.x += move_x; center_.y += move_y; }
Python
UTF-8
15,764
3.375
3
[ "MIT", "CC-BY-4.0" ]
permissive
# -*- coding: utf-8 -*- """ Elasticity solutions calculator Juan Vergara Juan Gomez """ # import scipy.special as sci import numpy as np import signals as sig # def myfunction(x,y,p): """ Template for user defined elasticity solution. """ ux=(x**2.+y**2.)**p return ux # def cunia(x,y,phi,l,nu,E,S): """Computes the solution for self-equilibated wedge at a point (x , y) Parameters ---------- nu :float, (-1, 0.5) Poisson coefficient. S :float Applied shear traction over the faces of the wedge. E :float, >0 Young modulus. l :float, >0 Length of the inclined face of the wedge. phi :float, >0 Half-angle of the wedge. Returns ------- ux : float Horizontal displacement at (x , y). uy : float Vertical displacement at (x , y). References ---------- .. [1] Timoshenko, S. & Goodier, J., 1970. Theory of Elasticity, McGraw-Hill, 3rd Ed. """ # K1=(np.cos(phi)/np.sin(phi))+nu*(np.sin(phi)/np.cos(phi)) K2=(np.sin(phi)/np.cos(phi))+nu*(np.cos(phi)/np.sin(phi)) ux=(S/E)*K1*(x-l*np.cos(phi)) uy=-(S/E)*K2*y sigx = S*(np.cos(phi)/np.sin(phi)) sigy =-S*(np.sin(phi)/np.cos(phi)) return ux , uy , sigx , sigy # def beam(x, y, nu, P, E, I, L, h): """Compute the solution for a cantilever beam Parameters ---------- x : ndarray (float) Array with x coordinates. y : ndarray (float) Array with y coordinates. nu : float, (-1, 0.5) Poisson coefficient. P : float Applied force at the end of the beam. E : float, >0 Young modulus. I : float, >0 Moment of inertia. L : float, >0 Length of the beam. h : float, >0 Height of the beam. Returns ------- u : ndarray (float) Horizontal displacement at the nodes. v : ndarray (float) Vertical displacement at the nodes. exx : ndarray (float) xx component of the strain tensor. eyy : ndarray (float) yy component of the strain tensor. gammaxy : ndarray (float) xy component of the strain tensor. References ---------- .. [1] Timoshenko, S. & Goodier, J., 1970. Theory of Elasticity, McGraw-Hill, 3rd Ed. """ G = E/(2*(1 + nu)) c = h/2 C1 = -P/(2*E*I) C2 = -(nu*P)/(6*E*I) C3 = P/(2*I*G) C4 = (P*L**2)/(2*E*I) C5 = -(P*c**2)/(2*I*G) C6 = C4 + C5 C7 = (nu*P)/(2*E*I) C8 = P/(6*E*I) C9 = -(P*L**2)/(2*E*I) C10 = (P*L**3)/(3*E*I) B1 = -P/(E*I) B2 = (nu*P)/(E*I) B3 = P/(2*I*G) u = C1*y*x**2 + C2*y**3 + C3*y**3 + (C5 + C6)*y v = C7*x*y**2 + C8*x**3 + C9*x + C10 exx = B1*x*y eyy = B2*x*y gammaxy = B3*(y**2 - c**2) return u, v, exx, eyy, gammaxy # def boussipol(x,y,p): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) Pi = np.pi if (r < 0.00001): srp = 0.0 else: srp = (-2*p/Pi)*(np.cos(teta)/r) sigma = srp return sigma # def boussicar(x,y,p): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) Pi = np.pi if (r < 0.00001): Sxx = 0.0 Syy = 0.0 Txy = 0.0 else: Sxx = (-2*p/Pi/r)*(np.cos(teta))**3 Syy = (-2*p/Pi/r)*(np.cos(teta)*(np.sin(teta)**2)) Txy = (-2*p/Pi/r)*(np.sin(teta)*(np.cos(teta)**2)) return Sxx , Syy , Txy # def boussidis(x , y , p , E , enu , d): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) Pi = np.pi omnu = 1.0 - enu if (r < 0.00001): ur = 0.0 ut = 0.0 else: ur = (-2*p/Pi/E)*(np.cos(teta)*np.log(r))-(omnu*p/Pi/E)*(teta*np.sin(teta))+(2*p/Pi/E)*(np.cos(teta)*np.log(d)) ut = ( 2*enu*p/Pi/E)*(np.sin(teta)) + (2*p/Pi/E)*(np.sin(teta)*np.log(r))-(omnu*p/Pi/E)*(teta*np.cos(teta))+(omnu*p/Pi/E)*(np.sin(teta))-(2*p/Pi/E)*(np.sin(teta)*np.log(d)) return ur , ut # def flamantP(x , y , p , phi): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) phir = radianes(phi) f1 = 2*phir f2 = np.sin(phir) f3 = f1+f2 if (r < 0.001): srp = 0.0 else: srp = (-2*p/f3)*(np.cos(teta)/r) sigma = srp return sigma # def flamantQ(x , y , q , phi): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) phir = radianes(phi) f1 = 2*phir f2 = np.sin(phir) f3 = f1-f2 if (r < 0.001): srp = 0.0 else: srp = (-2*q/f3)*(np.sin(teta)/r) sigma = srp return sigma # def flamantM(x , y , m , phi): r=(x**2.+y**2.)**0.5 teta = np.arcsin(y/r) phir = radianes(phi) f1 = np.sin(2*phir) f2 = (2.0*phir)*np.cos(2.0*phir) f3 = (f1-f2)*r*r f4 = (np.cos(2.0*phir)-np.cos(2.0*teta)) if (r > 0.1): srp = (2*m/f3)*(np.sin(2.0*teta)) trp = (m/f3)*f4 else: srp = 0.0 trp = 0.0 sigmar = srp taor = trp return sigmar , taor # def prering(x , y , a , b , pa , pb ): r=(x**2.+y**2.)**0.5 k1 = ((a**2)*(b**2)/(b**2-a**2))*(pb-pa) k2 = (pa*a*a-pb*b*b)/(b**2-a**2) srr = k1/(r**2)+k2 stt = -k1/(r**2)+k2 sigmar = srr sigmat = stt return sigmar , sigmat # def radianes(ang_grad): ang_rad=ang_grad*np.pi/180 return ang_rad def grados(ang_rad): ang_grad=ang_rad*180/np.pi return ang_grad # def tensor_polar(r,teta,f,beta,alfa): alfa=radianes(alfa) # para semi-espacio teta=radianes(teta) # paso teta a radianes beta=radianes(beta) # paso beta a radianes p=f*np.sin(beta) q=f*np.cos(beta) srp=-2.*p*np.cos(teta)/((2.*alfa+np.sin(2.*alfa))*r) srq=-2.*q*np.sin(teta)/((2.*alfa-np.sin(2.*alfa))*r) sigma=np.zeros((2,2)) sigma[0,0]=srp+srq return sigma def tensor_cart(r,teta,f,beta): #################################### variables de entrada #################### # r=...........................radio (coordenada polar) # teta=........................Angulo en grados (coordenada polar) # f=...........................Fuerza () # beta=....................... Angulo de la Fuerza en grados ############################################################################## teta=radianes(teta) # paso teta a radianes beta=radianes(beta) # paso beta a radianes # p=f*np.sin(beta) q=-f*np.cos(beta) sxp=-2.*p*np.cos(teta)**3./(np.pi*r) syp=-2.*p*np.cos(teta)*np.sin(teta)**2./(np.pi*r) txyp=-2.*p*np.cos(teta)**2.*np.sin(teta)/(np.pi*r) sxq=2.*q*np.cos(teta)**2.*np.sin(teta)/(np.pi*r) syq=2.*q*np.sin(teta)**3./(np.pi*r) txyq=2.*q*np.sin(teta)**2.*np.cos(teta)/(np.pi*r) # sigmaf=np.zeros((2,2)) sigmaf[0,0]=sxp+sxq sigmaf[1,1]=syp+syq sigmaf[0,1]=txyp+txyq sigmaf[1,0]=txyp+txyq return sigmaf def tensor_cart_m(r,teta,f,m,beta): teta=radianes(teta) # paso teta a radianes beta=radianes(beta) # paso beta a radianes # p=f*np.sin(beta) q=-f*np.cos(beta) # Carga Vertical sxp=-2.*p*np.cos(teta)**3./(np.pi*r) syp=-2.*p*np.cos(teta)*np.sin(teta)**2./(np.pi*r) txyp=-2.*p*np.cos(teta)**2.*np.sin(teta)/(np.pi*r) # CArga Horizontal sxq=2.*q*np.cos(teta)**2.*np.sin(teta)/(np.pi*r) syq=2.*q*np.sin(teta)**3./(np.pi*r) txyq=2.*q*np.sin(teta)**2.*np.cos(teta)/(np.pi*r) # Momento sxm=np.cos(teta)**3.*np.sin(teta)*(8.*m/(np.pi*r**2.)) sym=np.cos(2.*teta)*np.sin(2.*teta)*(-2.*m/(np.pi*r**2.)) txym=(3.*np.sin(teta)**2.*np.cos(teta)**2.-np.cos(teta)**4.)*(2.*m/(np.pi*r**2.)) # Tensor solución sigmaf=np.zeros((2,2)) sigmaf[0,0]=sxp+sxq+sxm sigmaf[1,1]=syp+syq+sym sigmaf[0,1]=txyp+txyq+txym sigmaf[1,0]=txyp+txyq+txym return sigmaf # def trifunac(x, y , Gamma , a): """ Author: Juan Fernando Zapata Writes VTK files for visualization with paraview """ ##################### DEFINICIÓN DE LOS VECTORES CON LOS TÉRMINOS DE HANKEL Y BESSEL ###################### def Especiales(Delta, f): # El parámetro f define cuál de los 4 vectores voy a retornar sumatoria = 130 #Número de veces que se van a evaluar las sumatorias de Hankekl H = np.zeros((sumatoria), dtype = complex) # Vector Hankel B = np.zeros((sumatoria)) # Vector Bessel if f == 0: for i in range (0, sumatoria): H[i] = sci.hankel2(i, Delta) return(H) else: for i in range (0, sumatoria): B[i] = sci.jv(i, Delta) return(B) ############################################################################################################# Beta = 1.0 # Velocidad de la onda incidente en el medio # Gamma = 0.523 # Ángulo de incidencia de la onda # a = 1.0 # Radio del cañón Tt = 16.0 #Tiempo total que tendrá el pulso Tc = 4.0 # Tiempo en el que estará centrado el pulso fc = 1.0 # Frecuencia del pulso Nf= 2048 Nt= 2*Nf+1 dt = Tt/(Nt-1) deta = 2.0*a/Beta/Tt # Delta de frecuencias neta = int(4*fc*2/deta) # Número de frecuencias que se evaluaran lieta = deta # #Límite inferior para eta lfeta = deta*neta # Límite superior para x Eta = np.linspace(lieta, lfeta, neta, dtype=float) desplaz = np.zeros(len(Eta), dtype=complex) suma = 64 if (y == 0): r = abs(x) if (x < 0): tetha = - np.pi/2.0 else: tetha = np.pi/2.0 elif (x == 0): r = y tetha = 0.0 else: r = np.sqrt((x)**2 + (y)**2) tetha = np.arctan(x / y) for j in range (0, len(Eta)): # Variación de frecuencias para cada X kappa = (np.pi / a) * Eta[j] ka = kappa * a kr = kappa * r Hankel = Especiales(kr, 0) #Vector de Hankel con argumento kr Bessel = Especiales(kr, 1) # Vector de Bessel con argumento kr ######################################### CÁLCULO DEL INCOMING ########################################### S1 = 0 # Acumulador de la primera sumatoria del incoming S2 = 0 #Acumulador de la segunda sumatoria del incoming for i in range (0,suma): #Términos de la sumatoria n1 = i+1 S1 = S1 + ((-1)**n1 * Bessel[2*n1] * np.cos(2*n1*Gamma) * np.cos(2*n1*tetha)) S2 = S2 + ((-1)**i * Bessel[2*i+1] * np.sin((2*i+1)*Gamma) * np.sin((2*i+1)*tetha)) incoming = (2.0 * Bessel[0]) + (4.0 * S1) - (4j * S2) ############################################## CÁLCULO DEL SCATTER ############################################# Hanka = Especiales(ka, 0) # Vector de hankel con argumento ka Beka = Especiales(ka, 1) # Vector de Bessel con argumento ka A0 = -2.0 * (Beka[1] / Hanka[1]) B0 = 4j * np.sin(Gamma) * ((ka*Beka[0] - Beka[1]) / (ka*Hanka[0] - Hanka[1])) scatter = 0 for i in range(0, suma): if i == 0: scatter = scatter + ( A0*Hankel[2*i]*np.cos(2*i*tetha) + B0*Hankel[2*i+1]*np.sin((2*i+1)*tetha) ) else: An = -4 * (-1)**i * np.cos(2*i*Gamma) * ((ka*Beka[2*i-1] - 2*i*Beka[2*i]) / (ka*Hanka[2*i-1] - (2*i)*Hanka[2*i])) Bn = 4j * ((-1)**i) * np.sin((2*i+1)*Gamma) * ((ka*Beka[2*i] - (2*i+1)*Beka[2*i+1]) / (ka*Hanka[2*i] - (2*i+1)*Hanka[2*i+1])) scatter = scatter + ( An*Hankel[2*i]*np.cos(2*i*tetha) + Bn*Hankel[2*i+1]*np.sin((2*i+1)*tetha) ) desplaz[j] = incoming + scatter #return(desplaz) #Tener en cuenta el lugar del return Rick, T= sig.ricker(Nt, Tt, Tc, fc) x , Sas , Saf , nfs = sig.Ftrans(Rick , Nt , dt , 10.0) TF = np.zeros(Nt, dtype=complex) for i in range(neta): TF[i+1] = desplaz[i] TF[-1-i] = np.conj(desplaz[i]) for i in range(Nt): TF[i] = Saf[i] * TF[i] signal = sig.IFtrans(TF , Nt , dt) return(signal) def dam(x,y,gamma): """Computes the solution for self-equilibated wedge at a point (x , y) Parameters ---------- nu :float, (-1, 0.5) Poisson coefficient. S :float Applied shear traction over the faces of the wedge. E :float, >0 Young modulus. l :float, >0 Length of the inclined face of the wedge. phi :float, >0 Half-angle of the wedge. Returns ------- ux : float Horizontal displacement at (x , y). uy : float Vertical displacement at (x , y). References ---------- .. [1] Timoshenko, S. & Goodier, J., 1970. Theory of Elasticity, McGraw-Hill, 3rd Ed. """ # sigx = gamma*x-2.0*gamma*y sigy = -gamma*x tao = -gamma*y return sigx , sigy , tao def DifractionSesma(x,y): Ui = 1j v = 3/2 r0 = 10 phi0 = 20*np.pi/180 r = np.sqrt((x)**2 + (y)**2) phi = np.arctan(x / y) R=[r,r0] Beta = 1.0 # Velocidad de la onda incidente en el medio Tt = 16.0 #Tiempo total que tendrá el pulso Tc = 4.0 # Tiempo en el que estará centrado el pulso fc = 1.0 # Frecuencia del pulso Nf= 2048 Nt= 2*Nf+1 dt = Tt/(Nt-1) deta = 2.0/Beta/Tt # Delta de frecuencias neta = int(4*fc*2/deta) # Número de frecuencias que se evaluaran lieta = deta # #Límite inferior para eta lfeta = deta*neta # Límite superior para x Eta = np.linspace(lieta, lfeta, neta, dtype=float) W = np.zeros(len(Eta), dtype=complex) Vdt =np.zeros(Nt) for i in range(Nt): Vdt[i] = i*dt def Especiales(Delta, f): # El parámetro f define cuál de los vectores voy a retornar sumatoria = 100 #Número de veces que se van a evaluar las sumatorias de Hankel H = np.zeros((sumatoria), dtype = complex) # Vector Hankel B = np.zeros((sumatoria)) # Vector Bessel if f == 0: for i in range (0, sumatoria): H[i] = sci.hankel1(i, Delta) return(H) else: for i in range (0, sumatoria): B[i] = sci.jv(i, Delta) return(B) for j in range (0, len(Eta)): k = Eta[j]/Beta r = min(R) bessel = Especiales(k*r,1) r = max(R) hankel = Especiales(k*r,0) S = hankel*bessel wii = 0 n = 100 for i in range (n): En = 0 if i==0: En = 1 else: En = 2 wi = (Ui/(2*v))*En*np.cos((i/v)*(phi + v*np.pi*0.5))*np.cos((i/v)*(phi0 + v*np.pi*0.5))*S[i/v] wii = wii + wi W[j] = wii Rick, T= sig.ricker(Nt, Tt, Tc, fc) x , Sas , Saf , nfs = sig.Ftrans(Rick , Nt , dt , 10.0) TF = np.zeros(Nt, dtype=complex) for i in range(neta): TF[i+1] = W[i] TF[-1-i] = np.conj(W[i]) for i in range(Nt): TF[i] = Saf[i] * TF[i] signal = sig.IFtrans(TF , Nt , dt) return(signal)
JavaScript
UTF-8
3,769
2.578125
3
[]
no_license
const should = require("should"); const mocha = require("mocha"); const supertest = require("supertest"); var fs = require("fs"); var configDir = "/Users/macbookpro/JavaScriptMocha/AirwallexTest/Test/test.config"; var urlInfo = fs.readFileSync(configDir).toString(); var url = urlInfo.substring(4); var server = supertest.agent(url); function setBankInfo(payMethod, countryCode, accountName, accountNum, swiftCode, aba, bsb ) { return { payment_method: payMethod, bank_country_code: countryCode, account_name: accountName, account_number: accountNum, swift_code: swiftCode, aba: aba, bsb:bsb }; } describe("Executing scenarios for parameter 'payment_method", function(){ it("value of 'SWIFT' is passed, verify success response is returned", function(done){ var cardWithValidInfo = setBankInfo("SWIFT", "US", "Matt Smith", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(200); console.log(res.body); done(); }); }); it("value of 'LOCAL' is passed, verify success response is returned", function(done){ var cardWithValidInfo = setBankInfo("LOCAL", "US", "John Smith", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(200); console.log(res.body); done(); }); }); it("parameter name payment_method is missing, verify 400 is returned", function(done){ server.post('/bank') .send({ bank_country_code: "US", account_name: "John Smith", account_number: "124", swift_code: "ICBCUSBJ", aba: "11122233A" }) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should. done(); }); }); it("parameter name payment_method is passed incorrectly, verifying status 400 is returned", function(done){ server.post('/bank') .send({ payt_method: "LOCAL", bank_country_code: "US", account_name: "John Smith", account_number: "124", swift_code: "ICBCUSBJ", aba: "11122233A" }) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should.exist('field required'); done(); }); }); it("invalid value passed, verify 400 is returned", function(done){ var cardWithValidInfo = setBankInfo("LLOCAL", "US", "SAM JOSE", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should. done(); }); }); it("null value passed, verify 400 is returned", function(done){ var cardWithValidInfo = setBankInfo("", "US", "SAM JOSE", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should. done(); }); }); it("value SWIFT is passed with a space at the end, verify 400 is returned", function(done){ var cardWithValidInfo = setBankInfo("SWIFT ", "US", "SAM JOSE", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should. done(); }); }); it("case sensitive value is passed, verify 400 is returned", function(done){ var cardWithValidInfo = setBankInfo("swift", "US", "SAM JOSE", "124","ICBCUSBJ","11122233A",""); server.post('/bank') .send(cardWithValidInfo) .end(function(err,res){ res.status.should.equal(400); console.log(res.body); // res.body.should. done(); }); }); });
Python
UTF-8
7,648
2.59375
3
[]
no_license
#!/usr/bin/env python # pagechange.py - quick script to check if page has changed # (eg - for price checking) # .product-prices .oldPrice # http://www.massimodutti.com/gb/two-tone-bluchers-with-laces-c1313028p6954836.html # //*[@id="product-info"]/div/div[2]/div[1]/div/div/p[2] import os import os.path import re import cPickle as pickle import tempfile import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import \ NoSuchElementException, StaleElementReferenceException from optparse import OptionParser from pyvirtualdisplay import Display # default SAVEDIR = os.path.join(os.path.expanduser('~'), '.pagechange') class EmptyMatchException(Exception): pass class Page(object): def __init__(self, savedir, url=None, xpath=None, filename=None): self.savedir = savedir self.url = url self.xpath = xpath self.oldmatch = '' self.datetime = '' self.match = '' self.filename = filename self.title = '' def save(self): '''Pickle Page object (self) and save to disk''' if self.filename is None: # create alphanumeric filename from URL self.filename = re.sub('(^https?://|[\W_]+)', '', self.url) + '.pk' fullfilename = os.path.join(self.savedir, self.filename) # print fullfilename with open(fullfilename, 'wb') as picklefile: pickle.dump(self, picklefile) def __str__(self): '''printable representation of self''' # handle missing datetime try: getattr(self, 'datetime') except AttributeError: self.datetime = '' return "Title: %s\nOld: (%s) New: (%s)\nChanged: %s\nURL: %s" \ % (self.title.encode('utf-8'), self.oldmatch.encode('utf-8'), self.match.encode('utf-8'), self.datetime, self.url) def load(self): '''load pickled page object from disk''' with open(os.path.join(self.savedir, self.filename), 'rb') as pfile: savedir = self.savedir a = pickle.load(pfile) # copy pickle object into self self.__dict__ = a.__dict__.copy() # restore savedir self.savedir = savedir class PageChange(object): def __init__(self, browser): '''instantiate webdriver''' if browser == 'firefox': self.driver = webdriver.Firefox() elif browser == 'chrome': self.driver = webdriver.Chrome() else: raise ValueError('No valid webdriver found') self.waittime = 5 self.xpmatch = None @staticmethod def dump_source(source): '''write source to tempfile & return filename''' fh, fname = tempfile.mkstemp(suffix='pchange', text=True) os.write(fh, source) os.close(fh) return fname def check(self, page): '''return content in page matching xpath''' # insert dummy about to wipe referer self.driver.get('about:blank') self.driver.get(page.url) self.driver.implicitly_wait(self.waittime) if os.getenv('DEBUG'): fname = self.dump_source(encode(self.driver.page_source)) print 'source html in %s' % fname # assert "Python" in driver.title self.xpmatch = self.driver.find_element(By.XPATH, page.xpath) # cookie cleanup - make optional? self.driver.delete_all_cookies() return self.xpmatch.text def update_page(self, page, forcesave=False): '''updates page object - saves if changed or if forcesave = True''' #if page.match == '': # raise EmptyMatchException('blank match in %s' % self.driver.title) changed = (self.xpmatch.text != page.match) if changed or forcesave: page.oldmatch = page.match page.match = self.xpmatch.text page.title = self.driver.title page.datetime = time.strftime('%d-%m-%Y %X %Z') page.save() return changed or forcesave def get_options(): '''parse CLI options''' parser = OptionParser() parser.add_option("-u", help="url", dest="url") parser.add_option("-x", help="xpath", dest="xpath") parser.add_option("-m", help="mode (add|check|list)", dest="mode", default="add") parser.add_option("-b", help="browser", dest="browser", default="firefox") parser.add_option("-d", help="savedir", dest="savedir", default=SAVEDIR) parser.add_option("-f", help="force save", dest="forcesave", action="store_true", default=False) parser.add_option("-n", help="no headless", dest="noheadless", action="store_true", default=False) (options, args) = parser.parse_args() return (options, args) def get_all_checks(savedir): '''loads all checks in savedir and returns list''' checkfiles = [cf for cf in os.listdir(savedir) if cf[-3:] == '.pk'] checks = [] for cf in checkfiles: check = Page(savedir=savedir, filename=cf) check.load() checks.append(check) return checks def list_pages(savedir): '''displays all checks in savedir''' for check in get_all_checks(savedir): print check print '' def encode(s, encoding="ascii", errors="ignore"): '''custom decode function to ignore errors''' return s.encode(encoding=encoding, errors=errors) def check_pages(options): '''run all checks & display changed''' pc = PageChange(browser=options.browser) for check in get_all_checks(options.savedir): try: pc.check(check) if pc.update_page(check, options.forcesave): # changed print check elif os.getenv('DEBUG'): print 'No change for %s' % encode(check.title, 'ascii') except (NoSuchElementException, StaleElementReferenceException) as e: # print '%s failed - error: %s' % (check.title, str(e)) print '%s failed - error: %s' % (encode(check.title, 'ascii'), e) except EmptyMatchException: print "Match returned empty string for %s" % encode(check.title, 'ascii') pc.driver.close() def add_page(options): '''add a check''' p = Page(options.savedir, options.url, options.xpath) pc = PageChange(browser=options.browser) try: pc.check(p) pc.update_page(p) print p except NoSuchElementException: print 'Cannot find match in page - not saving' except EmptyMatchException: print 'Match returns empty string - not saving' pc.driver.close() # TODO: convert to decorator def virt_display(function, options): '''launch virtual display (for selenium) and run function''' display = Display(visible=0, size=(800, 600)) display.start() function(options) display.stop() def main(): '''check args and run appropriate function''' (options, args) = get_options() if options.mode == 'add': if None in (options.url, options.xpath): print "No url/xpath provided" else: if options.noheadless: add_page(options) else: virt_display(add_page, options) elif options.mode == 'list': list_pages(savedir=options.savedir) elif options.mode == 'check': if options.noheadless: check_pages(options) else: virt_display(check_pages, options) if __name__ == '__main__': main()
Python
UTF-8
259
3.109375
3
[]
no_license
def to_int(x): return int(x) n = int(input()) l = [] for _ in range(n): g, s = map(to_int, input().split(" ")) l.append("%02d:%02d" % (s, g)) for ans in sorted(l, reverse=True): s, g = map(to_int, ans.split(":")) print("%d %d" % (g, s))
Python
UTF-8
18,996
2.59375
3
[]
no_license
import numpy as np from itertools import product import copy def _concatenate_sorted_list_of_integer_strings(l): l.sort(key=int) string = '' for i in l: string = string + i + "_" return string[:-1] def _diff_list(a, b): b = set(b) return [aa for aa in a if aa not in b] def _mask_node_list(union_factor_list, factor_list): mask = [] for i in union_factor_list: if i in factor_list: mask.append(True) else: mask.append(False) return mask def _masked_tuple(union_factor_index, mask): factor_index = [] for i in range(len(mask)): if mask[i]: factor_index.append(union_factor_index[i]) return tuple(factor_index) class Graph: def __init__(self): self._num_nodes = 0 self._num_edges = 0 self._nodes = {} self._factors = {} self._cliques = [] self._JTree = None class Node: def __init__(self, index, cardinality): self.index = index self.cardinality = cardinality self.neighbours = set() class Factor: def __init__(self, node_list): self._node_seq = node_list self._node_set = set(node_list) self._cardinality_seq = [] self._cardinality_product = 1 self._potentials = None class JunctionTree: def __init__(self): self._Nodes = [] self._nodeList = [] self._factorList = [] self._edgeList = [] self._messageList = [] self._messages ={} class JT_Node: def __init__(self): self._neighbours = [] self._clique = set([]) def _nodeMindegree(self, not_current_nodes): mindegree =float("inf") nodeMindegree = "" for key in self._nodes.keys(): if((key in not_current_nodes) == False): key_degree = 0 for index in self._nodes[key].neighbours: if((index in not_current_nodes) == False): key_degree = key_degree + 1 # print key, key_degree if(key_degree < mindegree): mindegree = key_degree nodeMindegree = key return nodeMindegree def _connectClique(self, clique): added_edges = 0 for i in clique: for j in clique: if((i != j) and (j not in self._nodes[i].neighbours)): print "-- Edge added : ",i,"-",j self._num_edges = self._num_edges + 1 added_edges = added_edges + 1 self._nodes[i].neighbours.add(j) self._nodes[j].neighbours.add(i) return added_edges def _maximalClique(self): new_cliques = [] for i in self._cliques: temp_cliques = copy.deepcopy(self._cliques) temp_cliques.remove(i) flag = True for j in temp_cliques: if (i <= j): flag = False break if (flag): new_cliques.append(i) self._cliques = new_cliques def _maximalEdge(self, crossing_edges): max_edge = (0,(0,0,set([]))) for edge1 in crossing_edges: if(edge1[1][1] > max_edge[1][1]): max_edge = edge1; return max_edge def _multiply_factors_for_clique_node(self, node_list): clique_node_factor = self.Factor([]) pair_node_list = [] node_list.sort(key=int) print "Entering _multiply_factors_for_clique_node...." print node_list for i in range(len(node_list)): for j in range(i + 1, len(node_list)): pair = [node_list[i], node_list[j]] pair_node_list.append(pair) if _concatenate_sorted_list_of_integer_strings(pair) not in self._factors: intermediate_factor = self.Factor(pair) intermediate_factor._potentials = np.ones((self._nodes[pair[0]].cardinality, self._nodes[pair[1]].cardinality)) self._factors[_concatenate_sorted_list_of_integer_strings(pair)] = intermediate_factor for pair in pair_node_list: #clique_node_factor = self.multiply_factor(pair, clique_node_factor._node_seq) clique_node_factor = self.multiply_factor_modified(self._factors[_concatenate_sorted_list_of_integer_strings(pair)], clique_node_factor) for node in node_list: if node in self._factors: print clique_node_factor._node_seq print clique_node_factor._potentials #clique_node_factor = self.multiply_factor([node], clique_node_factor._node_seq) clique_node_factor = self.multiply_factor_modified(self._factors[node], clique_node_factor) print "Multiplied a node potential....." print clique_node_factor._node_seq print self._factors[node]._potentials print clique_node_factor._potentials #self._factors[_concatenate_sorted_list_of_integer_strings(node_list)] = clique_node_factor return clique_node_factor #for pair in pair_node_list: # if _concatenate_sorted_list_of_integer_strings(pair) in self._factors and (pair[0] not in clique_node_factor._node_set or pair[1] not in clique_node_factor._node_set): # clique_node_factor = self.multiply_factor(pair, clique_node_factor._node_seq) def junctionTree(self): # Generate Graph with Maximal Cliques as Nodes and edge weight # between them as number of common Variables between them clique_graph = [] clique_nodes = self._cliques for i in clique_nodes: connection_list =[] for j in clique_nodes: if (i != j): intersect = len(i.intersection(j)) if(intersect > 0): connection_list.append((clique_nodes.index(j),intersect,j)) clique_graph.append(connection_list) # Prim's Algorithm n = len(clique_nodes) V = [0] E = [] print "\nNumber of Clique Nodes : ",n print "Number of Clique Nodes : ",n-1,"\n" self._JTree = self.JunctionTree() for node in clique_nodes: node_list = list(node) self._JTree._factorList.append(self._multiply_factors_for_clique_node(node_list)) for count_node in range(n): E.append([]) for count_node in range(n-1): crossing_edges =[] for node1 in V: for edge1 in clique_graph[node1] : if(edge1[0] not in V): # node2 = node1 crossing_edges.append((node1,edge1)) (node2,max_edge) = self._maximalEdge(crossing_edges) print "max :" ,max_edge V.append(max_edge[0]) E[node2].append((max_edge[0], max_edge[1], self.marginalize_factor(self._JTree._factorList[node2], list(clique_nodes[node2] - (clique_nodes[node2].intersection(clique_nodes[max_edge[0]]))), flag='msg'))) E[max_edge[0]].append((node2, max_edge[1], self.marginalize_factor(self._JTree._factorList[max_edge[0]], list(clique_nodes[max_edge[0]] - (clique_nodes[max_edge[0]].intersection(clique_nodes[node2]))), flag='msg'))) # Store JuntionTree in self._JTree for node1 in clique_nodes: jt_node = self.JT_Node() jt_node._clique = node1 self._JTree._Nodes.append(jt_node) for jt_node in self._JTree._Nodes: jt_node._neighbours = [] for e in E[clique_nodes.index(jt_node._clique)]: jt_node._neighbours.append((self._JTree._Nodes[e[0]],e[1])) self._JTree._edgeList = E self._JTree._nodeList = clique_nodes # Calculate & Print Largest Clique largest_clique = set([]) for i in self._JTree._nodeList: if (len(i) > len(largest_clique)): largest_clique = i print "Largest Clique : ",largest_clique, "\n" # Calculate Separatir Nodes for e in self._JTree._edgeList: for i in e: print "Cliques : ", self._JTree._nodeList[self._JTree._edgeList.index(e)]," & ", self._JTree._nodeList[i[0]], " | Separation Variables : ", self._JTree._nodeList[self._JTree._edgeList.index(e)].intersection(self._JTree._nodeList[i[0]]) def sum_query(self, node_list): node_list = set(node_list) for i in range(len(self._JTree._nodeList)): if node_list <= self._JTree._nodeList[i]: clique_index = i break print " Clique index : " + str(clique_index) MPA_tree = copy.deepcopy(self) for k in range(len(MPA_tree._JTree._edgeList) - 1): for i in range(len(MPA_tree._JTree._edgeList)): if len(MPA_tree._JTree._edgeList[i]) == 1 and clique_index != i: dest_clique_index = MPA_tree._JTree._edgeList[i][0][0] print "To be eliminated : " print MPA_tree._JTree._nodeList[i] message_factor = MPA_tree._JTree._edgeList[i][0][2] print "message_factor._node_seq" print message_factor._node_seq print "MPA_tree._JTree._factorList[dest_clique_index]._node_seq" print MPA_tree._JTree._factorList[dest_clique_index]._node_seq print self._factors.keys() #MPA_tree._JTree._factorList[dest_clique_index] = self.multiply_factor(message_factor._node_seq, MPA_tree._JTree._factorList[dest_clique_index]._node_seq, flag='m') MPA_tree._JTree._factorList[dest_clique_index] = self.multiply_factor_modified(message_factor, MPA_tree._JTree._factorList[dest_clique_index]) # removing nodes and edges. MPA_tree._JTree._nodeList[i] = None MPA_tree._JTree._factorList[i] = None MPA_tree._JTree._edgeList[i] = [] for j in range(len(MPA_tree._JTree._edgeList[dest_clique_index])): if MPA_tree._JTree._edgeList[dest_clique_index][j][0] == i: MPA_tree._JTree._edgeList[dest_clique_index].remove(MPA_tree._JTree._edgeList[dest_clique_index][j]) break break for m in MPA_tree._JTree._factorList: if m is not None: out_factor = m if len(out_factor._node_seq) > len(node_list): result_factor = self.marginalize_factor(out_factor, list(set(out_factor._node_seq) - set(node_list)), flag='notmsg') else: result_factor = out_factor probability = result_factor._potentials / np.sum(result_factor._potentials) return probability def parseGraph(self, fileName): line_no = 1 with open(fileName) as f: for line in f: line = line[:-1] if line_no == 1: self._num_nodes = int(line) elif line_no == 2: self._num_edges = int(line) # cardinality elif line_no > 2 and line_no <= 2 + self._num_nodes: line = line.split() self._nodes[line[0]] = self.Node(line[0], int(line[1])) elif line_no > 2 + self._num_nodes and line_no <= 2 + self._num_nodes + self._num_edges: node1, node2 = line.split() self._nodes[node1].neighbours.add(node2) self._nodes[node2].neighbours.add(node1) line_no = line_no + 1 def parseFactor(self, fileName): with open(fileName) as f: for line in f: line = line[:-1] line = line.split() if line[0] == '#': key = _concatenate_sorted_list_of_integer_strings(line[1:]) self._factors[key] = self.Factor(line[1:]) for i in self._factors[key]._node_seq: card = self._nodes[i].cardinality self._factors[key]._cardinality_seq.append(card) self._factors[key]._cardinality_product *= card self._factors[key]._potentials = np.zeros(tuple(self._factors[key]._cardinality_seq)) else: index = tuple(np.asarray(line[:-1]).astype(int)) self._factors[key]._potentials[index] = float(line[-1]) def multiply_factor_modified(self, factor1, factor2): if factor1._node_seq == []: union_factor = self._factors[_concatenate_sorted_list_of_integer_strings(factor2._node_seq)] return union_factor if factor2._node_seq == []: union_factor = self._factors[_concatenate_sorted_list_of_integer_strings(factor1._node_seq)] return union_factor union = list(factor1._node_set.union(factor2._node_set)) union.sort(key=int) union_factor_key = _concatenate_sorted_list_of_integer_strings(union) union_factor_cardinality_seq = [] union_indices = [] for i in union: union_indices.append(range(self._nodes[i].cardinality)) union_factor_cardinality_seq.append(self._nodes[i].cardinality) union_factor_potentials = np.zeros(tuple(union_factor_cardinality_seq)) mask1 = _mask_node_list(union, factor1._node_seq) mask2 = _mask_node_list(union, factor2._node_seq) for index in product(*union_indices): union_factor_potentials[index] = (factor1._potentials[_masked_tuple(index, mask1)] * factor2._potentials[_masked_tuple(index, mask2)]) union_factor = self.Factor(union) union_factor._potentials = union_factor_potentials union_factor._cardinality_seq = union_factor_cardinality_seq #self._factors[union_factor_key] = union_factor return union_factor def multiply_factor(self, factor_node_list1, factor_node_list2, flag='n'): if factor_node_list1 == []: union_factor = self._factors[_concatenate_sorted_list_of_integer_strings(factor_node_list2)] return union_factor if factor_node_list2 == []: union_factor = self._factors[_concatenate_sorted_list_of_integer_strings(factor_node_list1)] return union_factor factor_key1 = _concatenate_sorted_list_of_integer_strings(factor_node_list1) factor_key2 = _concatenate_sorted_list_of_integer_strings(factor_node_list2) if flag == 'm': union = list(self._JTree._messages[factor_key1]._node_set.union(self._factors[factor_key2]._node_set)) else: union = list(self._factors[factor_key1]._node_set.union(self._factors[factor_key2]._node_set)) union.sort(key=int) union_factor_key = _concatenate_sorted_list_of_integer_strings(union) union_factor_cardinality_seq = [] union_indices = [] for i in union: union_indices.append(range(self._nodes[i].cardinality)) union_factor_cardinality_seq.append(self._nodes[i].cardinality) union_factor_potentials = np.zeros(tuple(union_factor_cardinality_seq)) # print "union_factor_potentials.shape..." # print union_factor_potentials.shape mask1 = _mask_node_list(union, self._factors[factor_key1]._node_seq) mask2 = _mask_node_list(union, self._factors[factor_key2]._node_seq) # print "Multiplying factors...." # print union # print mask1 # print mask2 for index in product(*union_indices): if flag=='m': union_factor_potentials[index] = (self._JTree._messages[factor_key1]._potentials[_masked_tuple(index, mask1)] * self._factors[factor_key2]._potentials[_masked_tuple(index, mask2)]) else: union_factor_potentials[index] = (self._factors[factor_key1]._potentials[_masked_tuple(index, mask1)] * self._factors[factor_key2]._potentials[_masked_tuple(index, mask2)]) union_factor = self.Factor(union) union_factor._potentials = union_factor_potentials union_factor._cardinality_seq = union_factor_cardinality_seq #self._factors[union_factor_key] = union_factor return union_factor def marginalize_factor(self, original_factor, elimination_variables, flag='msg'): factor_node_list = original_factor._node_seq factor_key = _concatenate_sorted_list_of_integer_strings(factor_node_list) factor_node_list.sort(key=int) elimination_variables.sort(key=int) remaining_variables = list(set(factor_node_list) - set(elimination_variables)) output_factor = self.Factor(remaining_variables) sum_axes = [] for i in elimination_variables: sum_axes.append(factor_node_list.index(i)) output_factor._potentials = np.sum(original_factor._potentials, tuple(sum_axes)) #self._factors[_concatenate_sorted_list_of_integer_strings(remaining_variables)] = output_factor if flag == 'msg': self._JTree._messages[_concatenate_sorted_list_of_integer_strings(remaining_variables)] = output_factor return output_factor def triangulate(self): not_current_nodes = set() total_added_edges = 0 G_tri = copy.deepcopy(self) for count_node in range(G_tri._num_nodes): node1 = G_tri._nodeMindegree(not_current_nodes) current_clique = set([node1]) for neighbour in G_tri._nodes[node1].neighbours: if(neighbour not in not_current_nodes): current_clique.add(neighbour) print "MinDegree Node :", node1 total_added_edges = total_added_edges + G_tri._connectClique(current_clique) not_current_nodes.add(node1) G_tri._cliques.append(current_clique) G_tri._maximalClique() print "\nNumber of Edges Added : " ,total_added_edges return G_tri def printParameters(self): # print self._num_nodes # print self._num_edges # print self._nodes['1'].neighbours pass if __name__ == '__main__': G = Graph() G.parseGraph('TestCases/graph_1') G.parseFactor('TestCases/potentials_1') G.printParameters()
Python
UTF-8
730
3.046875
3
[]
no_license
#!/usr/bin/env python3 # File: anchortag-comments.py from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # ignore them cert errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, 'html.parser') comments = [] total = 0 num = 0 # Retrieve all of the anchor tags tags = soup('span') for tag in tags: # look @ the parts of the tag #print('TAG:', tag) #print('Contents:', tag.contents[0]) commentnum = tag.contents[0] commentnum = int(commentnum) comments.append(commentnum) total += commentnum num += 1 print(num,total) #print(comments)
Java
UTF-8
4,217
3.21875
3
[]
no_license
package _4Sum; import java.util.*; public class Solution { private class Node implements Comparable { protected int sum; protected int a; protected int b; public Node(int sum, int a, int b) { this.a = a; this.b = b; this.sum = sum; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Node node = (Node) o; if (sum != node.sum) return false; if (a != node.a) return false; return b == node.b; } @Override public int hashCode() { int result = sum; result = 31 * result + a; result = 31 * result + b; return result; } @Override public int compareTo(Object o) { if (!(o instanceof Node)) { return 0; } else { Node n = (Node)o; if (this.sum == n.sum) { if (this.a == n.a) { return this.b - n.b; } else { return this.a - n.a; } } else { return this.sum - n.sum; } } } } private class ResultNode { int a, b, c, d; public ResultNode(int a, int b, int c, int d) { int[] arr = new int[4]; arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; Arrays.sort(arr); this.a = arr[0]; this.b = arr[1]; this.c = arr[2]; this.d = arr[3]; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResultNode that = (ResultNode) o; if (a != that.a) return false; if (b != that.b) return false; if (c != that.c) return false; return d == that.d; } @Override public int hashCode() { int result = a; result = 31 * result + b; result = 31 * result + c; result = 31 * result + d; return result; } } public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> results = new LinkedList<List<Integer>>(); HashSet<ResultNode> resultNodeSet = new HashSet<ResultNode>(); Arrays.sort(nums); ArrayList<Node> nodeNums = new ArrayList<Node>(1 + (nums.length - 2) * (nums.length - 2) / 2); for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { nodeNums.add(new Node(nums[i] + nums[j], i, j)); } } Collections.sort(nodeNums); int i = 0; int j = nodeNums.size() - 1; while (i < j) { if (nodeNums.get(i).sum + nodeNums.get(j).sum == target) { int ia = nodeNums.get(i).a; int ib = nodeNums.get(i).b; int l = j; while (l > i && nodeNums.get(l).sum + nodeNums.get(i).sum == target) { int la = nodeNums.get(l).a; int lb = nodeNums.get(l).b; if (ia != la && ia != lb && la != ib && lb != ib) { resultNodeSet.add(new ResultNode(nums[ia], nums[ib], nums[la], nums[lb])); } l--; } i++; } else if (nodeNums.get(i).sum + nodeNums.get(j).sum < target) { i++; } else if (nodeNums.get(i).sum + nodeNums.get(j).sum > target) { j--; } } for (ResultNode rn : resultNodeSet) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(rn.a); result.add(rn.b); result.add(rn.c); result.add(rn.d); results.add(result); } return results; } }
JavaScript
UTF-8
1,070
2.796875
3
[]
no_license
(function(window){ var arrTests = []; var UnitTest = function(title, testFunction){ if(testFunction) { $('#testresults').append('<div>'+title+':</div>'); this.title = title; this.ul = $('<ul></ul>').appendTo($('#testresults')); this.test = testFunction; arrTests.push(this); } else console.log('Test function undefined for: ' + title); }; UnitTest.prototype.assert = function( test, description ) { var dec = test ? 'pass' : 'fail'; this.ul.append('<li class="'+dec+'">'+dec.toUpperCase()+': '+description+'</li>'); }; UnitTest.run = function() { for(var i = 0; i < arrTests.length; i++){ try { arrTests[i].test(); } catch(e){ var msg = 'Testing encountered error in '+arrTests[i].title+' (i='+i+')'; if(e) msg += ': ' + e.message; console.log(msg); } } } if ( typeof module === "object" && module && typeof module.exports === "object" ) { module.exports = UnitTest; } else { window.UnitTest = UnitTest; } })(window);
Python
UTF-8
701
2.78125
3
[]
no_license
#============================================ # Title: Exercise 9.3 # Author: Professor Krasso # Modified by: James Brown # Date: 6/26/2020 # Description: coding per requirements of exercise 9.3 #=========================================== #import statements from pymongo import MongoClient import pprint import datetime #connection to local db client = MongoClient('localhost', 27017) #specifying the collection db = client.web335 #update the user email address from assignment 9.2 db.users.update_one( {"employee_id": "1234567890"}, { "$set": { "email": "jamesbrown2@my365.bellevue.edu" } } ) #output the change with find_one pprint.pprint(db.users.find_one({"employee_id": "1234567890"}))
PHP
UTF-8
5,582
2.59375
3
[ "MIT", "GPL-1.0-or-later", "GPL-2.0-or-later", "GPL-2.0-only" ]
permissive
<?php /** * Creates common globals for the rest of WordPress * * Sets $pagenow global which is the current page. Checks * for the browser to set which one is currently being used. * * Detects which user environment WordPress is being used on. * Only attempts to check for Apache, Nginx and IIS -- three web * servers with known pretty permalink capability. * * Note: Though Nginx is detected, WordPress does not currently * generate rewrite rules for it. See https://codex.wordpress.org/Nginx * * @package WordPress */ global $pagenow, $is_lynx, $is_gecko, $is_winIE, $is_macIE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone, $is_IE, $is_edge, $is_apache, $is_IIS, $is_iis7, $is_nginx; // On which page are we ? if ( is_admin() ) { // wp-admin pages are checked more carefully if ( is_network_admin() ) preg_match('#/wp-admin/network/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); elseif ( is_user_admin() ) preg_match('#/wp-admin/user/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); else preg_match('#/wp-admin/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); $pagenow = $self_matches[1]; $pagenow = trim($pagenow, '/'); $pagenow = preg_replace('#\?.*?$#', '', $pagenow); if ( '' === $pagenow || 'index' === $pagenow || 'index.php' === $pagenow ) { $pagenow = 'index.php'; } else { preg_match('#(.*?)(/|$)#', $pagenow, $self_matches); $pagenow = strtolower($self_matches[1]); if ( '.php' !== substr($pagenow, -4, 4) ) $pagenow .= '.php'; // for Options +Multiviews: /wp-admin/themes/index.php (themes.php is queried) } } else { if ( preg_match('#([^/]+\.php)([?/].*?)?$#i', $_SERVER['PHP_SELF'], $self_matches) ) $pagenow = strtolower($self_matches[1]); else $pagenow = 'index.php'; } unset($self_matches); // Simple browser detection $is_lynx = $is_gecko = $is_winIE = $is_macIE = $is_opera = $is_NS4 = $is_safari = $is_chrome = $is_iphone = $is_edge = false; if ( isset($_SERVER['HTTP_USER_AGENT']) ) { if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Lynx') !== false ) { $is_lynx = true; } elseif ( strpos( $_SERVER['HTTP_USER_AGENT'], 'Edge' ) !== false ) { $is_edge = true; } elseif ( stripos($_SERVER['HTTP_USER_AGENT'], 'chrome') !== false ) { if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'chromeframe' ) !== false ) { $is_admin = is_admin(); /** * Filters whether Google Chrome Frame should be used, if available. * * @since 3.2.0 * * @param bool $is_admin Whether to use the Google Chrome Frame. Default is the value of is_admin(). */ if ( $is_chrome = apply_filters( 'use_google_chrome_frame', $is_admin ) ) header( 'X-UA-Compatible: chrome=1' ); $is_winIE = ! $is_chrome; } else { $is_chrome = true; } } elseif ( stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false ) { $is_safari = true; } elseif ( ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== false ) && strpos($_SERVER['HTTP_USER_AGENT'], 'Win') !== false ) { $is_winIE = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false ) { $is_macIE = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false ) { $is_gecko = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false ) { $is_opera = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Nav') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla/4.') !== false ) { $is_NS4 = true; } } if ( $is_safari && stripos($_SERVER['HTTP_USER_AGENT'], 'mobile') !== false ) $is_iphone = true; $is_IE = ( $is_macIE || $is_winIE ); // Server detection /** * Whether the server software is Apache or something else * @global bool $is_apache */ $is_apache = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false); /** * Whether the server software is Nginx or something else * @global bool $is_nginx */ $is_nginx = (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false); /** * Whether the server software is IIS or something else * @global bool $is_IIS */ $is_IIS = !$is_apache && (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'ExpressionDevServer') !== false); /** * Whether the server software is IIS 7.X or greater * @global bool $is_iis7 */ $is_iis7 = $is_IIS && intval( substr( $_SERVER['SERVER_SOFTWARE'], strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/' ) + 14 ) ) >= 7; /** * Test if the current browser runs on a mobile device (smart phone, tablet, etc.) * * @since 3.4.0 * * @return bool */ function wp_is_mobile() { if ( empty($_SERVER['HTTP_USER_AGENT']) ) { $is_mobile = false; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.) || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) { $is_mobile = true; } else { $is_mobile = false; } /** * Filters whether the request should be treated as coming from a mobile device or not. * * @since 4.9.0 * * @param bool $is_mobile Whether the request is from a mobile device or not. */ return apply_filters( 'wp_is_mobile', $is_mobile ); }
Java
UTF-8
651
3.21875
3
[]
no_license
package timing; public interface ITimer { /** * Starts a new timer. <br> * If called without a prior <b>stop</b>, it resets the current time loosing * all time information. */ public void start(); /** * Stop and reset current timer. * * @return Elapsed <b>nanoseconds</b> since <b>start</b> was invoked. */ public long stop(); /** * Pauses the running timer. Can be later resumed by calling <b>resume</b>. * @return Elapsed <b>nanoseconds</b> since <b>start</b> was invoked. */ public long pause(); /** * Resumes the paused timer. <br> * If timer is not paused it starts it. */ public void resume(); }
C
UTF-8
405
3.0625
3
[]
no_license
#include <cs50.h> #include <stdio.h> #include <math.h> int main (void){ float dollar; do{ dollar= get_float("enter dollar: "); } while(dollar <= 0); float money=round (dollar*100); int b=money/25; int c= money-(b*25); c=c/10; int d=money-(b*25)-c*10; d=d/5; int e= money-(b*25)-c*10-d*5; printf("%d\n", b+c+d+e); printf("%d\n", b); printf("%d\n", c); printf("%d\n", d); printf("%d\n", e); }
PHP
UTF-8
954
2.703125
3
[]
no_license
<?php namespace Repository\Component\Pagination\Handlers; use Repository\Component\Pagination\PaginationParameter; use Repository\Component\Contracts\Pagination\HandlerInterface; /** * Handle Pagination Logic over Array Collection. * * @package \Repository\Component\Pagination * @author Hariyanto - harrieanto31@yahoo.com * @version 1.0 * @link https://www.bandd.web.id * @copyright Copyright (C) 2019 Hariyanto * @license https://github.com/harrieanto/repository/blob/master/LICENSE.md */ class ArrayCollection implements HandlerInterface { /** * {@inheritdoc} * See \Repository\Component\Contracts\Pagination\HandlerInterface::handle() */ public function handle(PaginationParameter $pagination): void { $limit = $pagination->getLimit(); $offset = $pagination->getTotalRow(); $collection = $pagination->getArrayCollection(); $collection = $collection->slice($offset, $limit); $pagination->setPageItems($collection); } }
Markdown
UTF-8
6,392
3.984375
4
[]
no_license
# Assignment 1: Code Design & Efficiency Analysis ## Code Design ### Organization We separated our helper functions into files, and put them into `src/`. `heap.c` contains min heap functions. `flags.c` contains command line flag parsing functions. `tokens.c` contains functions that tokenize the file into the linked list with frequencies. `huffman.c` contains methods to create a huffman tree. `warning.c` contains helper methdos to print warnings. `free.c` contains helper functions used to free memory. Outside of `src/` we have a file for every subcommand—`compress.c`, `decompress.c`, and `build_codebook.c`. ### Tokenization In the terminal, we are given a 2 flags, the subcommand and the recursive flag, and additionally a path or a file. We tokenize the file in `tokens.c` using whitespace as a delimiter. `tokens.c` has a function called `Token_read_file` that reads files into a linked list. We also wrote a function called `Token_read_file_distinct` that reads files into a linked list and removes duplicates. ### Flags We have a `Flags` struct that stores flags and pathnames. We handled flag warnings in this file. If more than 2 of the accepted flags are inputted, we output a warning that says more than 2 flags can not be inputted. If more than 2 flags are inputted and one of the flags does not exist, we output a warning that you can not have more than 2 flags. When flags are mixed (ex. -Rb instead of -R -b), a warning is given to the user that flags can not be mixed. ## Efficiency Analysis ### Build Codebook Build codebook came in three parts: 1. Counting frequency 2. Creating the Huffman Tree 3. Printing the Huffman Tree ### Counting Freqeuncy We created a function called `Token_read_file_distinct` which read a file into a linked list containing words, delimeters and their respective frequencies. 1. First, it read all of the words and delimeters into a linked list. Each linked list insertion is $O(1)$ and we do $n$ of these. 2. Next, it removed all of the duplicates by inserting every linked list item into a new list only if it was not already containined in the list. Each linked list insertion for a distinct linked list is $O(n)$ and we do $n$ of these. The total run time is: $n$ + $n^2$ = $O(n^2)$ where $n$ is the number of words. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n^2)$ | $O(n)$ | ### Creating The Huffman Tree We created a min-heap to create the Huffamn Tree. The heap was used to build the Huffman codebook. This was done by heapifying the tokens from the linked list, and then removing and merging the two smallest elements of the min-heap and inserting it back in. Ultimately we are left with one elmenet, a tree, which is used to build the codebook. Since each node is visited once, the total run time is: $O(n)$ where $n$ is the number of words. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n)$ | $O(n)$ | ### Printing The Huffman Tree Printing a tree is $O(n)$ worst case, where $n$ is the number of nodes. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n)$ | $O(1)$ | ## Compression Compression came in three parts: 1. Reading in `HuffmanCodebook` 2. Creating a Binary Tree 3. Compressing the file ### Reading In `HuffmanCodebook` Compression is started by parsing through `HuffmanCodebook` and tokenizing each word and it's code into a tree node. We do this by creating a linked list called `tokens` from the `Tokens_read_file` function. We traverse the linked list and add each Huffman code with it's associated word to a node. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n)$ | $O(n)$ | Where $n$ is the size of the linked list. ### Creating A Binary Tree Using `TreeNode_create_encoding`, we insert each element into the tree using the `Tree_insert` function from `binary_tree.c`. Eventually, we have a tree which has each word and it's associated code. We created a function called `compress_helper` which takes in a file name and a `void*` pointer to a piece of data. The compress helper outputs the results of the compression to the file by searching for each token in the tree. > Searching and inserting into a binary tree is $O(log (n))$ runtime on average, with it's worstcase runtime being $O(n)$. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n)$ | $O(n)$ | ### Compressing The File Compression was a matter of traversing the already existing binary tree for every of the $n$ words and lookuping up their encodings. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n log(n))$ | $O(1)$ | ## Decompression Decompression came in three parts: 1. Reading in `HuffmanCodebook` 2. Recreating the Huffman Tree 3. Decompressing the file ### Reading In `HuffmanCodebook` To read in `HuffmanCodebook` we used our `Token_read_file` method which reads a file into a linked list. Since every character $n$is visited once and linked list insertion is $O(1)$ this operation is $O(n)$. Each of the $n$ lines is stored only once. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n)$ | $O(n)$ | ### Recreating The Huffman Tree To recreate the Huffman tree, every one of the $n$ lines in `HuffmanCodebook` is inserted into a tree. Since tree insertions are $O(n)$ worst case in our Huffman tree (Huffman tree's are unbalanced), this operation is $O(n^2)$. Every of the $n$ lines is stored once. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(n^2)$ | $O(n)$ | ### Decompressing The File To decompress the file, every one of the $k$ characters in our compessed file was visited once. On each character visit, the corresponding Huffman tree made one move, either to the left or the right $O(1)$. The only space allocated in this step is each character in the compressed file. | Time Complexity | Total Space Complexity | | --------------- | ---------------------- | | $O(k)$ | $O(k)$ |
PHP
UTF-8
1,687
2.953125
3
[]
no_license
<?php interface captcha { public function __construct( $width, $height, $size, $map ); public function __destruct(); public function getCode(); public function getImage(); } $captcha = new class implements captcha { private $_im; private $_code; public function __construct( $width = 80, $height = 30, $size = 4, $map = '234678qwertyuipkjhfdazxcvbnm' ) { $this->_im = $im = imagecreatetruecolor( $width, $height ); imagefilledrectangle( $im, 1, 1, $width - 2, $height - 2, imagecolorallocate( $im, 255, 255, 255 ) ); $color = imagecolorallocate( $im, mt_rand( 50, 90 ), mt_rand( 80, 200 ), mt_rand( 90, 180 ) ); $fonts = [ 'HelveticaNeueLTPro-Bd.otf', 'HelveticaNeueLTPro-Roman.otf' ]; for( $i = 0, $this->_code = '', $length = strlen( $map ) - 1, $font_length = count( $fonts ) - 1; $fs = mt_rand( 14, 20 ), $char = $map[mt_rand( 0, $length )], $i < $size; ++ $i, $this->_code .= $char ) imagettftext( $im, $fs, mt_rand( -15, 15 ), 5 + $i * $fs, mt_rand( 20, 26 ), $color, $fonts[mt_rand( 0, $font_length )], $char ); for ( $i = 0; $i < 30; ++ $i ) imagesetpixel( $im, mt_rand( 1, $width - 2 ), mt_rand( 1, $height - 2 ), $color ); for ( $i = 0; $i < 6; ++ $i ) imageline( $im, mt_rand( 1, $width - 2 ), mt_rand( 1, $height - 2 ), mt_rand( 1, $width - 2 ), mt_rand( 1, $height - 2 ), $color ); } public function __destruct() { imagedestroy( $this->_im ); } public function getCode() :string { return $this->_code; } public function getImage() :void { header( 'Content-type: image/gif' ); imagegif( $this->_im ); } }; $captcha->getImage();
Go
UTF-8
706
2.6875
3
[ "MIT" ]
permissive
// Go lang completion // By: Christian Gunderman package languageservice import ( "go/ast" "go/token" "golang.org/x/tools/go/ast/astutil" ) // GetCloseBraceOfEnclosingBlock returns the correct indentation of the selected position in the // document. func (id WorkspaceID) GetPositionOfCloseBraceOfEnclosingBlock(fileName string, position int) (int, error) { doc, err := id.getWorkspaceDocument(fileName) if err != nil { return 0, err } pos := token.Pos(position) enclosingPath, _ := astutil.PathEnclosingInterval(doc.File, pos, pos) for _, enclosingNode := range enclosingPath { if blockStmt, ok := enclosingNode.(*ast.BlockStmt); ok { return int(blockStmt.Rbrace), nil } } return -1, nil }
Java
UTF-8
3,447
3.703125
4
[]
no_license
package com.cracking.coding.company.linkedlist.removeduplicates; import java.util.HashMap; import java.util.Map; public class LinkedList { Node first; Node last; private static int size=0; public int getSize(){ return this.size; } public void add(Node node) { size++; if (first == null) { first = node; last = node; } else { last.next = node; last = node; } } public void removeUsingData(int data) { Node node = first; boolean flag = false; if (node.getData() == data) { first = node.next; node = null; flag = true; } else { while (node.next != null) { if (node.next.getData() == data) { Node nodeTemp = node.next; if (nodeTemp == last) { last = node; last.next = null; nodeTemp = null; flag = true; break; } else { node.next = node.next.next; nodeTemp = null; flag = true; break; } } node = node.next; } } if (!flag) { System.out.println("No such data found"); } } public void remove(Node node) { if (node == first) { first = node.next; node = null; } else { Node temp = first; while (temp.next != null) { if (temp.next == node && temp.next != last) { temp.next = temp.next.next; node = null; break; } else if (temp.next == node) { last = temp; temp.next = null; node = null; break; } temp = temp.next; } } } public void display() { Node node = first; while (node != null) { System.out.print(node.getData() + " -> "); node = node.next; } } public void removeDuplicates() { Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); Node prev = first; Node current = first.next; while (current != null) { if (!hashMap.isEmpty()) { if (hashMap.get(current.getData()) == null) { hashMap.put(current.getData(), 1); } else { prev.next = prev.next.next; current = null; current = prev.next; continue; } } else { hashMap.put(prev.getData(), 1); continue; } prev = prev.next; current = current.next; } } public void removeDuplicatesWithoutBuffer() { Node prev=first; Node head=prev; Node current=first.next; Node fast=current; Node slow=prev; while(prev!=null){ while(fast!=null){ if(slow.getData()==fast.getData()){ if(head.next==last){ last=head; head.next=null; continue; }else{ head.next=head.next.next; fast=null; fast=head.next; continue; } } slow=slow.next; fast=fast.next; head=head.next; } head=prev; prev=prev.next; slow=first; current=current.next; fast=current; } } private Node getKthElementToLast(int k){ Node node=first; int totalNumberOfElementsToPrint=size+1-k; for(int i=1;i<=size;i++){ if(size+1-i==totalNumberOfElementsToPrint){ return node; }else{ node=node.next; } } return null; } public void printFormKthElement(int k){ Node node=getKthElementToLast(k); if(node!=null){ while(node!=null){ System.out.print(node.getData()+((node.next==null)?"":" -> ")); node=node.next; } }else{ System.out.println("Sorry but invalid input :-"); } } public void reverseLinkedList(){ Node head=first; Node nextNode,temp=null; do{ nextNode=head.next; head.next=temp; temp=head; head=nextNode; first=temp; }while(head!=null); } }
Java
UTF-8
938
2.078125
2
[]
permissive
package com.juzi.oerp.model.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.time.LocalDateTime; /** * <p> * * </p> * * @author Juzi * @since 2020-07-14 */ @Data @TableName("user_info") public class UserInfoPO { /** * 用户id */ @TableId(value = "user_id", type = IdType.AUTO) private Integer userId; /** * 昵称 */ private String nickname; /** * 头像 */ private String avatarUrl; /** * 姓名 */ private String name; /** * 性别:0未知/1男/2女 */ private Integer gender; /** * 身份证号码 */ private String identityNo; /** * 生日 */ private LocalDateTime birthday; /** * 手机号 */ private String phoneNo; }
JavaScript
UTF-8
522
3.25
3
[]
no_license
class Wagon{ constructor(capacity){ this.capacity = capacity this.passengers = [] } getAvailableSeatCount(){ return this.capacity - this.passengers.length } join(traveler){ if (this.getAvailableSeatCount() > 0){this.passengers.push(traveler)} } shouldQuarantine(){ return this.passengers.some(passenger => passenger.isHealthy !== true) } totalFood(){ return this.passengers.reduce((acc, passenger) => acc + passenger.food, 0) } }
Java
UTF-8
5,226
2.546875
3
[]
no_license
package booksys.presentation; import java.awt.*; import javax.swing.*; import javax.swing.filechooser.*; import javax.swing.text.StyledEditorKit; import java.awt.event.*; import java.io.*; public class Note extends JFrame { // ���� ���� JTextArea text; Container pane; JMenuBar nb = new JMenuBar(); JMenu file, help; JMenuItem newI,openI,saveI,infoI,helpI; JFileChooser open = new JFileChooser();//���� �� ���丮 ���� ������Ʈ ���� public Note() { super("MemoNote"); // �θ�Ŭ���� ������ ȣ�� pane=getContentPane(); //JFrame �������� ���� ������ ���� ���� pane.setLayout(new BorderLayout()); //JFrame ���� setJMenuBar(nb); // �޴��� ���� // �޴� �� �޴� ������ ���� file = new JMenu("파일(F)"); //Ű���� �����ȣ ���� file.setMnemonic('F'); //���� �޴� ���� ���� newI = new JMenuItem("새문서"); openI = new JMenuItem("열기"); saveI = new JMenuItem("저장"); // �޴� ����Ű�� ���� ���� newI.setAccelerator(KeyStroke.getKeyStroke('N',Event.CTRL_MASK)); // Ctrl + N openI.setAccelerator(KeyStroke.getKeyStroke('O',Event.CTRL_MASK)); // Ctrl + O saveI.setAccelerator(KeyStroke.getKeyStroke('S',Event.CTRL_MASK)); // Ctrl + S // �޴��� ���� ���� file.add(newI); file.add(openI); file.add(saveI); // �޴� �ϼ� nb.add(file); // �޴����� ������ Ŭ�������� �̺�Ʈ ó�� newI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { text.setText(""); // text������ ��� ����� } }); // �޴����� ���� Ŭ�������� �̺�Ʈ ó�� openI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int re = open.showOpenDialog(Note.this); //���Ͽ��� ���̾�α�â�� ���� if (re==JFileChooser.APPROVE_OPTION) //���� ���� Ȯ�� { String fN; String dir; String str; File file_open = open.getSelectedFile(); // ������ ���ϸ��� �����´� FileInputStream fis; //���� �ý����� ���� �Է� ����Ʈ ��� ��Ʈ�� ���� ByteArrayOutputStream bo; //������ ����Ʈ �迭�� ���������� ��� ��Ʈ�� ���� try { fis = new FileInputStream(file_open); // FileInputStream��ü�� ���� bo = new ByteArrayOutputStream(); // ByteArrayOutputStream��ü�� ���� int i = 0; while ((i = fis.read()) != -1) // ������ ���������� �о�帲 { bo.write(i); //len ����Ʈ�� ����Ʈ �迭 ��� Stream�� ���� } text.setText(bo.toString()); // ȭ�鿡 �ѷ��ش� fis.close(); // FileInputStream�� �ݴ´�. bo.close(); // ByteArrayOutputStreamm�� �ݴ´�. } catch(FileNotFoundException fe) {} catch(IOException ie) {} } } }); //�޴����� ���� Ŭ�������� �̺�Ʈ ó�� saveI.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int re = open.showSaveDialog(Note.this); if (re==JFileChooser.APPROVE_OPTION) // �������� ���̾�α׸� ���� { File file_open = open.getSelectedFile(); // ������ ���ϸ��� �����´� try { PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file_open))); // PrintWriter��ü�� �����ؼ� pw.write(text.getText()); // ȭ���� ������ ���Ͽ� ���� pw.close(); } catch(FileNotFoundException ie2) {} catch(IOException ie) {} } } }); text = new JTextArea(); // ȭ�鿡 ������ text���� ���¿� ���� ���� ���� text.setCaretColor(Color.black); text.setSelectedTextColor(Color.white); text.setSelectionColor(Color.blue); text.setBackground(Color.white); pane.add(new JScrollPane(text)); } public static void main(String[] args) { Note note = new Note(); // ��ü���� note.setSize(400,300); // ������ ���� note.setVisible(true); // ȭ�鿡 ���̰� �� } }
Java
UTF-8
6,105
1.90625
2
[ "Apache-2.0" ]
permissive
package org.succlz123.s1go.app.ui.thread.info; import org.succlz123.s1go.app.MainApplication; import org.succlz123.s1go.app.R; import org.succlz123.s1go.app.bean.ThreadInfo; import org.succlz123.s1go.app.bean.UserInfo; import org.succlz123.s1go.app.config.RetrofitManager; import org.succlz123.s1go.app.ui.base.BaseThreadRvFragment; import org.succlz123.s1go.app.ui.login.LoginActivity; import org.succlz123.s1go.app.ui.thread.send.SendReplyActivity; import org.succlz123.s1go.app.utils.common.MyUtils; import org.succlz123.s1go.app.utils.common.SysUtils; import org.succlz123.s1go.app.utils.common.ToastUtils; import android.graphics.Rect; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; /** * Created by succlz123 on 2015/6/13. */ public class ThreadInfoFragment extends BaseThreadRvFragment { public static final String BUNDLE_KEY_TID = "tid"; public static final String BUNDLE_KEY_TOTAL_PAGER_NUM = "totalPagerNum"; public static final String BUNDLE_KEY_CURRENT_PAGER_NUM = "currentPagerNum"; private String mTid; private String mFormHash; private int mCurrentPagerNum; private int mTotalPagerNum; private LinearLayoutManager mLayoutManager; private ThreadInfoRvAdapter mThreadInfoRvAdapter; public static ThreadInfoFragment newInstance(String tid, int currentPagerNum, int totalPagerNum) { ThreadInfoFragment threadInfoFragment = new ThreadInfoFragment(); Bundle bundle = new Bundle(); bundle.putString(BUNDLE_KEY_TID, tid); bundle.putInt(BUNDLE_KEY_CURRENT_PAGER_NUM, currentPagerNum); bundle.putInt(BUNDLE_KEY_TOTAL_PAGER_NUM, totalPagerNum); threadInfoFragment.setArguments(bundle); return threadInfoFragment; } @Override public void onViewCreated(RecyclerView recyclerView, @Nullable Bundle savedInstanceState) { super.onViewCreated(recyclerView, savedInstanceState); if (getArguments() == null) { return; } mTid = getArguments().getString(BUNDLE_KEY_TID); mCurrentPagerNum = getArguments().getInt(BUNDLE_KEY_CURRENT_PAGER_NUM); mTotalPagerNum = getArguments().getInt(BUNDLE_KEY_CURRENT_PAGER_NUM); if (mTid == null) { return; } swipeRefreshLayout.setEnabled(false); recyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); int margin = MyUtils.dip2px(5); if (position == 0) { outRect.set(0, margin, 0, margin); } else { outRect.set(0, 0, 0, margin); } } }); mThreadInfoRvAdapter = new ThreadInfoRvAdapter(mCurrentPagerNum); recyclerView.setAdapter(mThreadInfoRvAdapter); floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UserInfo.Variables loginInfo = MainApplication.getInstance().loginInfo; if (loginInfo == null) { LoginActivity.start(getActivity()); } else { SendReplyActivity.start(getActivity(), mTid, mFormHash); } } }); loadThreadInfo(); } @Override public void onDestroyView() { super.onDestroyView(); mThreadInfoRvAdapter = null; } // public void goToTop() { // if (recyclerView == null || mLayoutManager == null) { // return; // } // recyclerView.stopScroll(); // mLayoutManager.setSmoothScrollbarEnabled(true); // int firstVisibilityPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition(); // if (firstVisibilityPosition > 10) { // mLayoutManager.scrollToPositionWithOffset(10, 0); // } // recyclerView.smoothScrollToPosition(0); // } private void loadThreadInfo() { setRefreshing(); Observable<ThreadInfo> observable = RetrofitManager.apiService().getThreadInfo(mCurrentPagerNum, mTid); Subscription subscription = observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .filter(new Func1<ThreadInfo, Boolean>() { @Override public Boolean call(ThreadInfo threadInfo) { return SysUtils.isActivityLive(ThreadInfoFragment.this); } }) .subscribe(new Action1<ThreadInfo>() { @Override public void call(ThreadInfo threadInfo) { //每次刷新时获得的回帖数 int replies = threadInfo.Variables.thread.replies; mFormHash = threadInfo.Variables.formhash; mThreadInfoRvAdapter.setData(threadInfo.Variables.postlist); setRefreshCompleted(); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { setRefreshError(); ToastUtils.showToastShort(getContext(), R.string.sorry); } }); compositeSubscription.add(subscription); } }
Java
UTF-8
1,178
3.609375
4
[]
no_license
class Counter { public synchronized void count(boolean countEven) { for (int i = (countEven ? 0 : 1); i < 100; i+=2) { System.out.println("I'm in thread with id = " + Thread.currentThread().getId() + " and counting = " + i); notify(); try { wait(); } catch (InterruptedException e) { System.err.println("Problem here"); e.printStackTrace(); } } notify(); } } class TestThread extends Thread { private Counter counter; private boolean countEven; public TestThread(Counter counter, boolean countEven) { this.counter = counter; this.countEven = countEven; } @Override public void run() { counter.count(countEven); } } public class SyncCounter { public static void main(String[] args) { System.out.println("I'm in main thread with id = " + Thread.currentThread().getId()); Counter counter = new Counter(); TestThread t1 = new TestThread(counter, true); TestThread t2 = new TestThread(counter, false); t1.start(); t2.start(); } }
Python
UTF-8
385
3.140625
3
[]
no_license
class Hero: jumlah = 0 # class Variabel __privateJumlah = 0 def __init__(self,name,health): self.nama = name self.darah = health # Variable instance private self.__private = 'private' # variable intance protected self._protected = "protected" lina = Hero("Lina",100) print(lina.__dict__) print(Hero.__dict__)
Java
UTF-8
1,715
3.65625
4
[]
no_license
package RotateArray; import java.util.Arrays; public class RotateClass { public static void main(String[] args){ } //Rotate array One by One public static Integer[] usingOneByOne(Integer[] array, int rotateBy, int n){ Integer[] result = Arrays.copyOf(array,n); for(int i=0;i<rotateBy;i++){ int temp=result[0]; for(int j=0;j<n-1;j++){ result[j]=result[j+1]; } result[n-1]=temp; } return result; } //Using Mod public static Integer[] usingMod(Integer[] array, int rotateBy, int n){ Integer[] result = new Integer[n]; int mod = rotateBy % n; for(int i=0,j=0;i<n;++i) result[j++] = array[(mod+i)%n]; return result; } //using reverse algorithm public static Integer[] usingReverse(Integer[] array, int rotateBy, int n){ Integer[] result = Arrays.copyOf(array,n); reverse(result,0,rotateBy-1); reverse(result,rotateBy,n-1); reverse(result,0,n-1); return result; } public static void reverse(Integer[] a, int start, int end){ while(start<end){ int temp = a[start]; a[start]=a[end]; a[end]=temp; start++; end--; } } //Using extra array //O(n)-Time Complexity //O(d)- Space Complexity public static Integer[] usingTempArray(Integer[] array, int rotateBy, int n){ Integer[] result= new Integer[n]; int j=0,k=0; for(int i=rotateBy;i<n;i++) result[j++]=array[i]; while (k!=rotateBy) result[j++] = array[k++]; return result; } }
Shell
UTF-8
2,511
4.25
4
[]
no_license
#!/bin/bash set -o errexit -o pipefail -o noclobber -o nounset USAGE="Usage: $0 [-u string] [-p string] [-t string,string] (up|down|status|help) connection where: -u|--user User name -p|--password Password -t|--tokens Comma separated list of OTPs " # ensure running as root if [ "$(id -u)" != "0" ]; then exec sudo "$0" "$@" fi # -allow a command to fail with !’s side effect on errexit # -use return value from ${PIPESTATUS[0]}, because ! hosed $? ! getopt --test > /dev/null if [[ ${PIPESTATUS[0]} -ne 4 ]]; then echo 'I’m sorry, `getopt --test` failed in this environment.' exit 1 fi OPTIONS=u:p:t: LONGOPTS=user:,password:,tokens: # -regarding ! and PIPESTATUS see above # -temporarily store output to be able to check for errors # -activate quoting/enhanced mode (e.g. by writing out “--options”) # -pass arguments only via -- "$@" to separate them correctly ! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") if [[ ${PIPESTATUS[0]} -ne 0 ]]; then # e.g. return value is 1 # then getopt has complained about wrong arguments to stdout exit 2 fi # read getopt’s output this way to handle the quoting right: eval set -- "$PARSED" while true; do case "$1" in -u|--user) user="$2" shift 2 ;; -p|--password) password="$2" shift 2 ;; -t|--tokens) tokens="$2" shift 2 ;; --) shift break ;; *) echo "Programming error" exit 3 ;; esac done if (( "$#" < 2 )); then echo "2 positional arguments required" 1>&2 echo "$USAGE" exit 1 fi state_dir=$(dirname "$0")/../state pid_file="${state_dir}/globalprotect_$2.pid" action="$1" shift case "${action}" in 'up') if [[ -z ${user+x} || -z ${password+x} ]]; then echo "Missing required parameters" 1>&2 echo "$USAGE" exit 1 fi if [[ -z ${tokens+x} ]]; then pwd_str="${password}" else IFS=',' read -ra tokens <<< "$tokens" pwd_str="" for t in "${tokens[@]}"; do pwd_str="${pwd_str}${password}${t}\n" done fi endpoint="$1" shift printf "$pwd_str" | openconnect --protocol=gp -b --non-inter --passwd-on-stdin --pid-file="$pid_file" -u "$user" "$@" "$endpoint" 1>&2 ;; 'down') kill -INT $(cat "$pid_file") ;; 'status') if [[ -f "$pid_file" ]]; then echo "up" else echo "down" fi ;; 'help') echo "$USAGE" exit 1 ;; esac
Markdown
UTF-8
19,546
2.546875
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Erőforrások zárolása a módosítások megakadályozása érdekében description: Annak megakadályozása, hogy a felhasználók az összes felhasználóra és szerepkörre vonatkozó zárolást alkalmazzanak az Azure-erőforrások frissítésére vagy törlésére. ms.topic: conceptual ms.date: 03/09/2021 ms.custom: devx-track-azurecli ms.openlocfilehash: 28c31681b8fbe981cd51db294c91276dfd65d71f ms.sourcegitcommit: e6de1702d3958a3bea275645eb46e4f2e0f011af ms.translationtype: MT ms.contentlocale: hu-HU ms.lasthandoff: 03/20/2021 ms.locfileid: "102619171" --- # <a name="lock-resources-to-prevent-unexpected-changes"></a>Erőforrások zárolása a váratlan módosítások megelőzése érdekében Rendszergazdaként zárolhat egy előfizetést, erőforráscsoportot vagy erőforrást, hogy megakadályozza a szervezet más felhasználói számára a kritikus erőforrások véletlen törlését vagy módosítását. A zárolás felülbírálja a felhasználó által esetlegesen felmerülő engedélyeket. A zárolási szintet **CanNotDelete** (nem törölhető) vagy **ReadOnly** (csak olvasható) értékre állíthatja be. A portálon a zárolások neve **Törlés** és **csak olvasható** . * A **CanNotDelete** azt jelzi, hogy a jogosult felhasználók továbbra is olvashatják és módosíthatják az erőforrásokat, de nem tudják törölni az erőforrást. * A **readonly** érték azt jelenti, hogy a jogosult felhasználók olvasni tudnak egy erőforrást, de nem tudják törölni vagy frissíteni az erőforrást. A zárolás alkalmazása hasonló ahhoz, hogy korlátozza az összes jogosult felhasználót az **olvasó** szerepkör által megadott engedélyekkel. ## <a name="how-locks-are-applied"></a>A zárolások alkalmazása Ha egy fölérendelt hatókörben zárolja a zárolást, akkor a hatókörben lévő összes erőforrás örökli ugyanazt a zárolást. A később hozzáadott erőforrások még a szülőtől öröklik a zárolást. Az öröklés legszigorúbb zárolása elsőbbséget élvez. A felügyeleti zárolás a szerepköralapú hozzáférés-vezérléssel szemben minden felhasználóra és szerepkörre érvényes korlátozásokat alkalmaz. A felhasználók és szerepkörök engedélyeinek beállításáról további információt az [Azure szerepköralapú hozzáférés-vezérlés (Azure RBAC)](../../role-based-access-control/role-assignments-portal.md)című témakörben talál. A Resource Manager zárolásai csak a felügyeleti síkon történő műveletekre érvényesek, ezek pedig a `https://management.azure.com` címre küldött műveletek. A zárolások nem korlátozzák, hogy az erőforrások hogyan végzik saját funkcióikat. Az erőforrás változásai korlátozva vannak, de az erőforrás működése nincs korlátozva. Egy SQL Database logikai kiszolgáló írásvédett zárolása például megakadályozza a kiszolgáló törlését vagy módosítását. Nem akadályozza meg az adatok létrehozását, frissítését és törlését az adott kiszolgálón lévő adatbázisokban. Az adattranzakciók engedélyezve vannak, mert ezek a műveletek nem lesznek elküldve a `https://management.azure.com` webhelyre. ## <a name="considerations-before-applying-locks"></a>Szempontok a zárolások alkalmazása előtt A zárolások alkalmazása váratlan eredményekhez vezethet, mert egyes olyan műveletek, amelyek látszólag nem módosítják az erőforrást, ténylegesen megkövetelik a zárolás által letiltott műveleteket. A zárolások megakadályozza, hogy a Azure Resource Manager API-nak POST-kérést igénylő műveletek is meglegyenek. Néhány gyakori példa a zárolások által blokkolt műveletekre: * A **Storage-fiók** csak olvasható zárolása megakadályozza, hogy a felhasználók listázzák a fiók kulcsait. Az Azure Storage- [lista kulcsai](/rest/api/storagerp/storageaccounts/listkeys) művelet egy post-kérésen keresztül történik, hogy megvédje a fiók kulcsaihoz való hozzáférést, amelyek teljes körű hozzáférést biztosítanak a Storage-fiókban lévő összes információhoz. Ha a Storage-fiókhoz csak olvasási zárolás van konfigurálva, a fiók kulcsaival nem rendelkező felhasználóknak az Azure AD-beli hitelesítő adatokkal kell rendelkezniük a blob-vagy üzenetsor-adatok eléréséhez. A írásvédett zárolás megakadályozza a Storage-fiókra vagy egy adattárolóra (blob-tárolóra vagy-várólistára) kiterjedő Azure RBAC-szerepkörök hozzárendelését is. * Egy **Storage-fiók** nem törölhető zárolása nem akadályozza meg a fiókban lévő adatok törlését vagy módosítását. Ez a zárolási típus csak a Storage-fiók törlését védi, és nem védi a blob, az üzenetsor, a tábla vagy a fájl adatait a Storage-fiókon belül. * A **Storage-fiók** írásvédett zárolása nem akadályozza meg, hogy a fiókban lévő adatok törölve vagy módosítva legyenek. Ez a típusú zárolás csak a Storage-fiók törlését vagy módosítását védi, és nem védi a blob, a várólista, a tábla vagy a fájl adatait a Storage-fiókon belül. * Egy **app Service** erőforrás írásvédett zárolása megakadályozza, hogy a Visual Studio Server Explorer megjelenítse az erőforráshoz tartozó fájlokat, mert az interakcióhoz írási hozzáférés szükséges. * Egy olyan **erőforráscsoport** írásvédett zárolása, amely egy **virtuális gépet** tartalmaz, megakadályozza, hogy minden felhasználó elindítsa vagy újraindítsa a virtuális gépet. Ezeknek a műveleteknek POST kérelemre van szükségük. * Egy **erőforráscsoport** nem törölhető zárolása megakadályozza, hogy Azure Resource Manager az előzményekben lévő [központi telepítések automatikus törlését](../templates/deployment-history-deletions.md) . Ha az előzményekben eléri a 800-es üzemelő példányokat, az üzemelő példányok sikertelenek lesznek. * A **Azure Backup szolgáltatás** által létrehozott **erőforráscsoport** nem törölhető zárolása miatt a biztonsági mentések sikertelenek lesznek. A szolgáltatás legfeljebb 18 visszaállítási pontot támogat. Zárolt állapotban a Backup szolgáltatás nem tudja törölni a visszaállítási pontokat. További információk: [Gyakori kérdések – Azure-beli virtuális gépek biztonsági mentése](../../backup/backup-azure-vm-backup-faq.yml). * Az **előfizetés** írásvédett zárolása megakadályozza, hogy a **Azure Advisor** megfelelően működjön. Az Advisor nem tudja tárolni a lekérdezések eredményét. ## <a name="who-can-create-or-delete-locks"></a>Kik hozhatnak létre vagy törölhetnek zárolásokat Felügyeleti zárolások létrehozásához vagy törléséhez hozzáféréssel kell rendelkeznie a `Microsoft.Authorization/*` vagy a `Microsoft.Authorization/locks/*` műveletekhez. A beépített szerepkörök esetén ezek a műveletek csak a **Tulajdonosi** és a **Felhasználói hozzáférés rendszergazdájának** vannak engedélyezve. ## <a name="managed-applications-and-locks"></a>Felügyelt alkalmazások és zárolások Bizonyos Azure-szolgáltatások, például a Azure Databricks a szolgáltatás megvalósításához a [felügyelt alkalmazásokat](../managed-applications/overview.md) használják. Ebben az esetben a szolgáltatás két erőforráscsoportot hoz létre. Egy erőforráscsoport a szolgáltatás áttekintését tartalmazza, és nincs zárolva. A másik erőforráscsoport tartalmazza a szolgáltatás infrastruktúráját, és zárolva van. Ha megpróbálja törölni az infrastruktúra-erőforráscsoportot, hibaüzenet jelenik meg arról, hogy az erőforráscsoport zárolva van. Ha megpróbálja törölni az infrastruktúra-erőforráscsoport zárolását, a rendszer hibaüzenetet kap arról, hogy a zárolás nem törölhető, mert egy rendszeralkalmazás tulajdonosa. Ehelyett törölje a szolgáltatást, amely az infrastruktúra-erőforráscsoportot is törli. Felügyelt alkalmazások esetében válassza ki a telepített szolgáltatást. ![Szolgáltatás kiválasztása](./media/lock-resources/select-service.png) Figyelje meg, hogy a szolgáltatás tartalmaz egy hivatkozást egy **felügyelt erőforráscsoporthoz**. Ez az erőforráscsoport tárolja az infrastruktúrát, és zárolva van. Nem lehet közvetlenül törölni. ![Felügyelt csoport megjelenítése](./media/lock-resources/show-managed-group.png) A szolgáltatás összes elemének törléséhez, beleértve a zárolt infrastruktúra erőforráscsoportot is, válassza a **Törlés** lehetőséget a szolgáltatáshoz. ![Szolgáltatás törlése](./media/lock-resources/delete-service.png) ## <a name="configure-locks"></a>Zárolások konfigurálása ### <a name="portal"></a>Portál [!INCLUDE [resource-manager-lock-resources](../../../includes/resource-manager-lock-resources.md)] ### <a name="arm-template"></a>ARM-sablon Ha Azure Resource Manager sablont (ARM-sablont) használ a zárolás üzembe helyezéséhez, tisztában kell lennie a zárolás hatókörével és a telepítés hatókörével. Ha a központi telepítési hatókörön szeretné alkalmazni a zárolást, például egy erőforráscsoport vagy előfizetés zárolását, ne állítsa be a hatókör tulajdonságot. Amikor zárol egy erőforrást a központi telepítési hatókörön belül, állítsa be a hatókör tulajdonságot. A következő sablon egy zárolást alkalmaz a rendszerre telepített erőforráscsoporthoz. Figyelje meg, hogy nincs hatókör-tulajdonság a zárolási erőforráson, mert a zárolás hatóköre megegyezik az üzembe helyezés hatókörével. Ez a sablon az erőforráscsoport szintjén van üzembe helyezve. ```json { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { }, "resources": [ { "type": "Microsoft.Authorization/locks", "apiVersion": "2016-09-01", "name": "rgLock", "properties": { "level": "CanNotDelete", "notes": "Resource Group should not be deleted." } } ] } ``` Erőforráscsoport létrehozásához és a zárolásához a következő sablont kell telepíteni az előfizetési szinten. ```json { "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "rgName": { "type": "string" }, "rgLocation": { "type": "string" } }, "variables": {}, "resources": [ { "type": "Microsoft.Resources/resourceGroups", "apiVersion": "2019-10-01", "name": "[parameters('rgName')]", "location": "[parameters('rgLocation')]", "properties": {} }, { "type": "Microsoft.Resources/deployments", "apiVersion": "2020-06-01", "name": "lockDeployment", "resourceGroup": "[parameters('rgName')]", "dependsOn": [ "[resourceId('Microsoft.Resources/resourceGroups/', parameters('rgName'))]" ], "properties": { "mode": "Incremental", "template": { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": {}, "variables": {}, "resources": [ { "type": "Microsoft.Authorization/locks", "apiVersion": "2016-09-01", "name": "rgLock", "properties": { "level": "CanNotDelete", "notes": "Resource group and its resources should not be deleted." } } ], "outputs": {} } } } ], "outputs": {} } ``` Ha az erőforráscsoport egyik **erőforrásához** zárolást alkalmaz, adja hozzá a hatókör tulajdonságot. Állítsa a hatókört a zárolni kívánt erőforrás nevére. Az alábbi példa egy olyan sablont mutat be, amely egy app Service-csomagot, egy webhelyet és egy zárolást hoz létre a webhelyen. A zárolás hatóköre a webhelyen van beállítva. ```json { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "hostingPlanName": { "type": "string" }, "location": { "type": "string", "defaultValue": "[resourceGroup().location]" } }, "variables": { "siteName": "[concat('ExampleSite', uniqueString(resourceGroup().id))]" }, "resources": [ { "type": "Microsoft.Web/serverfarms", "apiVersion": "2020-06-01", "name": "[parameters('hostingPlanName')]", "location": "[parameters('location')]", "sku": { "tier": "Free", "name": "f1", "capacity": 0 }, "properties": { "targetWorkerCount": 1 } }, { "type": "Microsoft.Web/sites", "apiVersion": "2020-06-01", "name": "[variables('siteName')]", "location": "[parameters('location')]", "dependsOn": [ "[resourceId('Microsoft.Web/serverfarms', parameters('hostingPlanName'))]" ], "properties": { "serverFarmId": "[parameters('hostingPlanName')]" } }, { "type": "Microsoft.Authorization/locks", "apiVersion": "2016-09-01", "name": "siteLock", "scope": "[concat('Microsoft.Web/sites/', variables('siteName'))]", "dependsOn": [ "[resourceId('Microsoft.Web/sites', variables('siteName'))]" ], "properties": { "level": "CanNotDelete", "notes": "Site should not be deleted." } } ] } ``` ### <a name="azure-powershell"></a>Azure PowerShell A [New-AzResourceLock](/powershell/module/az.resources/new-azresourcelock) parancs használatával zárolja a telepített erőforrásokat a Azure PowerShell. Egy erőforrás zárolásához adja meg az erőforrás nevét, típusát és az erőforráscsoport nevét. ```azurepowershell-interactive New-AzResourceLock -LockLevel CanNotDelete -LockName LockSite -ResourceName examplesite -ResourceType Microsoft.Web/sites -ResourceGroupName exampleresourcegroup ``` Egy erőforráscsoport zárolásához adja meg az erőforráscsoport nevét. ```azurepowershell-interactive New-AzResourceLock -LockName LockGroup -LockLevel CanNotDelete -ResourceGroupName exampleresourcegroup ``` A zárolással kapcsolatos információk beszerzéséhez használja a [Get-AzResourceLock](/powershell/module/az.resources/get-azresourcelock). Az előfizetés összes zárolásának beszerzéséhez használja a következőt: ```azurepowershell-interactive Get-AzResourceLock ``` Egy erőforrás összes zárolásának beszerzéséhez használja a következőt: ```azurepowershell-interactive Get-AzResourceLock -ResourceName examplesite -ResourceType Microsoft.Web/sites -ResourceGroupName exampleresourcegroup ``` Egy erőforráscsoport összes zárolásának beszerzéséhez használja a következőt: ```azurepowershell-interactive Get-AzResourceLock -ResourceGroupName exampleresourcegroup ``` Egy erőforrás zárolásának törléséhez használja a következőt: ```azurepowershell-interactive $lockId = (Get-AzResourceLock -ResourceGroupName exampleresourcegroup -ResourceName examplesite -ResourceType Microsoft.Web/sites).LockId Remove-AzResourceLock -LockId $lockId ``` Egy erőforráscsoport zárolásának törléséhez használja a következőt: ```azurepowershell-interactive $lockId = (Get-AzResourceLock -ResourceGroupName exampleresourcegroup).LockId Remove-AzResourceLock -LockId $lockId ``` ### <a name="azure-cli"></a>Azure CLI Az üzembe helyezett erőforrásokat az az [Lock Create](/cli/azure/lock#az-lock-create) paranccsal zárolhatja az Azure CLI használatával. Egy erőforrás zárolásához adja meg az erőforrás nevét, típusát és az erőforráscsoport nevét. ```azurecli az lock create --name LockSite --lock-type CanNotDelete --resource-group exampleresourcegroup --resource-name examplesite --resource-type Microsoft.Web/sites ``` Egy erőforráscsoport zárolásához adja meg az erőforráscsoport nevét. ```azurecli az lock create --name LockGroup --lock-type CanNotDelete --resource-group exampleresourcegroup ``` A zárolással kapcsolatos információk lekéréséhez használja [az az Lock List](/cli/azure/lock#az-lock-list). Az előfizetés összes zárolásának beszerzéséhez használja a következőt: ```azurecli az lock list ``` Egy erőforrás összes zárolásának beszerzéséhez használja a következőt: ```azurecli az lock list --resource-group exampleresourcegroup --resource-name examplesite --namespace Microsoft.Web --resource-type sites --parent "" ``` Egy erőforráscsoport összes zárolásának beszerzéséhez használja a következőt: ```azurecli az lock list --resource-group exampleresourcegroup ``` Egy erőforrás zárolásának törléséhez használja a következőt: ```azurecli lockid=$(az lock show --name LockSite --resource-group exampleresourcegroup --resource-type Microsoft.Web/sites --resource-name examplesite --output tsv --query id) az lock delete --ids $lockid ``` Egy erőforráscsoport zárolásának törléséhez használja a következőt: ```azurecli lockid=$(az lock show --name LockSite --resource-group exampleresourcegroup --output tsv --query id) az lock delete --ids $lockid ``` ### <a name="rest-api"></a>REST API A telepített erőforrásokat zárolhatja a [felügyeleti zárolások Rest APIával](/rest/api/resources/managementlocks). A REST API lehetővé teszi zárolások létrehozását és törlését, valamint a meglévő zárolásokkal kapcsolatos információk lekérését. Zárolás létrehozásához futtassa a következő parancsot: ```http PUT https://management.azure.com/{scope}/providers/Microsoft.Authorization/locks/{lock-name}?api-version={api-version} ``` A hatókör lehet előfizetés, erőforráscsoport vagy erőforrás. A zárolási név a zárolás meghívásához szükséges. Az API-Version esetében használja az **2016-09-01**-es verziót. A kérelemben adjon meg egy JSON-objektumot, amely meghatározza a zárolás tulajdonságait. ```json { "properties": { "level": "CanNotDelete", "notes": "Optional text notes." } } ``` ## <a name="next-steps"></a>Következő lépések * Az erőforrások logikus rendszerezésével kapcsolatos további információkért lásd: [címkék használata az erőforrások rendszerezéséhez](tag-resources.md). * Az előfizetésre vonatkozó korlátozásokat és konvenciókat egyéni szabályzatokkal is alkalmazhat. További információ: [Mi az az Azure Policy?](../../governance/policy/overview.md) * Nagyvállalatoknak az [Azure enterprise scaffold - prescriptive subscription governance](/azure/architecture/cloud-adoption-guide/subscription-governance) (Azure nagyvállalati struktúra - előíró előfizetés-irányítás) című cikk nyújt útmutatást az előfizetéseknek a Resource Managerrel való hatékony kezeléséről.
C
UTF-8
886
2.796875
3
[]
no_license
/* * CustomTimer.c * * Created: 16/02/2021 12:06:28 AM * Author: Nicolas VERHELST */ #include "Timer/CustomTimer.h" #include "Timer/atmega-timers.h" #include "LCD/lcd_drv.h" #include <stdbool.h> // Global variable to be accessed within this file static functionTypeAction G_Action; static long G_TargetCount = 1; static bool G_RepeatAction = false; void actionWrapper() { G_Action(); if (!G_RepeatAction) { timer1_stop(); } } void waitUntilAction() { static long count = 0; count++; if (count==G_TargetCount) { count = 0; actionWrapper(); } } void startTimerAction(long timeMs, bool repeat, void (*action)()) { G_RepeatAction = repeat; G_Action = action; if(timeMs<=4) { int ticksToWait = 65535/4*timeMs; timer1(TIMER1_PRESCALER_1, ticksToWait, actionWrapper); } else { G_TargetCount = timeMs/4; timer1(TIMER1_PRESCALER_1, 65535, waitUntilAction); } }
Java
UTF-8
1,388
3.03125
3
[]
no_license
package pl.pawelkwiecien.commons; public class StaticSupportMethods { private static final int FIRST_ROW_NUMBER_IN_ASCII = 49; private static final int LAST_ROW_NUMBER_IN_ASCII = 56; private static final int FIRST_COLUMN_LETTER_IN_ASCII = 97; private static final int LAST_COLUMN_LETTER_IN_ASCII = 104; private static final int FIRST_CHARACTER_FROM_INPUT = 0; private static final int SECOND_CHARACTER_FROM_INPUT = 1; private static final int MAX_INPUT_LENGTH = 2; public static boolean isValid(String input) { if (input.length() < MAX_INPUT_LENGTH) { return false; } else { return input.charAt(FIRST_CHARACTER_FROM_INPUT) >= FIRST_COLUMN_LETTER_IN_ASCII && input.charAt(FIRST_CHARACTER_FROM_INPUT) <= LAST_COLUMN_LETTER_IN_ASCII && input.charAt(SECOND_CHARACTER_FROM_INPUT) >= FIRST_ROW_NUMBER_IN_ASCII && input.charAt(SECOND_CHARACTER_FROM_INPUT) <= LAST_ROW_NUMBER_IN_ASCII && input.length() == MAX_INPUT_LENGTH; } } public static int generateColumn(String input) { return (input.charAt(FIRST_CHARACTER_FROM_INPUT) - FIRST_COLUMN_LETTER_IN_ASCII); } public static int generateRow(String input) { return (input.charAt(SECOND_CHARACTER_FROM_INPUT) - FIRST_ROW_NUMBER_IN_ASCII); } }
TypeScript
UTF-8
339
3.59375
4
[]
no_license
interface Ship { name: string; cannons: number; } const testShip: Ship = { name: 'Barca', cannons: 2, }; type MyCustomReadonly<T> = { readonly [P in keyof T]: T[P]; // For each prop/key of T }; function freezeShip<T>(ship: T): MyCustomReadonly<T> { return Object.freeze(ship); } const newShip = freezeShip<Ship>(testShip);
JavaScript
UTF-8
312
2.828125
3
[]
no_license
if (!sessionStorage['counter']) { sessionStorage['counter'] = 0; } else { sessionStorage['counter']++; } document.querySelector('#content').innerHTML = '<p>This sample has been run ' + sessionStorage.getItem('counter') + ' times</p>' + '<p>(The value will be available until we close the tab)</p>';
JavaScript
UTF-8
389
3.171875
3
[ "MIT" ]
permissive
function Plane() { this.status = "Flying"; } Plane.prototype.land = function () { if (this.status === "Landed") throw "The plane has already landed!"; this.status = "Landed"; return "The plane landed"; }; Plane.prototype.takeoff = function () { if (this.status === "Flying") throw "The plane has already taken off!"; this.status = "Flying"; return "The plane took off"; };
Python
UTF-8
402
3.625
4
[]
no_license
# Match score is X:Y, user prediction is A:B. # If user predicts the result of the match - user gets 10 point # If user predicts the win or lose or draw - user gets 5 point # If user make a mistake - user gets nothing def f(x, y, a, b): score = 0 if x == a and b == y: score = 10 elif x > y and a > b or y > x and b > a or a == b and x == y: score = 5 return score
C
UTF-8
3,911
2.78125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { // int x = 100; //ได้ 3 อย่าง ตัวแปร ค่าตัวแปร และ ที่อยู่ // int a = 0144; //มีค่า 100 ในฐาน16 // int b = 0x64; //มีค่า 100 ในฐาน16 // printf("x = %d\n",x); // printf("reference x = %lu\n", &x); //จะได้ค่า ที่อยู่ออกมา // printf("reference x = %p\n", &x); // %p จะออกค่าที่อยู่เป็น ฐาน 16 (pointer) //printf("-----------------------------------\n"); //อาเรย์ //int number[] = {3,4,5,6,7}; //array ขนาด 5 //int number[100]; //int number[100] = {3,4,5,6,7}; //printf("index 1 = %d\n",number[1]); //printf("reference number[1] = %p\n", &number[1]); //printf("reference number[0] = %p\n", &number[0]); //printf("reference number = %p\n", &number); //หาที่อยู่ number จาก array ที่ 0 ได้่ //printf("reference number = %p\n", &number +1 );//ถ้า pointer +1 จะเป็นการ+ที่อยู่ จะได้เป็นค่าที่อยู่ ของarrayถัดไป โดยในที่นี้ค่าของ numberเป็นint มีค่า4 บิตพอบวกแล้วจะเพิ่มอีก 4 //+ เท่าขนาด type เช่น char+1 ,int+4 //ข้อควรระวัง //int number[] = {3,4,5,6,7}; //number[2000] = 2000 //printf("index 1 = %d\n",number[2000]); //printf("reference number[1] = %p\n", &number[2000]); //จากตรงนี้นอกจากจะสร้างได้แล้วยังเปลี่ยนค่าในที่อยู๋ที่เกินไปได้ด้วย ไม่เหมือนภาษาอื่น //ถ้าเราทำให้มันเป็น inf แล้วมันไปเปลี่ยนค่าในที่อยู่อื่นนอกจากที่ตั้งไว้แล้ววิ่งไปเลขลบมันจะไปทำให้ค่าบ้างค่าของคอมเป็น 0 ทำให้ memory พัง //printf("------------------------------------------\n"); //int number[] = {3,4,5,6,7}; //int *ptr = &x; //ประกาศแล้วให้ค่า //int *arrPtr; // ประกาศก่อนให้ค่า //arrPtr = number; // 00 //การให้ค่า ไม่ต้องมี * (ถ้าประกาศไว้แล้ว) //arrPtr +=2; // เปลี่ยนที่อยู่ถัดไป 2 //*arrPtr = *arrPtr + 10;//เปลี่ยนค่าที่อยู่ปัจจุบัน +10 //printf("arrptr = %p, *arrPtr = %d",arrPtr, *arrPtr); //printf("number[2] = %d\n",number[2]); //ที่ที่อยู่ 2 เปลีย่นค่าเป็น 15 เพราะเรานำค่าไป +10 ที่บรรทัด36 //int number[] = {3,4,5,6,7}; //for (int *ptr = number; ptr <= &number[4];ptr++) //{ // printf("[%p] = %d\n",ptr,*ptr); //} //int *ptr2 = number; //printf("------------------------------------------\n"); //for(int i = 0;i < 5; i++) //{ // printf("[%p] = %d\n",ptr2 + i,*(ptr2 + i)); //} //char input[100]; //int count = 0; //char c; //while ((c = getchar())!= '\n') //{ // input[count] = c; // ++count; //}//ถ้าวนรับ เอง getchar เราต้องปิดด้วย /0 เอง มันไม่เหมือน กับ fgets //input[count] = '\0'; //for(char *cPtr = input ; *cPtr != '\0' ;cPtr++){ // printf("%c\n",*cPtr); //} //scanf() char c; int i ; char s[100]; scanf("%d-%c-%s",&i,&c,s); //ตัวเลข 4 บิต คาเรค 1 ตัว char 100 printf("%d %c %s",i,c,s); }
TypeScript
UTF-8
1,323
2.640625
3
[]
no_license
import transform, { ByIdDictionary } from '../services/transform'; import { DynamicEntity, StaticEntity } from '../services/api/area'; import { AreaAction, AreaActions } from '../actions/area'; export interface AreaState { isPending: boolean, size: { width: number, height: number }, statics: StaticEntity[], dynamics: { byId: ByIdDictionary<DynamicEntity>, allIds: number[] } } const defaultState: AreaState = { isPending: false, size: { width: -1, height: -1 }, statics: [], dynamics: { byId: {}, allIds: [] } }; export default function areaReducer(state: AreaState = defaultState, action: AreaAction): AreaState { switch (action.type) { case AreaActions.REQUEST_AREA: return { ...state, isPending: true }; case AreaActions.RECEIVE_AREA: return { ...state, isPending: false, size: action.area.size, statics: action.area.statics, dynamics: { byId: transform.byId(action.area.dynamics), allIds: transform.allIds(action.area.dynamics) } }; default: return state; } }
Python
UTF-8
496
3.875
4
[]
no_license
#!/bin/python concat='' frase = raw_input("Ingresa una palabra o frase: ") print "Contiene %s caracteres" % len(frase) print "Aplicando lower(): %s" % frase.lower() print "Aplicando upper(): %s" % frase.upper() ind = raw_input("Obtener la letra en indice: ") concat = concat + frase[int(ind)] ind = raw_input("Obtener la letra en indice: ") concat = concat + frase[int(ind)] ind = raw_input("Obtener la letra en indice: ") concat = concat + frase[int(ind)] print concat print frase[4:9]
Python
UTF-8
2,110
2.828125
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
class NcellResponse(object): def __init__(self, response): self.__response = response self.__responseDict = self.__response.json() self.__responseDict2 = self.__responseDict.copy() def __repr__(self): return f"<Response [{self.responseHeader['responseDescDisplay']}]>" @property def responseHeader(self): """ Returns a dictionary of response header from ncell """ return self.__responseDict['responseHeader'] @property def content(self): """ Returns the content of the response """ self.__responseDict2.pop('responseHeader', None) return self.__responseDict2 @property def cookies(self): """ Returns a CookieJar object with the cookies sent back from the server """ return self.__response.cookies @property def elapsed(self): """ Returns a timedelta object with the time elapsed from sending the request to the arrival of the response """ return self.__response.elapsed @property def headers(self): """ Returns a dictionary of response headers """ return self.__response.headers @property def ok(self): """ Returns True if status_code is less than 400, otherwise False """ return self.__response.ok @property def reason(self): """ Returns a text corresponding to the status code of the response """ return self.__response.reason @property def request(self): """ Returns the request object that requested this response """ return self.__response.request @property def statusCode(self): """ Returns a number that indicates the status (200 is OK, 404 is Not Found) """ return self.__response.status_code @property def url(self): """ Returns the URL of the response """ return self.__response.url
Java
UTF-8
1,796
2.171875
2
[]
no_license
/** * This file is part of linkoopdb. * <p> * Copyright (C) 2016 - 2018 Datapps, Inc */ package com.datapps.linkoopdb.worker.spark.ai.classifier; import com.datapps.linkoopdb.worker.spark.ai.core.MetaDataType; import com.datapps.linkoopdb.worker.spark.ai.core.SparkFunctionContext; import com.datapps.linkoopdb.worker.spark.ai.core.SparkMLModelBase; import com.datapps.linkoopdb.worker.spark.ai.core.model.ModelLogicPlan; import org.apache.spark.ml.PipelineStage; import org.apache.spark.ml.classification.NaiveBayesModel; import org.apache.spark.ml.param.ParamPair; import org.apache.spark.ml.param.Params; import org.apache.spark.sql.SparkSession; public class NaiveBayes extends SparkMLModelBase { @Override public String version() { return "1.0.0"; } @Override public String[] methods() { return new String[]{"naive_bayes_train", "naive_bayes_predict"}; } @Override public ParamPair[] addExtraMetas(SparkFunctionContext context, Params params) { NaiveBayesModel dtm = (NaiveBayesModel) params; return new ParamPair[]{ MetaDataType.buidParamPair("numClasses", "the number of classes", dtm.numClasses()), MetaDataType.buidParamPair("numFeatures", "the number of features", dtm.numClasses()), }; } @Override public PipelineStage createSimplePipelineStage() { return new org.apache.spark.ml.classification.NaiveBayes() .setLabelCol("LABEL") .setFeaturesCol("FEATURES").setPredictionCol("PREDICTION"); } @Override public ModelLogicPlan load(SparkSession session, String alias, String path) { return new ModelLogicPlan(session.read().parquet(path).alias(alias).logicalPlan(), NaiveBayesModel.load(path)); } }
Markdown
UTF-8
2,063
3.125
3
[ "MIT" ]
permissive
# Getting Started ## Installation 1. Install the **peer dependencies** listed below: ```bash yarn add @xstyled/styled-components @xstyled/system prop-types react react-dom styled-components ``` 2. Install the the `core` component and any other components you need for your webapp e.g. if you need just a button… ```bash yarn add @welcome-ui/core @welcome-ui/button ``` ## Usage Welcome UI provides an helper to help you setup your project: `<WuiProvider />`. ```jsx live=false import React from 'react' import { createTheme, WuiProvider } from '@welcome-ui/core' import { Button } from '@welcome-ui/button' // Add theme options (if you want) const options = { defaultFontFamily: 'Helvetica', headingFontFamily: 'Georgia', colors: { primary: { 500: '#FF0000' }, secondary: { 500: '#00FF00' } } } // Create your theme const theme = createTheme(options) export default function Root() { return ( // Wrap your components with <WuiProvider /> with your theme <WuiProvider theme={theme} // Will inject our global style with normalize and fonts hasGlobalStyle // Will inject our global style with https://meyerweb.com/eric/tools/css/reset/ reset useReset > <Button variant="secondary">Welcome!</Button> </WuiProvider> ) } ``` ## Hide the focus ring on mouse move or on keydown WuiProvider takes a `shouldHideFocusRingOnClick` prop which defaults to `true`. It hides the focus ring on mouse move, click or on keydown. It only adds styles to remove the outline on focus. If you need to remove another css property, you have to write your own styles using the data-attribute `hideFocusRingsDataAttribute` exported from `@welcome-ui/utils`. ⚠️ Troubleshooting If it doesn't work for you, check that the id of your react root is set to `root`. If you have another id (nextjs uses `__next`), just use the `reactRootId` prop on `WuiProvider` to change it: ``` <WuiProvider theme={theme} hasGlobalStyle reactRootId="__next" > {your app} </WuiProvider> ```
PHP
UTF-8
2,096
2.65625
3
[]
no_license
<?php require_once dirname(dirname(__FILE__)) . '/Klarna.php'; // Dependencies from http://phpxmlrpc.sourceforge.net/ require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc'; require_once dirname(dirname(__FILE__)) . '/transport/xmlrpc-3.0.0.beta/lib/xmlrpc_wrappers.inc'; /** * 1. Initialize and setup the Klarna instance. */ $k = new Klarna(); $k->config( 123456, // Merchant ID 'sharedSecret', // Shared Secret KlarnaCountry::SE, // Country KlarnaLanguage::SV, // Language KlarnaCurrency::SEK, // Currency Klarna::BETA, // Server 'json', // PClass Storage '/srv/pclasses.json', // PClass Storage URI path true, // SSL true // Remote logging of response times of xmlrpc calls ); // OR you can set the config to loads from a file, for example /srv/klarna.json: // $k->setConfig(new KlarnaConfig('/srv/klarna.json')); /** * 2. Partially activate the invoice */ // Here you specify the quantity of an article you wish to partially activate. // artNo must be the same as the one you used in addArticle() when you made the // addTransaction() call. $k->addArtNo( 1, // Quantity 'MG200MMS' // Article number ); // Here you enter the invoice number you got from addTransaction(): $invNo = '123456'; try { $result = $k->activatePart( $invNo, // Invoice number KlarnaPClass::INVOICE // Or the PClass ID used to make the order. ); $url = $result['url']; echo "url: ${url}\n"; if (isset($result['invno'])) { $invno = $result['invno']; echo "invno: ${invno}\n"; } // The url points to a PDF file for the invoice. // The invno field is only present if the invoice was not entirely activated, // and in that case it contains the new invoice number. // Invoice activated, proceed accordingly. } catch(Exception $e) { // Something went wrong or the invoice doesn't exist. echo "{$e->getMessage()} (#{$e->getCode()})\n"; }
C#
UTF-8
944
2.90625
3
[]
no_license
using System; using FluentAssertions; using NUnit.Framework; using RomanNumberConverter.Console.ApplicationServices; using RomanNumberConverter.Console.Domain; namespace RomanNumberConverter.Tests.ApplicationServices { [TestFixture] public class RomanConverterTests { [TestCase("10", "X")] [TestCase("4", "IV")] [TestCase("11", "XI")] [TestCase("89", "LXXXIX")] [TestCase("456", "CDLVI")] [TestCase("990", "CMXC")] [TestCase("1244", "MCCXLIV")] [TestCase("2999", "MMCMXCIX")] public void When_Number_Is_Given_Should_Return_Roman_Number(string number, string expected) { Numeric testNumber = new Numeric(number); RomanConverter romanConverter = new RomanConverter(); var convertedValue = romanConverter.ToRoman(testNumber.Number); convertedValue.Should().BeEquivalentTo(expected); } } }
C++
UTF-8
1,325
3.703125
4
[ "MIT" ]
permissive
/** * Find the longest increasing subsequence of a given sequence / array. * * In other words, find a subsequence of array in which the subsequence’s elements are in strictly increasing order, and in which the subsequence is as long as possible. * This subsequence is not necessarily contiguous, or unique. * In this case, we only care about the length of the longest increasing subsequence. * * Example : * * Input : [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] * Output : 6 * The sequence : [0, 2, 6, 9, 13, 15] or [0, 4, 6, 9, 11, 15] or [0, 4, 6, 9, 13, 15] */ /** * This function calculates the LIS based on DP. * Complexity : T(n) = O(n^2), S(n) = O(n) * Recursive relation : LIS[i] = max(1 + LIS[j], LIS[i]) for j : [0.. i - 1] and A[i] > A[j] * * @param const vector<int> A the sequence * @return int the length of the longest increasing subsequence */ int Solution::lis(const vector<int> &A) { int sz = A.size(); if (sz <= 1) { return sz; } vector<int> LIS(sz, 1); int maxLIS = 1; for (int i = 1; i < sz; i ++) { for (int j = 0; j < i; j ++) { if (A[i] > A[j]) { LIS[i] = max(1 + LIS[j], LIS[i]); } } maxLIS = max(LIS[i], maxLIS); } return maxLIS; }
SQL
UTF-8
1,248
2.890625
3
[]
no_license
DROP DATABASE IF EXISTS bamazon_DB; CREATE DATABASE bamazon_DB; USE bamazon_DB; CREATE TABLE product( id INT NOT NULL AUTO_INCREMENT, article VARCHAR(100) NOT NULL, department VARCHAR(45) NOT NULL, quantityInStock INT default 0, PRIMARY KEY (id) ); INSERT INTO product (article, department, quantityInStock) values ('dress oxford', 'footwear', 11); INSERT INTO product (article, department, quantityInStock) values ('running shoe', 'footwear', 12); INSERT INTO product (article, department, quantityInStock) values ('hiking boot', 'footwear', 13); INSERT INTO product (article, department, quantityInStock) values ('short sleeve', 'shirts', 14); INSERT INTO product (article, department, quantityInStock) values ('long sleeve', 'shirts', 15); INSERT INTO product (article, department, quantityInStock) values ('red flanel', 'shirts', 16); INSERT INTO product (article, department, quantityInStock) values ('blue jeans', 'pants', 17); INSERT INTO product (article, department, quantityInStock) values ('dress slacks', 'pants', 18); INSERT INTO product (article, department, quantityInStock) values ('hooded parka', 'outerwear', 19); INSERT INTO product (article, department, quantityInStock) values ('leather mitts', 'outerwear', 20);
Java
UTF-8
21,237
2.46875
2
[]
no_license
package org.lwjglb.engine; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; /** * Created by Lucas on 20/04/2017. */ public class MainMenu extends JFrame { private JPanel rootpanel; private JButton backwardsButton; private JButton upButton; private JButton forwardsButton1; private JButton downButton1; private JButton rightButton; private JButton leftButton; private JButton focusButton; private JButton prevRobotButton; private JButton nextRobotButton; private JButton playButton; private JButton nextTimeStepButton; private JButton previousTimeStepButton; private JButton stopButton; private JButton loadFileButton; private JButton loadStartEndConfigButton; private JButton loadEnvirmentSizeButton; private JButton loadObstaclesButton; private JFileChooser fileChooser=new JFileChooser(); private volatile File startEndConfiguration=null; private volatile File envirmentSize=null; private volatile File obstacles=null; private volatile boolean bbackwardsButton; private volatile boolean bupButton; private volatile boolean bforwardsButton1; private volatile boolean bdownButton1; private volatile boolean brightButton; private volatile boolean bleftButton; private volatile boolean bfocusButton; private volatile boolean bprevRobotButton; private volatile boolean bnextRobotButton; private volatile boolean bplayButton; private volatile boolean bbpreviousTimeStepButton; private volatile boolean bstopButton; private volatile boolean bloadFileButton; private volatile boolean bnextTimeStepButton; private volatile boolean bpreviousTimeStepButton; public MainMenu() { super("Menu"); setSize(650, 380); setContentPane(rootpanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); upButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bupButton = true; } @Override public void mouseReleased(MouseEvent e) { bupButton = false; } }); downButton1.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bdownButton1 = true; } @Override public void mouseReleased(MouseEvent e) { bdownButton1 = false; } }); leftButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bleftButton = true; } @Override public void mouseReleased(MouseEvent e) { bleftButton = false; } }); rightButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { brightButton = true; } @Override public void mouseReleased(MouseEvent e) { brightButton = false; } }); backwardsButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bbackwardsButton = true; } @Override public void mouseReleased(MouseEvent e) { bbackwardsButton = false; } }); forwardsButton1.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bforwardsButton1 = true; } @Override public void mouseReleased(MouseEvent e) { bforwardsButton1 = false; } }); focusButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bfocusButton = true; } @Override public void mouseReleased(MouseEvent e) { bfocusButton = false; } }); prevRobotButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bprevRobotButton = true; } @Override public void mouseReleased(MouseEvent e) { bprevRobotButton = false; } }); nextRobotButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { bnextRobotButton = true; } @Override public void mouseReleased(MouseEvent e) { bnextRobotButton = false; } }); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bplayButton = true; } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { bplayButton = false; } }); JFrame frame=this; loadStartEndConfigButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int ret=fileChooser.showOpenDialog(frame); if(ret==JFileChooser.APPROVE_OPTION) { startEndConfiguration=fileChooser.getSelectedFile(); } } }); loadEnvirmentSizeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int ret=fileChooser.showOpenDialog(frame); if(ret==JFileChooser.APPROVE_OPTION) { envirmentSize=fileChooser.getSelectedFile(); } } }); loadObstaclesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int ret=fileChooser.showOpenDialog(frame); if(ret==JFileChooser.APPROVE_OPTION) { obstacles=fileChooser.getSelectedFile(); } } }); nextTimeStepButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { System.out.println(e.getButton()); if(e.getButton()==MouseEvent.BUTTON1) { bnextTimeStepButton=true; } } @Override public void mouseReleased(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1) { bnextTimeStepButton=false; } } }); previousTimeStepButton.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1) { bpreviousTimeStepButton=true; } } @Override public void mouseReleased(MouseEvent e) { if(e.getButton()==MouseEvent.BUTTON1) { bpreviousTimeStepButton=false; } } }); } public static void main(String[] args) { MainMenu test = new MainMenu(); // System.out.println("sup"); while (true) { //System.out.println(test.cameraUp()); // System.out.println(test.getSize()); } } public boolean cameraUp() { return bupButton; } public boolean cameraDown() { return bdownButton1; } public boolean cameraLeft() { return bleftButton; } public boolean cameraRight() { return brightButton; } public boolean cameraForwards() { return bforwardsButton1; } public boolean cameraBackwards() { return bbackwardsButton; } public boolean nextTimeStep() { return bnextTimeStepButton; } public boolean previouseTimeStep() { return bpreviousTimeStepButton; } public boolean isBprevRobotButton() {return bprevRobotButton;} public boolean isBnextRobotButton() {return bnextRobotButton;} public boolean isBplayButton() {return bplayButton;} public boolean isBstopButton() {return bstopButton;} { // GUI initializer generated by IntelliJ IDEA GUI Designer // >>> IMPORTANT!! <<< // DO NOT EDIT OR ADD ANY CODE HERE! $$$setupUI$$$(); } /** * Method generated by IntelliJ IDEA GUI Designer * >>> IMPORTANT!! <<< * DO NOT edit this method OR call it in your code! * * @noinspection ALL */ private void $$$setupUI$$$() { rootpanel = new JPanel(); rootpanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); final JPanel panel1 = new JPanel(); panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(2, 4, new Insets(0, 0, 0, 0), -1, -1)); rootpanel.add(panel1); final JPanel panel2 = new JPanel(); panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(3, 4, new Insets(0, 0, 0, 0), -1, -1)); panel1.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 4, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); panel2.setBorder(BorderFactory.createTitledBorder("")); playButton = new JButton(); playButton.setText("play"); panel2.add(playButton, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 4, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); previousTimeStepButton = new JButton(); previousTimeStepButton.setText("previous time step"); panel2.add(previousTimeStepButton, new com.intellij.uiDesigner.core.GridConstraints(2, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); nextRobotButton = new JButton(); nextRobotButton.setText("next robot"); panel2.add(nextRobotButton, new com.intellij.uiDesigner.core.GridConstraints(0, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); focusButton = new JButton(); focusButton.setText("focus"); panel2.add(focusButton, new com.intellij.uiDesigner.core.GridConstraints(0, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); prevRobotButton = new JButton(); prevRobotButton.setText("prev robot"); panel2.add(prevRobotButton, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 2, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); nextTimeStepButton = new JButton(); nextTimeStepButton.setText("next time step"); panel2.add(nextTimeStepButton, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 2, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); stopButton = new JButton(); stopButton.setText("Stop"); panel2.add(stopButton, new com.intellij.uiDesigner.core.GridConstraints(2, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); loadEnvirmentSizeButton = new JButton(); loadEnvirmentSizeButton.setText("load envirment size"); panel1.add(loadEnvirmentSizeButton, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); loadObstaclesButton = new JButton(); loadObstaclesButton.setText("load obstacles "); panel1.add(loadObstaclesButton, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); loadStartEndConfigButton = new JButton(); loadStartEndConfigButton.setText("load start/end config"); panel1.add(loadStartEndConfigButton, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); loadFileButton = new JButton(); loadFileButton.setText("Load file"); panel1.add(loadFileButton, new com.intellij.uiDesigner.core.GridConstraints(1, 3, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)); final JPanel panel3 = new JPanel(); panel3.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(2, 3, new Insets(0, 0, 0, 0), -1, -1)); rootpanel.add(panel3); final JPanel panel4 = new JPanel(); panel4.setLayout(new BorderLayout(0, 0)); panel3.add(panel4, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(2, 2), new Dimension(100, 100), new Dimension(100, 100), 0, false)); upButton = new JButton(); upButton.setText("up"); panel4.add(upButton, BorderLayout.CENTER); final JPanel panel5 = new JPanel(); panel5.setLayout(new BorderLayout(0, 0)); panel3.add(panel5, new com.intellij.uiDesigner.core.GridConstraints(1, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(100, 100), new Dimension(100, 100), 0, false)); downButton1 = new JButton(); downButton1.setText("down"); panel5.add(downButton1, BorderLayout.CENTER); final JPanel panel6 = new JPanel(); panel6.setLayout(new BorderLayout(0, 0)); panel3.add(panel6, new com.intellij.uiDesigner.core.GridConstraints(1, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); rightButton = new JButton(); rightButton.setText("right"); panel6.add(rightButton, BorderLayout.CENTER); final JPanel panel7 = new JPanel(); panel7.setLayout(new BorderLayout(0, 0)); panel3.add(panel7, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); leftButton = new JButton(); leftButton.setText("left"); panel7.add(leftButton, BorderLayout.CENTER); final JPanel panel8 = new JPanel(); panel8.setLayout(new BorderLayout(0, 0)); panel3.add(panel8, new com.intellij.uiDesigner.core.GridConstraints(0, 2, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); forwardsButton1 = new JButton(); forwardsButton1.setText("forwards"); panel8.add(forwardsButton1, BorderLayout.CENTER); final JPanel panel9 = new JPanel(); panel9.setLayout(new BorderLayout(0, 0)); panel3.add(panel9, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)); backwardsButton = new JButton(); backwardsButton.setText("backwards"); panel9.add(backwardsButton, BorderLayout.CENTER); final JPanel panel10 = new JPanel(); panel10.setLayout(new BorderLayout(0, 0)); rootpanel.add(panel10); } /** * @noinspection ALL */ public JComponent $$$getRootComponent$$$() { return rootpanel; } }
Python
UTF-8
3,401
2.765625
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt #from scipy.optimize import curve_fit grid = [] for k in list(np.round(np.logspace(0, 4))): if k not in grid: grid.append(k) msd = np.loadtxt('msd10.dat') food = np.loadtxt('food10.dat') diff = np.loadtxt('diff10.dat') corr1 = np.loadtxt('corr1_10.dat').reshape(45,10,10) corr2 = np.loadtxt('corr2_10.dat').reshape(45,20,20) escp = np.loadtxt('escp10.dat') diff_avg = diff.copy() for k in range(2,len(diff)-2): diff_avg[k] = (diff[k-2] + diff[k-1] + diff[k] + diff[k+1] + diff[k+2])/5.0 #plt.figure(num=1, figsize=(6, 10), dpi=80, facecolor='w', edgecolor='k') #plt.subplot(4,1,1) #plt.loglog(grid,msd,label='$F=5$',lw = 1.5) #plt.loglog(grid,grid,label='$F=0$',lw = 1.5) #plt.title('$10\%\ density\ on\ a\ free\ 100x100\ lattice$') ##plt.xlabel('$steps$', size = 15) #plt.ylabel('$msd$', size = 18) #plt.xticks(fontsize=15) #plt.yticks(fontsize=15) #plt.legend(fontsize=11) #plt.subplot(4,1,2) #plt.plot(grid,food/0.90483934**2) #plt.xscale('log') #plt.xlabel('$steps$', size = 15) #plt.ylabel('$food$', size = 18) #plt.xticks(fontsize=15) #plt.yticks(fontsize=15) #plt.subplot(4,1,3) #plt.plot(grid,corr1[:,0,0]/corr1[0,0,0]) #plt.xscale('log') #plt.xlabel('$steps$', size = 18) #plt.ylabel('$corr[0,0]$', size = 18) #plt.xticks(fontsize=15) #plt.yticks(fontsize=15) #plt.subplot(4,1,4) #plt.plot(grid, diff / msd * grid, label='$central\ difference$', lw=1.5) #plt.plot(grid, diff_avg / msd * grid, label='$local\ mean$', lw=1.5) #plt.legend(fontsize=11) #plt.xscale('log') #plt.xlabel('$steps$', size = 18) #plt.ylabel('$diff\ exponent$', size = 18) #plt.xticks(fontsize=15) #plt.yticks(fontsize=15) ##plt.savefig('abs1.pdf') plt.figure(num=2, dpi=80, facecolor='w', edgecolor='k') plt.plot(range(10),corr1[7,:,0]/corr1[0,0,0], label='$t=10$') plt.plot(range(10),corr1[20,:,0]/corr1[0,0,0], label='$t=110$') plt.plot(range(10),corr1[29,:,0]/corr1[0,0,0], label='$t=596$') plt.plot(range(10),corr1[32,:,0]/corr1[0,0,0], label='$t=1048$') plt.plot(range(10),corr1[44,:,0]/corr1[0,0,0], label='$t=10000$') plt.xlim(0,5) plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.legend(fontsize=11) plt.ylabel('$corr\ at\ fixed\ time$', size = 18) plt.xlabel('$\Delta x$', size=18) plt.title('$10x10\ Box$') plt.figure(num=3, dpi=80, facecolor='w', edgecolor='k') plt.plot(range(20),corr2[7,:,0]/corr2[0,0,0], label='$t=10$') plt.plot(range(20),corr2[20,:,0]/corr2[0,0,0], label='$t=110$') plt.plot(range(20),corr2[29,:,0]/corr2[0,0,0], label='$t=596$') plt.plot(range(20),corr2[32,:,0]/corr2[0,0,0], label='$t=1048$') plt.plot(range(20),corr2[44,:,0]/corr2[0,0,0], label='$t=10000$') plt.xlim(0,10) plt.xticks(fontsize=15) plt.yticks(fontsize=15) plt.legend(fontsize=11) plt.ylabel('$corr\ at\ fixed\ time$', size = 18) plt.xlabel('$\Delta x$', size=18) plt.title('$5x5\ Box$') plt.savefig('corr5.pdf') plt.figure(num=4, figsize=(6, 10), dpi=80, facecolor='w', edgecolor='k') plt.subplot(2,1,1) plt.title('$10\%\ density\ on\ a\ free\ 100x100\ lattice$') plt.loglog(grid,msd,label='$F=5$',lw = 1.5) plt.loglog(grid,grid,label='$F=0$',lw = 1.5) plt.ylabel('$msd$', size = 18) plt.legend() plt.subplot(2,1,2) plt.plot(grid, escp, label='$g_{0}(t)$') plt.xscale('log') plt.legend() plt.ylabel('$autocorrelation\ of\ steps$', size = 18) plt.xlabel('$steps$', size = 18) plt.savefig('autocorr.pdf')
PHP
UTF-8
3,054
3.328125
3
[]
no_license
<?php class Sudoku { private $_initial_board = []; private $_working_board = []; public function Sudoku($input_file) { $file = file_get_contents($input_file); $lines = explode("\n", $file); $i=0; foreach($lines as $line) { $this->_initial_board[$i++] = array_map('intval', explode(',',$line)); } $this->_working_board = $this->_initial_board; } public function print_result() { for($i=0;$i<9;$i++) { for($j=0;$j<9;$j++) { echo $this->_working_board[$i][$j]." "; } echo "\n"; } } public function validate_result() { return $this->_validate($this->_working_board); } public function solve() { $empty_cell = $this->_get_empty(); if($empty_cell !== null) { list($x, $y) = $empty_cell; $this->_try($x, $y); } $this->print_result(); } private function _validate_line(array $line) { $unique = array_unique($line); if(array_sum($unique) == array_sum($line)) { return true; } else { return false; } } private function _validate(array $array) { for($i=0;$i<9;$i++) { $validate_row = $this->_validate_line($array[$i]); $validate_column = $this->_validate_line(array_column($array,$i)); if(!$validate_column || !$validate_row) { return false; } } for($i=0;$i<3;$i++) { for($j=0;$j<3;$j++) { $square = [ $array[3*$i][3*$j], $array[3*$i][3*$j+1], $array[3*$i][3*$j+2], $array[3*$i+1][3*$j], $array[3*$i+1][3*$j+1], $array[3*$i+1][3*$j+2], $array[3*$i+2][3*$j], $array[3*$i+2][3*$j+1], $array[3*$i+2][3*$j+2], ]; if(!$this->_validate_line($square)) { return false; } } } return true; } private function _get_empty() { for($i=0;$i<9;$i++) { for($j=0;$j<9;$j++) { if($this->_working_board[$i][$j]===0) { return [$i, $j]; } } } return null; } private function _try($x, $y) { for($i=1; $i<=9; $i++) { $this->_working_board[$x][$y] = $i; if(!$this->_validate($this->_working_board)) { continue; } $empty_cell = $this->_get_empty(); if($empty_cell !== null) { list($m, $n) = $empty_cell; if($this->_try($m, $n)) { return true; } } else { return true; } } if($i==9 or $this->_get_empty()) { $this->_working_board[$x][$y] = 0; return false; } else { return true; } } }
Python
UTF-8
637
2.5625
3
[ "MIT" ]
permissive
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declared_attr from .config import Base class MenuCategory(Base): @declared_attr def event_id(cls): # Null for dining items because they don't belong to a specific event return Column(Integer, ForeignKey("campusEateryHours.id"), nullable=True) @declared_attr def eatery_id(cls): return Column(Integer, ForeignKey("campusEateryHours.eatery_id"), nullable=False) __tablename__ = "menuCategories" id = Column(Integer, nullable=False, primary_key=True) category = Column(String, nullable=False)
Markdown
UTF-8
2,619
3.171875
3
[]
no_license
# Challenge 1: Got Containers? [< Previous Challenge](./00-prereqs.md) - **[Home](../README.md)** - [Next Challenge >](./02-acr.md) ## Introduction The first step in our journey will be to take our application and package it as a container image using Docker. ## Demo Your coach will demonstrate running the application natively without using containers. ## Description In this challenge we'll use a Dockerfiles to build container images of our app, and we'll test them locally. Choice: you can choose to build the docker images locally on your workstation, or you can deploy a linux VM in Azure to act as your build server. ### Deploying and Access a Linux VM Build Server If you choose to use a VM in Azure, deploy the build machine VM with Linux + Docker using the provided ARM Template and parameters file in the "Student/Resources/Chapter 1/build-machine" folder of this repo. You can run the following script: ``` RG="akshack-RG" LOCATION="EastUS" # Change as appropriate az group create --name $RG --location $LOCATION az deployment group create --name buildvmdeployment -g $RG \ -f docker-build-machine-vm.json \ -p docker-build-machine-vm.parameters.json ``` You will then need to ssh into the machine (which is using port 2266): `ssh -p 2266 wthadmin@12.12.12.12 # replace 12.12.12.12 with the public IP of the vm` (Alternatively, you can use the VSCode Remote Shell extension to remotely access the VM) ### Building the Docker Image Our Fab Medical App consists of two components, a web component and an api component. Your task is to build containers for each of these. You have been provided source code (no need to edit) and a Docker file for each. ### Success Criteria - Build Docker images for both `content-api` and `content-web` - Run both containers you just built and verify that the app is working. - **Hint:** Run the containers in 'detached' mode so that they run in the background. - The content-web app expects an environment variable named `CONTENT_API_URL` that points to the API app's URL. - **NOTE:** The containers need to run in the same network to talk to each other. - Create a Docker network named "fabmedical" - Run each container using the "fabmedical" network - **Hint:** Each container you run needs to have a "name" on the fabmedical network and this is how you access it from other containers on that network. - **Hint:** You can run your containers in "detached" mode so that the running container does NOT block your command prompt. ## Learning Resources See Docker documentation: https://docs.docker.com/get-started/07_multi_container/
C
UTF-8
3,126
2.96875
3
[]
no_license
/******************************************************* * * * Full test case for addition of multi-dimensional * * arrays to Small C V2.0 using the modified * * CUG disk #163, and PC Club of Toronto #152. * * Release 1.01 * * - Don Lang 1/91 * *******************************************************/ #define LASTROW 1 #define CLOSELAST 2 /* Declaration required for c.lib */ extern int printf(); /* Test for global declaration of a 2-D array and for proper initialization. This will exercise the modified Small C functions, "declglb", "initials", and "addsym." Size of 1st dimension is determined by the number of initialized elements as per the C language definition. */ char garray[][2] = { 1, 2, 3, 4 }; int garray2 [3] [3]; /* Test to see that 1-D is unaffected. */ char gar1D[] = { 1,2 }; /* Try an external 2-D array of unknown size. */ /* (in file: ext.c) */ extern char ext2_D [] [CLOSELAST + 2]; main() { /* Declare local 2-D array and thus test the function "declloc" for 2-D. */ int i, k, count, larray[3][4]; count = 0; for (i = 0; i < 3; i++) for (k=0; k < 4; k++) { ext2_D[i][k] = larray[i][k] = count; count++; } /* The following strange code has been written to test the compiler's ability to correctly generate code for multi-dimensional array expressions using both variable and constant expressions as array indices. This, and the above nested "for" loop, will test the modifications to the Small-C expression analyzer; specifically the function "heir14." */ for (i=0; i<3; i++) { printf("\n"); printf(" %d ", larray[i][0]); printf(" %d ", larray[i][LASTROW]); printf(" %d ", larray[i][2]); printf(" %d ", larray[i][3]); } printf("\n"); printf("\n"); for (i=0; i<4; i++) printf(" %d ", larray[CLOSELAST-2][i]); printf("\n"); for (i=0; i<4; i++) printf(" %d ", larray[CLOSELAST/2][i]); printf("\n"); /* Try printing initialized global character array and the processed external. */ ga_print(2,2, garray); for (i=0; i<3; i+=1) { printf("\n"); for (k=0; k<4; k++) printf(" %d ", ext2_D[i][k]); } /* Print out 1-D array to see that it hasn't been changed by the modifications for "n" dimensions. */ printf("\n"); ga2_print(2, gar1D); } /* This global print function will test passing of array arguments, and thus the modified Small C function "doargs." */ ga_print (a,b, array) int a,b; char array[][2]; { int i,k; printf("\n"); i=0; while (i < a) { for(k=0; k<b; k++) printf(" %d ", array[i][k]); printf("\n"); i++; } } ga2_print (a, array) int a; char array[]; { int i; printf("\n"); for (i = 0; i < a; i++) printf(" %d ", array[i]); } 
C++
UTF-8
732
3.140625
3
[]
no_license
#pragma once #include <cstring> #include <stdexcept> #define DIM 4 class Matrix4x4 { public: Matrix4x4(); Matrix4x4(const float* m); Matrix4x4(const float m[DIM][DIM]); Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44); void Set(const float* m); void Set(size_t row, size_t col, float val); float Get(size_t row, size_t col) const; void GetRowMajor(float* m) const; void GetColumnMajor(float* m) const; bool IsRowColCorrect(size_t row, size_t col) const; private: float matrix[DIM][DIM]; public: static const Matrix4x4 Identity; static const Matrix4x4 Zero; };
PHP
UTF-8
1,428
2.578125
3
[]
no_license
<?php namespace Core; use Core\Auth; class View { public function __construct() { } public function render($template, $data = null, $layout = null) { $content = $this->getTemplatePath($template); if ($data) { extract($data); } if ($layout) { require $this->getTemplatePath($layout); } else { require $content; } } public function getTemplatePath($template) { return APP_DIR . '/../src/views/'.$template.'.php'; } // public static function renderController($action, $data = []) // { // list($class, $action) = explode(':', $action, 2); // $class = 'Controller\\' . $class . 'Controller'; // call_user_func_array(array(new $class(), $action), $data); // } public function path($name, array $parameters = []) { global $router; return $router->generate($name, $parameters); } public function url($name, array $parameters = []) { global $router; return $router->generate($name, $parameters, true); } public function getUser() { return Auth::user(); } public function hasFlash($alias) { return FlashBag::hasFlash($alias); } public function getFlash($alias) { return FlashBag::getFlash($alias); } }
C#
UTF-8
672
2.875
3
[]
no_license
string myXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine + "<!-- This is a comment -->" + Environment.NewLine + "<Root><Data>Test</Data></Root>"; System.Xml.XmlDocument xml = new System.Xml.XmlDocument(); xml.PreserveWhitespace = true; xml.LoadXml(myXml); var newElem = xml.CreateElement("Data"); newElem.InnerText = "Test 2"; xml.SelectSingleNode("/Root").AppendChild(newElem); System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings(); xws.Indent = true; using (System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(Console.Out, xws)) { xml.WriteTo(xw); }
C++
UTF-8
463
2.96875
3
[]
no_license
#include <Arduino.h> #include "USB_Serial.h" void USB_Serial_init(uint32_t baudRate) { Serial.begin(baudRate); } uint32_t USB_Serial_available() { return Serial.available(); } uint8_t USB_Serial_writeByte(uint8_t data) { return Serial.write(data); } size_t USB_Serial_writeBytes(uint8_t * data, size_t count) { return Serial.write(data, count); } void USB_Serial_flush() { Serial.flush(); } uint8_t USB_Serial_readByte() { return Serial.read(); }
Python
UTF-8
2,359
2.921875
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/12/22 17:57 # @Author : Python12_秋 # @Email : 793630871@qq.com # @File : mysql.py # @Software : PyCharm # @Explain : MYsql数据量链接 """ 1.链接数据库 2.编写sql 3.建立游标 4.执行 """ from common import http_path from common.Http_config import Reading import pymysql class MysqlUtill: def __init__(self): #获取配置文件里面的MySQL配置 config = Reading(http_path.config_path_control) host = config.get('MYSQL', 'Host_name') port = config.get_int('MYSQL', 'port') #port是一个数字,使用getint user = config.get('MYSQL', 'user') pwd = config.get('MYSQL', 'pwd') try: self.mysql = pymysql.connect(host=host, user=user, password=pwd, database='future',port=port,cursorclass=pymysql.cursors.DictCursor) #cursorclass=pymysql.cursors.DictCursor 返回字典格式 except BaseException as e: print("数据库链接异常:{}".format(e)) raise e def get_fetch_one(self,sql): #查询一条数据并返回数据 cursor = self.mysql.cursor() #建立游标 cursor.execute(sql) #根据sql进行查询 date = cursor.fetchone() #返回一条数据 #max_phone = eval(phone["MobilePhone"]) + 1 #字符串格式 return date def get_fetch_all(self,sql): cursor = self.mysql.cursor() # 建立游标 cursor.execute(sql) # 根据sql进行查询 date = cursor.fetchall() # 返回多条数据,如获取用户列表,标列表等 #max_phone = (phone[0]) + 1 # 返回的是元组嵌套格式 return date def get_fetch_many(self,sql): cursor = self.mysql.cursor() # 建立游标 cursor.execute(sql) # 根据sql进行查询 date = cursor.fetchmany() # 指定返回多少条数据 #max_phone = eval(phone[0]) + 1 return date if __name__ == '__main__': sql = 'SELECT Id FROM financelog WHERE IncomeMemberId =(SELECT Id FROM member WHERE MobilePhone = 18999999653) ORDER BY Id DESC' print(sql) m = MysqlUtill().get_fetch_one(sql=sql) #结果是元组 print(type(m),m)
Java
UTF-8
3,528
2.28125
2
[]
no_license
package edu.uapa.ui.gamify.views.security; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.ComponentEventListener; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dependency.HtmlImport; import com.vaadin.flow.component.polymertemplate.Id; import com.vaadin.flow.component.polymertemplate.PolymerTemplate; import com.vaadin.flow.component.textfield.EmailField; import com.vaadin.flow.component.textfield.PasswordField; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.templatemodel.TemplateModel; import edu.uapa.ui.gamify.models.interfaces.FormStructure; import edu.uapa.ui.gamify.utils.captions.Captions; import edu.utesa.lib.models.dtos.security.UserDto; import edu.utesa.lib.models.enums.Language; /** * A Designer generated component for the user-form-design template. * <p> * Designer will add and remove fields with @Id mappings but * does not overwrite or otherwise change this file. */ @Tag("user-form-design") @HtmlImport("src/views/security/user-form-design.html") public class UserFormDesign extends PolymerTemplate<UserFormDesign.UserFormDesignModel> implements FormStructure<UserDto> { @Id("tfUserName") private TextField tfUserName; @Id("pfPassword") private PasswordField pfPassword; @Id("cbLanguage") private ComboBox<Language> cbLanguage; @Id("efEmail") private EmailField efEmail; @Id("btnPermission") private Button btnPermission; /** * Creates a new UserFormDesign. */ public UserFormDesign() { tfUserName.setLabel(Captions.USER_NAME); tfUserName.setRequired(true); pfPassword.setLabel(Captions.PASSWORD); pfPassword.setRequired(true); cbLanguage.setLabel(Captions.LANGUAGE); cbLanguage.setRequired(true); efEmail.setLabel(Captions.EMAIL); btnPermission.setText(Captions.PERMISSION); this.getElement().getStyle().set("max-width", "720px"); setAction(); } public void setPermissionAction(ComponentEventListener<ClickEvent<Button>> clickEvent) { btnPermission.addClickListener(clickEvent); } private void setAction() { cbLanguage.setItems(Language.values()); } @Override public void restore(UserDto data) { tfUserName.setValue(data.getNickName()); pfPassword.setValue("qwerty"); cbLanguage.setValue(data.getLanguage()); efEmail.setValue(data.getMail()); } @Override public void visualize() { tfUserName.setReadOnly(true); pfPassword.setReadOnly(true); cbLanguage.setReadOnly(true); efEmail.setReadOnly(true); } @Override public boolean validField() { return !tfUserName.isInvalid() && !pfPassword.isInvalid() && !cbLanguage.isInvalid() && !efEmail.isInvalid(); } @Override public UserDto collectData(UserDto model) { model.setNickName(tfUserName.getValue()); model.setPassword(pfPassword.getValue()); model.setLanguage(cbLanguage.getValue()); model.setMail(efEmail.getValue()); return model; } @Override public void security() { } /** * This model binds properties between UserFormDesign and user-form-design */ public interface UserFormDesignModel extends TemplateModel { // Add setters and getters for template properties here. } }
SQL
UTF-8
4,552
3.1875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 18-04-2019 a las 14:27:44 -- Versión del servidor: 10.1.38-MariaDB -- Versión de PHP: 7.3.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `serviciotecnico` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `item` -- CREATE TABLE `item` ( `cod_item` int(11) NOT NULL, `descripcion` varchar(150) NOT NULL, `precio unitario` double NOT NULL, `cantidad` int(11) NOT NULL, `contado` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `niveles` -- CREATE TABLE `niveles` ( `cod_nivel` int(11) NOT NULL, `nombre_nivel` varchar(150) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `niveles` -- INSERT INTO `niveles` (`cod_nivel`, `nombre_nivel`) VALUES (3, 'ADMINISTRADOR'), (2, 'SECRETARIA'), (1, 'TECNICO'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `presupuesto` -- CREATE TABLE `presupuesto` ( `num_presupuesto` int(11) NOT NULL, `nombre` varchar(70) NOT NULL, `fecha` date NOT NULL, `forma_pago` varchar(120) DEFAULT NULL, `total` double NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `presupuesto_item` -- CREATE TABLE `presupuesto_item` ( `num_presupuesto` int(11) NOT NULL, `cod_item` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuarios` -- CREATE TABLE `usuarios` ( `dni_usuario` int(11) NOT NULL, `contrasenia` varchar(255) NOT NULL, `nombre` varchar(150) NOT NULL, `apellido` varchar(60) NOT NULL, `cod_nivel` int(11) DEFAULT NULL, `estado_usuario` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuarios` -- INSERT INTO `usuarios` (`dni_usuario`, `contrasenia`, `nombre`, `apellido`, `cod_nivel`, `estado_usuario`) VALUES (12345678, '123456', 'admin', 'admin', 3, 'ONLINE'), (15654456, '123456', 'Carlos', 'Massera', 4, 'ONLINE'), (16660440, '123456', 'Pablo Emilio', 'Escobar', 1, 'ONLINE'), (31456665, '123456', 'Roberto Alsides', 'Robles', 2, 'ONLINE'), (34456123, '123456', 'Carla', 'Gomez', 1, 'ONLINE'), (45454545, '123456', 'leonel', 'ramirez', 2, 'ONLINE'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `item` -- ALTER TABLE `item` ADD PRIMARY KEY (`cod_item`); -- -- Indices de la tabla `niveles` -- ALTER TABLE `niveles` ADD PRIMARY KEY (`cod_nivel`), ADD UNIQUE KEY `nombre_nivel` (`nombre_nivel`); -- -- Indices de la tabla `presupuesto` -- ALTER TABLE `presupuesto` ADD PRIMARY KEY (`num_presupuesto`); -- -- Indices de la tabla `presupuesto_item` -- ALTER TABLE `presupuesto_item` ADD KEY `num_presupuesto` (`num_presupuesto`), ADD KEY `cod_item` (`cod_item`); -- -- Indices de la tabla `usuarios` -- ALTER TABLE `usuarios` ADD PRIMARY KEY (`dni_usuario`), ADD KEY `cod_nivel` (`cod_nivel`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `item` -- ALTER TABLE `item` MODIFY `cod_item` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `niveles` -- ALTER TABLE `niveles` MODIFY `cod_nivel` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `presupuesto` -- ALTER TABLE `presupuesto` MODIFY `num_presupuesto` int(11) NOT NULL AUTO_INCREMENT; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `presupuesto_item` -- ALTER TABLE `presupuesto_item` ADD CONSTRAINT `presupuesto_item_ibfk_1` FOREIGN KEY (`num_presupuesto`) REFERENCES `presupuesto` (`num_presupuesto`), ADD CONSTRAINT `presupuesto_item_ibfk_2` FOREIGN KEY (`cod_item`) REFERENCES `item` (`cod_item`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
TypeScript
UTF-8
241
2.59375
3
[]
no_license
import { Injectable } from "@angular/core"; //a service is just a normal TypeScript class @Injectable() export class LoggingService { logStatusChange(status: string){ console.log('Ammm server status changed, new status: ' + status); } }
Swift
UTF-8
1,628
3.140625
3
[]
no_license
// // PACServices.swift // PR3 // // Copyright © 2018 UOC. All rights reserved. // import Foundation class Services { static var storedMovements: [Movement]? static func validate(username: String, password: String) -> Bool { if (username == "uoc" && password == "1234") { return true; } else { return false; } } static func validate(code: String) -> Bool { if (code == "1234") { return true; } else { return false; } } static func calculateFinalAmount(ForAmount amount: Float, WithInterest interest: Double, AndYears years: Double) -> Double { let final = Double(amount) * pow(1 + Double(interest), Double(years)) return final } static func getMovements() -> [Movement] { // Provide a seed to generate predictable but random Movements srandom(10) if let movements = storedMovements { return movements } else { Services.storedMovements = [Movement]() for i:Int in 1...50 { var date: Date if i <= 4 { date = Date() } else { date = Calendar.current.date(byAdding: .day, value: -i, to: Date()) ?? Date() } let movement = Movement(random: true, date: date) Services.storedMovements?.append(movement) } return Services.storedMovements ?? [Movement]() } } }
C++
UTF-8
2,358
3.296875
3
[]
no_license
#ifndef __SDR_LOGGER_HH__ #define __SDR_LOGGER_HH__ #include <string> #include <sstream> #include <list> namespace sdr { // DIFFERENT TYPES of LOG MESSAGES typedef enum { LOG_DEBUG = 0, // Everything that may be of interest LOG_INFO, // Messages about state changes LOG_WARNING, // Non-critical errors LOG_ERROR // Critical error } LogLevel; // Log Message class LogMessage: public std::stringstream { public: // Constructor with log level and message LogMessage(LogLevel level, const std::string &msg=""); // Contructor from another log message LogMessage(const LogMessage &other); // Destructor virtual ~LogMessage(); // Methods // Returns level of message LogLevel level() const; // Returns the message inline std::string message() const { return this->str(); } protected: LogLevel _level; }; // Log Handler (base class) class LogHandler { protected: // Hidden constructor LogHandler(); public: // Destructor virtual ~LogHandler(); // Needs to be implemented by sub-classes to handle log messages virtual void handle(const LogMessage &msg) = 0; }; // Serializes log message into the specified stream class StreamLogHandler: public LogHandler { public: // Constructor with specified stream, messages are serializes into // level specifies the minimum log level of the message being serialized StreamLogHandler(std::ostream &stream, LogLevel level); // Destructor virtual ~StreamLogHandler(); // Handle methods virtual void handle(const LogMessage &msg); protected: // Output stream std::ostream &_stream; // Minimum log level LogLevel _level; }; // Logger class class Logger { protected: // Hidden constructor Logger(); public: // Destructor virtual ~Logger(); // Returns the singleton instance of the logger static Logger &get(); // Log method: log a message void log(const LogMessage &message); // message handler void addHandler(LogHandler *handler); protected: // the singleton instance static Logger *_instance; // registered handler std::list<LogHandler*> _handler; }; } #endif
Shell
UTF-8
2,259
3.453125
3
[]
no_license
#!/bin/bash red=`tput setaf 1` reset=`tput sgr0` cur_dir="$(pwd)" action=$1 bench=$2 if [ "$3" != "" ]; then individual=$3 else individual=all fi #check if additional arguments are given; otherwise use defaults. if [ "$bench" == "spec2006" ] || [ "$bench" == "spec2017" ]; then if [ "$4" != "" ]; then tune=$4 else tune=peak fi if [ "$5" != "" ]; then size=$5 else size=ref fi elif [ "$bench" == "nas" ]; then if [ "$4" != "" ]; then class=$4 else class=A fi else "error: non-existent scalar benchmark" exit 1 fi if [ "$bench" == "spec2006" ]; then echo "${red}running spec2006 benchmarks${reset}" cd spec2006-install . ./shrc if [ $SPEC2006_CONFIG == "" ]; then echo "error specify spec2006 config using env var SPEC2006_CONFIG" exit fi if [ "$action" == "build" ]; then FC1=$FC CC1=$CC CXX1=$CXX runspec --config=$SPEC2006_CONFIG --action=scrub --noreportable --tune=$tune --size=$size $individual fi FC1=$FC CC1=$CC CXX1=$CXX runspec --config=$SPEC2006_CONFIG --action=$action --noreportable --tune=$tune --size=$size $individual elif [ "$bench" == "spec2017" ]; then echo "${red}running spec2017 benchmarks${reset}" cd spec2017-install . ./shrc if [ $SPEC2017_CONFIG == "" ]; then echo "error specify spec2017 config using env var SPEC2017_CONFIG" exit fi if [ "$action" == "build" ]; then FC1=$FC CC1=$CC CXX1=$CXX runcpu --config=$SPEC2017_CONFIG --action=scrub --noreportable --tune=$tune --size=$size $individual fi FC1=$FC CC1=$CC CXX1=$CXX runcpu --config=$SPEC2017_CONFIG --action=$action --noreportable --tune=$tune --size=$size $individual elif [ "$bench" == "nas" ]; then echo "${red}running nas benchmarks${reset}" cd NPB3.0-omp-C mkdir -p bin if [ "$individual" == "all" ]; then nas="bt sp lu mg ft is cg ep" else nas=$individual fi if [ "$action" == "build" ]; then make clean fi if [ "$action" == "build" ] || [ "$action" == "run" ]; then for bench in $nas; do CFLAGS1=$CFLAGS make $bench CLASS=$class done fi if [ "$action" == "run" ]; then for bench in $nas; do ./bin/$bench.$class done fi fi cd $cur_dir
SQL
UTF-8
3,718
2.609375
3
[]
no_license
INSERT INTO tweet (id_parent, id_user, text, timestamp) VALUES (0, 1, 'This is my first twitter! Yeah!', '2019-05-03 13:44:03'), (0, 1, 'Hello Twitter', '2019-05-03 13:45:03'), (0, 1, 'Today is a great day!', '2019-05-03 13:46:03'), (0, 1, 'Cant wait til summer!!!', '2019-05-03 13:50:03'), (0, 1, 'Im bored!', '2019-05-03 13:51:03'), (0, 1, 'Whats 2+2?', '2019-05-03 12:52:03'), (0, 1, 'Im like to eat kebab', '2019-05-03 13:53:03'), (0, 1, 'Programming in spring boot is fun', '2019-05-03 13:55:03'), (0, 1, 'hehehehe, im drunk', '2019-05-03 13:57:03'), (0, 1, 'Donald Trump for prezzz', '2019-05-03 14:00:03'), (0, 2, 'Going to Japan this easter! Konnichiwa!', '2019-05-03 14:00:05'), (0, 2, 'Tokyo is amazing!!', '2019-05-03 14:03:03'), (0, 2, 'Kyoto is a cool city!', '2019-05-03 14:05:03'), (0, 2, 'Cant wait til summer!!!', '2019-05-03 14:11:03'), (0, 2, 'Im bored!', '2019-05-03 14:25:03'), (0, 2, 'This is my first twitter! Yeah!', '2019-05-03 14:26:03'), (0, 2, 'Hello Twitter', '2019-02-03 15:00:03'), (0, 2, 'Today is a great day!', '2019-02-04 14:00:03'), (0, 2, 'Cant wait til summer!!!', '2019-01-05 14:00:03'), (0, 2, 'aloe vera is good for tha skin', '2019-01-05 16:00:03'), (0, 3, '#Bærum Politiet har kommet over russebuss som tidligere har fått en advarsel vedr. støy. Den støyet fortsatt og vi har tatt en vital del av musikkanlegget.', '2019-04-05 16:00:04'), (0, 3, 'Vi har fått personen ned fra taket i god behold.', '2019-04-05 16:15:03'), (0, 3, 'How about you watch your ugly lookin mouth when you talk to the two time.', '2019-03-05 17:00:03'), (0, 3, 'Now that firestorm has duos and can replace fortnite. Let''s do a duo triple threat challenge like we talked about. DMs for the date and time.', '2019-03-05 16:00:03'), (0, 3, 'Watch Litecoin surviving the test of time. It''s not easy fighting off all the shitcoins and scamcoins to stay in the top 10. ', '2019-03-05 20:00:03'), (0, 3, 'OKEx will support the airdrops for USDT-TRC20 holders. You can convert your USDT to USDT-TRC20 in your Assets Account to receive the bonus.', '2019-02-05 00:00:03'), (0, 3, 'My kids enjoying watching the 2x while I make them a filet mignon dinner. @drdisrespect They are learning how to hit that 360 shot and how to be on top of that mountain, but only half way up.', '2019-02-05 16:00:03'), (0, 3, '#Consensus2019 discount codes are bigger than actual ticket prices for @magicalcrypto conference', '2019-02-05 16:00:03'), (0, 3, 'I have to say this newly launched live SLOTS game is crazy! ', '2019-01-05 16:00:03'), (0, 3, 'aloe vera is good for tha skin', '2019-01-05 20:00:03'), (0, 4, 'Violence. SPEED. Momentum.” - Heading into Game 1 ', '2019-04-05 16:12:03'), (0, 4, 'Festen er avsluttet og det ble gitt pålegg om å holde ro.', '2019-04-05 16:15:03'), (0, 4, 'mmmmmRecapitashe?!?!?! LIVE ETA 30ish Mins!', '2019-03-05 14:12:03'), (0, 4, 'Air-drop for voters , 2000 TONE will be airdrop for voters this week ! Cheers ! Celebrate for TRON-ONE CONTENT PROTOCAL !', '2019-03-05 12:05:03'), (0, 4, 'We have recorded the highest transaction volume and transaction within 24hours from launch! :)', '2019-03-05 13:00:03'), (0, 4, 'Guests get a random one in their swag bags. VIPs get a set of 4 with matching serial numbers! 😮', '2019-02-05 16:00:03'), (0, 4, 'Thanks for the support to #TRC20 based #USDT from VenaPi. #TRON #TRX $USDT', '2019-02-05 10:00:03'), (0, 4, 'It''s a 150 billion dollar industry. Where are the quality competitive shooter games?', '2019-01-05 05:00:03'), (0, 4, 'This will be the Mans who Bodies The Night King', '2019-01-05 13:13:03'), (0, 4, 'En person letter skadd som kjøres til legevakten av ambulanse. Politiet oppretter sak på forholdet.', '2019-01-06 16:45:03');
JavaScript
UTF-8
959
2.59375
3
[]
no_license
function validateForm() { var a = document.forms["rreg"]["rname"].value; var b = document.forms["rreg"]["rpass1"].value; var c = document.forms["rreg"]["rpass2"].value; var d = document.forms["rreg"]["rmail"].value; var e = document.forms["rreg"]["rmobile"].value; var f = document.forms["rreg"]["rsecques"].value; if(a == null || a == "") { alert("Enter UserName"); return false; } else if (b == null || b == "") { alert("Enter Password"); return false; } if(c == null || c == "") { alert("Enter Confirm Password"); return false; } else if (b != c) { alert("Passwords Donot Match"); return false; } if(d == null || d == "") { alert("Enter E-Mail Address"); return false; } else if (e == null || e == "") { alert("Enter Mobile Number"); return false; } if(b == null || b == "") { alert("Enter Answer"); return false; } else { return true; } return false; }
Markdown
UTF-8
9,541
3.109375
3
[ "MIT" ]
permissive
## 这是关于 store 相关的使用介绍 #### createStore(mixin?: Function, hooks?: Object, Options?: Object) : Store store 是通过 `mp-store` 导出的 `createStore` 这个方法来创建的,这个方法接受三个参数 + 第一个参数为 [`mixin`](./mixin.md) 的注入函数 + 第二个参数为 [`hooks`](./hooks.md) + 第三个参数为 `options` store 会把原生的 `Page`、`Component` 函数包装一层,来做一层拦截,这样 store 就可以收集到所有使用到全局状态的组件,也就是收集依赖。这也就是为什么 store 对原有的功能不影响的原因,下面是 store 的一些介绍 + `每个 store 拥有唯一的 id,可以通过 store.id 拿到` + `store 的 state 是不可变的,所以你不能这样操作 this.store.state.xx = 1` + `store 会把用到的全局状态放到所用到的 data 中去,默认的命名空间是 global,所以你可以这样在组件中拿到当前所用到的全局状态 this.data.global,如果与原有的项目有冲突,你可以在 App 初始化之前调用 setNamespace 方法更改为其他的名字` + `store 会在 onLoad 和 attached 被调用之前被注入进实例中,依赖的收集也是在这个时间进行的` + `store 会被注入到 page 和 component 示例中,所以你可以通过 this.store 来拿到 store` ### Options + `env: 'develop' | 'product'`: 如果指定为 `product`,会去掉状态和模块合并时的检测,state 将不会被冻结住,从而提升性能 + `storeNamespace: string`: 可以指定注入到组件内部的 store 命名空间,默认为 `store` + `globalNamespace: string`: 可以指定注入到组件 data 中使用的全局状态命名空间,默认为 `global` ### 启动 ```js import createStore from '@ruslte/mp-store' const store = createStore(() => {}, {}) ``` ### API + `store.add` + `store.dispatch` + `store.restore` + `store.forceUpdate` + `store.use` + `store.setNamespace` + `store.getModule` + `store.addModule` #### add(action: string | symbol, reducer: Object) : void `add` 方法用于添加一个 `reducer`, `action` 是唯一的,如果有重复,将会报错,`reducer` 的类型如下 ```ts interface Reducer{ namespace?: string partialState?: Object setter?: (state: module, payload: any, rootState?: Store['state'] ) : Object } ``` `partialState` 定义的状态将被合并到全局状态,如果里面包含着全局状态已有的字段,是不被允许的,`setter` 函数可以用来返回一个对象,这个对象将被合并到全局状态中 ```js store.add('action', { partialState: { name: 'tao', }, setter (state, payload) { return { name: payload } }, }) console.log(store.state.name) // 'tao' store.dispatch('action', 'imtaotao') console.log(store.state.name) // 'imtaotao' ``` #### dispatch(action: string | symbol, payload: any, callback?: destPayload => void) : void `dispatch` 方法用于触发一个 `action`,他会调用所有的中间件,最后在调用 `reducer` 的 `setter` 函数,你将不能在 `setter` 函数中调用 `dispatch` 方法,以下的写法将会报错。这样做的愿意是为了避免逻辑过于混乱,但你可以在中间件中调用 `dispatch` ```js store.add('action', { partialState: { name: 'tao', }, setter (state, payload) { store.dispatch('xx') // 这一句将会报错 return { name: payload } }, }) store.dispatch('action', 'imtaotao') ``` `dispatch` 这个行为触发时,对 store 的状态更改是同步的,对视图的更新是异步的。mpStore 对视图的更新是批量的 ```js store.add('action', { partialState: { name: 'chen', }, setter (state, payload) { return { name: payload } }, }) Page({ storeConfig: { useState (store) { return ({ name: state => state.name, }) }, }, onLoad() { this.data.global.name // 'chen' this.store.dispatch('action', 'tao', () => { // 或者在回调里面拿到最新的值 this.data.global.name // 'tao' }) this.data.global.name // 'chen',store 的更新是同步的 this.store.state.name // 'tao' // 由于视图的更新是异步的,所以可以这样 setTimeout(() => { this.data.global.name // 'chen' }) } }) ``` `callback` 方法会在 `store.state` 改变后,所有依赖的组件更新后(包括视图)调用,因为**中间件中可能会处理异步行为**,所以这个 `callback` 的存在是必要的 ```js store.add('action', { partialState: { name: 'tao', }, setter (state, payload) { return { name: payload } }, }) store.use((payload, next) => { setTimeout(next(payload)) }) console.log(store.state.name) // 'tao' store.dispatch('action', 'imtaotao', () => { console.log(store.state.name) // 'imtaotao' }) console.log(store.state.name) // 'tao' ``` #### restore(action: string | symbol, callback: initState => void, notUpdate?: boolean) : void `restore` 会将定义的 reducer 恢复到初始状态。通常的情况下,我们需要在组件卸载时,及时清空相应的状态,为此而定义对应的 reducer,这一步完全可以由 mpStore 来做,所以这也是 `restore` 这个 api 出现的原因。`restore` 恢复为初始状态时,也会去异步更新依赖的组件,第二个参数与 `dispatch` 方法中的 callback 基本一致,除了接受的参数为初始状态之外,用法如下: ```js store.add('action', { partialState: { name: 'tao' }, setter (state, payload) { return { name: payload } } }) store.dispatch('action', 'chen', () => { store.state.name // 'chen' store.restore('action', initState => { initState // { name: 'tao' } store.state.name // 'tao' }) }) ``` 如果你希望在恢复初始状态后,不需要更新视图的变化,可以将 `notUpdate` 传为 `true` #### forceUpdate() : void `forceUpdate` 会强制所有依赖的组件走一遍 diff -> patch 的过程,从而更新视图,当你用的这个方法时,99% 都是你自己的代码写的有问题。 #### setNamespace(namespace: string) : void store 默认会在组件的 data 中添加 `global` 来接受用到的全局状态,如果需要更改,可以通过此方法。需要注意的是你必须在 `App` 初始化之前调用(此方法已经被弃用,请使用 options.globalNamespace 替换) ```js store.setNamespace('xxx') App({ // ... }) ``` #### use(action: string | symbol | array | Function, layer?: Function) : Function `use` 方法用来添加中间件,中间件的详细文档在[这里](./middleware.md)可以看到。如果只传了一个参数,则默认拦截所有的 `action`,也可以传一个数组,选择性的拦截你想要的 action。use 方法会返回一个 remove 函数,用来注销掉当前添加的中间件 ```js // 将会拦截 `changed` 这个 action // 中间件的添加顺序为执行顺序,所以你必须调用 next,否则,后面添加的中间件将不会执行 const remove = store.use('changed', (payload, next) => { payload++ next(payload) }) ``` 如果是一个数组,则会选择性的拦截 ```js const remove = store.use(['one', 'two'], (payload, next, action) => { payload++ next(payload) }) ``` 下面这种语法将会拦截所有的 `action` ```js const remove = store.use((payload, next, action) => { if (action === 'changed') { payload++ next(payload) } }) // 注销掉中间件 remove() ``` ### getModule(namespace: string) : Module `getModule` 可以根据 namespace 得到一个 module,如果 namespace 为一个空字符串,则会返回 rootModule(就是全局 state) ```js store.add('action', { namespace: 'a.b', partialState: { name: 'tao' }, }) const module = store.getModule('a.b') console.log(module) // { name: 'tao' } console.log(module === store.state.a.b) // true ``` ### addModule(namespace: string, reducers: Object) : void `addModule` 用于添加一个模块,也是添加多个 reducer,共用一个 namespace,底层也是调用 `store.add` 方法,所以这只是一个语法糖,你也可以自己封装一套你自己熟悉的语法 ```js const s = Symbol() store.addModule('a.b', { // key 作为 action, value 作为 reducer [s]: { partialState: { name: 'tao' }, setter (state, payload) {}, }, 'action': { partialState: { age: 24 }, setter (state, payload) {}, }, }) console.log(store.state) // { a: { b: { name: 'tao', age: 24 } } } ``` ### 数据不可变 整个 store 拥有一个唯一的 state,这个全局 state 是不可变的,所以在 store 中,数据的转换都是通过深拷贝来进行的,这带来了一定的性能消耗,但为了数据不被污染,牺牲一定的性能是值得的,为此,mpstore 暴露出来了一个 `clone` 方法。需要注意的是,这个方法会深拷贝数据,并允许拷贝循环引用的数据结构 ```js import createStore, { clone } from '@ruslte/mp-store' const newData = clone({ ... }) ```
Python
UTF-8
9,079
2.984375
3
[]
no_license
#Import libraries import pygame, os, sys from pygame.locals import * from time import sleep from math import sin, cos, atan, atan2, radians, degrees, pi, sqrt from random import randint pygame.init() #Start pygame pygame.mixer.init() #Start pygame mixer #Functions def parabolic_shot(arrow, arrow_copy, velocity, arrow_rect, angle, GRAVITY): angle_atan = -atan(velocity[1]/velocity[0]) center_original = arrow_rect.center if angle <= 90 or angle > 270: arrow = pygame.transform.rotate(arrow_copy, degrees(angle_atan)) else: arrow = pygame.transform.rotate(arrow_copy, degrees(angle_atan)+180) arrow_rect = arrow.get_rect() arrow_rect.center = center_original velocity[1] += GRAVITY arrow_rect.center = [arrow_rect.center[0] + velocity[0], arrow_rect.center[1] + velocity[1]] return arrow, arrow_rect def initialization_variables_parabolic_shot(velocity, angle): velocity_arrow_x = cos(radians(angle)) * velocity velocity_arrow_y = sin(radians(angle)) * velocity velocity_x = +velocity_arrow_x velocity_y = -velocity_arrow_y velocity = [velocity_x, velocity_y] return velocity def calculate_angle(point_1, point_2): x = point_2[0] - point_1[0] y = point_2[1] - point_1[1] angle = abs(degrees(atan2(y,x))- 180) return angle def calculate_distance(point_1, point_2): x = point_2[0] - point_1[0] y = point_2[1] - point_1[1] distance = sqrt(x**2+y**2) return distance def rotate_image(screen, image, pos, originPos, angle): w, h = image.get_size() box = [pygame.math.Vector2(p) for p in [(0, 0), (w, 0), (w, -h), (0, -h)]] box_rotate = [p.rotate(angle) for p in box] min_box = (min(box_rotate, key=lambda p: p[0])[0], min(box_rotate, key=lambda p: p[1])[1]) max_box = (max(box_rotate, key=lambda p: p[0])[0], max(box_rotate, key=lambda p: p[1])[1]) pivot = pygame.math.Vector2(originPos[0], -originPos[1]) pivot_rotate = pivot.rotate(angle) pivot_move = pivot_rotate - pivot origin = (pos[0] - originPos[0] + min_box[0] - pivot_move[0], pos[1] - originPos[1] - max_box[1] + pivot_move[1]) rotated_image = pygame.transform.rotate(image, angle) screen.blit(rotated_image, origin) def choose_operation(): option = randint(1,3) n1 = randint(1,99) n2 = randint(1,99) operator = '' a = 0 if option == 1: a = n1 + n2 operator = '+' elif option == 2: a = n1 - n2 operator = '-' elif option == 3: n1 = randint(1,10) n2 = randint(1,20) a = n1 * n2 operator = 'x' return n1,n2,operator,a def collision_rect(arrow_rect, block_rect): ar = pygame.Rect(arrow_rect.center[0] + 5,arrow_rect.center[1]+10, 120,9) collision = False z = None for y in range(12): if ar.colliderect(block_rect[y]): print("\nBloque "+str(y+1)+": ") collision = True z = y return collision, z return collision, z def save_time(minutes, seconds): time = [str(minutes), str(seconds)] outFile = open('dataTime.txt', 'w') for d in time: outFile.write(d+"\n") outFile.close() def load_time(): inFile = open('dataTime.txt', 'r') loaded_time = [] for line in inFile: loaded_time.append(int(line.strip())) inFile.close() return loaded_time #Constants SCREEN_SIZE = 800, 600 GRAVITY = 0.2 FPS = 60 screen = pygame.display.set_mode((SCREEN_SIZE)) pygame.display.set_caption("Math Arrow") background = pygame.image.load("Sprites/background.jpg").convert() arrow = pygame.sprite.Sprite() arrow = pygame.image.load("Sprites/arrow.png").convert_alpha() block = pygame.sprite.Sprite() block = pygame.image.load("Sprites/block.png").convert_alpha() block = pygame.transform.scale(block, (50, 50)) arrow_sound = pygame.mixer.Sound("Sounds/arrow_shot.wav") correct_sound = pygame.mixer.Sound("Sounds/correct.wav") incorrect_sound = pygame.mixer.Sound("Sounds/incorrect.wav") #Lists start_point = [] end_point = [] velocity = [] block_rect = [] index_block = [] loaded_time = [] aux_position_block = [(520,15), (520,115), (520,215), (520,315), (520,415), (520,515), (670,15), (670,115), (670,215), (670,315), (670,415), (670,515)] position_block = [(520,15), (520,115), (520,215), (520,315), (520,415), (520,515), (670,15), (670,115), (670,215), (670,315), (670,415), (670,515)] block = [block] * 12 #Variables position_initial_arrow =(45,285) velocity_arrow = 0 arrow_copy = arrow.copy() arrow_rect = arrow.get_rect() arrow_rect.center = position_initial_arrow angle = 0 w, h = arrow.get_size() draw_line = False shoot = False initialization = True arrow_visible = True rotate_arrow = True operation = True collision = False frames = 0 minutes = 0 seconds = 0 clock = pygame.time.Clock() for j in range(12): br = pygame.Rect((position_block[j]), (50,50)) block_rect.append(br) while True: clock.tick(FPS) frames += 1 if frames == 60: frames = 0 seconds += 1 if seconds == 60: seconds = 0 minutes += 1 screen.blit(background, (0,0)) for i in range(12): screen.blit(block[i], position_block[i]) block_rect[i] = pygame.Rect((position_block[i]), (50, 50)) if arrow_rect.right >= 500: collision, z = collision_rect(arrow_rect, block_rect) if collision: arrow = arrow_copy shoot = False initialization = True rotate_arrow = True n1,n2,operator,a = choose_operation() answer = int(input(str(n1)+" "+operator+" "+str(n2)+" = ")) if answer == a: correct_sound.play() print("¡Correcto!") position_block[z] = (1000, 1000) index_block.append(z) if len(index_block) == 12: print("\n¡Felicidades has ganado!") loaded_time = load_time() if loaded_time[0] > minutes: print("¡Nuevo record!") save_time(minutes, seconds) elif loaded_time[0] == minutes and loaded_time[1] > seconds: print("¡Nuevo record!") save_time(minutes, seconds) print("Tiempo final: ", end="") if minutes < 10 and seconds < 10: print("0"+str(minutes)+":0"+str(seconds)) elif minutes < 10: print("0"+str(minutes)+":"+str(seconds)) elif seconds < 10: print(str(minutes)+":0"+str(seconds)) else: print(str(minutes)+":"+str(seconds)) sys.exit() else: incorrect_sound.play() print("¡Incorrecto!") if len(index_block) != 0: position_block[index_block[len(index_block)-1]] = aux_position_block[index_block[len(index_block)-1]] index_block.pop(len(index_block)-1) for event in pygame.event.get(): if event.type == pygame.QUIT or pygame.key.get_pressed()[pygame.K_ESCAPE]: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: start_point = event.pos if event.type == pygame.MOUSEMOTION and event.buttons[0] == 1: end_point = event.pos draw_line = True if event.type == pygame.MOUSEBUTTONUP: arrow_sound.play() draw_line = False shoot = True if draw_line and rotate_arrow: distance = calculate_distance(start_point, end_point) pygame.draw.aaline(screen, (0,0,0),(start_point), (end_point), 1) angle = calculate_angle(start_point, end_point) pos = (100, 300) rotate_image(screen, arrow, pos, (w/2, h/2), angle) if distance > 300: velocity_arrow = 15 else: velocity_arrow = distance * 0.05 else: if shoot == True: if initialization == True: velocity = initialization_variables_parabolic_shot(velocity_arrow, angle) initialization = False if arrow_rect.center[0] > 850 or arrow_rect.center[1] > 650 or arrow_rect.center[0] < -200: shoot = False initialization = True rotate_arrow = True sleep(0.3) else: rotate_arrow = False arrow, arrow_rect = parabolic_shot(arrow, arrow_copy, velocity, arrow_rect, angle, GRAVITY) screen.blit(arrow, arrow_rect.center) arrow = arrow_copy else: arrow_rect.center = position_initial_arrow screen.blit(arrow, arrow_rect.center) pygame.display.update() pygame.quit()
Markdown
UTF-8
7,027
2.53125
3
[]
no_license
# Origami_in_Unity ***  Unity上でメッシュを折り紙のように折れるデモプロジェクトです。 <br /> <br /> [Go to English Readme](https://github.com/Mpaop/Origami_in_Unity/blob/master/README.md)<br /> <br /> <br /> <img src="https://raw.githubusercontent.com/wiki/Mpaop/Origami_in_Unity/images/fold01.gif" alt="Demo" width="700"/> <br /> <br /> *** ## 環境  Unity (2019.2.19f1) <br /> ## デモの使い方 1. プロジェクトをクローン後、Scenesフォルダの "FoldDemoScene" をプレイしてください。 シーンが起動すると、画面中央に四角いメッシュが表示されるはずです。 2. 画面上でドラッグ&クリックすることで、直線を引くことが出来ます。 メッシュを横切るように線を引いてみてください。 3. 画面右下の"Fold"ボタンをクリックしてください。メッシュを折る処理が実行されます。 (不具合が発生したり、新しいメッシュで折りたくなった場合、画面右下の"Reset"ボタンを押してください。シーンの再ロードが行われます。) *** <br /> ## ゲーム上の使用例 <img src="https://raw.githubusercontent.com/wiki/Mpaop/Origami_in_Unity/images/demo02.gif" alt="Gameplay" width="600"/> *** ## 詳細  このプロジェクトのソースをゲームなどで使いたい場合、まずはScriptsフォルダの直下にある"MeshCreaseDrawer.cs"の内容から確認することをお勧めします。  このクラスは画面上に線を引く機能を持つ他、実際にメッシュを折るクラスを呼び出す役割を担っています。 ### **Origami_Demo (namespace)**  この名前空間にはMeshCreaseDrawerというクラスが含まれています。あくまでデモ用に作成されたコードであるため、 紙を折る処理を実行する上では必要ありません。 - **クラスなどの概要:** - MeshCreaseDrawer - 画面上に直線を引く。 - MeshFoldMachineなどメッシュを折る処理を実行する他クラスを呼び出す。 ### **Origami_Fold (namespace)**  この名前空間には、MeshFoldMachineというメッシュを折る処理の中心核を担うクラスが含まれています。 - **クラスなどの概要:** - MeshFoldMachine - メッシュを折る。 - 本デモにおいて、このクラスはMeshCreaseDrawerより直線の始点と終点の座標を"InitializeFold"というメソッドを介して受け取ります。これら二点からなる直線に沿ってメッシュは分割されます。 この処理を行ってから、"FoldMeshToAngle"というメソッドで折りたい角度(ラジアン)の値を指定すと、メッシュを折ることが出来ます。最後に、"EndFold"というメソッドを呼ぶと、MeshFoldMachineの内部的な後処理等が行われます(※"EndFold"の仕様は今後変更される予定にあります) ### **Origami_Mesh (namespace)**  この名前空間は、メッシュや頂点など、MeshFoldMachineが処理を行う対象となるクラス等がまとめられています。 - **クラスなどの概要:** - OrigamiBase - MeshFoldMachineにて扱うメッシュの抽象クラス。UnityのMeshオブジェクトを管理する他、 回転したベクトルの値を返す機能などを持っています。 - OrigamiMesh - OrigamiBaseを継承するクラス。独自の機能はあまり多くありませんが、折り目のメッシュに接した頂点の値を 調整するなどといった処理を行っています。 - CreaseMesh - メッシュを折る際に生じる隙間を埋めるメッシュクラス。OrigamiMeshのオブジェクトを折る際、 Z-ファイティングを回避する目的で頂点を少しだけずらすといった調整が必要となります。 その際、メッシュを紙より分離させないためにCreaseMeshのメッシュを生成します。 - CreaseMeshクラスの仕様は近い将来変更予定にあります。 - Crease - CreaseMeshは基本的に二個一組で扱うため、その管理を行うクラス。 メッシュを折る箇所を埋める目的で生成するため、Readmeやソースのコメントでは便宜的に折り目と呼んでいきます。 - MeshVertex - MeshVertexは読み取り専用の構造体であり、メッシュを折る際に必要となる情報を一つに束ねるという意図で作られています。 - MeshVertices - MeshverticesはMeshVertexオブジェクトを生成するために必要なデータをリスト毎に有するクラスです。 MeshVertexのリストを宣言した方が管理しやすいように思われるかもしれませんが、UnityのMeshクラスを扱う関係から分けています。 - IFoldMeshCallbacks - コールバックメソッドを定義するためのインターフェイス ### **Origami_Result (namespace)**  この名前空間は、OrigamiMeshオブジェクトなどが折られる際に必要とする情報などを格納する構造体をまとめたものです。 - **クラスなどの概要:** - FoldResult - 頂点を折る(回転させる)上で必要なデータを持つ読み取り専用の構造体。 - OrigamiFoldResult - FoldResultをラップし、更にOrigamiMeshの頂点を折る上で必要なデータもまとめた構造体。 - OrigamiFoldResults - 複数のOrigamiFoldResultをメンバーとして持つ構造体。各メンバーはOrigamiMeshオブジェクトの頂点に対応します。 - CreaseGenerationInfo/CreaseGenerateResults/CreaseFoldResult/CreaseFoldResults - Crease/CreaseMeshesの仕様が変更されるため、上記の構造体は破棄、または再設計の対象となる予定です。 - IFoldResults - 上の構造体に実装させたいメソッドをまとめたインターフェイス ### **Origami_Utility(namespace)**  この名前空間には、OrigamiUtilityというクラスが含まれています。 - **クラスなどの概要:** - OrigamiUtility - 便利なメソッドや定数などを提供するクラス。 *** ## **今後の予定** - 折り目のアルゴリズムを変更。 - 折る際の計算量を減らすための修正。 *** ## **確認されている不具合** - 折る際、折り目のメッシュが折り紙の中からはみ出てくることがあります。現在修正中です。 - 時々、折る処理に失敗した後に再度折り紙を折ろうとすると、メッシュの形状が極端に崩れる場合があります。
Java
UTF-8
7,110
2.78125
3
[]
no_license
/* Pavel Yakovlev pyakovlev@bearcubs.santarosa.edu 29.12.2017 Final Project - IMDb Browser Application Java 17.11 IMDbBrowserController.java */ package edu.srjc.yakovlev.pavel.imdb_browser; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import java.sql.*; public class IMDbBrowserController implements Initializable { private String currentMovie = ""; @FXML private TextField searchBar; @FXML private ImageView moviePosterView; @FXML private Label movieNameLabel; @FXML private Label typeLabel; @FXML private Label yearLabel; @FXML private Label ratingLabel; @FXML private Label numRatingsLabel; @FXML private Label movieSummaryLabel; @FXML private Label genreLabel; @FXML private Label reviewsLabel; @FXML private Label noPosterLabel; @FXML private Button watchlistButton; @FXML public void onEnter(ActionEvent event) throws Exception { // TODO: 12/28/2017 is it necessary to instantiate Movie every time..? Movie someMovie = new Movie(); if (!currentMovie.equals("")) { String sql = "DELETE FROM Movies WHERE Name = '"+ currentMovie +"'"; doSQL(sql); } String movieTitle = searchBar.getText(); APIRequest API = new APIRequest(movieTitle); API.send(someMovie); //DEBUG: System.out.println(someMovie.toString()); if(someMovie.getName().equals("")) { currentMovie = ""; movieNameLabel.setText("No results found!"); ratingLabel.setText(""); reviewsLabel.setText(""); numRatingsLabel.setText(""); yearLabel.setText(""); movieSummaryLabel.setText(""); genreLabel.setText(""); moviePosterView.setImage(null); noPosterLabel.setText(""); } else { currentMovie = someMovie.getName(); String sql = "INSERT INTO Movies ('Name', 'Type', 'Genre', 'Year', 'Reviews', 'NumReviews', 'Rating', 'Poster', 'Summary')"+ "VALUES ('"+someMovie.getName()+"','"+someMovie.getType()+"','"+someMovie.getGenre()+"','"+ someMovie.getYear()+"','"+someMovie.getImdbRating()+"','"+someMovie.getNumRatings()+"','"+ someMovie.getRating()+"','"+someMovie.getPoster()+"','"+someMovie.getSummary()+"')"; doSQL(sql); movieNameLabel.setText(someMovie.getName()); reviewsLabel.setText(someMovie.getImdbRating() + " out of 10 stars"); numRatingsLabel.setText(someMovie.getNumRatings() + " total ratings"); yearLabel.setText(someMovie.getYear()); genreLabel.setText(someMovie.getGenre()); movieSummaryLabel.setText(someMovie.getSummary()); ratingLabel.setText(someMovie.getRating()); try { ImageView moviePoster = new ImageView(someMovie.getPoster()); moviePosterView.setImage(moviePoster.getImage()); } catch(Exception noImage) { noPosterLabel.setText("No Poster Available!"); } } if (isInWatchlist(currentMovie)) { watchlistButton.setText("remove"); } else { watchlistButton.setText("add"); } // TODO: 12/12/2017 maybe expand movie artwork on click? } @FXML public void onPress(ActionEvent event) throws Exception { if (watchlistButton.getText().equals("add")) { watchlistButton.setText("remove"); String sql = "INSERT INTO Watchlist SELECT * FROM Movies WHERE Name = '"+currentMovie+"'"; doSQL(sql); } else { watchlistButton.setText("add"); String sql = "DELETE FROM Watchlist WHERE Name = '"+ currentMovie +"'"; doSQL(sql); } } public void doSQL(String sql)throws SQLException { Connection conn = null; String connectionString = "jdbc:sqlite:database/MyMovies.sqlite3"; conn = DriverManager.getConnection(connectionString); Statement statement = null; statement = conn.createStatement(); statement.setQueryTimeout(20); statement.execute(sql); sql = "SELECT * FROM Movies"; ResultSet rs = statement.executeQuery(sql); System.out.println("Movies Table:"); while (rs.next()) { String r = String.format("ID: %s, Name: %s, Type: %s, Genre: %s, Year: %s, Reviews: %s, NumReviews: %s, " + "Rating: %s, Poster: %s, Summary: %s", rs.getLong("ID"), rs.getString("Name"), rs.getString("Type"), rs.getString("Genre"), rs.getString("Year"), rs.getString("Reviews"), rs.getString("NumReviews"), rs.getString("Rating"), rs.getString("Poster"), rs.getString("Summary")); System.out.println(r); } sql = "SELECT * FROM Watchlist"; rs = statement.executeQuery(sql); System.out.println("Watchlist Table:"); while (rs.next()) { String r = String.format("ID: %s, Name: %s, Type: %s, Genre: %s, Year: %s, Reviews: %s, NumReviews: %s, " + "Rating: %s, Poster: %s, Summary: %s", rs.getLong("ID"), rs.getString("Name"), rs.getString("Type"), rs.getString("Genre"), rs.getString("Year"), rs.getString("Reviews"), rs.getString("NumReviews"), rs.getString("Rating"), rs.getString("Poster"), rs.getString("Summary")); System.out.println(r); } conn.close(); } public boolean isInWatchlist(String name)throws Exception { String sql = "SELECT 1 WHERE EXISTS(SELECT * FROM Watchlist WHERE Name = '"+name+"' LIMIT 1) "; Connection conn = null; String connectionString = "jdbc:sqlite:database/MyMovies.sqlite3"; conn = DriverManager.getConnection(connectionString); Statement statement = null; statement = conn.createStatement(); statement.setQueryTimeout(20); ResultSet rs = statement.executeQuery(sql); boolean inWatchlist = rs.next(); System.out.println("in watchlist?: " + inWatchlist); conn.close(); return inWatchlist; } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } }
JavaScript
UTF-8
831
3.34375
3
[]
no_license
/** * @param {string} s * @param {number} numRows * @return {string} */ var convert = function (s, numRows) { if (numRows == 1) { return s } new_s = "" n = s.length for (i = 0; i < numRows; i++) { for (j = 0; j < n; j++) { u = parseInt(j / (numRows - 1)) us = u * 2 * (numRows - 1) if (j % (numRows - 1) == 0) { k = us + i if (k < n) { new_s = new_s + s[k] } } else if (i + (j % (numRows - 1)) == numRows - 1) { k = us + numRows + (numRows - 2 - i) if (k < n) { new_s = new_s + s[k] } } } } return new_s }; (function main() { console.log(convert("LEETCODEISHIRING", 4)) }())
PHP
UTF-8
1,851
2.515625
3
[]
no_license
</!DOCTYPE html> <html lang="fr"> <?php include("en-tete.php");?> <?php include 'openbdd.php';?> <body> <?php if (isset($_POST['Titre']) && isset($_POST['Date']) && isset($_SESSION['identifiant'])){ $T=$_POST['Titre']; $Des=$_POST['Description']; $D=$_POST['Date']; $I=$_POST['Infos']; $requete = "INSERT INTO evenements VALUES (\"".$T."\",\"".$Des."\",\"".$D."\",\"".$I."\",\"".$_SESSION['identifiant']."\")"; if ($reponse= $bdd->query($requete)){ ?> <p class="enr">Enregistrement terminée </p><br/> <form action ="index.php" method="post"> <input type="submit" value="Retour" /> </form> <?php } else{ ?> <p class="enr">Problème d'écriture </p><br/> <form action ="ajout.php" method="post"> <input type="submit" value="Recommencer" /> </form> <?php } } else{ if (isset($_SESSION['identifiant'])) { ?> <h1>Ajouter un évènement </h1> <form method="post" id="Bouton"> <div class="formulaire"> <label for="Titre">Titre de l'évènement: </label><br/> <input type="text" name="Titre" required/> </div> <div class="formulaire"> <label for="Description">Description : </label><br/> <input type="text" name="Description" required/> </div> <div class="formulaire"> <label for="Date">Date:</label><br/> <input type="date" name="Date" value="0"/> </div> <div class="formulaire"> <label for="Infos">Infos supplémentaires:</label><br/> <input type="text" name="Infos" /> </div> <br/> <input type="submit" value="Envoyer" /> </form> <?php } else{ ?> <p class="enr">Veuillez vous connecter s'il-vous-plaît.</p><br/> <form action ="connexion.php" method="post"> <input type="submit" value="Se connecter" /> </form> <?php } } ?> <?php include("pied_de_page.php"); ?> </body> </html>
Swift
UTF-8
1,143
2.5625
3
[]
no_license
// // PaginatedTosList.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation #if canImport(AnyCodable) import AnyCodable #endif public struct PaginatedTosList: Codable, Hashable { public var count: Int? public var next: String? public var previous: String? public var results: [Tos]? public init(count: Int? = nil, next: String? = nil, previous: String? = nil, results: [Tos]? = nil) { self.count = count self.next = next self.previous = previous self.results = results } public enum CodingKeys: String, CodingKey, CaseIterable { case count case next case previous case results } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(count, forKey: .count) try container.encodeIfPresent(next, forKey: .next) try container.encodeIfPresent(previous, forKey: .previous) try container.encodeIfPresent(results, forKey: .results) } }
Java
UTF-8
425
3.109375
3
[]
no_license
package testeIO; import java.util.Collection; import java.util.HashSet; public class TesteDuplicadosNaLista { public static void main(String[] args) { Collection<Conta> contas = new HashSet<>(); Conta contaA = new Conta(135, 150.0F, "Andrey F. Alves"); Conta contaB = new Conta(135, 150.0F, "Andrey Frazatti"); contas.add(contaA); contas.add(contaB); for (Conta conta : contas) { System.out.println(conta); } } }
Shell
UTF-8
2,852
3
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # # Copyright (C) 2021-2022 Chair of Electronic Design Automation, TUM. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # 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. # # Positional arguments: # $1 - path to binary file # $2 - arch string, i.e. rv32gc or rv32gcv or rv32gcp # $3 - VLEN, from 64 to 1024 (only applicable if arch string is rv32gcv) # $4 - enable floating point and vector unit by default, either 0 or 1 (only applicable if arch string is rv32gcv) # Example call to invoke OVPsim: # ./run.sh my_binary.elf rv32gcv 256 0 set -e SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" if [[ $2 == "rv32gcv" ]]; then $SCRIPT_DIR/bin/riscvOVPsimPlus \ --program $1 \ --variant RVB32I \ --override riscvOVPsim/cpu/add_Extensions=MAFDCV \ --override riscvOVPsim/cpu/unaligned=T \ --override riscvOVPsim/cpu/vector_version=1.0 \ --override riscvOVPsim/cpu/VLEN=$3 \ --override riscvOVPsim/cpu/ELEN=32 \ --override riscvOVPsim/cpu/mstatus_FS=$4 \ --override riscvOVPsim/cpu/mstatus_VS=$4 # --trace # --port 3333 # --gdbconsole elif [[ $2 == "rv32gcp" ]]; then $SCRIPT_DIR/bin/riscvOVPsimPlus \ --program $1 \ --variant RVB32I \ --override riscvOVPsim/cpu/add_Extensions=MAFDCBP \ --override riscvOVPsim/cpu/dsp_version=0.9.6 \ --override riscvOVPsim/cpu/bitmanip_version=0.94 \ --override riscvOVPsim/cpu/unaligned=T \ --override riscvOVPsim/cpu/mstatus_FS=$4 elif [[ $2 == "rv32gc" ]]; then $SCRIPT_DIR/bin/riscvOVPsimPlus \ --program $1 \ --variant RVB32I \ --override riscvOVPsim/cpu/add_Extensions=MAFDC \ --override riscvOVPsim/cpu/unaligned=T \ --override riscvOVPsim/cpu/mstatus_FS=$4 elif [[ $2 == "rv32imv" || $2 == "rv32imzve32x" ]]; then $SCRIPT_DIR/bin/riscvOVPsimPlus \ --program $1 \ --variant RVB32I \ --override riscvOVPsim/cpu/add_Extensions=MV \ --override riscvOVPsim/cpu/unaligned=T \ --override riscvOVPsim/cpu/vector_version=1.0 \ --override riscvOVPsim/cpu/VLEN=$3 \ --override riscvOVPsim/cpu/ELEN=32 \ --override riscvOVPsim/cpu/mstatus_VS=$4 elif [[ $2 == "rv32im" ]]; then $SCRIPT_DIR/bin/riscvOVPsimPlus \ --program $1 \ --variant RVB32I \ --override riscvOVPsim/cpu/add_Extensions=MV \ --override riscvOVPsim/cpu/unaligned=T else echo "Unsupported arch string $2" fi
PHP
UTF-8
1,009
2.546875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php class Srdata_Model_Layer extends Zend_Db_Table_Row_Abstract { private $_columnMap = array( 'sphericalMercator' => 'sphericalmercator', 'isBaseLayer' => 'isbaselayer', 'numZoomLevels' => 'numzoomlevels', 'maxZoomLevel' => 'maxzoomlevel', 'minZoomLevel' => 'minzoomlevel' ); protected function _transformColumn($columnName) { $retStr = strtolower($columnName); if( array_key_exists($columnName, $this->_columnMap) ) { $retStr = $this->_columnMap[$columnName]; } return $retStr; } public function setFromArray($data) { foreach($data as $key => $val) { unset( $data[$key] ); $key = $this->_transformColumn($key); $data[$key] = $val; } return parent::setFromArray($data); } public function toArray() { $retArr = parent::toArray(); foreach($retArr as $key => $val) { if( $newColName = array_search( $key, $this->_columnMap) ) { unset( $retArr[$key] ); $retArr[$newColName] = $val; } } return $retArr; } //END toArray }
Python
UTF-8
2,899
2.96875
3
[]
no_license
import collections import sys ID, FORENAME, MIDDLENAME, SURNAME, DEPARTMENT = range(5) User = collections.namedtuple("User", "username forename middlename surname id") def process_line(line, usernames): fields = line.split(":") username = generate_username(fields, usernames) user = User(username, fields[FORENAME], fields[MIDDLENAME], fields[SURNAME], fields[ID]) return user def generate_username(fields, usernames): username = ((fields[FORENAME][0] + fields[MIDDLENAME][:1] + fields[SURNAME]).replace("-", "").replace("'", "")) username = original_name = username[:8].lower() count = 1 while username in usernames: username = "{0}{1}".format(original_name, count) count += 1 usernames.add(username) return username def get_page_header(namewidth, usernamewidth): header = "{0:<{nw}} {1:^6} {2:{uw}}".format( "Name", "ID", "Username", nw=namewidth, uw=usernamewidth) headers_spaces = " " first_combined_headers = header + headers_spaces + header hr = "{0:-<{nw}} {0:-<6} {0:-<{uw}}".format( "", nw=namewidth, uw=usernamewidth) second_combined_headers = hr + headers_spaces + hr return first_combined_headers + "\n" + second_combined_headers def get_user_data(user, namewidth, usernamewidth, ellipsis_text_length): tempData = "" if user.middlename: tempData = " " + user.middlename[0] name = "{0.surname}, {0.forename}{1}".format(user, tempData) return "{0:.<{nw}.{np}} ({1.id:4}) {1.username:{uw}}".format( name, user, nw = namewidth, uw = usernamewidth, np = namewidth - ellipsis_text_length) def print_users(users): namewidth = 17 usernamewidth = 9 ellipsis_text_length = 0 max_page_length = 64 page_header = get_page_header(namewidth, usernamewidth) sorted_users = sorted(users) for i, (lcol, rcol) in enumerate(zip(sorted_users[::2], sorted_users[1::2])): if i % max_page_length == 0: print("\f" + page_header) record = "{}{}".format(" ", get_user_data(users[rcol], namewidth, usernamewidth, ellipsis_text_length)) if rcol is not None else "" print(get_user_data(users[lcol], namewidth, usernamewidth, ellipsis_text_length) + record) def main(): if len(sys.argv) == 1 or sys.argv[1] in {"-h", "--help"}: print("usage: {0} file1 [file2 [... fileN]]".format( sys.argv[0])) sys.exit() usernames = set() users = {} for filename in sys.argv[1:]: with open(filename, encoding="utf8") as file: for line in file: line = line.rstrip() if line: user = process_line(line, usernames) users[(user.surname.lower(), user.forename.lower(), user.id)] = user print_users(users) main()
PHP
UTF-8
2,904
2.921875
3
[]
no_license
<?php //echo "here";exit; define('__ROOT__', dirname(__FILE__)); //echo "here1 ".__ROOT__; exit; // load the db specific handlers //require_once( __ROOT__."/db_mysql.php" ); require_once( dirname(__FILE__)."/meekrodb.2.3.class.php" ); //DB::$user = 'root'; //DB::$password = 'daff0d1l'; //DB::$dbName = 'mullsoft'; //DB::$encoding = 'utf8'; //DB::$host = 'localhost'; class MullSoftDatabaseObject { private $thedb; public function __construct($dbname, $dbuser, $dbpass, $dbhost = 'localhost', $dbport = "3306", $dbencoding = 'utf8') { $this->thedb = new MeekroDB($dbhost, $dbuser, $dbpass, $dbname, $dbport, $dbencoding); } public function query($sql) { return $this->thedb->query($sql); } /** * This global function loads the first field of the first row returned by the query. * * @param string The SQL query * @return The value returned in the query or null if the query failed. */ public function loadResult( $sql ) { return $this->thedb->queryFirstField($sql); } /** * This global function return a result row as an associative array * * @param string The SQL query * @param array An array for the result to be return in * @return <b>True</b> is the query was successful, <b>False</b> otherwise */ public function loadHash( $sql, &$hash ) { $hash1 = $this->thedb->queryFirstRow($sql); $ret = false; if ($hash1 != null) { $ret = true; foreach ($hash1 as $k => $v) { $hash[$k] = $v; } } return $ret; } /** * Document::db_loadList() * * { Description } * * @param [type] $maxrows */ public function loadList( $sql ) { return $this->thedb->query($sql); } /** * Document::db_loadColumn() * * { Description } * * @param [type] $maxrows */ public function loadColumn( $sql ) { return $this->thedb->queryFirstColumn($sql); } /** * Document::db_insertArray() * * { Description } * * @param [type] $verbose */ public function insertArray( $table, &$hash ) { $this->thedb->insert($table, $hash); return $this->thedb->insertId(); } /** * Document::db_updateArray() * * { Description } * * @param [type] $verbose */ public function updateArray( $table, &$hash, $keyName ) { $hash1 = array(); $where = ""; foreach ($hash as $k => $v) { if ($k == $keyName) { if (is_numeric($v)) { $where = "$keyName=".$v; } else { $where = "$keyName='".$v."'"; } } else { $hash1[$k] = $v; } } if (strlen($where) > 0) { $this->thedb->update($table, $hash1, $where); } } public function delete( $table, $where ) { if (strlen($where) > 0) { $this->thedb->delete($table, $where); } return $this->thedb->affectedRows() > 0; } } ?>
Java
UTF-8
1,313
2.421875
2
[ "Apache-2.0" ]
permissive
package com.zte.shawn.persistence; import android.content.Context; import android.os.Environment; /** * Created by 10192984 on 2017/2/10. */ public class PersistPathManager { private Context context; private static PersistPathManager instance; private String privateExternalPath; private String publicExternalPath; private String externalCachePaht; private PersistPathManager(Context context) { this.context = context; privateExternalPath = context.getExternalFilesDir(null).getAbsolutePath(); publicExternalPath= Environment.getExternalStoragePublicDirectory("lotteryCheck").getAbsolutePath(); externalCachePaht = context.getExternalCacheDir().getAbsolutePath(); } public static PersistPathManager getInstance(Context context){ if(instance ==null){ synchronized (PersistPathManager.class){ if(instance==null){ instance = new PersistPathManager(context); } } } return instance; } public String privateExternalPath(){ String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return privateExternalPath; } else{ return ""; } } }
Java
UTF-8
3,754
2.21875
2
[ "Apache-2.0" ]
permissive
/* * #%L * wcm.io * %% * Copyright (C) 2014 wcm.io * %% * 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. * #L% */ package io.wcm.handler.link; import java.util.HashMap; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.api.wrappers.ValueMapDecorator; import com.day.cq.wcm.api.Page; /** * Defines a link reference */ public final class LinkReference implements Cloneable { private Resource resource; private ValueMap resourceProperties; private Page page; private LinkArgsType linkArgs; /** * @param resource Resource with target link properties */ public LinkReference(Resource resource) { this.resource = resource; } /** * @param resource Resource with target link properties * @param linkArgs Link args */ public LinkReference(Resource resource, LinkArgsType linkArgs) { this.resource = resource; this.linkArgs = linkArgs; } /** * @param page Target page of the link */ public LinkReference(Page page) { this.page = page; } /** * @param page Target page of the link * @param linkArgs Link args */ public LinkReference(Page page, LinkArgsType linkArgs) { this.page = page; this.linkArgs = linkArgs; } /** * @return Resource with target link properties */ public Resource getResource() { return this.resource; } /** * @param resource Resource with target link properties */ public void setResource(Resource resource) { this.resource = resource; // clear "cached" resource properties map as well this.resourceProperties = null; } /** * @return Properties from resource containing target link. The value map is a copy * of the original map so it is safe to change the property values contained in the map. */ public ValueMap getResourceProperties() { if (this.resourceProperties == null) { // create a copy of the original map this.resourceProperties = new ValueMapDecorator(new HashMap<String, Object>()); if (this.resource != null) { ValueMap props = this.resource.adaptTo(ValueMap.class); if (props != null) { this.resourceProperties.putAll(props); } } } return this.resourceProperties; } /** * @return Target page of the link */ public Page getPage() { return this.page; } /** * @param page Target page of the link */ public void setPage(Page page) { this.page = page; } /** * @return Link arguments */ public LinkArgsType getLinkArgs() { return this.linkArgs; } /** * @param linkArgs Link arguments */ public void setLinkArgs(LinkArgsType linkArgs) { this.linkArgs = linkArgs; } @Override public Object clone() throws CloneNotSupportedException { LinkReference clone = (LinkReference)super.clone(); // explicitly clone LinkArgs contents (primitive properties are properly cloned by super.clone() if (getLinkArgs() != null) { clone.setLinkArgs((LinkArgsType)getLinkArgs().clone()); } return clone; } }
Java
UTF-8
1,554
2.15625
2
[]
no_license
package info.esblurock.reaction.chemconnect.core.client.pages; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import gwt.material.design.client.ui.MaterialCollapsible; import gwt.material.design.client.ui.MaterialLink; import info.esblurock.reaction.chemconnect.core.base.utilities.HierarchyNode; public class MainDataStructureVisualization extends Composite { private static MainDataStructureVisualizationUiBinder uiBinder = GWT .create(MainDataStructureVisualizationUiBinder.class); interface MainDataStructureVisualizationUiBinder extends UiBinder<Widget, MainDataStructureVisualization> { } @UiField MaterialLink title; @UiField MaterialCollapsible contentcollapsible; public MainDataStructureVisualization() { initWidget(uiBinder.createAndBindUi(this)); init(); } private void init() { title.setText("Main Data Structures"); /* ContactDatabaseAccessAsync async = ContactDatabaseAccess.Util.getInstance(); CatalogClassificationInformationCallback callback = new CatalogClassificationInformationCallback(this); async.getCatalogHierarchy(callback); */ } public void addMainStructures(HierarchyNode node) { Window.alert("addMainStructures(HierarchyNode node)"); StructureHierarchyCollapsible collapse = new StructureHierarchyCollapsible(node); contentcollapsible.add(collapse); } }
Python
UTF-8
825
3.484375
3
[]
no_license
""" [질문 3] http://python-data.dr-chuck.net/comments_42.xml 해당 URL의 xml을 load한 후, comments의 총 갯수와 comments에 있는 각 count들을 모두 더해서 출력하는 파이썬 프로그램을 작성해주세요. (urllib, xml.etree.ElementTree 등을 import 하여 사용하시면 됩니다.) * """ import xml.etree.ElementTree as ET import urllib.request, urllib.parse, urllib.error import re raw = urllib.request.urlopen('http://python-data.dr-chuck.net/comments_42.xml').read() lines = raw.decode() stuff = ET.fromstring(lines) lst = stuff.findall('comments/comment') sum = 0; for item in lst: word = item.find('count').text word = word.strip() check = re.findall("[0-9]+", word) if len(check) == 1: sum += int(check[0]) print('totalcount: ', len(lst)) print('sum: ', sum)
Markdown
UTF-8
1,300
3.65625
4
[ "MIT" ]
permissive
# 函数 + 优点: + 允许模块化设计程序。函数存储在数据库中,可独立于程序源代码修改。 + 每次调用时无需重新解析和优化,缩短了执行时间,执行速度更快。 + 减少网络流量。 + 与存储过程对比 + 共同点 + 可重复使用编程代码,减少开发时间。 + 隐藏SQL细节,给业务开发人员提供良好的数据库操作接口。 + 模块化设计便于维护和扩展。 + 不同点 + 存取过程的权限允许程序执行存储过程而不允许其存取数据表,增强程序安全性。 + 函数必须返回一个值。 + 存储过程的返回值不能被直接使用而函数可以。 + 函数定义 ### 示例1 ``` #删除函数 DROP FUNCTION IF EXISTS simpleFun; #创建无参函数,返回varchar(20) CREATE FUNCTION simpleFun() RETURNS varchar(20) RETURN 'Hello MySQL!'; #调用函数 SELECT simpleFun() AS '结果'; ``` --- ![fun1.PNG](pictures/fun1.PNG) --- ### 示例2 ``` #创建函数,根据传入的姓名,返回年龄信息 CREATE FUNCTION nameFun(Ename char(8)) RETURNS INT RETURN (SELECT `e`.`Age` FROM `Employee` e WHERE `e`.`Ename` = Ename); #调用函数 SELECT nameFun('王超') AS '年龄'; ``` --- ![fun2.PNG](pictures/fun2.PNG) ---
Java
UTF-8
1,397
1.921875
2
[]
no_license
package hello.entity; import java.util.List; public class LoginResponse { public boolean success; public Data data; public static class Contacts { public String vk; public String phone; public String email; public String updated; } public static class Data { public User user; public String token; } public static class ProfileValues { public Integer homeTask; public Integer projects; public Integer linesCode; public Integer rait; public String updated; } public static class PublicInfo { public String bio; public String avatar; public String photo; public String updated; } public static class Repo { public String id; public String git; public String title; } public static class Repositories { public List<Repo> repo = null; public String updated; } public static class User { public String id; public String firstName; public String secondName; public Integer v; public Repositories repositories; public Contacts contacts; public ProfileValues profileValues; public PublicInfo publicInfo; public String specialization; public String role; public String updated; } }
Markdown
UTF-8
2,044
2.65625
3
[]
no_license
git init : activate a folder as repository git add "file" or git add . or better git add --all : to generate an index of all the files to follow git commit -m "add message here" : to save the modifications you did to your files git log: to view the commits you've done before git commit -a -m "Ajouté itinéraire dans checklist-vacances.md" : to commit changes to an already indexed file git checkout SHADuCommit : to position ourselfs in a specific commit we've made git checkout master : to comeback to the actual code git revert SHADuCommit : revert a commit AKA create a commit that will revert the last commit git commit --amend -m "Votre nouveau message" : to just change the last message git reset --hard : to cancel all the changes you did before commiting git clone linktoGitHub : to clone a repo to your local drive. git remote add origin https://github.com/zexedex/git_cheatsheet.git : create a remote so you can manipulate things by using it after, the remote here is called origin git push -u origin master : pushing git pull origin master : this is mostly when working with others so you can merge the changes from the repo ---- now to branching (for more info) => https://git-scm.com/book/en/v1/Git-Branching-What-a-Branch-Is git branch : to see the current branch git branch newbranchname: to create a newbranch git checkout newbranchename : to switch to the branch newbranchname git merge branchB: after selecting what branch you want git blame file.ext : to see who made what changement in a file and on what line git show 05b1233 : after git blame and trying to understand why a changement has been made in a line, take the corresponding sha and get show it .gitignore: create this file and list in it all the files you want(full path to the file) to ignore and not upload to your git git stash : this is not to do a commit, it's a temporary safe you can say, once you want to go back to it you just git stash pop, if you want to save your modifications in the stach you do git stash apply
SQL
UTF-8
1,258
3.65625
4
[ "Apache-2.0" ]
permissive
ALTER TABLE collection ADD COLUMN theme INT(11) NOT NULL; UPDATE collection, questionnaire SET collection.theme = questionnaire.theme WHERE collection.id = questionnaire.id; -- The first step is to get all the 'questionnaire.permalink' fields unique UPDATE questionnaire q1 JOIN questionnaire q2 ON q1.permalink = q2.permalink SET q1.permalink = CONCAT(q1.permalink, '-', SUBSTR(MD5(RAND()), 27)) WHERE q1.id < q2.id; -- Now we update the entity.permalink with the contextualized q.permalink field UPDATE entity e JOIN questionnaire q ON e.id = q.id SET e.permalink = CONCAT('/questionnaires/', q.permalink); -- Now we update the Collections, which are not Questionnaires. UPDATE entity e JOIN collection c ON e.id = c.id LEFT OUTER JOIN questionnaire q ON c.id = q.id SET e.permalink = concat('/collections/', e.permalink) WHERE q.id IS NULL; UPDATE entity, questionnaire SET entity.title = questionnaire.title WHERE entity.id = questionnaire.id; ALTER TABLE questionnaire DROP FOREIGN KEY fk_questionnaire_theme, DROP COLUMN theme, DROP COLUMN title, DROP COLUMN permalink; ALTER TABLE formElement DROP FOREIGN KEY fk_formElement_questionnaire, ADD CONSTRAINT fk_formElement_collection FOREIGN KEY (questionnaire) REFERENCES collection (id);
Swift
UTF-8
1,211
2.8125
3
[]
no_license
// // UIer+UIView.swift // // // Created by Minhyuk Kim on 2020/03/14. // import UIKit public extension UIView { @IBInspectable var cornerRadius: CGFloat { set (radius) { self.layer.cornerRadius = radius self.layer.masksToBounds = radius > 0 } get { return self.layer.cornerRadius } } @IBInspectable var borderWidth: CGFloat { set (width) { self.layer.borderWidth = width } get { return self.layer.borderWidth } } @IBInspectable var borderColor: UIColor { set (color) { self.layer.borderColor = color.cgColor } get { guard let color = self.layer.borderColor else { return .black } return UIColor(cgColor: color) } } @IBInspectable var bgHexColor: String? { set (hexString) { guard let str = hexString else { return } self.backgroundColor = UIColor.hexStringToUIColor(hex: str) } get { return self.backgroundColor?.toHexString() } } }
Java
UTF-8
3,686
3.09375
3
[]
no_license
package genericCheckpointing.util; public class MyAllTypesFirst extends SerializableObject { private int myInt, myOtherInt; private long myLong, myOtherLong; private String myString; private boolean myBool; /** * Constructor for the MyAllTypesFirst class * * @param int - initial value for myInt * @param int - initial value for myOtherInt * @param long - initial value for myLong * @param long - initial value for myOtherLong * @param String - initial value for myString * @param boolean - initial value for myBool */ public MyAllTypesFirst(int i, int i2, long l, long l2, String s, boolean b) { myInt = i; myOtherInt = i2; myLong = l; myOtherLong = l2; myString = s; myBool = b; } /** * Setter for myInt of MyAllTypesFirst * * @param int - new value of myInt */ public void setMyInt(int i) { myInt = i; } /** * Setter for myOtherInt of MyAllTypesFirst * * @param int - new value of myOtherInt */ public void setMyOtherInt(int i) { myOtherInt = i; } /** * Setter for myLong of MyAllTypesFirst * * @param long - new value of myLong */ public void setMyLong(long l) { myLong = l; } /** * Setter for myOtherLong of MyAllTypesFirst * * @param long - new value of myOtherLong */ public void setMyOtherLong(long l) { myOtherLong = l; } /** * Setter for myString of MyAllTypesFirst * * @param String - new value of myString */ public void setMyString(String s) { myString = s; } /** * Setter for myBool of MyAllTypesFirst * * @param boolean - new value of myBool */ public void setMyBool(boolean b) { myBool = b; } /** * Getter for myInt of MyAllTypesFirst * * @return int - myInt */ public int getMyInt() { return myInt; } /** * Getter for myOtherInt of MyAllTypesFirst * * @return int - myOtherInt */ public int getMyOtherInt() { return myOtherInt; } /** * Getter for myLong of MyAllTypesFirst * * @return long - myLong */ public long getMyLong() { return myLong; } /** * Getter for myOtherLong of MyAllTypesFirst * * @return long - myOtherLong */ public long getMyOtherLong() { return myOtherLong; } /** * Getter for myString of MyAllTypesFirst * * @return String - myString */ public String getMyString() { return myString; } /** * Getter for myBool of MyAllTypesFirst * * @return boolean - myBool */ public boolean getMyBool() { return myBool; } /** * Calculates hashcode of a MyAllTypesFirst object * * @return int - hashcode */ @Override public int hashCode() { return (3*myInt) + (5*myOtherInt) + (int)(7*myLong) + (int)(11*myOtherLong) + (13*myString.hashCode()) + (17 * ((myBool)?1:0)); } /** * Determines if another object is equal * * @param MyAllTypesFirst - comparing obj */ public boolean equals(Object obj) { return (this.hashCode() == obj.hashCode()); } public String toString() { return "MyAllTypesFirst Object:\n" + "\n MyInt: " + myInt + "\n MyOtherInt: " + myOtherInt + "\n MyLong: " + myLong + "\n MyOtherLong: " + myOtherLong + "\n MyString: " + myString + "\n MyBool: " + myBool +'\n'; } }
SQL
UTF-8
358
2.90625
3
[]
no_license
drop database if exists business; create database business; use business; create table Customers ( CustomerID int NOT NULL auto_increment, CompanyName varchar(40), Country varchar(40), City varchar(40), primary key (CustomerID) ); insert into Customers (CustomerID, CompanyName, Country, City) values(1, "Company", "Deutschland", "Berlin");
Java
UTF-8
282
1.820313
2
[]
no_license
package com.tyss.Bussinessmanagement.dto; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import lombok.Data; @Entity @Data public class Products { @Id @Column private int id; @Column private String name; }
TypeScript
UTF-8
1,210
2.6875
3
[ "MIT" ]
permissive
/** * motor */ //% weight=100 color=#0fbc11 icon="\uf1b9" namespace custom { /** * TODO: 控制电机 * @param n1 在此处描述参数, eg: AnalogPin.P0 * @param n2 在此处描述参数, eg: AnalogPin.P1 * @param e 在此处描述参数, eg:0 */ //% block="电机A+%n1|A-%n2|速度%e" //%e.min=-255 e.max=255 export function setSpeedA(n1: AnalogPin, n2: AnalogPin, e: number): void { if (e <= 0) { pins.analogWritePin(n1, -e) pins.analogWritePin(n2, 0) } else { pins.analogWritePin(n2, e) pins.analogWritePin(n1, 0) } } /** * TODO: 控制电机 * @param n1 在此处描述参数, eg: AnalogPin.P0 * @param n2 在此处描述参数, eg: AnalogPin.P1 * @param e 在此处描述参数, eg:0 */ //% block="电机B+%n1|B-%n2|速度%e" //%e.min=-255 e.max=255 export function setSpeedB(n1: AnalogPin, n2: AnalogPin, e: number): void { if (e <= 0) { pins.analogWritePin(n1, -e) pins.analogWritePin(n2, 0) } else { pins.analogWritePin(n2, e) pins.analogWritePin(n1, 0) } } }
JavaScript
UTF-8
3,553
2.578125
3
[]
no_license
const http = require('../../util/http') const config = require('../../config') const iconv = require('iconv-lite'); const redisUtil = require('../../util/redisUtil') function isIntNum(val) { var regPos = /^\d+$/; // 非负整数 if (regPos.test(val)) { return true; } else { return false; } } module.exports = { /** * 实时调用获取sina实时股价 * @param {*} formData */ async fetchSinaStock(formData) { let codes = formData.codes codes = codes.replace(/,/g, ",") let codeArr = codes.split(',') let param = '' codeArr.forEach(code => { if (isIntNum(code) && (code.startsWith('6') || code.startsWith('11') || code.startsWith('50') || code.startsWith('51')) && code.length == 6) { param += `sh${code},` } else if (isIntNum(code) && (code.startsWith('0') || code.startsWith('3') || code.startsWith('12') || code.startsWith('16')) && code.length == 6) { param += `sz${code},` } }); if (!param) { throw new Error("输入股票代码错误!"); } param = param.replace(/(.*)[,]$/, '$1'); let lxrData = await http.get(`http://hq.sinajs.cn/list=${param}`, _responseType = 'arraybuffer') const buf = Buffer.alloc(lxrData.data.length, lxrData.data, 'binary') let retData = iconv.decode(buf, 'GBK') let retArr = retData.split(';') let jsonArr = [] retArr.forEach(data => { let arr = data.split('=') let codeStr = arr[0] if (arr[1]) { let str = arr[1].substr(1) let ret = {} ret['name'] = str.split(',')[0] ret['code'] = codeStr.substr(codeStr.length - 6) ret['open'] = parseFloat(str.split(',')[1]) ret['close'] = parseFloat(str.split(',')[2]) ret['price'] = parseFloat(str.split(',')[3]) ret['high'] = parseFloat(str.split(',')[4]) ret['low'] = parseFloat(str.split(',')[5]) ret['time'] = `${str.split(',')[30]} ${str.split(',')[31]}` jsonArr.push(ret) } }) // console.log(jsonArr) return jsonArr }, //查询对应股票一年最低价 codes样例 600030,600001 async queryStockYearLowPrice(formData) { if (!formData) { return null } let codes = formData.codes if (!codes) { return null } let stocks = codes.split(',') let promiseArr = [] for (let i = 0; i < stocks.length; i++) { promiseArr.push(redisUtil.redisHGet(config.redisStoreKey.yearLowStockSet, stocks[i])) } return Promise.all(promiseArr).then(function (values) { return values.filter(value => { return value != null }).map((jsonStr) => { let json = JSON.parse(jsonStr) let retObj = { 'code': json['code'], 'name': json['name'], 'citiV1': json['citiV1'], 'citiV2': json['citiV2'], 'gz2': json['gz2'] ? json['gz2'] : '', 'gz3': json['gz3'] ? json['gz3'] : '', 'low': json['low'], 'lowGenDate': json['lowGenDate'], 'ma20': json['ma20'] } console.log(retObj) return JSON.stringify(retObj) }) }); } }
Markdown
UTF-8
3,396
3.265625
3
[]
no_license
# University-course-scheduling University departments offer many courses each semester. Creating a schedule is a big challenge since a huge number of constraints have to be considered, e.g. availability of rooms, number of estimated participants, no overlap with other courses or courses belonging to the same field of study and many more. In addition some time slots are favored (e.g. Tue, Thu 10-12) than others (Mo 8-10, Fr 4-6). The aim of this project is to develop a web based system that is browser independent, having a user friendly and interactive graphical user interface to help schedule the courses. The system is expected to serve as the link between the lecturers and the study coordinator. The system should be able to provide lecturers options which fulfil as many requirements as possible while avoiding strong inconveniences. All constraints must be clearly identified and algorithms that enable the lecturer and the study coordinator to interact efficiently should be developed. These algorithms should therefore optimize the scheduling process. Also a database should be incorporated and the front ends should be coded. The database model of this project looks like the following. ![UCSS](/static/DB_model.jpg) ### Prerequisites ``` Python 2.7 python Flask Flask mail Python constraint regular expression bcrypt ``` ### Installing Download the zip file or clone the repository to your local folder. Install python 2.7 Install python flask ``` pip install Flask ``` Install python constraint ``` pip install python-constraint ``` Install python mail ``` pip install python-mail ``` Install re ``` pip install re101 ``` Install bcrypt ``` pip install bcrypt ``` Open command prompt and navigate to the UCSS folder and run the below command ``` python coco_app.py ``` ### Usage Types of Users Study Coordinator Lecturer To use the system for the first time you need to register. ### Registration(New User) as coordinator Register as Coordinator by providing the passphrase i.e ucss ### Registration(New User)as lecturer Register with your email address and a preferred password After registering,you can login with your email/password. ### Add semester(Study coordinator) To create a new semester, click on the "add semester button" Add core courses/Estimated number of students/Fields of study (Study coordinator) After creating a semester, add a list of the courses taking place in the current semester, Estimated number of students for each core course added and the Fields of study Save the entries. Manually change/block time slots ### Add Preferences(Lecturer) Select add preferences to fill in information about the course such as course name, the number of hours allocated to the course per week and the preffered days of the week Submit/Reset your chosen preferences After a schedule has been generated by the system for a particular course and viewed by the coordinator, the coordinator can change the time slot/preferences for a particular course manually and save the changes accordingly. Time slots can also be blocked by selecting the "Mark timeslots" function, providing a reason for the blocked time and saving the entry. ### Change password Forgot or want to change your password? Click on the forgot/change password label. A reset password link will be sent to your email. Please click on the link to update your password.
Java
UTF-8
1,882
2.640625
3
[]
no_license
package com.xworkz.projector; import java.awt.Container; import java.util.ArrayList; import java.util.ListIterator; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.xworkz.ball.Ball; import com.xworkz.country.Country; import com.xworkz.countrylist.ArrayListConfig; import com.xworkz.projector.custom.Projector; import com.xworkz.switchboard.SwitchBoard; public class SpringTester { public static void main(String args[]) { String ref = "fw/spring.xml"; ApplicationContext spring = new ClassPathXmlApplicationContext(ref); System.out.println(spring.getBeanDefinitionCount()); // Projector projector = spring.getBean(Projector.class); // System.out.println(projector); // Ball ball = spring.getBean(Ball.class); // System.out.println(ball); // Country country = spring.getBean(Country.class); // System.out.println(country); // // // CountryList countrylist = spring.getBean(CountryList.class); // System.out.println(countrylist); // // ApplicationContext spring = new FileSystemXmlApplicationContext("resouses/fw/spring.xml"); // ArrayListConfig alistConfig = spring.getBean("countryList",ArrayListConfig .class); // ArrayList<String> countryList = alistConfig.getCountryList(); // ListIterator<String> lIterator = countryList.listIterator(); // System.out.println("******************"); // while(lIterator.hasNext()){ // System.out.println(lIterator.next()); // } SwitchBoard refOfSwitchBoard=Container.getBean(SwitchBoard.class); refOfSwitchBoard.supplyPower(); // } }
C++
UTF-8
3,622
2.65625
3
[ "BSD-3-Clause" ]
permissive
#ifndef _Scene_H_ #define _Scene_H_ #include "../../Headers/QwerkE_Enums.h" #include "../../Headers/QwerkE_Global_Constants.h" #include <map> #include <vector> #include <string> namespace QwerkE { extern int g_WindowWidth, g_WindowHeight; // TODO: Remove class GameCore; class MyMatrix; class Scenes; class GameObject; class Scene; // forward declare for function* typedef typedef void (Scene::* StateFunc)(double deltatime); // Scene state function class Scene // Abstract class { public: Scene(); Scene(const char* sceneFileName) { m_LevelFileName = sceneFileName; } virtual ~Scene(); virtual void Initialize(); virtual void OnWindowResize(unsigned int width, unsigned int height); virtual void ResetScene(); virtual void Update(double deltatime) { (this->*m_UpdateFunc)(deltatime); } virtual void Draw(); // cameras virtual bool AddCamera(GameObject* camera); virtual void RemoveCamera(GameObject* camera); virtual void SetupCameras(); // lights virtual bool AddLight(GameObject* light); virtual void RemoveLight(GameObject* light); virtual void SetupLights(); virtual bool AddObjectToScene(GameObject* object); virtual void RemoveObjectFromScene(GameObject* object); virtual void RemoveAllObjectsFromScene(); // Possibly a scene reset // Save/Load virtual void SaveScene(); virtual void LoadScene(const char* sceneFileName); virtual void ReloadScene(); /* Getters + Setters */ // getters GameObject* GetGameObject(const char* name); bool GetIsEnabled() { return m_IsEnabled; }; std::vector<GameObject*> GetCameraList() { return m_CameraList; }; std::map<std::string, GameObject*> GetObjectList() { return m_pGameObjects; }; int GetCurrentCamera() { return m_CurrentCamera; }; std::vector<GameObject*> GetLightList() { return m_LightList; }; eSceneTypes GetSceneID() { return m_ID; } eSceneState GetState() { return m_State; } // setters void SetIsEnabled(bool isEnabled) { m_IsEnabled = isEnabled; }; void SetCurrentCamera(int camera) { m_CurrentCamera = camera; }; // TODO:: Better way for ImGUI to change camera void SetState(eSceneState newState); // TODO: void ToggleFrozenState() { SetIsFrozen(!m_IsFrozen); } protected: virtual void p_Running(double deltatime); virtual void p_Frozen(double deltatime); // only update cameras virtual void p_Paused(double deltatime) {} // Currently empty to avoid updating virtual void p_Animating(double deltatime); // for testing animations virtual void p_SlowMotion(double deltatime); StateFunc m_UpdateFunc = &Scene::p_Running; void CameraInput(double deltatime); bool m_IsEnabled = false; eSceneState m_State = eSceneState::SceneState_Running; std::string m_LevelFileName = gc_DefaultCharPtrValue;// "Uninitialized"; // TODO: Find out why I can't assign gc_DefaultCharPtrValue MyMatrix* m_pViewMatrix = nullptr; // TODO:: create cameras with different view matrices std::map<std::string, GameObject*> m_pGameObjects; eSceneTypes m_ID = eSceneTypes::Scene_Null; int m_CurrentCamera = 0; std::vector<GameObject*> m_CameraList; std::vector<GameObject*> m_LightList; std::vector<GameObject*> m_SceneDrawList; // TODO: sort by render order }; } #endif //!_Scene_H_
Markdown
UTF-8
8,977
2.875
3
[]
no_license
## TL;DR Knowledge-based system for blood glucose control in T1 Diabetes. Clone and run demo.py for interactive demo. ## DiaBuddy - Developing a knowledge-based system for T1 Diabetes disease management ### T1DM Type 1 Diabetes Mellitus (T1DM) is a chronic metabolic disorder, characterized by abnormal blood glucose regulation patterns, with which only 5-10\% of all diabetes cases are being accounted for. The defining component in T1DM is the immune system related destruction of pancreatic $\beta$-cells, responsible for the secretion of insulin. Type 1 diabetes requires lifelong treatment consisting of blood glucose monitoring, exogenous insulin administration, meal planning as well as suffering from disease management related complications and comorbid conditions. Poor glycaemic control is one of the greatest risk factors of diabetes related complications and has been a focal point of an ongoing bulk of research on the disease. Recent advances in continuous glucose monitoring (CGM) have enabled real-time CGM, which aims at improving patient self-care. This technology however still remains limited because of the delays between detection of glucose levels in interstitial fluid compared to venous levels (5-10 min) as well as the delayed onset of action of rapid insulin (10-30 min). This motivates the development of an external, knowledge-based system in the form of a smartphone application that helps patients monitor their blood glucose levels and presents them reasoned, on-time recommendations on adequate amounts of insulin/glucose to inject/ingest. It can relieve patients of the burden of calculating and assessing suitable insulin doses and at the same time teach them how food, sports and blood glucose concur. Input to the system are the subcutaneous glucose level invasively measured by the patient's CGM, several parameters of physical activity measures by the patient's smartwatch and finally information about food intake, which the patient inserts manually to the proposed smartphone application. The system output should be an accurate recommendation on the amount of insulin to inject at a certain time as well as diagrams or text explaining the occurrence of the recommendation. ### Implementation This repo has been created to demonstrate the effectivity of the system in a controlled environment, and thus should only be seen as a proof of concept. A demo script is included that allows to experiment with input parameters to investigate limitations of the current implementation (see section Demo). #### General structure To maintain the structure of the knowledge system as developed using the CommonKADS approach, we created five different classes: a task class, three inference classes, and a knowledge base class. Besides those main classes we used two helper classes which were responsible for generating message strings as well as storing the series of predictions made by the system. Each of the main classes implemented the methods that corresponded to the responsibilities as described by the knowledge model. Because the goal use of our system is a constant monitoring loop, we built a rough draft of a controller instance on top of this hierarchy that creates a list of sample data observation that iteratively are fed into the pipeline. We also implemented an interactive console application that each iteration generates some output, an intervention message when needed and queried the user whether action should be taken (eat x grams of sugar/ inject x units of fast insulin). Those actions were then incorporated into the next iteration of the system. #### Predicting future blood glucose concentrations A major challenge of the system was the implementation structure of the blood glucose prediction. The mathematical functions that describe the impact of certain factors on blood glucose levels can only be described on a conceptual level as the factual values of those functions depend on too many factors that cannot be assessed, e.g. individual patient factors (sleep quality, mood, hormones), time of the day, temperature and many more. Expecting patients or even trained medical specialist to quantify those functions exactly would be absurd. In order to nevertheless extract the valuable expert knowledge we decided upon a strategy that approximates those functions in a way that allows us to directly relate the parameters of those functions to intuitive expert knowledge. ![Alt text](images/increaseBGC.png?raw=true "Title") ![Alt text](images/cumulativeincreaseBGC.png?raw=true "Title") After the first interview with our experts we knew that the increase in blood glucose levels should approximately follow the function as shown in left in the figure above. In order to bring it conceptually closer to the absolute change in blood glucose levels we compute the cumulative increase as shown in the right figure. Albeit more intuitive to understand, it still did not allow to extract meaningful parameters from the function. This however could be achieved, using a simple piece wise linear function approximation of that function, as shown below. On a conceptual level, this function can be described using three parameters: the delay of the onset of the effect, the total increase at the end of the effect and the duration of the effect. All three of those parameters describe the function in terms that can easily be described by diabetes experts. <p align="center"> <img src="https://github.com/maragori/Diabuddy/blob/master/images/approx.png" alt=""/> </p> Using those linear functions, we were able to describe all rule types for factors that increase or decrease the blood glucose levels. In order to account for the delaying effects of other factors, i.e. uptake of protein or fat, we just needed to alter the given effect function such that the first part of the linear function (effect=0) was prolonged. This approximation system thus allowed us to describe and combine all factors that influence blood glucose level in a simple and intuitive way. The linear approximation also enabled for a straightforward implementation of the general prediction model given a set of influence factors in each iteration of the monitoring loop. In order for this approximation to work we also had to assume that the case of multiple factors influencing blood glucose could be described using an additive model without any interaction between those factors. Given this assumption we could simply add all influences and the current prediction of the blood glucose timeline, rendering us with an aggregated piecewise linear function describing both the blood glucose prediction function and all factors influencing blood glucose. <p align="center"> <img src="https://github.com/maragori/Diabuddy/blob/master/images/multiple_influences.png" alt=""/> </p> #### Code implementation Given the additive model approximation, the implementation into software was straightforward. Both predicted blood glucose curves and cumulative influences were segmented into 10 minute timesteps and stored in arrays. This thus does not yet realize the intended event-driven monitoring system, but rather a time based iteration approach that each timestep aggregates data from the past iteration period. Simplifying the monitoring frequency however allowed to construct more intuitive and easy to follow example scenarios and should not limit the generalization of this prototypical system to a more complex setting. Each iteration of the monitoring loop the output blood glucose array from last iteration would be passed to the system, new influence arrays were created according to the knowledge model and aggregated into the blood glucose array. After each iteration all influence arrays were discarded and only the resulting blood glucose array was passed on further down the pipeline. ## DEMO To run the demo, clone the repo and run demo.py from console. Requires only numpy, matplotlib and argparse. Two scenarios are available: #### Scenario 1 Type 1 diabetes patient Anna eats a medium-sized banana for breakfast and drinks black coffee. This meal contains 89 calories. The nutritional values are composed of 1.1g protein, 12.8g fast carbohydrates, 10g complex carbohydrates, and 12.2g sugar. After entering the nutritional data into the system, it advises her to inject 3 units of fast insulin, which she does after 10 minutes. #### Scenario 2 After work. type 1 diabetes patient Peter decides to perform an intensive, 30-minute running workout followed by another 30 minutes of moderate walking. After the high intensity workout, he injects 2 units of fast insulin to counteract the effects of the workout. In order to strengthen himself, he eats a chocolate bar after 40 minutes, during his moderate exercise unit. The same contains 250 calories, 13g fat, 31g (fast) carbs and 4g of proteins. Demo options: -s choose scenario 1 or 2 (int) -c set starting blood glucose concentration (int)
Shell
UTF-8
1,031
3.46875
3
[]
no_license
#!/bin/bash # install headphones # update programs and Upgrade any software packages echo 'Start update and upgrade' sudo apt-get update -y && sudo apt-get upgrade -y # Install dependencies sudo apt-get install git-core -y # Git clone the Headphones installation into Raspbian echo 'Download from github' sudo git clone https://github.com/rembo10/headphones.git /opt/headphones # Make pi the owner (change to desired user if wanted) sudo chown -R pi:pi /opt/headphones # set to listen external machines aswell (otherwise only local) sed -i "/http_host = /c\http_host = 0.0.0.0" /opt/headphones/config.ini #auto start by init.d file echo 'auto start file settings' cat > /etc/default/headphones <<EOF HP_USER=pi HP_HOME=/opt/headphones HP_PORT=8181 EOF #copy the defailt init.d script sudo cp /opt/headphones/init-scripts/init.ubuntu /etc/init.d/headphones # make executeable sudo chmod +x /etc/init.d/headphones # Update init to use the headphones script sudo update-rc.d headphones defaults echo 'finished installation'
Python
UTF-8
115
2.65625
3
[]
no_license
#asctime import time print(time.asctime(time.gmtime())) """ output: ------- Wed Jul 21 10:16:16 2021 """
Java
UTF-8
1,262
2.765625
3
[]
no_license
package methodEmbedding.Cookie_Clicker_Alpha.S.LYD1244; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.DecimalFormat; public class CookieClickerAlpha { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("C:/B-small-attempt0.in"))); int numCase = Integer.parseInt(br.readLine()); String output[] = new String[numCase]; DecimalFormat df = new DecimalFormat("#.0000000"); for (int i = 0; i < numCase; i++) { String CXF[] = br.readLine().split(" "); double rate = 2; double timeTaken = 0; double minTime; double C = Double.parseDouble(CXF[0]); double X = Double.parseDouble(CXF[1]); double F = Double.parseDouble(CXF[2]); minTime = F/rate; while(true){ timeTaken = timeTaken + C/rate; rate = rate + X; timeTaken = timeTaken + F/rate; if(timeTaken > minTime) break; else minTime = timeTaken; timeTaken = timeTaken - F/rate; } output[i] = df.format(minTime); } for (int out = 0; out < numCase; out++) System.out.println("Case #" + (out + 1) + ": " + output[out]); } }
JavaScript
UTF-8
1,696
2.515625
3
[]
no_license
// 모듈을 추출합니다. var connect = require('connect'); var fs = require('fs'); // 변수를 선언 합니다. var id = 'rintiantta'; var password = '12345678'; // 서버를 생성합니다. var server = connect.createServer(); // 미들웨어를 사용합니다. server.use(connect.cookieParser()); server.use(connect.bodyParser()); server.use(connect.router(function (app) { // GET - /LOGIN app.get('/Login', function (request, response) { if (request.cookies.auth == true) { // 응답합니다. response.writeHead(200, { 'Content-Type': 'text/html' }); response.end('<h1>Login Success</h1>'); } else { // 로그인이 되어있지 않을 경우 fs.readFile('Login.htm', function (error, data) { // 응답합니다. response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(data); }); } }); // POST - /LOGIN app.post('/Login', function (request, response) { if (request.body.id == id && request.body.password == password) { // 로그인 성공 시 response.writeHead(302, { 'Location': '/Login', 'Set-Cookie': ['auth=true'] }); response.end(); } else { // 로그인 실패 시 response.writeHead(200, { 'Content-Type': 'text/html' }); response.end('<h1>Login FAIL</h1>'); } }); })); // 서버를 실행합니다. server.listen(52273, function () { console.log('server running at http://127.0.0.1:52273'); });