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
Java
UTF-8
320
2.375
2
[ "MIT" ]
permissive
package de.henningBrinkmann.mybatisSample.util; public class SurroundingClassnameLogger extends LoggerAdapter { private String name; public SurroundingClassnameLogger() { this.name = "???"; } public void setName(String name) { this.name = name; } @Override public String getName() { return name; } }
Java
UTF-8
946
2.796875
3
[ "Apache-2.0" ]
permissive
package com.steven.common.valid; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.HashSet; import java.util.Set; /** * @author steven * @desc 自定义校验器的处理方法 * @date 2021/2/8 10:51 */ public class ShowStatusValidator implements ConstraintValidator<ShowStatusValue,Integer> { private Set<Integer> values = new HashSet<>(); @Override public void initialize(ShowStatusValue constraintAnnotation) { System.out.println("ShowStatusValidator.initialize"); int[] valuesInt = constraintAnnotation.values(); for (int value : valuesInt) { values.add(value); } } /** * 校验传入的参数 * @param value * @param context * @return */ @Override public boolean isValid(Integer value, ConstraintValidatorContext context) { return values.contains(value); } }
PHP
UTF-8
3,710
2.515625
3
[]
no_license
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ include_once '../DAO/daoUsuarios.php'; include_once '../Controladores/UsuarioController.php'; include_once '../Modelos/UsuarioModel.php'; if (session_status() != PHP_SESSION_ACTIVE) { session_start(); } if (isset($_GET['busuario'])) { $daoUsuario = new daoUsuarios(); $usuarios = $daoUsuario->get_usuario_by_nombre_usuario($_GET['user']); $daoUsuario->destruct(); if (mysqli_num_rows($usuarios) > 0) { echo '<table>'; while ($aux = mysqli_fetch_array($usuarios)) { echo '<tr>'; echo '<td>' . $aux[0] . '</td>'; echo '<td>' . $aux[1] . '</td>'; echo '<td>' . $aux[2] . '</td>'; echo '<td>' . $aux[3] . '</td>'; echo '<td><form action="../Controladores/busquedaUsuarioController_admin.php" method="POST" ><input type="submit" id="eliminar" name="eliminar" value="Eliminar usuario"/><input name="nombre_usuario" id="nombre_usuario" value="' . $aux[0] . '" hidden /></form></td>'; echo '<td><a href="../Vistas/modificar_usuario_admin.php?nombre_usuario=' . $aux[0] . '" ><button>Modificar usuario</button></a></td>'; echo '</tr>'; } echo '</table>'; } unset($_GET['busuario']); } if (isset($_POST['eliminar'])) { $daoUsuario = new daoUsuarios(); $usuarios = $daoUsuario->eliminar_usuario($_POST['nombre_usuario']); $daoUsuario->destruct(); header("Location: ../Vistas/busqueda_usuario_admin.php"); } if (isset($_POST['guardar'])) { $usuario = new Usuario($_POST['nombre_apellidos'], $_POST['nombre_usuario'], $_POST['contrasenya'], $_POST['moroso']); $usuario->set_moroso($_POST['moroso']); $usuario->setTipo($_POST['tipo']); $usuario->set_contrasenya_user($_POST['contrasenya']); $usuario->set_nombre_apellidos($_POST['nombre_apellidos']); $usuario->set_nombre_usuario($_POST['nombre_usuario']); $daoUsuario = new daoUsuarios(); $daoUsuario->modificar_usuario($usuario); $daoUsuario->destruct(); unset($_SESSION['searchuser']); unset($_POST['guardar']); header("Location: ../Vistas/busqueda_usuario_admin.php"); } function listar_usuarios() { $daoUsuario = new daoUsuarios(); $usuarios = $daoUsuario->leer_usuarios(); $daoUsuario->destruct(); if (mysqli_num_rows($usuarios) > 0) { echo '<table>'; while ($aux = mysqli_fetch_array($usuarios)) { echo '<tr>'; echo '<td>' . $aux[0] . '</td>'; echo '<td>' . $aux[1] . '</td>'; echo '<td>' . $aux[2] . '</td>'; echo '<td>' . $aux[3] . '</td>'; echo '<td><form action="../Controladores/busquedaUsuarioController_admin.php" method="POST" ><input type="submit" id="eliminar" name="eliminar" value="Eliminar usuario"/><input name="nombre_usuario" id="nombre_usuario" value="' . $aux[0] . '" hidden /></form></td>'; echo '<td><a href="../Vistas/modificar_usuario_admin.php?nombre_usuario=' . $aux[0] . '" ><button>Modificar usuario</button></a></td>'; echo '</tr>'; } echo '</table>'; } } function getDatosPerfil_admin($nombre_usuario) { $usuario = getUsuarioByUsuario($nombre_usuario); $datos = []; array_push($datos, $usuario->get_nombre_usuario()); array_push($datos, $usuario->get_nombre_apellidos()); array_push($datos, $usuario->get_contrasenya_user()); array_push($datos, $usuario->get_moroso()); array_push($datos, $usuario->getTipoUsr()); return $datos; }
Python
UTF-8
56
2.734375
3
[]
no_license
import math def square_root(a): return math.sqrt(a)
C#
UTF-8
9,344
2.625
3
[ "MIT" ]
permissive
namespace Ren.CMS.CORE.Language { using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Security; using Ren.CMS.CORE.SettingsHelper; using Ren.CMS.CORE.SqlHelper; using Ren.CMS.Persistence.Base; public class Language { #region Fields ThisApplication.ThisApplication AppT = new ThisApplication.ThisApplication(); private string lineName = ""; private string lngcode = null; private string pPackage = "Root"; private MembershipUser User = new MemberShip.nProvider.CurrentUser().nUser; #endregion Fields #region Constructors /// <summary> /// Init the Language Class with a given Lang-Code /// </summary> /// <param name="langcode">Lang-Code for this Instance</param> /// <param name="package">The Package for the Language Instance (Default: Root)</param> public Language(string langcode, string package = "Root") { if (langcode == "__USER__") { langcode = Helper.CurrentLanguageHelper.CurrentLanguage; } this.lngcode = langcode; this.pPackage = package; } /// <summary> /// Init the Language Class and sets the Lang-Code to "deDE" /// </summary> /// <param name="package">The Package for the Language Instance (Default: Root)</param> public Language() { } /// <summary> /// Instant init. This Init activates the "GetInstant()" Function and returns directly an language line. /// Example: Name = new Language("name","Root","deDE").GetInstant(); /// </summary> /// <param name="LangLineName">Name of the language line</param> /// <param name="PackageName">Name of the Package</param> /// <param name="code">Language code (default: deDE)</param> public Language(string LangLineName, string PackageName, string code = "deDe") { this.lineName = LangLineName; this.pPackage = PackageName; this.lngcode = code; } #endregion Constructors #region Properties /// <summary> /// Sets the Package for this instance. Default: Root /// </summary> public string Package { get { return this.pPackage; } set { this.pPackage = value; } } #endregion Properties #region Methods public string GetInstant() { return this.getLine(lineName); } /// <summary> /// Loads a Language Line String from the Package (Set by this.Package / Default: Root) /// </summary> /// <param name="name">Name of the Language Line</param> /// <returns>(String)Content</returns> public string getLine(string name, Dictionary<string, string> DefaultReturnValue = null) { SqlHelper Sql = new SqlHelper(); string cmd = "SELECT TOP 1 * FROM " + AppT.getSqlPrefix + "Language WHERE Package=@Package AND Name=@Name AND Code=@Code"; SqlParameter[] P = new SqlParameter[] { new SqlParameter("@Package",this.pPackage), new SqlParameter("@Name",name), new SqlParameter("@Code",this.lngcode) }; string line = ""; try { Sql.SysConnect(); SqlDataReader Reader = Sql.SysReader(cmd, P); Reader.Read(); if (Reader.HasRows) { line = ((string)Reader["Content"]); } Sql.SysDisconnect(); } catch (SqlException e) { line = e.Message; } finally { } if (!LanglineExists(name, Package, this.lngcode) && DefaultReturnValue != null) { line = this.registerDefaultValues(name, this.pPackage, DefaultReturnValue); } if (String.IsNullOrEmpty(line)) line = name; return line; } /// <summary> /// Inserts an Language Line. /// </summary> /// <param name="name">Name of the Line</param> /// <param name="Content">Content of the Line</param> public void InsertLine(string name, string Content, bool overwriteDB = false) { //Checking for langline SqlHelper Sql = new SqlHelper(); Sql.SysConnect(); if (this.LanglineExists(name, Package, this.lngcode) && !overwriteDB) throw new Exception("Language Line " + name + "(" + this.lngcode + ") does allready exists in Package: " + Package); if (this.LanglineExists(name, Package, this.lngcode)){ BaseRepository<Ren.CMS.Persistence.Domain.tbLanguage> LangRepo = new BaseRepository<Persistence.Domain.tbLanguage>(); Ren.CMS.Persistence.Domain.tbLanguage l = LangRepo.GetOne(NHibernate.Criterion.Expression.Where<Ren.CMS.Persistence.Domain.tbLanguage>(e => e.Code == this.lngcode && e.Name == name && e.Package == Package)); if(l != null) { l.Content = Content; LangRepo.Update(l); } } else{ string cmd = "INSERT INTO " + AppT.getSqlPrefix + "Language (Name, Content, Package, Code) VALUES (@Name,@Content,@Package,@Code)"; SqlParameter[] Parameters = new SqlParameter[]{ new SqlParameter("@Name", name), new SqlParameter("@Content", Content), new SqlParameter("@Package", this.pPackage), new SqlParameter("@Code", this.lngcode), }; try { Sql.SysNonQuery(cmd, Parameters); Sql.SysDisconnect(); } catch (SqlException e) { throw e; } finally { } } } public bool LanglineExists(string LangName, string LangPackage, string LangCode) { if (LangCode == "__USER__" && HttpContext.Current.Request.IsAuthenticated) { if (User == null) User = new MemberShip.nProvider.CurrentUser().nUser; Settings.UserSettings Us = new Settings.UserSettings(User); object lc = Us.getSetting("langCode").Value; if (lc != null) LangCode = lc.ToString(); else LangCode = ""; } if (String.IsNullOrEmpty(LangCode)) { SettingsHelper.GlobalSettingsHelper GS = new SettingsHelper.GlobalSettingsHelper(); LangCode = GS.Read("GLOBAL_DEFAULT_LANGUAGE"); } string check = "SELECT * FROM " + AppT.getSqlPrefix + "Language WHERE Name=@name AND Package=@package AND Code=@code"; SqlHelper Sql = new SqlHelper(); Sql.SysConnect(); bool exists = false; SqlDataReader R = Sql.SysReader(check, new nSqlParameterCollection(){ {"@name", LangName }, {"@package", LangPackage}, {"@code", LangCode}}); exists = R.HasRows; R.Close(); Sql.SysDisconnect(); return exists; } private string registerDefaultValues(string forLangLine, string forPackage, Dictionary<string, string> DefaultReturnValue) { string returnValue = null; //Database Action CORE.SqlHelper.SqlHelper SQL = new CORE.SqlHelper.SqlHelper(); CORE.ThisApplication.ThisApplication TA = new CORE.ThisApplication.ThisApplication(); string prefix = TA.getSqlPrefix; string query = "SELECT code FROM " + prefix + "Lang_Codes"; CORE.SqlHelper.nSqlParameterCollection SQLCOL = new CORE.SqlHelper.nSqlParameterCollection(); SQL.SysConnect(); SqlDataReader Codes = SQL.SysReader(query, SQLCOL); Language Lang = null; if (Codes.HasRows) { while (Codes.Read()) { Lang = new Language((string)Codes["code"], forPackage); if (DefaultReturnValue[(string)Codes["code"]] == null) { DefaultReturnValue.Add((string)Codes["code"], DefaultReturnValue.Where(code => code.Value != null).First().Value); } Lang.InsertLine(forLangLine, DefaultReturnValue[(string)Codes["code"]]); } } Codes.Close(); Lang = new CORE.Language.Language(this.lngcode, forPackage); returnValue = Lang.getLine(forLangLine); if (returnValue == "") { returnValue = forLangLine; } SQL.SysDisconnect(); return returnValue; } #endregion Methods } }
Java
UTF-8
1,036
3.828125
4
[]
no_license
package ch06_Sorting; import java.util.Scanner; public class ShellSort2 { //셀 정렬 static void shellSort(int[] a,int n){ int h; for(h=1; h<n/9; h=h*3+1); for(; h>0; h/=3) for(int i=h; i<n; i++){ int j; int tmp = a[i]; for (j=i-h; j>=0&& a[j]>tmp;j-=h ) a[j+h] = a[j]; a[j+h] = tmp; } } public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.println("셀 정렬(버전2)"); System.out.print("요솟수: "); int nx = stdIn.nextInt(); int[] x = new int[nx]; for(int i=0; i<nx; i++){ System.out.print("x["+i+"]: "); x[i] = stdIn.nextInt(); } shellSort(x,nx); //배열 x를 셀 정렬 System.out.println("오름차순으로 정렬했습니다."); for (int i=0; i<nx; i++) System.out.println("x["+i+"]: "+x[i]); } }
Java
UTF-8
2,594
2.46875
2
[]
no_license
package com.stockbit.AnswerNo2.listener; import com.stockbit.AnswerNo2.model.MappingData; import com.stockbit.AnswerNo2.model.Data; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Service public class Consumer { private LocalDateTime previousMinutes = null; private List<ConsumerRecord<String, Data>> listRecord = new ArrayList<>(); private List<String> result = new ArrayList<>(); @KafkaListener(topics = "tester6", groupId = "test-consumer-group", containerFactory = "kafkaListenerContainerFactory") public void consume(ConsumerRecord<String, Data> record) { LocalDateTime localDateTime = LocalDateTime.parse(record.value().getLocalDateTime()); if(previousMinutes != null){ long duration = Duration.between(previousMinutes.truncatedTo(ChronoUnit.MINUTES),localDateTime.truncatedTo(ChronoUnit.MINUTES)).toMinutes(); if(duration > 0){ calculateMap(listRecord, previousMinutes); listRecord.clear(); listRecord.add(record); previousMinutes = localDateTime; }else{ listRecord.add(record); } }else{ previousMinutes = localDateTime; listRecord.add(record); } } public void calculateMap(List<ConsumerRecord<String, Data>> batchRecord, LocalDateTime time){ HashMap<String, MappingData> dataContainer = new HashMap<>(); String stringTime = time.getHour() +":"+ time.getMinute() +":00"; for (ConsumerRecord<String, Data> data: batchRecord) { String key = data.key(); long amount = data.value().getAmount(); if(dataContainer.containsKey(key)){ dataContainer.get(key).setMin(amount); dataContainer.get(key).setMax(amount); }else{ MappingData mappingData = new MappingData(); mappingData.setId(key); mappingData.setMax(amount); mappingData.setMin(amount); mappingData.setTime(stringTime); dataContainer.put(key, mappingData); } } for (String key :dataContainer.keySet()) { System.out.println(dataContainer.get(key).formatter()); } } }
JavaScript
UTF-8
2,747
3.03125
3
[]
no_license
$("#error").hide(); $("#tipo").change(function(e){ var opcion = $("select option").filter(":selected").val(); if (opcion === "1"){ $("#rut-label").html("Rut"); } else if (opcion === "2"){ $("#rut-label").html("Pasaporte"); } } ); $("#formulario").submit(function(e){ var mensaje = ""; var opcion = $("select option").filter(":selected").val(); var rut = $("#rut").val().trim(); if (opcion === "Tipo de Identificación"){ mensaje ="No se seleccionó el tipo de identificación"; } else if (rut.length === 0){ mensaje = "Debes ingresar la identificación"; } else if (opcion === "1" && !checkRut(rut)){ mensaje = "Rut Inválido"; } else if($("#nombre").val().trim().length === 0){ mensaje = "Debes ingresar el nombre"; } else if($("#apellido").val().trim().length === 0){ mensaje = "Debes ingresar el apellido"; } else if($("#mail").val().trim().length === 0){ mensaje = "Debes ingresar un correo electrónico"; } else if($("#ciudad").val().trim().length === 0){ mensaje = "Debes ingresar tu ciudad de residencia"; } else if($("#comentarios").val().trim().length > 50){ mensaje = "El comentario no puede tener mas de 50 caracteres"; } if (mensaje != ""){ e.preventDefault(); $("#error").html(mensaje); $("#error").show(); } }) function checkRut(rut) { // Despejar Puntos var valor = rut.replace('.', ''); // Despejar Guión valor = valor.replace('-', ''); // Aislar Cuerpo y Dígito Verificador cuerpo = valor.slice(0, -1); dv = valor.slice(-1).toUpperCase(); // Si no cumple con el mínimo ej. (n.nnn.nnn) if (cuerpo.length < 7) { return false; } // Calcular Dígito Verificador suma = 0; multiplo = 2; // Para cada dígito del Cuerpo for (i = 1; i <= cuerpo.length; i++) { // Obtener su Producto con el Múltiplo Correspondiente index = multiplo * valor.charAt(cuerpo.length - i); // Sumar al Contador General suma = suma + index; // Consolidar Múltiplo dentro del rango [2,7] if (multiplo < 7) { multiplo = multiplo + 1; } else { multiplo = 2; } } // Calcular Dígito Verificador en base al Módulo 11 dvEsperado = 11 - (suma % 11); // Casos Especiales (0 y K) dv = (dv == 'K') ? 10 : dv; dv = (dv == 0) ? 11 : dv; // Validar que el Cuerpo coincide con su Dígito Verificador if (dvEsperado != dv) { return false; } // Si todo sale bien, eliminar errores (decretar que es válido) return true; }
Markdown
UTF-8
4,494
2.65625
3
[ "Apache-2.0" ]
permissive
--- title: Control de Acceso linktitle: Control de Acceso description: Gestionar el Control de Acceso weight: 10 --- Jenkins X utiliza políticas de control de acceso basado en roles - en inglés Role-Based Access Control (RBAC) - para controlar el acceso a sus diversos recursos. La aplicación de las políticas es proporcionada por el [RBAC de Kubernetes](https://kubernetes.io/docs/reference/access-authn-authz/rbac/). Los [Equipos](/about/concepts/features/#teams) pueden tener varios [Entornos](/about/concepts/features/#environments) (p.ej, Dev, Staging, Production) junto con dinámicos [Entornos de Vista Previa](/docs/reference/preview/). Mantener sincronizados los recursos [`Role`](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) y [`RoleBinding`](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) pertenecientes al mecanismo RBAC de Kubernetes con todos los namespaces y miembros de su equipo puede ser un desafío. Para facilitar esta gestión, Jenkins X crea un nuevo [Recurso Personalizado](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) llamado [`EnvironmentRoleBinding`](/docs/reference/components/custom-resources/#environmentrolebinding) que le permite asociar un `Role` etiquetado con `jenkins.io/kind=EnvironmentRole` con tantos `Users` o `ServiceAccounts` como desee. Luego, el [controlador de roles](/commands/jx_controller_role/#jx-controller-role) tiene la misión de mantener la información replicada y consistente a través de todos los namespaces y entornos. El controlador de roles garantiza esta tarea actualizando constantemente los recursos `Role` y `RoleBinding` de cada namespace. Los roles son por equipo, por lo que es posible tener roles especiales por equipo o utilizar nombres comunes para los roles, pero personalizarlos para cada equipo. ## Implicaciones de Seguridad para el namespace admin Jenkins X almacena varias configuraciones y ajustes (por ejemplo, `Users`,` Teams`) en el namespace de administración principal (`jx`). Tenga cuidado al otorgar roles en el equipo `jx` predeterminado, ya que permitir a los usuarios editar algunos de estos archivos puede permitirles escalar sus permisos. En lugar de otorgar a los usuarios que no son administradores acceso al espacio de nombres `jx`, cree equipos y otorgue acceso a los usuarios cuando usen un clúster compartido. ## Roles Predeterminados Jenkins X incluye una colección de objetos `Role` predeterminados que puede utilizar en la plantilla `jenkins-x-platform`. Puede crear el suyo si lo desea, pero cualquier edición puede perderse cuando se actualiza Jenkins X. [viewer](https://github.com/jenkins-x/jenkins-x-platform/blob/master/jenkins-x-platform/templates/viewer-role.yaml) : El rol `viewer` permite el acceso de lectura a proyectos, construcciones y logs. No permite el acceso a información confidencial. [committer](https://github.com/jenkins-x/jenkins-x-platform/blob/master/jenkins-x-platform/templates/committer-role.yaml) : El role `committer` proporciona los mismos permisos que el `viewer` y permite al usuario iniciar construcciones e importar nuevos proyectos. [owner](https://github.com/jenkins-x/jenkins-x-platform/blob/master/jenkins-x-platform/templates/owner-role.yaml) : El rol `owner` permite a los usuarios modificar todos los recursos del equipo. ## Adicionar Usuarios Para adicionar usuarios utilice el comando [jx create user](/commands/jx_create_user/), p.ej: ```sh jx create user --email "joe@example.com" --login joe --name "Joe Bloggs" ``` ## Modificar Roles del Usuario Para modificar los roles de un usuario utilice el comando [jx edit userroles](/commands/jx_edit_userroles/), p.ej: ```sh jx edit userrole --login joe ``` Si no utiliza el parámetro `--login` (`-l`) en la línea de comando el sistema le pedirá que elija el usuario a editar. Por ejemplo, para asignarle a `joe` el role `committer` (y elimine cualquier otro rol existente): ```sh jx edit userrole --login joe --role committer ``` Si tiene roles específicos y desea otorgar múltiples roles a un usuario, puede especificar los roles como una lista separada por comas: ```sh jx edit userrole --login joe --role committer,viewer ``` La modificación de los roles de un usuario cambia el `EnvironmentRoleBinding`. El [controlador de roles](/commands/jx_controller_role/#jx-controller-role) replicará estos cambios en todos los namespaces de entorno subyacentes.
PHP
UTF-8
1,818
2.65625
3
[]
no_license
<?php # FileName="Connection_php_mysql.htm" # Type="MYSQL"^M# HTTP="true" $hostname = "localhost"; $database = "polywords"; $username = "root"; $password = "cire1069"; $table = "scores"; $mysql = mysql_pconnect($hostname, $username, $password) or die(mysql_error()); mysql_select_db($database, $mysql); //print_r($_POST); $game_id = mysql_real_escape_string($_POST['GameID']); $mode = mysql_real_escape_string($_POST['Mode']); $time_counter = 0; while (!$data_available) { $query = "select word, score from in_progress_games where game_id = $game_id and mode != $mode and fetched = 0"; $result = mysql_query($query); $num_rows = mysql_num_rows($result); if ($num_rows) $data_available = TRUE; usleep(100000); $time_counter += 0.1; if ($time_counter > 2000) die(); } $query = "update in_progress_games set fetched = 1 where game_id = $game_id and mode != $mode"; mysql_query($query); $new_words_array = array(); $new_scores_array = array(); while ($row = mysql_fetch_array($result)) { $new_words_array[] = "<string>".$row['word']."</string>\n"; // $new_scores_array[] = "<string>".$row['score']."</string>\n"; } $query = "select sum(score) as total_score from in_progress_games where game_id = $game_id"; $result = mysql_query($query); $row = mysql_fetch_array($result); $total_score = $row['total_score']; if (sizeof($new_words_array)) { echo '<?xml version="1.0" encoding="UTF-8"?>'."\n"; echo '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'."\n"; echo '<plist version="1.0">'."\n"; echo "<array>\n"; echo "<array>\n"; echo implode("",$new_words_array); echo "</array>\n"; // echo "<array>\n"; echo "<string>$total_score</string>\n"; // echo "<string>4</string>\n"; // echo "</array>\n"; echo "</array>\n"; echo "</plist>\n"; } ?>
Python
UTF-8
1,051
2.8125
3
[]
no_license
from Myro import * init("sim") def forwardback (x): for i in range(0,x): forward(3, 0.5) backward(3, 0.5) stop forwardback(14) turnRight(10, 4.5) turnLeft(10, 4.5) def cross (x): for i in range(0,x): forward(5, 0.25) backward(5, 0.25) turnLeft(9, .2) wait(0.5) stop cross (6) def jazzsquare (x): for i in range (0,x): forward(4,.5) turnRight(5, 0.5) stop jazzsquare (3) turnRight(10, 4.5) turnLeft(10,4.5) cross(8) jazzsquare(2) turnRight(10, 2) turnLeft(10,2) def crazy (x): for i in range (0,x): forward(10, .1) backward(10, .1) turnRight(10, 2) turnLeft(10, 2) stop crazy(4) cross(4) def tensecondcircle (x): for i in range (0,x): move(3,3) wait(10) stop tensecondcircle(1) cross(4) jazzsquare(4) def sevensecondcircle (x): for i in range (0,x): move(3,3) wait(7) stop sevensecondcircle(1) cross(3) jazzsquare(4)
Java
UTF-8
572
2.90625
3
[]
no_license
package inJava.chapter2; import inJava.chapter0.LinkedListNode; public class Q8 { public LinkedListNode loopDetection(LinkedListNode l1) { if (l1 == null || l1.next == null) return null; LinkedListNode dummy = new LinkedListNode(0); dummy.next = l1; LinkedListNode fast = l1.next, slow = l1; while (fast.next != null && fast.next.next != null && fast != slow) { fast = fast.next.next; slow = slow.next; } if (fast != slow) return null; slow = dummy; while (slow != fast) { slow = slow.next; fast = fast.next; } return slow; } }
Python
UTF-8
1,897
3.171875
3
[]
no_license
# Unsolved with open('p059_cipher.txt') as f: nums = f.readlines() nums = [int(x) for x in nums[0].strip().split(',')] print len(nums), len(nums) / 3 perms = [] validPerms = [] def populatePerms(perms): for first in xrange(97, 122 + 1): for second in xrange(97, 122 + 1): for third in xrange(97, 122 + 1): tup = (first, second, third) perms.append(tup) validPerms.append(1) populatePerms(perms) def solve(perms, validPerms): for i in xrange(0, 1197 + 1, 3): if i % 100 == 0: print "At index: ", i for perm in enumerate(perms): # check if permutation of keys is a valid permutation if validPerms[perm[0]] == 0: continue # unpack permutation first, second, third = perm[1] isValid = decryptString(i, first, second, third) if not isValid: #print first, second, third, "Not valid at index: ", i validPerms[perm[0]] = 0 def decryptString(i, first, second, third): # retrieve chars to be decrypted (in sets of 3, per instructions) nFirst, nSecond, nThird = nums[i], nums[i+1], nums[i+2] # reverse XOR using first, second, and third as keys dFirst, dSecond, dThird = nFirst^first, nSecond^second, nThird^third # convert to string dFirst, dSecond, dThird = chr(dFirst), chr(dSecond), chr(dThird) if i == 0 and first == 97 and second == 97 and third == 97: print chr(first) + chr(second) + chr(third) + ": ", dFirst, dSecond, dThird dFirstValid = dFirst.isalpha() or dFirst == " " or dFirst == "'" dSecondValid = dSecond.isalpha() or dSecond == " " or dSecond == "'" dThirdValid = dThird.isalpha() or dThird == " " or dThird == "'" if dFirstValid and dSecondValid and dThirdValid: return True else: print chr(first) + chr(second) + chr(third) + ": ", dFirst, dSecond, dThird return False return True solve(perms, validPerms) perms = [x for x in perms if validPerms[perms.index(x)]] print len(perms)
C
UTF-8
746
2.9375
3
[]
no_license
#include "stdio.h" #include "stdlib.h" #include "string.h" #include "math.h" int main(int argc, char *argv[]) { int d, s, i, m[32], n[32], a = 0, b = 0, c; scanf("%d %d", &d, &s); for (i = 0; i < d; i++) { scanf("%d %d", &m[i], &n[i]); a += m[i]; b += n[i]; } if (s < a || s > b) { printf("NO"); } else { printf("YES\n"); c = b - s; for (i = 0; i < d; i++) { if (n[i] - m[i] <= c) { c -= n[i] - m[i]; printf("%d ", m[i]); } else if (c > 0) { printf("%d ", m[i] + c); c = 0; } else { printf("%d ", n[i]); } } } return 0; }
Markdown
UTF-8
2,015
2.96875
3
[ "MIT" ]
permissive
# AttrArray A high performance ActiveRecord concern for Rails using the PostgreSQL array type. ## Installation To install add the line to your Gemfile: ```ruby gem 'attr_array' ``` And `bundle install`. ## Dependencies AttrArray is developed as a ActiveRecord model concern, therefore it is dependent upon ActiveSupport. It is also developed only for use with PostgreSQL. It may work with other databases, but I haven't tried them. ## How To Use To add AttrArray to a model, include the concern: ```ruby class Post < ActiveRecord::Base include AttrArray attr_array :tags end ``` To autoload AttrArray for all models, add the following to an initializer: ```ruby require 'attr_array/active_record' ``` You then don't need to `include AttrArray` in any model. ### Scopes ```ruby with_any_#{tag_name} with_all_#{tag_name} without_any_#{tag_name} without_all_#{tag_name} ``` ### Class methods ```ruby all_#{tag_name} {tag_name}_cloud ``` ### Setup Add the model attributes you want to use with AttrArray in your migration: ```ruby class CreatePost < ActiveRecord::Migration[5.1] def change create_table :posts do |table| table.column :tags, :string, array: true, default: [], index: {using: 'gin'} table.column :authors, :string, array: true, default: [], index: {using: 'gin'} table.timestamps end end end ``` You can nominate multiple attributes in the `attr_array` class method: ```ruby class Post < ApplicationRecord include AttrArray attr_array :tags, :authors end ``` ### Usage ```ruby @post.tags = ["awesome", "slick"] @post.authors = ["Roald Dahl"] Post.with_any_authors("Roald Dahl") Post.without_any_tags("slick") ``` ## Acknowledgements This gem is based on code from [pg_tags](https://github.com/yosriady/pg_tags). Modified to use ActiveSupport::Concern and doesn't automatically hook into ActiveRecord. This gem is maintained by [Jurgen Jocubeit](https://github.com/JurgenJocubeit). ## Copyright Copyright 2017 Brightcommerce, Inc. All rights reserved.
C++
GB18030
1,919
2.953125
3
[]
no_license
#include "EnemyBase.h" EnemyBase::EnemyBase() :sprite(NULL) , hpBgSprite(NULL) , animationRight(NULL) , animationLeft(NULL) , animationExplode(NULL) , runSpeed(0) , maxHp(0) , currHp(0) , hpPercentage(100) , hpBar(NULL) , enemySuccessful(false) { } EnemyBase::~EnemyBase() { } bool EnemyBase::init() { if (!Sprite::init()) { return false; } return true; } void EnemyBase::createAndSetHpBar()//Ѫ { hpBgSprite = Sprite::createWithSpriteFrameName("hpBg1.png"); hpBgSprite->setPosition(Point(sprite->getContentSize().width / 2, sprite->getContentSize().height)); sprite->addChild(hpBgSprite); hpBar = ProgressTimer::create(Sprite::createWithSpriteFrameName("hp1.png")); hpBar->setType(ProgressTimer::Type::BAR); hpBar->setMidpoint(Point(0, 0.5f)); hpBar->setBarChangeRate(Point(1, 0)); hpBar->setPercentage(hpPercentage); hpBar->setPosition(Point(hpBgSprite->getContentSize().width / 2, hpBgSprite->getContentSize().height / 3 * 2)); hpBgSprite->addChild(hpBar); } Animation* EnemyBase::createAnimation(std::string prefixName, int framesNum, float delay)// { //һ֡Vector洢ÿһ֡ Vector<SpriteFrame*> animFrames; //ÿһ֡ͨgetSpriteFrameByNameдÿһ֡ͬʱӵ animFramesȥ for (int i = 1; i <= framesNum; i++) { char buffer[20] = { 0 }; sprintf(buffer, "_%i.png", i); std::string str = prefixName + buffer; auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str); animFrames.pushBack(frame); } //createWithSpriteFramesһ֡һAnimation return Animation::createWithSpriteFrames(animFrames, delay); } void EnemyBase::moveToArrow(Point position1,Point position2) { sprite->setPosition(position1); auto moveTo = MoveTo::create(15.0f, position2); sprite->runAction(moveTo); }
Python
UTF-8
2,707
2.828125
3
[]
no_license
import numpy as np import struct import matplotlib.pyplot as plt import matplotlib.cm as cm import pylab import read_mnist from sklearn.decomposition import PCA def display_reduced(data, labels): plt.figure(figsize=(12, 10)) axes = plt.subplot(111) type0_x = [] type0_y = [] type1_x = [] type1_y = [] type2_x = [] type2_y = [] type3_x = [] type3_y = [] type4_x = [] type4_y = [] type5_x = [] type5_y = [] type6_x = [] type6_y = [] type7_x = [] type7_y = [] type8_x = [] type8_y = [] type9_x = [] type9_y = [] for i in range(len(labels)): if labels[i] == 0: type0_x.append(data[i][0]) type0_y.append(data[i][1]) elif labels[i] == 1: type1_x.append(data[i][0]) type1_y.append(data[i][1]) elif labels[i] == 2: type2_x.append(data[i][0]) type2_y.append(data[i][1]) elif labels[i] == 3: type3_x.append(data[i][0]) type3_y.append(data[i][1]) elif labels[i] == 4: type4_x.append(data[i][0]) type4_y.append(data[i][1]) elif labels[i] == 5: type5_x.append(data[i][0]) type5_y.append(data[i][1]) elif labels[i] == 6: type6_x.append(data[i][0]) type6_y.append(data[i][1]) elif labels[i] == 7: type7_x.append(data[i][0]) type7_y.append(data[i][1]) elif labels[i] == 8: type8_x.append(data[i][0]) type8_y.append(data[i][1]) elif labels[i] == 9: type9_x.append(data[i][0]) type9_y.append(data[i][1]) type0 = axes.scatter(type0_x, type0_y, s=10, marker='.') type1 = axes.scatter(type1_x, type1_y, s=10, marker='o') type2 = axes.scatter(type2_x, type2_y, s=10, marker='v') type3 = axes.scatter(type3_x, type3_y, s=10, marker='^') type4 = axes.scatter(type4_x, type4_y, s=10, marker='8') type5 = axes.scatter(type5_x, type5_y, s=10, marker='s') type6 = axes.scatter(type6_x, type6_y, s=10, marker='p') type7 = axes.scatter(type7_x, type7_y, s=10, marker='*') type8 = axes.scatter(type8_x, type8_y, s=10, marker='+') type9 = axes.scatter(type9_x, type9_y, s=10, marker='x') axes.legend((type0, type1, type2, type3, type4, type5, type6, type7, type8, type9), ('0','1','2','3','4','5','6','7','8','9'), loc=1) plt.show() images = read_mnist.read_images('train-images.idx3-ubyte') labels = read_mnist.read_labels('train-labels.idx1-ubyte') X = np.array(images) pca = PCA(n_components=2) X_new = pca.fit_transform(X) display_reduced(X_new, labels[:,0])
C#
UTF-8
520
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace xave.web.generator.helper.Util { public static class ArrayHandler { public static T[] Add<T>(this T[] target, T item) { if (item == null) return target; if (target == null) target = new T[] { }; T[] result = new T[target.Length + 1]; target.CopyTo(result, 0); result[target.Length] = item; return result; } } }
Java
UTF-8
1,361
2.265625
2
[]
no_license
package compasso.estagio.grupo.projeto5.Telas.model; import java.io.Serializable; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; @Entity public class Aula implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String titulo; private String video; private String descricao; private String pdf; private Tipo tipo; @ManyToMany(mappedBy = "aulas") private List<Perfil> alunos; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getVideo() { return video; } public void setVideo(String video) { this.video = video; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public String getPdf() { return "https://compersonal-bucket.s3.amazonaws.com/"+pdf; } public void setPdf(String pdf) { this.pdf = pdf; } public Tipo getTipo() { return tipo; } public void setTipo(Tipo tipo) { this.tipo = tipo; } }
C#
UTF-8
2,035
3.078125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; namespace AutoRenamer.BOL.Utils { public static class XmlSerializationHelper { public static string SerializeObject<T>(T obj) { string result; try { MemoryStream memoryStream = new MemoryStream(); XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); xmlSerializer.Serialize(xmlTextWriter, obj); memoryStream = (MemoryStream)xmlTextWriter.BaseStream; result = XmlSerializationHelper.Utf8ByteArrayToString(memoryStream.ToArray()); } catch { result = string.Empty; } return result; } public static T DeserializeObject<T>(string xml) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); MemoryStream stream = new MemoryStream(XmlSerializationHelper.StringToUtf8ByteArray(xml)); return (T)((object)xmlSerializer.Deserialize(stream)); } private static string Utf8ByteArrayToString(byte[] characters) { UTF8Encoding uTF8Encoding = new UTF8Encoding(); return uTF8Encoding.GetString(characters); } private static byte[] StringToUtf8ByteArray(string xmlString) { return xmlString.ToUtf8ByteArray(); } public static byte[] ToUtf8ByteArray(this string original) { if (original == null) { throw new NullReferenceException("ToUtf8ByteArray - The original string cannot be null"); } UTF8Encoding uTF8Encoding = new UTF8Encoding(); return uTF8Encoding.GetBytes(original); } } }
Markdown
UTF-8
2,792
3.453125
3
[ "MIT" ]
permissive
##Project ###Write a program to list out local shoe stores and the brands of shoes they carry. Make a Store class and a Brand class. * _Create a database called shoes and a testing database called shoes_test, and remember to follow proper naming conventions for your tables and columns. As you create your tables, copy all MySQL commands into your README._ * _Build full CRUD functionality for Stores. Create, Read (all and singular), Update, Delete (all and singular)._ * _Allow a user to create Brands that are assigned to a Store. Don't worry about updating or deleting Brands._ * _There is a many-to-many relationship between Brands and shoe Stores. Many Stores can carry many Brands and a Brand can be carried in many Stores. Create a join table to store these relationships._ * _When a user is viewing a single Store, list all Brands that Store currently carries, and allow them to add another Brand to that store. Create a method to get the Brands sold at a Store, and use a join statement in it._ * _When a user is viewing a single Brand, list all Stores that carry that Brand and allow them to add a Store to that Brand. Use a join statement in this method too._ * _When you are finished with the assignment, make sure to export your databases and commit the .sql.zip files for both the app database and the test database at the top of your project directory._ ##Objectives Does your Store class have all CRUD methods implemented in your app? That includes: Create, Read (all and singular) Update and Delete (all and singular). Are you able to view all the brands sold at a single store, as well as all the stores selling a particular brand? Is the many-to-many relationship set up correctly in the database? Did you use join statements? Are the commands on how to setup the database in the README? Did you include the .sql files? Are previous standards met? (See below) Is the project in a polished, portfolio-quality state? Does the application work as expected? Does the project demonstrate an understanding of all concepts from the week? If prompted, can you discuss your code with an instructor using the correct terminology? Previous Objectives Do the database table and column names follow proper naming conventions? Were Twig template files used for all Silex pages? Is your logic easy to understand? Are all tests passing? Did you use descriptive variable names? Does your code have proper indentation and spacing? Did you include a README with a description of the program, setup instructions, a copyright, a license, and your name? Is the project tracked in Git, and did you regularly make commits with clear messages that finish the phrase "This commit will…"?
Markdown
UTF-8
1,092
3.375
3
[]
no_license
# Actividad de ensamble En esta parte se invita a la discusión y se proponen los siguiente ejercicios de programaci\'on. Los puede realizar en papel. Puedes usar el repositorio que está en el la siguiente liga [:link:](https://github.com/UNAM-FESAc/c-prgrmmng-I-FESAc) - Realice un programa en C que imprima en pantalla __hola mundo__. - Realice un programa que muestre las tablas de multiplicar del 1 al 10. - Realice un programa, que use arreglos, que te pregunte tu nombre y otro dato personal, guarde esta informaci\'on y muestre un mensaje de bienvenida con los datos ingresados. ## Ejercicios: - *10array.c* Incrementa el número de elementos en el arreglo e inicializa algunos elementos en valores diferentes de cero. Por ejemplo: incializa los elementos [1], [2] en 10.0 y 105.3, respectivamente. Observa lo que sucede y comenta tu resultado con los demás compañeros. - Crea un arreglo que contenga el número de días de los meses del año, inicialice los meses 4, 6 y 12 en cero. Discuta sus resultados. - *11array.c* Discute lo que se realiza en este código.
Markdown
UTF-8
1,869
2.59375
3
[ "MIT" ]
permissive
## PIG DICE GAME ### Description This is a dice rolling game referred to as pig dice. Minimum number of players is 2. ### Requirements * Atom or Visual studio ### Technologies Used HTML CSS JAVASCRIPT JQUERY ### BDD | BEHAVIOR. This program should handle | INPUT. When it receives | OUTPUT. It should return. | | :------------- | :------------- | :--------------- | | Rolling dice | dice number:2,3,4,5,6 |records number got and adds to previous output.| | Rolling dice.| dice number:1 |Erases all recorded output and passes turn to second player.| | Addition to 100 points| Points that add up to 100| Player x has won!| ### Known bugs Currently no bugs have been detected. Incase of any kindly do not hesitate to contact me via my email. ### License MIT License Copyright (c) [2019] [Rodney Somoire] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### contacts rayr30667@gmail.com
Markdown
UTF-8
907
2.953125
3
[]
no_license
## 凯利公式 当前讨论凯利公式是按照最完美的情况,且投资的金额为单位1 | 结果 | 概率 | 盈利(元) | | ---- | ---- | -------- | | 成功 | P | b | | 失败 | 1-P | 0(亏光) | 那么得到重复多次最优的投资比例为: ``` f=(Pb-(1-P))/b ``` 从上述公式中我们可以得出: ``` 1. 当Pb-(1-P)<=0的时没有必要投资 2. 当Pb-(1-P)=1时可以all in 3. 其他任何时候都必须按照公式按照一定比例投资 ``` **注意事项:** 介于市场上的概率不好预测并且概率也是在不断变化,你的盈利也在不断变化,所以按照上述公式并不一定是最优解。套用**李永乐老师**的一句话: >如果仅靠一个公式就可以成为巴菲特的话,我早就是巴菲特了。 ## 折线图参考blog ```jshelllanguage https://www.cnblogs.com/newwind/p/5680389.html http://www.jfree.org/ ```
C
UTF-8
558
2.9375
3
[]
no_license
#include <stdio.h> #define LOCAL int main(void) { #ifdef LOCAL freopen("data2-5.in","r",stdin); freopen("data2-5.out","w",stdout); #endif int a,b,c,tmp; while(scanf("%d%d%d",&a,&b,&c) != EOF) { if (a==0 || b==0 ||c==0) {break;} printf("%d.",a/b); a = a%b*10; while(c-- >1) { printf("%d",a/b); a=a%b*10; } tmp = a%b * 10/b; if (tmp<5) printf("%d\n",a/b); else printf("%d\n",a/b+1); } return 0; }
JavaScript
UTF-8
2,438
2.5625
3
[ "MIT" ]
permissive
import nextID from "makeup-next-id"; const focusExitEmitters = {}; function doFocusExit(el, fromElement, toElement) { el.dispatchEvent( new CustomEvent("focusExit", { detail: { fromElement, toElement }, bubbles: false, // mirror the native mouseleave event }), ); } function onDocumentFocusIn(e) { const newFocusElement = e.target; const targetIsDescendant = this.el.contains(newFocusElement); // if focus has moved to a focusable descendant if (targetIsDescendant === true) { // set the target as the currently focussed element this.currentFocusElement = newFocusElement; } else { // else focus has not gone to a focusable descendant window.removeEventListener("blur", this.onWindowBlurListener); document.removeEventListener("focusin", this.onDocumentFocusInListener); doFocusExit(this.el, this.currentFocusElement, newFocusElement); this.currentFocusElement = null; } } function onWindowBlur() { doFocusExit(this.el, this.currentFocusElement, undefined); } function onWidgetFocusIn() { // listen for focus moving to anywhere in document // note that mouse click on buttons, checkboxes and radios does not trigger focus events in all browsers! document.addEventListener("focusin", this.onDocumentFocusInListener); // listen for focus leaving the window window.addEventListener("blur", this.onWindowBlurListener); } class FocusExitEmitter { constructor(el) { this.el = el; this.currentFocusElement = null; this.onWidgetFocusInListener = onWidgetFocusIn.bind(this); this.onDocumentFocusInListener = onDocumentFocusIn.bind(this); this.onWindowBlurListener = onWindowBlur.bind(this); this.el.addEventListener("focusin", this.onWidgetFocusInListener); } removeEventListeners() { window.removeEventListener("blur", this.onWindowBlurListener); document.removeEventListener("focusin", this.onDocumentFocusInListener); this.el.removeEventListener("focusin", this.onWidgetFocusInListener); } } export function addFocusExit(el) { let exitEmitter = null; nextID(el); if (!focusExitEmitters[el.id]) { exitEmitter = new FocusExitEmitter(el); focusExitEmitters[el.id] = exitEmitter; } return exitEmitter; } export function removeFocusExit(el) { const exitEmitter = focusExitEmitters[el.id]; if (exitEmitter) { exitEmitter.removeEventListeners(); delete focusExitEmitters[el.id]; } }
Java
UTF-8
2,460
2.484375
2
[]
no_license
package com.nambar.schoolbuslocator; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.util.Log; public class PreferencesStore { private static PreferencesStore _instance = new PreferencesStore(); static final String TAG = "Preferences"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private PreferencesStore() {} public static PreferencesStore getInstance() { return _instance; } private SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(LocatorSetup.class.getSimpleName(), Context.MODE_PRIVATE); } public String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } private int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } public void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } }
Python
UTF-8
2,308
2.78125
3
[]
no_license
import sqlite3 import pygal def getAdminData(): conn = sqlite3.connect("C:/Users/Administrator/Desktop/rollerorange.github.io-master/sportschoolDatabase.db") c = conn.cursor() cursor = c.execute('SELECT klantID FROM KLANT_SPORTSCHOOL') klanten = c.fetchall() klantenAantal = len(klanten) cursor = c.execute('SELECT klantID, locatie FROM KLANT_SPORTSCHOOL') locKlanten = c.fetchall() aantalAmsterdam = 0; aantalUtrecht = 0; aantalDenhaag = 0; aantalLelystad = 0; aantalAmersfoort = 0; for x in locKlanten: if x[1] == "Amsterdam": aantalAmsterdam += 1; elif x[1] == "Utrecht": aantalUtrecht += 1; elif x[1] == "Den Haag": aantalDenhaag += 1; elif x[1] == "Lelystad": aantalLelystad += 1; elif x[1] == "Amersfoort": aantalAmersfoort += 1 return(klantenAantal, aantalAmsterdam, aantalUtrecht, aantalDenhaag, aantalLelystad, aantalLelystad) def createAdminDataGraph(TOTAAL, KLANTENAMSTERDAM, KLANTENUTRECHT, KLANTENDENHAAG, KLANTENLELYSTAD, KLANTENAMERSFOORT): '''Maakt een .svg grafiek bestand data1 = List object met alle data data2 = List object met alle data data3 = List object met alle data data4 = List object met alle data data5 = List object met alle data''' custom_style = pygal.style.Style( colors=('#E853A0', '#E8537A', '#E95355', '#E87653', '#E89B53'), font_family='googlefont:Rubik') gauge = pygal.SolidGauge( half_pie=True, inner_radius=0.50, style=custom_style) gauge.add('Totaal', [{'value': TOTAAL, 'max_value': TOTAAL}]) gauge.add('Amsterdam', [{'value': KLANTENAMSTERDAM, 'max_value': TOTAAL}]) gauge.add('Utrecht', [{'value': KLANTENUTRECHT, 'max_value': TOTAAL}]) gauge.add('Den Haag', [{'value': KLANTENDENHAAG, 'max_value': TOTAAL}]) gauge.add('Lelystad', [{'value': KLANTENLELYSTAD, 'max_value': TOTAAL}]) gauge.add('Amersfoort', [{'value': KLANTENAMERSFOORT, 'max_value': TOTAAL}]) gauge.render_to_file("C:/Users/Administrator/Desktop/rollerorange.github.io-master/charts/adminChart.svg") locatieData = getAdminData() createAdminDataGraph(locatieData[0], locatieData[1], locatieData[2], locatieData[3], locatieData[4], locatieData[5])
C#
UTF-8
3,478
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; using nilnul.num.natural; namespace nilnul.num.rational { /// <summary> /// guratee that denominator is positive. /// </summary> public partial class Fraction_natural : RationalA, RationalI { public Natural2 numerator; public PositiveNatural3 _denominator; public PositiveNatural3 denominator { get{ return _denominator; } set{ nilnul.num.integer.Zero.AssertNot(value); _denominator=value; } } public Fraction_natural(Natural2 numerator) :this(numerator, new PositiveNatural3( 1)) { } public Fraction_natural(Natural2 numerator,PositiveNatural3 denominator) { this.numerator = numerator; this.denominator = denominator; } public Fraction_natural(BigInteger numerator, BigInteger denominator) :this(new Natural2(numerator),new PositiveNatural3(denominator)) { } public Fraction_natural inverse() { return Inverse(this); } public override string ToString() { return numerator.ToString() +"/"+denominator.ToString(); } public void simplify() { var standFrac=Divide.Eval(numerator, denominator); this.numerator = standFrac.numerator; this.denominator = standFrac.denominator; } public void reduce() { var standFrac = Divide.Eval(numerator, denominator); this.numerator = standFrac.numerator; this.denominator = standFrac.denominator; } public Fraction_natural reduce1() { var standFrac = Divide.Eval(numerator, denominator); this.numerator = standFrac.numerator; this.denominator = standFrac.denominator; return this; } public double toDouble() { return (double)(numerator) / (double)(denominator.val); } static public Fraction_natural Inverse(Fraction_natural a) { return new Fraction_natural(a.numerator, a.denominator); } static public Fraction_natural AddAndSimplify(Fraction_natural a,Fraction_natural b) { Fraction_natural r=new Fraction_natural(a.numerator.val*b.denominator.val+a.denominator.val*b.numerator.val,a.denominator.val*b.denominator.val); r.simplify(); return r; } static public Fraction_natural ToFraction2(long a) { return new Fraction_natural(a, 1); } static public Fraction_natural AddAndSimplify(Fraction_natural a, int b) { return AddAndSimplify(a, new Fraction_natural(b, 1)); } static public Fraction_natural AddAndSimplify(Fraction_natural a, long b) { return AddAndSimplify(a, new Fraction_natural(b, 1)); } static public Fraction_natural AddAndSimplify(int a,Fraction_natural b) { return AddAndSimplify( b,a); } static public Fraction_natural AddAndSimplify(long a, Fraction_natural b) { return AddAndSimplify(b, a); } /// <summary> /// to parse a string as fraction /// </summary> /// <param name="s"></param> /// <returns></returns> static public Fraction_natural Parse(string s) { ///first find the / /// /// string[] terms= s.Split(Divide.Sign); if (terms.Length!=2) { throw new Exception(string.Format("There are more than two terms sperated by {0}.",Divide.Sign)); } return new Fraction_natural(BigInteger.Parse(terms[0]), BigInteger.Parse(terms[1])); /// ///first is it an integer? /// } } }
Java
UTF-8
559
1.617188
2
[ "LGPL-2.1-or-later", "EPL-1.0", "Apache-2.0", "LGPL-2.0-or-later" ]
permissive
package org.strategoxt.lang.parallel.stratego_parallel; import org.spoofax.interpreter.core.IContext; import org.strategoxt.lang.Context; /** * @author Lennart Kats <lennart add lclnet.nl> */ public class InteropRegisterer extends org.strategoxt.lang.InteropRegisterer { @Override public void register(IContext context, Context compiledContext) { // TODO: stratego_parallel InteropRegisterer } @Override public void registerLazy(IContext context, Context compiledContext, ClassLoader classLoader) { // TODO: stratego_parallel InteropRegisterer } }
Python
UTF-8
4,266
2.71875
3
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/python2 import os import pygame import pycurl import StringIO import time import signal import logging import RPi.GPIO as GPIO WEBCAM_URL = 'http://user:password@10.13.37.128/snapshot.cgi' class ImageViewer(object): def __init__(self): self._running = False self._image_surf = None self._screen = None self._setup_logger() self._connection_problem = False def _setup_logger(self): self._logger = logging.getLogger('image') ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) self._logger.addHandler(ch) self._logger.setLevel(logging.DEBUG) def fast_capture(self, *args, **kwargs): self._wait_time = 0 #Turn on the screen: GPIO.output(11, GPIO.HIGH) self._logger.debug("FAST image capture enabled.") def slow_capture(self, *args, **kwargs): self._wait_time = 5 # Turn off the screen: GPIO.output(11, GPIO.LOW) self._logger.debug("SLOW image capture enabled.") def setup_screen(self): drivers = ['fbcon', 'directfb', 'svgalib'] found = False for driver in drivers: if not os.getenv('SDL_VIDEODRIVER'): os.putenv('SDL_VIDEODRIVER', driver) try: pygame.display.init() except pygame.error: print 'Driver: {0} failed.'.format(driver) continue found = True break pygame.mouse.set_visible(False) if not found: raise Exception('No suitable video driver found!') size = (pygame.display.Info().current_w, pygame.display.Info().current_h) screen = pygame.display.set_mode(size, pygame.FULLSCREEN) return screen def on_init(self): pygame.font.init() self._screen = self.setup_screen() # Font rendering: self._timestamp_font = pygame.font.SysFont("dejavusansmono", 15) # Curl self._curl = pycurl.Curl() self._curl.setopt(self._curl.URL, WEBCAM_URL) self._curl.setopt(pycurl.CONNECTTIMEOUT, 2) self._curl.setopt(pycurl.TIMEOUT, 2) self._curl.setopt(pycurl.NOSIGNAL, 1) # Raspberry Pi GPIO: GPIO.setmode(GPIO.BOARD) GPIO.setup(11, GPIO.OUT) self.slow_capture() self._running = True def on_event(self, event): if event.type == "QUIT": self._running = False def on_loop(self): self._image = StringIO.StringIO() self._curl.setopt(self._curl.WRITEFUNCTION, self._image.write) try: self._curl.perform() except Exception, e: #Problem fetching the image self._logger.error("Problem fetching image: %s" % e) self._connection_problem = True #Try again in a few seconds: time.sleep(5) return else: if self._connection_problem: self._connection_problem = False self._logger.info("Connection problem resolved, contining capture") self._image.seek(0) self._image_surf = pygame.image.load(self._image, "cam1.jpg").convert() time.sleep(self._wait_time) def on_render(self): self._screen.fill((0,0,0)) if self._connection_problem: self._screen.fill((255,0,0)) else: self._screen.blit(self._image_surf,(0,0)) timestamp = self._timestamp_font.render(time.ctime(), True, (255,255,255)) self._screen.blit(timestamp, (0,0)) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while( self._running ): for event in pygame.event.get(): self.on_event(event) self.on_loop() self.on_render() self.on_cleanup() if __name__ == "__main__": app = ImageViewer() #Setup signals to control the speed of image capture: # 20 - slow # 21 - fast signal.signal(20, app.slow_capture) signal.signal(21, app.fast_capture) app.on_execute()
SQL
UTF-8
896
3.5
4
[]
no_license
-- Drop existing tables DROP TABLE original_terms; DROP TABLE ontology_terms; DROP TABLE symbols; DROP TABLE synonyms; -- create metis tables CREATE TABLE ontology_terms ( id serial, ontology_uri text, ontology_term text, source_uri text, short_name text, PRIMARY KEY (id), UNIQUE (ontology_term) ); CREATE TABLE original_terms ( id serial, original text, ontology_uid integer, confidence float, PRIMARY KEY (id), UNIQUE (original), FOREIGN KEY (ontology_uid) REFERENCES public.ontology_terms(id) ); CREATE TABLE synonyms ( id serial, list_synonyms text, last_update timestamp, UNIQUE (list_synonyms), PRIMARY KEY (id) ); CREATE TABLE symbols ( id serial, synonyms_uid integer, symbol text, PRIMARY KEY (id), FOREIGN KEY (synonyms_uid) REFERENCES public.synonyms(id) );
Rust
UTF-8
978
3.46875
3
[ "Apache-2.0" ]
permissive
fn main() { let _v: Vec<i32> = Vec::new(); let _v2 = vec![1, 2, 3]; let mut v3 = Vec::new(); v3.push(5); v3.push(6); v3.push(7); v3.push(8); let v4 = vec![1, 2, 3, 4, 5]; let third: &i32 = &v4[2]; println!("The third element is {}", third); match v4.get(2) { Some(third) => println!("The third element is {}", third), None => println!("There is no third element"), } let v4 = vec![100, 32, 57]; for i in &v4 { println!("{}", i) } let mut v5 = vec![100, 32, 57]; for i in &mut v5 { *i += 50; } for i in &v5 { println!("{}", i) } #[derive(Debug)] enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; for i in &row { println!("{:?}", i) } }
C
UTF-8
657
3.046875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> // Ejemplo aprenderaprogramar.com int main() { FILE* fichero; char *uno="Espero se pueda esta mierda"; fichero = fopen("cursoAF1.txt", "w"); fputs(uno, fichero); fclose(fichero); printf("Proceso completado"); FILE *archivo; char caracteres[200]; archivo = fopen("cursoAF1.txt","r"); if (archivo == NULL) exit(1); else { printf("\nEl contenido del archivo de prueba es \n\n"); while (feof(archivo) == 0) { fgets(caracteres,200,archivo); printf("%s",caracteres); } } fclose(archivo); return 0; }
Java
UTF-8
12,505
1.5
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.cloud.teleport.v2.clients; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.services.dataplex.v1.CloudDataplex; import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones; import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Assets; import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Entities; import com.google.api.services.dataplex.v1.CloudDataplex.Projects.Locations.Lakes.Zones.Entities.Partitions; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Asset; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1AssetDiscoverySpec; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Entity; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ListEntitiesResponse; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ListPartitionsResponse; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Partition; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Schema; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1StorageFormat; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Zone; import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1ZoneDiscoverySpec; import com.google.cloud.teleport.v2.values.DataplexEnums.EntityType; import com.google.cloud.teleport.v2.values.DataplexEnums.StorageSystem; import com.google.cloud.teleport.v2.values.GetEntityRequestEntityView; import com.google.common.collect.ImmutableList; import java.io.IOException; import org.junit.Test; import org.mockito.Answers; /** * Test cases for the {@link DefaultDataplexClient} class. Inspired by {@link CsvConvertersTest}. */ public class DefaultDataplexClientTest { private static final String ZONE_NAME = "projects/project_1/locations/location_1/lakes/lake_1/zones/zone_1"; private static final String SHORT_ASSET_NAME1 = "asset_1"; private static final String ASSET_NAME1 = ZONE_NAME + "/asset/" + SHORT_ASSET_NAME1; private static final String ASSET_NAME2 = ZONE_NAME + "/asset/asset_2"; private static final String PAGE_TOKEN = "token_1"; // Entity for use in tests where it doens't matter what the values are private static final GoogleCloudDataplexV1Entity UNUSED_ENTITY = new GoogleCloudDataplexV1Entity() .setDataPath("invalid") .setSchema(new GoogleCloudDataplexV1Schema()) .setFormat(new GoogleCloudDataplexV1StorageFormat()) .setType(EntityType.TYPE_UNSPECIFIED.name()) .setSystem(StorageSystem.STORAGE_SYSTEM_UNSPECIFIED.name()) .setAsset("invalid") .setId("invalid"); private static final GoogleCloudDataplexV1AssetDiscoverySpec ENABLED_ASSET_DISCOVERY_SPEC = new GoogleCloudDataplexV1AssetDiscoverySpec().setEnabled(true); private static final GoogleCloudDataplexV1AssetDiscoverySpec DISABLED_ASSET_DISCOVERY_SPEC = new GoogleCloudDataplexV1AssetDiscoverySpec().setEnabled(false); private static final GoogleCloudDataplexV1ZoneDiscoverySpec ENABLED_ZONE_DISCOVERY_SPEC = new GoogleCloudDataplexV1ZoneDiscoverySpec().setEnabled(true); private static final GoogleCloudDataplexV1ZoneDiscoverySpec DISABLED_ZONE_DISCOVERY_SPEC = new GoogleCloudDataplexV1ZoneDiscoverySpec().setEnabled(false); @Test public void testGetGetCloudStorageEntitiesByAssetName() throws IOException { CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS); Entities.List entitiesListRequest = mock(Entities.List.class, Answers.RETURNS_DEEP_STUBS); when(cloudDataplexClient.projects().locations().lakes().zones().entities().list(ZONE_NAME)) .thenReturn(entitiesListRequest); GoogleCloudDataplexV1Entity entity1 = new GoogleCloudDataplexV1Entity() .setName("entity1") .setAsset(ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); GoogleCloudDataplexV1Entity entity2 = new GoogleCloudDataplexV1Entity() .setName("entity2") .setAsset(ASSET_NAME1) .setSystem("BIGQUERY"); // storage mismatch GoogleCloudDataplexV1Entity entity3 = new GoogleCloudDataplexV1Entity() .setName("entity3") .setAsset(ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); GoogleCloudDataplexV1Entity entity4 = new GoogleCloudDataplexV1Entity() .setName("entity4") .setAsset(ASSET_NAME2) .setSystem(StorageSystem.CLOUD_STORAGE.name()); // asset mismatch // an entity with a short asset name GoogleCloudDataplexV1Entity entity5 = new GoogleCloudDataplexV1Entity() .setName("entity5") .setAsset(SHORT_ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); GoogleCloudDataplexV1ListEntitiesResponse response1 = new GoogleCloudDataplexV1ListEntitiesResponse(); response1.setEntities(ImmutableList.of(entity1, entity2, entity3)); response1.setNextPageToken(PAGE_TOKEN); GoogleCloudDataplexV1ListEntitiesResponse response2 = new GoogleCloudDataplexV1ListEntitiesResponse(); response2.setEntities(ImmutableList.of(entity4, entity5)); when(entitiesListRequest.setPageToken(any())).thenReturn(entitiesListRequest); when(entitiesListRequest.execute()).thenReturn(response1, response2); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity1") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity1); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity3") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity3); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity5") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity5); assertEquals( ImmutableList.of(entity1, entity3, entity5), DefaultDataplexClient.withClient(cloudDataplexClient).getCloudStorageEntities(ASSET_NAME1)); } @Test public void testGetEntitiesByEntityNames() throws IOException { CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS); GoogleCloudDataplexV1Entity entity1 = new GoogleCloudDataplexV1Entity() .setName("entity1") .setAsset(ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); GoogleCloudDataplexV1Entity entity2 = new GoogleCloudDataplexV1Entity() .setName("entity2") .setAsset(ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); GoogleCloudDataplexV1Entity entity3 = new GoogleCloudDataplexV1Entity() .setName("entity3") .setAsset(ASSET_NAME1) .setSystem(StorageSystem.CLOUD_STORAGE.name()); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity1") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity1); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity2") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity2); when(cloudDataplexClient .projects() .locations() .lakes() .zones() .entities() .get("entity3") .setView(GetEntityRequestEntityView.FULL.name()) .execute()) .thenReturn(entity3); assertEquals( ImmutableList.of(entity1, entity2, entity3), DefaultDataplexClient.withClient(cloudDataplexClient) .getEntities(ImmutableList.of("entity1", "entity2", "entity3"))); } @Test public void testGetPartitionsByEntityName() throws IOException { CloudDataplex cloudDataplexClient = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS); Partitions partitions = mock(Partitions.class, Answers.RETURNS_DEEP_STUBS); when(cloudDataplexClient.projects().locations().lakes().zones().entities().partitions()) .thenReturn(partitions); GoogleCloudDataplexV1Partition partition1 = new GoogleCloudDataplexV1Partition().setName("partition1"); GoogleCloudDataplexV1Partition partition2 = new GoogleCloudDataplexV1Partition().setName("partition2"); GoogleCloudDataplexV1Partition partition3 = new GoogleCloudDataplexV1Partition().setName("partition2"); GoogleCloudDataplexV1ListPartitionsResponse response1 = new GoogleCloudDataplexV1ListPartitionsResponse() .setPartitions(ImmutableList.of(partition1, partition2)) .setNextPageToken(PAGE_TOKEN); GoogleCloudDataplexV1ListPartitionsResponse response2 = new GoogleCloudDataplexV1ListPartitionsResponse() .setPartitions(ImmutableList.of(partition3)); when(partitions.list("entity0").execute()).thenReturn(response1); when(partitions.list("entity0").setPageToken(eq(PAGE_TOKEN)).execute()).thenReturn(response2); assertEquals( ImmutableList.of(partition1, partition2, partition3), DefaultDataplexClient.withClient(cloudDataplexClient).getPartitions("entity0")); } @Test public void testCreateEntity() throws IOException { CloudDataplex dataplex = mock(CloudDataplex.class, Answers.RETURNS_DEEP_STUBS); Entities entities = getEntities(dataplex); DataplexClient client = DefaultDataplexClient.withClient(dataplex); GoogleCloudDataplexV1Entity entity = new GoogleCloudDataplexV1Entity() .setDataPath("gs://bucket/table1") .setSchema(new GoogleCloudDataplexV1Schema()) .setFormat(new GoogleCloudDataplexV1StorageFormat()) .setType(EntityType.TYPE_UNSPECIFIED.name()) .setSystem(StorageSystem.STORAGE_SYSTEM_UNSPECIFIED.name()) .setAsset(SHORT_ASSET_NAME1) .setId("table1"); GoogleCloudDataplexV1Entity expectedEntity = entity.clone(); client.createEntity(ZONE_NAME, entity); verify(entities, atLeastOnce()).create(ZONE_NAME, expectedEntity); } private static Zones getZones(CloudDataplex dataplex) { return dataplex.projects().locations().lakes().zones(); } private static Assets getAssets(CloudDataplex dataplex) { return dataplex.projects().locations().lakes().zones().assets(); } private static Entities getEntities(CloudDataplex dataplex) { return dataplex.projects().locations().lakes().zones().entities(); } private static GoogleCloudDataplexV1Zone createZone( GoogleCloudDataplexV1ZoneDiscoverySpec discoverySpec) { return new GoogleCloudDataplexV1Zone().setDiscoverySpec(discoverySpec); } private static GoogleCloudDataplexV1Asset createAsset( GoogleCloudDataplexV1AssetDiscoverySpec discoverySpec) { return new GoogleCloudDataplexV1Asset().setDiscoverySpec(discoverySpec); } }
Markdown
UTF-8
1,634
3.25
3
[]
no_license
# Setting up my SCSS Environment - This Readme is to help me remember how to setup my SCSS environment. Install Sass with Ruby: ``` gem install sass ``` #### Compile CSS to SCSS: To compile your SCSS into CSS you need to let your Sass know where you are writing your code and give it a place to precompile the CSS into another file. ``` sass input.scss output.css ``` Link your new CSS file in your HTML. ``` <link href="output.css" rel="stylesheet"> ``` - You can name your files whatever you'd like. The output css file should now contain all your pain CSS. ###### Remember to never work in the CSS file generated by your Sass #### Watch command: ``` sass --watch /(inputfoldername:/(outputfoldername) ``` This command tells your Sass to recompile your ```.scss``` file to CSS when the file is saved. #### Organising SASS: - Create a new ```folder``` in your directory for your ```.scss``` files. It is best practice to name it ```scss```. - Move the ```.scss``` file into your new folder. - Create a new CSS folder and run the watch command for those folders. ``` sass --watch /(inputfoldername:/(outputfoldername) ``` - Remember to change the ```<link>``` tag in your HTML file. #### Creating Partials: - Create a new folder inside your ```scss``` folder called ```partials```. - Next make a new file ```_newfile.scss``` or ```_colors.scss``` for example, inside the ```partials``` folder. - Import the partials with ```@import``` at the top of your main SCSS file. ``` @import 'partials/main-styles, 'partials/colors', 'partials/variables, 'partials/mixins, 'partials/helpers; ```
JavaScript
UTF-8
3,531
2.5625
3
[]
no_license
var N3 = require('n3'), fs = require('fs'), byline = require('byline'), request = require('superagent'), zlib = require('zlib'); if (process.stdin.isTTY) { console.error("This node script only works with a stream (via bash pipe) of n-quads"); process.exit(1); } var prefixCcList = require('./prefixcc.js'); var getPrefix = function(find, startIndex, lastIndex) { if (startIndex === undefined) startIndex = 0; if (lastIndex === undefined) lastIndex = prefixCcList.length - 1; //search in middle; var checkIndex = lastIndex - (parseInt((lastIndex - startIndex) / 2)); // console.log(startIndex, lastIndex, checkIndex); if (find.indexOf(prefixCcList[checkIndex]) == 0) { //found it! return prefixCcList[checkIndex]; } else { if (startIndex == lastIndex) { //no use searching. could not find it return null; } else if (lastIndex - startIndex === 1) { //just 1 item as offset. Can be because of rounding issue. just try and add 1 return getPrefix(find, startIndex+1, lastIndex); } if (find > prefixCcList[checkIndex]) { return getPrefix(find, checkIndex, lastIndex); } else { return getPrefix(find, startIndex, checkIndex); } } }; var prevDoc = null; var numDocsDone = 0; //init prefix cc counters var counters = {}; prefixCcList.forEach(function(ns){ counters[ns] = 0; }); var writeCounters = function() { console.log('writing to file'); var wstream = fs.createWriteStream(__dirname + '/results.tsv'); for (var ns in counters) { wstream.write(ns + '\t' + counters[ns] + '\n'); } wstream.end(); } var subPrefix, predPrefix, objPrefix; var numDocsDone = 0; var triplesCount = 0; function handleDoc() { var docNamespaces = {}; var writer = new require('stream').Writable({ objectMode: true }); writer._write = function (doc, encoding, done) { numDocsDone++; var lineStream = byline.createStream(); var zlibStream = zlib.createGunzip({ encoding: 'utf8' }); var parser = new N3.StreamParser(); var req = request.get(doc) .pipe(zlibStream) .pipe(lineStream) .pipe(parser); parser.on('data', function(triple) { triplesCount++; if (triplesCount % 1000 == 0) process.stdout.write("Processed " + numDocsDone + " documents (" + triplesCount + " triples)\r") ; if (subPrefix = getPrefix(triple.subject)) docNamespaces[subPrefix] = true; if (predPrefix = getPrefix(triple.predicate)) docNamespaces[predPrefix] = true; if (triple.object.charAt(0) !== '"' && (objPrefix = getPrefix(triple.object))) docNamespaces[objPrefix] = true; }); parser.on('error', function() { // console.log(arguments); }); parser.on('end', function() { //up counters for (var ns in docNamespaces) { counters[ns]++; } var msg = "Processed " + numDocsDone + " documents (" + triplesCount + " triples)"; if (numDocsDone % 50 === 0) { process.stdout.write(msg + "\n"); writeCounters(); } else { process.stdout.write(msg + "\r"); } done(); }); }; return writer; } var stream = byline.createStream(process.stdin, { encoding: 'utf8' }); stream.pipe(new handleDoc());
PHP
UTF-8
653
3.0625
3
[]
no_license
<?php namespace Lib; /** * Input Class */ class Input { /** * Protect from xss attack * * @param mixed $dirty * @return void */ public static function sanitize($dirty) { return htmlentities($dirty, ENT_QUOTES, "UTF-8"); } /** * getter for data from global $_POST and $_GEt * * @param mixed $input * @return void */ public static function get($input) { if (isset($_POST[$input])) { return self::sanitize($_POST[$input]); } else if (isset($_GET[$input])) { return self::sanitize($_GET[$input]); } } }
C#
UTF-8
672
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ploeh.Study.ExtensibilityForMasses { public class Debug : Combine<IExp, IPrint> { public Debug() : base(new IntFactory(), new IntPrint()) { } public override Pair<IExp, IPrint> Add(Pair<IExp, IPrint> e1, Pair<IExp, IPrint> e2) { Console.WriteLine($"The first expression {e1.TheB.Print()} evaluates to {e1.TheA.Eval()}"); Console.WriteLine($"The second expression {e2.TheB.Print()} evaluates to {e2.TheA.Eval()}"); return base.Add(e1, e2); } } }
C#
UTF-8
2,075
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EverLight.TreeStructure.Core.BusinessLogic; using EverLight.TreeStructure.Core.Utility; namespace EverLight.TreeStructure.Core { public class Application { public string PredictedContainerName { get; set; } public string ActualContainerName { get; set; } private readonly ILogger _logger; private readonly ITreeNode<int> _treeNode; public Application(ILogger logger, ITreeNode<int> treeNode) { _logger = logger; _treeNode = treeNode; } public void PredictWhichContainerWillNotReceiveABall(int depth) { var root = _treeNode; _treeNode.BuildTree(root, depth); var listOfReceivedBallsContainerNames = new List<string>(); for (var i = 1; i <= _treeNode.NumberOfBallsToRun; i++) { listOfReceivedBallsContainerNames.Add(root.GetLeafNodeContainerName(root)); } var listOfLeafNodeNames = _treeNode.ListOfLeafNodeNames; PredictedContainerName = listOfLeafNodeNames.Except(listOfReceivedBallsContainerNames).FirstOrDefault(); } public void RunBall(int depth) { var root = _treeNode; _treeNode.BuildTree(root, depth); var listOfLeafNodeNames = _treeNode.ListOfLeafNodeNames; var listOfReceivedBallsContainerNames = new List<string>(); for (var i = 1; i <= _treeNode.NumberOfBallsToRun; i++) { var leafNodeContainerName = root.GetLeafNodeContainerName(root); listOfReceivedBallsContainerNames.Add(leafNodeContainerName); _treeNode.AssignNodeValue(root, leafNodeContainerName, i); _logger.Log("Container Name: " + leafNodeContainerName + ", Value: " + i); } ActualContainerName = listOfLeafNodeNames.Except(listOfReceivedBallsContainerNames).FirstOrDefault(); } } }
Java
UTF-8
575
3.125
3
[]
no_license
public class LongestCommonPrefix{ public String longestCommonPrefix(String[] strs){ String res = ""; if(strs==null || strs.length==0) return res; int minLength = Integer.MAX_VALUE; for(int i=0;i<strs.length;++i){ if(strs[i].length()<minLength) minLength = strs[i].length(); } for(int i=0;i<minLength;++i){ char ch = strs[0].charAt(i); boolean flag = true; for(int j=0;j<strs.length;++j){ if(strs[j].charAt(i)!=ch){ flag = false; break; } } if(flag==true){ res = res+ch; } else{ break; } } return res; } }
Markdown
UTF-8
962
2.671875
3
[]
no_license
# Exercise-Files-for-Dart-Course-DSCKIIT ![](https://dsckiit.tech/assets/img/events/Flutter%20&%20Dart.jpeg) ## Short Description * I teach Dart in DSCKIIT's Youtube channel. So the code, I write are uploaded here. ### 👉 If you like this repo then please give it a ⭐️ <br> ## Tutorial Link * Youtube link - [Link](https://www.youtube.com/playlist?list=PLT-AS3Wcy-plOzvgU8R3Jo8LzH1tiiZmE) ## Testing out the code 1. Clone this repo in your machine. 2. Open the project folder in VS Code 3. For testing out the programs use this command: ``` dart filename.dart ``` ## Developed & Maintained by [👨 Sayan Nath](https://sayan-nath.web.app/)<br> [📷 Insta](https://www.instagram.com/sayannath235/)<br> [🐤 Twitter](https://twitter.com/SayanNa20204009)<br> [🧳 LinkedIn](https://www.linkedin.com/in/sayan-nath-15a989182/)<br> [![ForTheBadge built-with-love](http://ForTheBadge.com/images/badges/built-with-love.svg)](https://github.com/sayannath)
Python
UTF-8
4,736
3.03125
3
[]
no_license
import numpy as np from matplotlib import pyplot as plt import pandas as pd class get_metrics: def __init__(self, dt_range): self.dt_range = dt_range def graph_output(self, y, name): fig = plt.figure() ts = pd.Series(y,name=name) ts.plot(x = "Time", y = name, title = "{} for Test Data from {} to {}".format(name, self.dt_range.split("_")[0], self.dt_range.split("_")[1])) fig.savefig("{}_{}".format(name, self.dt_range)) plt.close() def apv_single_asset(self, y_true, weights, pv_0 = 1, get_graph = False): """ :param y_true: true closing/opening value of the stock/crypto :param weights: denotes decision taken at each time step :param lbl_dict: mappings required for dictionary [lower value when purchasing and higher when selling] :return: final portfolio value """ assert len(y_true) == len(weights), "Dimension Mismatch!, Length of True labels {} != Decision length {}".format(len(y_true), len(weights)) rp_vector = np.array([1] + [np.divide(y , x) for (x, y) in zip(y_true, y_true[1:])]) portfolio_val = pv_0 * np.product([np.multiply(r , w) for (r, w) in zip(rp_vector, weights)], axis = 0) # Finding change in portfolio values for sharpe ratio del_portfolio = np.ndarray(shape = (rp_vector.shape[0] + 1,)) del_portfolio[0] = 1.0 for idx in range(1, del_portfolio.shape[0]): del_portfolio[idx] = del_portfolio[idx - 1] * (rp_vector[idx - 1] * weights[idx - 1]) if get_graph: self.graph_output(del_portfolio, "ratios") self.graph_output(y_true, "actual_price") mdd = self.mdd_vals(del_portfolio) print("MDD = {}, fAPV = {}".format(mdd, portfolio_val)) return mdd, portfolio_val def mdd_vals(self, del_pv): """ :param del_pv: changes in portfolio value :return: MDD """ pv_vals = [del_pv[0]] drawdown_lst = [0] max_val = 0 for idx in range(1, del_pv.shape[0]): pv_vals.append(pv_vals[idx - 1] * del_pv[idx]) if pv_vals[idx] > max_val: max_val = pv_vals[idx] else: drawdown_lst.append( (max_val - pv_vals[idx]) / max_val) return max(drawdown_lst) def apv_multiple_asset(self, rp_vector, weights, pv_0 = 1, get_graph = False, tag=""): """ :param rp_vector: time_steps X num_assets :param weights: time_steps X num_assets :return: MDD, final portfolio value, SR """ assert rp_vector.shape == weights.shape, "Dimension Mismatch!, True labels {} != Weights {}".format(rp_vector.shape, weights.shape) # final portfolio value => scalar. At any time t, fAPV = p_initial * _prod { rp_{t} * w_{t - 1}} portfolio_val = pv_0 * np.product([np.dot(r , w) for (r, w) in zip(rp_vector, weights)]) # time_steps = total_time_steps time_steps = rp_vector.shape[0] + 1 del_portfolio = np.ndarray(shape = (time_steps,)) # Initial value of portfolio = pv_0 del_portfolio[0] = pv_0 for idx in range(1, time_steps): del_portfolio[idx] = del_portfolio[idx - 1] * np.dot(rp_vector[idx - 1, :] , weights[idx - 1, :]) sharpe_ratio = self.sr_vals_multiple_asset(rp_vector, weights) mdd = self.mdd_vals_multiple_asset(del_portfolio) if get_graph: self.graph_output(del_portfolio, "APV") self.graph_output(sharpe_ratio, "Sharpe Ratio") print("MDD = {}, fAPV = {}".format(mdd, portfolio_val)) print("Saving allocation weights....") np.save("allocation_wts_{}_{}.npy".format(portfolio_val, tag), weights) return mdd, portfolio_val def sr_vals_multiple_asset(self, rp, weights): """ :param rp: relative price vector :param weights: weight vector :return: sharpe ratio at each time step """ out = np.ndarray(shape = (rp.shape[0],)) for sr in range(out.shape[0]): rho_val = np.multiply(rp[sr, :] , weights[sr, :]) - 1 out[sr] = np.mean(rho_val) / np.std(rho_val) return out def mdd_vals_multiple_asset(self, del_pv): """ :param del_pv: changes in portfolio value :return: MDD """ drawdowns = [] trough = peak = del_pv[0] for idx in range(1, del_pv.shape[0]): if del_pv[idx] <= peak: trough = min(trough, del_pv[idx]) else: drawdowns.append((trough - peak) / peak) peak = del_pv[idx] return max(drawdowns[1:]) if len(drawdowns) > 0 else 0.0
Shell
UTF-8
274
3.171875
3
[]
no_license
#!/usr/bin/env bash for((a=0;a<5;a++)); do echo "Interation $i:" for((b=1;b<3;b++)) do if [$a -gt 2 ] && [ $a -lt 4 ] then continue 2 fi var3=$[ $a * $b] echo " The result of $a * $b is $var3" done done
PHP
UTF-8
1,140
2.53125
3
[ "MIT" ]
permissive
<?php namespace Omnipay\GoCardlessV2Tests\Message; use Omnipay\GoCardlessV2\Message\CreateCustomerBankAccountRequest; use Omnipay\GoCardlessV2\Message\BankAccountResponse; use Omnipay\Tests\TestCase; class CustomerBankAccountResponseTest extends TestCase { /** * @var CreateCustomerBankAccountRequest|\Mockery\MockInterface */ private $request; public function setUp() { parent::setUp(); $this->request = $this->getMockBuilder(CreateCustomerBankAccountRequest::class) ->disableOriginalConstructor() ->getMock(); } public function testGetCustomerBankAccountData() { $data = json_decode('{"id":"BA1234"}'); $response = new BankAccountResponse($this->request, $data); $this->assertEquals($data, $response->getBankAccountData()); $this->assertEquals('BA1234', $response->getBankAccountReference()); } public function testFailedCustomerBankAccountData() { $data = null; $response = new BankAccountResponse($this->request, $data); $this->assertNull($response->getBankAccountData()); } }
Markdown
UTF-8
7,949
2.828125
3
[]
no_license
+++ title = "Как смартфон тебя подслушивает" date = 2020-03-07T22:39:01+05:00 author = "Rustam Safin" cover = "img/assistant.jpg" tags = ["безопасность"] description = "Спросили, может ли быть такое, что телефон не такой конфиденциальный, как хотелось бы. Рассказываю." showFullContent = false +++ Анна спросила ============ > Сидим, обсуждаем с подружками что-нибудь, например чулки. И уже в этот же день в Instagram/VK/Yandex начинает отображаться реклама чулков. Да ещё с какой-нибудь скидкой, фразой "у всех молодых девушек такие" и кнопкой "Купить". > Помню, что если что-то вбиваешь в поисковике, то потом контекстная реклама вылезает повсюду по тому запросу, который вводила. Но я же ничего не искала в Интернете. Просто сидели обсуждали. Расскажу всё, что знаю про эту тему. Хотя до меня это сделал Эдвард Сноудэн. Спасибо ему. Телефон слушает тебя ==================== Главной причиной сложившейся ситуации является установленный на смартфоне Google Ассистент. Это тот самый, который откликается на фразу "OK, Google". Аналог в iOs - Siri, русский аналог от Яндекса — Алиса, в Windows это Cortana. Открыл настройки своего Google Ассистент. Смотрите, написан тот запрос, который я не связывал с фразой "OK, Google". ![Google assistant 1](/img/assistant1.jpg) И вот ещё настройки, которые позволяют Google Ассистенту сделать всё, что он захочет. ![Google assistant 2](/img/assistant2.jpg) Получается, что смартфон может записать всё, что ты произносишь дома, при конфиденциальной беседе. Все фразы будут отправлены на сервера Google, обработаны, запомнены и связаны с твоим аккаунтом. Навсегда. Большой брат следит за тобой ============================ Телефон пишет геотеги для каждой фотографии. Про них вроде бы все знают. Когда у вас включен трек местоположения, приложение камеры заодно к фотографии дописывает координаты места, где оно было сделано. Удобно, чтобы выкладывать свои фотографии в Instagram. Instagram как раз подтягивает информацию из геометок. Кажется, что можно выключить у себя геотеги и всё станет хорошо. Это не так. Все загруженные в облако фотографии классифицируются по разным признакам. Google Photo любезно создал мне вот такой альбом, хотя я не просил: ![](/img/piza.jpg) Просто на обоях на одной из фотографий, сделанных в те два дня, была Пизанская башня. Кучу фотографий Пизанской башни загрузили другие пользователи, у которых включены геометки. Или вручную проставляли, что это именно Пизанская башня, а не абы какая. Нейросеть умеет складывать дважды два. Если две фотки похожи, то будет выдавать результат "Эта фотография похожа на ту, что сделана возле Пизанской башни с вероятность 82%". Вот ещё пример таких альбомов, где я НЕ ставил геотеги, но Google определил верно: ![](/img/image_classification.jpg) Облачные хранилища фотографий неустанно занимаются классификацией. Особенно там, где можно продать товары. Сервисы сливают информацию друг другу ===================================== Я иногда покупаю товары на Ozon.ru. Иногда нажимаю на заинтересовавший меня товар. И, разочаровавшись ценой, закрываю. Если зайти после этого в Instgram, в рекламе покажут товары, которыми ты интересовался. Режим инкогнито не всегда помогает ================================== Видели на сайтах такой вопрос? ![](/img/location.jpg) На сетевом оборудовании тоже ставят геометки. То есть, ко всем сетевым запросам, проходящим через этот маршрутизатор, будут добавляться координаты, где вы примерно находитесь. С одной стороны, это удобно для сайтов, чтобы определять местоположение пользователя и не предлагать лишнего. С другой стороны, каждая собака в Интернете знает, где вы сейчас. "Я тебя по IP вычислю" - это полуправда. VPN поможет отчасти. Что делать? ============== Попробую порекомендовать: 1. Попробовать отключить те настройки, которые возможно отключить в настройках смартфона. Это, правда, всё равно ничего не будет гарантировать. Кто сказал, что кнопка не бутафория и действительно отключит слежение? На Android-смартфонах удалить или отключить приложение Google/Алису. 2. В браузере пользоваться режимом "Инкогнито" для ваших запросов. Правда, если вам что-то нужно в Интернет-магазине, придется авторизоваться и с этого момента сервис запомнит, кто вы, что искали, что покупали и что можно впарить ещё. 3. Для покупки "опасных" товаров (эротическое бельё, подарки, квартиры в тайне от супруга) создавать новые учетные записи через временные почтовые ящики. Пример такого сервиса временной почты вот https://temp-mail.org/ru/ 4. Пользоваться VPN. 5. В качестве поисковика пользоваться https://duckduckgo.com/ Не уверен в его полной конфиденциальности. И релевантности не хватает.
Rust
UTF-8
1,132
3.515625
4
[ "MIT" ]
permissive
// Definition for a binary tree node. // #[derive(Debug, PartialEq, Eq)] // pub struct TreeNode { // pub val: i32, // pub left: Option<Rc<RefCell<TreeNode>>>, // pub right: Option<Rc<RefCell<TreeNode>>>, // } // // impl TreeNode { // #[inline] // pub fn new(val: i32) -> Self { // TreeNode { // val, // left: None, // right: None // } // } // } use std::rc::Rc; use std::cell::RefCell; impl Solution { pub fn range_sum_bst(root: Option<Rc<RefCell<TreeNode>>>, low: i32, high: i32) -> i32 { match root { Some(tree_node) => { let tree_node = tree_node.borrow(); if tree_node.val >= low && tree_node.val <= high { tree_node.val + Solution::range_sum_bst(tree_node.left.clone(), low, high) + Solution::range_sum_bst(tree_node.right.clone(), low, high) } else { Solution::range_sum_bst(tree_node.left.clone(), low, high) + Solution::range_sum_bst(tree_node.right.clone(), low, high) } } None => { 0 } } } }
TypeScript
UTF-8
1,666
2.765625
3
[ "MIT" ]
permissive
import { FormGroup, FormControl, ValidatorFn } from '@angular/forms'; export function emailValidator(control: FormControl): {[key: string]: any} { var emailRegexp = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/; if (control.value && !emailRegexp.test(control.value)) { return {invalidEmail: true}; } } export function matchingPasswords(passwordKey: string, passwordConfirmationKey: string) { return (group: FormGroup) => { let password= group.controls[passwordKey]; let passwordConfirmation= group.controls[passwordConfirmationKey]; if (password.value !== passwordConfirmation.value) { return passwordConfirmation.setErrors({mismatchedPasswords: true}) } } } export function numberLimits(prms : any) : ValidatorFn{ return (control: FormControl): {[key: string]: any} => { let cantidad = control.value; if(cantidad !=null){ let cadena: string = cantidad.toString(); if(!isNaN(prms.max) && !isNaN(prms.min)){ if(cadena.length > prms.max){ return {maximoExedido : {prms}} }else{ if(cadena.length < prms.min){ return {minimoExedido : {prms}} }else{ return null; } } }else{ if(!isNaN(prms.max)){ if(cadena.length > prms.max){ return {maximoExedido : {prms}} }else{ return null; } }else { if(!isNaN(prms.min)){ if(cadena.length < prms.min){ return {minimoExedido : {prms}} }else{return null;} } } } } } };
PHP
GB18030
3,646
2.90625
3
[]
no_license
<?php namespace Framework\Core; class Base{ public $_filter; /* * Cache Base ------------------------------------------------------ */ public function Cache( $type = 'file' ){ $cache = LC("Cache"); $cache->type = $type; return $cache; } /* * ֵ ------------------------------------------------------ */ // POSTֵ public function getPost($keyName='' , $filterTypeArr = array()){ $val = isset($_POST[$keyName]) ? $_POST[$keyName] : ''; if(!empty($filterTypeArr)){ if( is_array($val) ){ $arr = array(); foreach($val as $key=>$v){ $arr[$key] = $this->actionFilter($v , $filterTypeArr); } $val = $arr; }else{ $val = $this->actionFilter($val , $filterTypeArr); } } return $val; } /* * GETֵ */ public function getGet($keyName='' , $filterTypeArr = array()){ $val = isset($_GET[$keyName]) ? $_GET[$keyName] : ''; if(!empty($filterTypeArr)){ $val = $this->actionFilter($val , $filterTypeArr); } return $val; } /** * ͨ php://input ȡDELETEʽֵ * @param string $keyName * @param array $filterTypeArr * @return bool|int|mixed|number|string */ public function getDelete($keyName='' , $filterTypeArr = array()){ if( $_SERVER['REQUEST_METHOD'] == 'DELETE'){ $data = explode("&", file_get_contents("php://input")); foreach($data as $da){ list($key, $val) = explode("=", $da); if( $key == $keyName){ return $this->actionFilter($val , $filterTypeArr); } } }else{ return false; } } /* * ֵܴ */ public function getParams($keyName='' , $filterTypeArr = array()){ $val = isset($_GET[$keyName]) ? $_GET[$keyName] : ''; if( $val =='' ){ $val = isset($_POST[$keyName]) ? $_POST[$keyName] : ''; } if(!empty($filterTypeArr)){ $val = $this->actionFilter($val , $filterTypeArr); } return $val; } /* * post get ֱ滻ж */ private function actionFilter($val ='' , $filterTypeArr= '') { if(is_array($filterTypeArr)){ foreach($filterTypeArr as $type){ $val = $this->getFilterVal($val , $type); } }else{ $val = $this->getFilterVal($val , $filterTypeArr); } return $val; } /** * 򵥴ֵ * @param string $val * @param string $type * @return int|mixed|number|string */ private function getFilterVal($val='' , $type='') { switch($type){ case 'int': $val = preg_replace("/[^0-9]/isU", "" , $val); $val = intval($val); $val = abs($val); break; case 'alphanum': $val = preg_replace("/[^a-zA-Z0-9_@.\-:\/,]/isU" , "" , $val); break; case 'striptags': $val = strip_tags($val); break; case 'trim': $val = trim($val); break; case 'lower': $val = strtolower($val); break; case 'upper': $val = strtoupper($val); break; } return $val; } } ?>
JavaScript
UTF-8
481
2.625
3
[]
no_license
$("#learn-more a").click(function(e) { e.preventDefault(); var container = $('body'); var scrollTo = $('#section-2'); container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() }) }); $("#go-down a").click(function(e) { e.preventDefault(); var container = $('body'); var scrollTo = $('#section-3'); container.animate({ scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() }) });
Java
UTF-8
5,640
1.898438
2
[ "MIT" ]
permissive
/* * Phrase API Reference * * The version of the OpenAPI document: 2.0.0 * Contact: support@phrase.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.phrase.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; /** * TagWithStats1Statistics */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-10-05T12:08:13.290146Z[Etc/UTC]") public class TagWithStats1Statistics { public static final String SERIALIZED_NAME_KEYS_TOTAL_COUNT = "keys_total_count"; @SerializedName(SERIALIZED_NAME_KEYS_TOTAL_COUNT) private Integer keysTotalCount; public static final String SERIALIZED_NAME_TRANSLATIONS_COMPLETED_COUNT = "translations_completed_count"; @SerializedName(SERIALIZED_NAME_TRANSLATIONS_COMPLETED_COUNT) private Integer translationsCompletedCount; public static final String SERIALIZED_NAME_TRANSLATIONS_UNVERIFIED_COUNT = "translations_unverified_count"; @SerializedName(SERIALIZED_NAME_TRANSLATIONS_UNVERIFIED_COUNT) private Integer translationsUnverifiedCount; public static final String SERIALIZED_NAME_KEYS_UNTRANSLATED_COUNT = "keys_untranslated_count"; @SerializedName(SERIALIZED_NAME_KEYS_UNTRANSLATED_COUNT) private Integer keysUntranslatedCount; public TagWithStats1Statistics keysTotalCount(Integer keysTotalCount) { this.keysTotalCount = keysTotalCount; return this; } /** * Get keysTotalCount * @return keysTotalCount **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Integer getKeysTotalCount() { return keysTotalCount; } public void setKeysTotalCount(Integer keysTotalCount) { this.keysTotalCount = keysTotalCount; } public TagWithStats1Statistics translationsCompletedCount(Integer translationsCompletedCount) { this.translationsCompletedCount = translationsCompletedCount; return this; } /** * Get translationsCompletedCount * @return translationsCompletedCount **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Integer getTranslationsCompletedCount() { return translationsCompletedCount; } public void setTranslationsCompletedCount(Integer translationsCompletedCount) { this.translationsCompletedCount = translationsCompletedCount; } public TagWithStats1Statistics translationsUnverifiedCount(Integer translationsUnverifiedCount) { this.translationsUnverifiedCount = translationsUnverifiedCount; return this; } /** * Get translationsUnverifiedCount * @return translationsUnverifiedCount **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Integer getTranslationsUnverifiedCount() { return translationsUnverifiedCount; } public void setTranslationsUnverifiedCount(Integer translationsUnverifiedCount) { this.translationsUnverifiedCount = translationsUnverifiedCount; } public TagWithStats1Statistics keysUntranslatedCount(Integer keysUntranslatedCount) { this.keysUntranslatedCount = keysUntranslatedCount; return this; } /** * Get keysUntranslatedCount * @return keysUntranslatedCount **/ @javax.annotation.Nullable @ApiModelProperty(value = "") public Integer getKeysUntranslatedCount() { return keysUntranslatedCount; } public void setKeysUntranslatedCount(Integer keysUntranslatedCount) { this.keysUntranslatedCount = keysUntranslatedCount; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TagWithStats1Statistics tagWithStats1Statistics = (TagWithStats1Statistics) o; return Objects.equals(this.keysTotalCount, tagWithStats1Statistics.keysTotalCount) && Objects.equals(this.translationsCompletedCount, tagWithStats1Statistics.translationsCompletedCount) && Objects.equals(this.translationsUnverifiedCount, tagWithStats1Statistics.translationsUnverifiedCount) && Objects.equals(this.keysUntranslatedCount, tagWithStats1Statistics.keysUntranslatedCount); } @Override public int hashCode() { return Objects.hash(keysTotalCount, translationsCompletedCount, translationsUnverifiedCount, keysUntranslatedCount); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class TagWithStats1Statistics {\n"); sb.append(" keysTotalCount: ").append(toIndentedString(keysTotalCount)).append("\n"); sb.append(" translationsCompletedCount: ").append(toIndentedString(translationsCompletedCount)).append("\n"); sb.append(" translationsUnverifiedCount: ").append(toIndentedString(translationsUnverifiedCount)).append("\n"); sb.append(" keysUntranslatedCount: ").append(toIndentedString(keysUntranslatedCount)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
C#
UTF-8
2,075
2.6875
3
[]
no_license
using System.Collections.Generic; using System.Dynamic; using System.Threading.Tasks; namespace Common.DynamicModel.Expandos { /// <summary> /// 动态属性的上下文 /// </summary> public class ExpandoPropertyContext<TResult>// where TResult : Expando { public ExpandoPropertyContext(TResult data) { Result = data; } /// <summary> /// 上下文的结果 /// </summary> public TResult Result { get; set; } /// <summary> /// 上下文的状态 /// </summary> public dynamic State { get; set; } = new ExpandoObject(); /// <summary> /// 应用动态属性的提供者列表,按需提供和调用即可 /// </summary> /// <param name="expandoPropertyProviders"></param> /// <returns></returns> public async Task ApplyProviders(IEnumerable<IExpandoPropertyProvider<TResult>> expandoPropertyProviders) { if (expandoPropertyProviders == null) { return; } foreach (var provider in expandoPropertyProviders) { await provider.Process(this); } } /// <summary> /// Create ExpandoPropertyContext Factory /// </summary> /// <param name="result"></param> /// <returns></returns> public static ExpandoPropertyContext<TResult> Create(TResult result) { var context = new ExpandoPropertyContext<TResult>(result); return context; } } /// <summary> /// 动态属性的提供者接口 /// </summary> /// <typeparam name="TResult"></typeparam> public interface IExpandoPropertyProvider<TResult>// where TResult : Expando { /// <summary> /// 动态属性上下文的处理逻辑 /// </summary> /// <param name="context"></param> /// <returns></returns> Task Process(ExpandoPropertyContext<TResult> context); } }
Java
UTF-8
4,117
3.703125
4
[]
no_license
package com.company; import java.sql.Array; import java.util.*; public class TicTacToe { static ArrayList<Integer> playerPosition = new ArrayList<>(); //Array list for player position. static ArrayList<Integer> cpuPosition = new ArrayList<>(); //Array list for cpu position. public static void main(String[] args) { char[][] gameBoard = { {' ', '|', ' ', '|', ' '}, {'-', '+', '-', '+', '-'}, {' ', '|', ' ', '|', ' '}, {'-', '+', '-', '+', '-'}, {' ', '|', ' ', '|', ' '}}; printGameBoard(gameBoard); //Game board print while (true) { // Scanner for catch entered position by user Scanner scanner = new Scanner(System.in); System.out.println("Enter your placement (1 - 9)"); int playerPosition = scanner.nextInt(); // position of entered by user placePiece(gameBoard, playerPosition, "player"); Random random = new Random(); //Random int cpuPosition = random.nextInt(9) + 1; //position in array start from 0. Position changed form 1 to 9. placePiece(gameBoard, cpuPosition, "cpu"); printGameBoard(gameBoard); //Game Board print each time is entered a number position(update a clipBoard) String winingString = winnerCheck(); System.out.println(winingString); } } public static void printGameBoard(char[][] gameBoard) { for (char[] row : gameBoard) { for (char c : row) { System.out.print(c); } System.out.println(); }// Enhanced loop iterating throw gameBoard Array. } //method printed Board public static void placePiece(char[][] gameBoard, int pos, String user) { char symbol = ' '; if (user.equals("player")) { symbol = 'X'; playerPosition.add(pos); } else if (user.equals("cpu")) { symbol = '0'; cpuPosition.add(pos); } switch (pos) { case 1: gameBoard[0][0] = symbol; break; case 2: gameBoard[0][2] = symbol; break; case 3: gameBoard[0][4] = symbol; break; case 4: gameBoard[2][0] = symbol; break; case 5: gameBoard[2][2] = symbol; break; case 6: gameBoard[2][4] = symbol; break; case 7: gameBoard[4][0] = symbol; break; case 8: gameBoard[4][2] = symbol; break; case 9: gameBoard[4][4] = symbol; break; default: break; }//switch case place X or O in to a board } public static String winnerCheck() { // List o possible winning combinations regular array List topRow = Arrays.asList(1, 2, 3); List midRow = Arrays.asList(4, 5, 6); List botRow = Arrays.asList(7, 8, 9); List leftCol = Arrays.asList(1, 4, 7); List midCol = Arrays.asList(2, 5, 8); List rigCol = Arrays.asList(3, 6, 9); List cross1 = Arrays.asList(1, 5, 9); List cross2 = Arrays.asList(3, 5, 7); //List checking winnig combination List<List> winning = new ArrayList<>(); winning.add(topRow); winning.add(midRow); winning.add(botRow); winning.add(leftCol); winning.add(midCol); winning.add(rigCol); winning.add(cross1); winning.add(cross2); for (List l : winning) { if (playerPosition.containsAll(l)) { return "Player Wins"; } else if (cpuPosition.containsAll(l)) { return "CPU Wins"; } else if (playerPosition.size() + cpuPosition.size() == 9) return "CAT"; } return ""; } }
C#
UTF-8
1,765
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MongoDB.Bson; namespace OneTimeUses2 { public class PaperFormatted //public for web app { public ObjectId Id { get; set; } public string Fields { get; set; } //I would prefer Enums for most, but get it working first public string PsychArea { get; set; } public string KeyTopic { get; set; } public string TargetPopulation { get; set; } public int Number { get; set; } //not necessary but useful for correlating data between VS and Excel public string Title { get; set; } public List<string> Authors { get; set; } public string JournalName { get; set; } public string AlertMonth { get; set; } public DateTime PublicationDate { get; set; } public string Link { get; set; } public string Abstract { get; set; } public PaperFormatted() { } public PaperFormatted(PaperIntake pi) { Id = pi.Id; Fields = pi.Fields; PsychArea = pi.PsychArea; KeyTopic = pi.KeyTopic; TargetPopulation = pi.TargetPopulation; Number = pi.Number; Title = pi.Title; Authors = pi.Authors.Split(',').ToList(); JournalName = pi.JournalName; AlertMonth = pi.AlertMonth; SetPublicationDate(pi.PublicationDate); Link = pi.Link; Abstract = pi.Abstract; } private void SetPublicationDate(string pubDateString) { int month = 0; int year = 0; if (pubDateString.Contains('/')) { string[] temp = pubDateString.Split('/'); month = Convert.ToInt32(temp[1]); year = Convert.ToInt32(temp[0]) + 2000; //Bec the input years are i.e. 15, 16 PublicationDate = new DateTime(year, month, 1); } else { PublicationDate = DateTime.MinValue; } } } }
Java
UTF-8
7,616
1.890625
2
[ "Apache-2.0", "CC-BY-SA-4.0", "CC-BY-4.0", "CC-BY-NC-SA-4.0" ]
permissive
/* * Copyright 2017 NEOautus Ltd. (http://neoautus.com) * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.lucidj.navtool; import org.lucidj.api.vui.IconHelper; import org.lucidj.api.vui.NavTool; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vaadin.data.Container; import com.vaadin.data.Item; import com.vaadin.data.util.HierarchicalContainer; import com.vaadin.server.Resource; import java.net.URI; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Context; import org.apache.felix.ipojo.annotations.Instantiate; import org.apache.felix.ipojo.annotations.Provides; import org.apache.felix.ipojo.annotations.Requires; @Component (immediate = true, publicFactory = false) @Instantiate @Provides public class NavToolService implements NavTool { private final static Logger log = LoggerFactory.getLogger (NavToolService.class); @Requires private IconHelper iconHelper; @Context private BundleContext bundleContext; private Map<Integer, NavContainer> handle_to_container = new HashMap<> (); private Map<String, Integer> id_to_handle = new HashMap<> (); private String make_id (String section, String caption) { return ((section == null? "": section) + "." + (caption == null? "": caption)); } public int getHandle (String section, String caption) { String id = make_id (section, caption); if (id_to_handle.containsKey (id)) { return (id_to_handle.get (id)); } return (0); } public int publish (String section, String caption) { int handle = getHandle (section, caption); if (handle != 0) { return (handle); } NavContainer container = new NavContainer (); handle = container.newHandle (); handle_to_container.put (handle, container); id_to_handle.put (make_id (section, caption), handle); Dictionary<String, Object> props = container.getProperties (); props.put ("@section", section == null? "": section); props.put ("@caption", caption == null? "": caption); props.put ("@handle", handle); props.put ("@itemCaptionPropertyId", PROPERTY_NAME); props.put ("@itemIconPropertyId", PROPERTY_ICON); props.put ("@itemURIPropertyId", PROPERTY_URI); ServiceRegistration reg = bundleContext.registerService (Container.class, container, props); container.setServiceRegistration (reg); return (handle); } public Container hackGetContainer (int handle) { // Use at your own risk :) return (handle_to_container.get (handle)); } public Object addItem (int handle, Object parentItemId, String name, Resource icon, URI uri, Object itemId) { log.info ("addItem: handle={} parentItemId={} name={} icon={} uri={} itemId={}", handle, parentItemId, name, icon, uri, itemId); NavContainer container = handle_to_container.get (handle); if (itemId == null) { itemId = container.newHandle (); } Item item = container.addItem (itemId); container.setChildrenAllowed (itemId, false); if (parentItemId != null) { container.setChildrenAllowed (parentItemId, true); container.setParent (itemId, parentItemId); } item.getItemProperty (PROPERTY_NAME).setValue (name); if (icon != null) { item.getItemProperty (PROPERTY_ICON).setValue (icon); } if (uri != null) { item.getItemProperty (PROPERTY_URI).setValue (uri); } return (itemId); } public Object addItem (int handle, Object parentItemId, String name, String icon, String uri, Object itemId) { Resource item_icon = (icon == null || icon.isEmpty ())? null: iconHelper.getIcon (icon, 32); URI item_uri = (uri == null || uri.isEmpty ())? null: URI.create (uri); return (addItem (handle, parentItemId, name, item_icon, item_uri, itemId)); } public int addItem (int handle, int parentItemId, String name, String icon, String uri, int itemId) { return ((Integer)addItem (handle, new Integer (parentItemId), name, icon, uri, new Integer (itemId))); } public int addItem (int handle, int parentItemId, String name, String icon, String uri) { return ((Integer)addItem (handle, parentItemId, name, icon, uri, null)); } public Object addItem (int handle, String name, String icon, String uri, Object itemId) { return (addItem (handle, null, name, icon, uri, itemId)); } public int addItem (int handle, String name, String icon, String uri) { return ((Integer)addItem (handle, name, icon, uri, null)); } public boolean containsId (int handle, Object itemId) { Container container = handle_to_container.get (handle); return (container != null && container.containsId (itemId)); } public boolean containsId (int handle, int itemId) { return (containsId (handle, new Integer (itemId))); } public void setChildrenAllowed (int handle, Object itemId, boolean childrenAllowed) { if (handle_to_container.containsKey (handle)) { HierarchicalContainer container = handle_to_container.get (handle); container.setChildrenAllowed (itemId, childrenAllowed); } } public void setChildrenAllowed (int handle, int itemId, boolean childrenAllowed) { setChildrenAllowed (handle, new Integer (itemId), childrenAllowed); } public void setParent (int handle, Object itemId, Object newParentId) { if (handle_to_container.containsKey (handle)) { HierarchicalContainer container = handle_to_container.get (handle); container.setChildrenAllowed (newParentId, true); container.setParent (itemId, newParentId); } } public void setParent (int handle, int itemId, int newParentId) { setParent (handle, new Integer (itemId), new Integer (newParentId)); } public void setExpandItem (int handle, Object itemId) { log.info ("setExpandItem: handle={} itemId={}", handle, itemId); if (handle_to_container.containsKey (handle)) { NavContainer container = handle_to_container.get (handle); log.info ("setExpandItem: container={}", container); container.setChildrenAllowed (itemId, true); Dictionary<String, Object> properties = container.getProperties (); properties.put ("@expandItem", itemId); container.updateProperties (properties); } } public void setExpandItem (int handle, int itemId) { setExpandItem (handle, new Integer (itemId)); } } // EOF
C#
UTF-8
2,579
3.40625
3
[]
no_license
using System; namespace Graupel.Util { public static class Expect { public static T CanCast<T>(object value) { if (value.GetType() != typeof(T)) throw new InvalidOperationException("Value must be of type " + typeof(T)); return (T) value; } public static void IsEqual<T>(T var1, T var2) { NotNull(var1, var2); if (!var1.Equals(var2)) throw new InvalidOperationException("Values must match."); } public static void NotNull(params object[] args) { foreach (var arg in args) { if (arg == null) throw new InvalidOperationException("Value cannot be null."); } } public static T NotNull<T>(T arg) where T : class { if (arg == null) throw new InvalidOperationException("Value cannot be null."); return arg; } public static void IsNull<T>(T arg) where T : class { if (arg != null) throw new InvalidOperationException("Value must be null."); } public static void NotEmpty (params string[] args) { foreach (string t in args) { NotNull(t); if (t == String.Empty) throw new InvalidOperationException("String cannot be empty."); } } public static string NotEmpty(string arg) { NotNull(arg); if (arg == String.Empty) throw new InvalidOperationException("String cannot be empty."); return arg; } public static T NonNegative<T>(T arg) where T : struct, IComparable, IFormattable // numeric { if (arg.CompareTo(0) < 0) throw new InvalidOperationException("Number must be Non-negative."); return arg; } public static T PositiveNonZero<T>(T arg) where T : struct, IComparable, IFormattable // numeric { if (arg.CompareTo(0) <= 0) throw new InvalidOperationException("Number must be greater than zero."); return arg; } public static T NotZero<T>(T arg) where T : struct, IComparable, IFormattable // numeric { if (arg.CompareTo(0) == 0) throw new InvalidOperationException("Number cannot be zero."); return arg; } } }
Go
UTF-8
3,694
2.890625
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
// // Copyright (c) 2016-2023 Snowplow Analytics Ltd. All rights reserved. // // This program is licensed to you under the Apache License Version 2.0, // and you may not use this file except in compliance with the Apache License Version 2.0. // You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. // // Unless required by applicable law or agreed to in writing, // software distributed under the Apache License Version 2.0 is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. // package common import ( "bytes" "encoding/gob" "encoding/json" "github.com/google/uuid" "net/url" "strconv" "time" ) // NewString returns a pointer to a string. func NewString(val string) *string { return &val } // NewInt64 returns a pointer to an int64. func NewInt64(val int64) *int64 { return &val } // NewFloat64 returns a pointer to a float64. func NewFloat64(val float64) *float64 { return &val } // GetTimestamp returns the current unix timestamp in milliseconds func GetTimestamp() int64 { return time.Now().UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond)) } // GetTimestampString returns the current unix timestamp in milliseconds func GetTimestampString() string { return strconv.FormatInt(GetTimestamp(), 10) } // GetUUID generates a Version 4 UUID string. func GetUUID() string { return uuid.NewString() } // IntToString converts an Integer to a String. func IntToString(value int) string { return strconv.Itoa(value) } // Int64ToString converts an Integer of 64 bits to a String. func Int64ToString(value *int64) string { if value != nil { return strconv.FormatInt(*value, 10) } else { return "" } } // Float64ToString does conversion of floats to string values. func Float64ToString(value *float64, places int) string { if value != nil { return strconv.FormatFloat(*value, 'f', places, 64) } else { return "" } } // IntArrayToString converts an array of integers to a string delimited // by a string of your choice. func IntArrayToString(values []int, delimiter string) string { var strBuffer bytes.Buffer for index, val := range values { strBuffer.WriteString(IntToString(val)) if index < (len(values) - 1) { strBuffer.WriteString(delimiter) } } return strBuffer.String() } // CountBytesInString takes a string and gets a byte count. func CountBytesInString(str string) int { return len(str) } // MapToQueryParams takes a map of string keys and values and builds an encoded query string. func MapToQueryParams(m map[string]string) url.Values { params := url.Values{} for key, value := range m { params.Add(key, value) } return params } // MapToString takes a generic and converts it to a JSON representation. func MapToJson(m interface{}) string { b, err := json.Marshal(m) if err == nil { return string(b) } else { return "" } } // SerializeMap takes a map and attempts to convert it to a byte buffer. func SerializeMap(m map[string]string) []byte { b := new(bytes.Buffer) e := gob.NewEncoder(b) e.Encode(m) return b.Bytes() } // DeserializeMap takes a byte buffer and attempts to convert it back to a map. func DeserializeMap(b []byte) (map[string]string, error) { var decodedMap map[string]string d := gob.NewDecoder(bytes.NewBuffer(b)) err := d.Decode(&decodedMap) if err != nil { return nil, err } else { return decodedMap, nil } } // CheckErr throws a panic for all non-nil errors passed to it. func CheckErr(err error) { if err != nil { panic(err.Error()) } }
Markdown
UTF-8
9,204
2.65625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
> *The following text is extracted and transformed from the kalahariresorts.com privacy policy that was archived on 2019-06-15. Please check the [original snapshot on the Wayback Machine](https://web.archive.org/web/20190615131127id_/https%3A//www.kalahariresorts.com/legal) for the most accurate reproduction.* # Legal Kalahari Development LLC, LMN Development LLC, Kalahari Resorts LLC and Kalahari Management Co. LLC (collectively, "we", "us", "our") are committed to safeguarding the privacy of every individual who visits our Internet sites ("Websites"), specifically www.KalahariResorts.com. The following Privacy Policy outlines the information we will collect through the Websites and how that information will be used. This Policy will also instruct you on what to do if you do not want this information collected or further disseminated. Any changes to the Privacy Policy will always be posted on the Websites.  **Information We Collect** :  Personally identifiable information - The term 'personally identifiable information' refers to data you voluntarily provide while using the Websites that identifies you and/or the company on whose behalf you are accessing and using the Websites. Examples of personal information may include data in connection with our services, such as your name, e-mail address, phone number, company affiliation, physical address and/or certain other personal information.  Personally identifiable information is never collected through the Websites in a non-obvious manner.  Non-personally identifiable information - The term 'non-personally identifiable information' refers to general information collected through technology regarding Websites visitors and users that relates specifically to the Websites. For instance, when visiting the Websites, your IP address may be collected. An IP address is often associated with the portal or service through which you enter the Internet. Standing alone, your IP address is not personally identifiable.  The Websites also use cookies. A cookie is a text file placed on your computer’s hard drive that identifies your computer so the site can remember information you have told us before or activities you have carried out on our site. The cookies can only contain data you told us about yourself. They cannot examine your computer or read data from it. Cookies cannot transmit a virus or do damage to your system. Most browsers are initially set up to accept cookies. By clicking on the Help portion of your browser's menu bar, you can learn how to reset your browser to refuse all cookies, or to indicate when a cookie is being sent.  Examples of non-personally identifiable information collected include traffic patterns, number of visits to certain pages, visits from other Internet sites or to third-party Internet sites linked to the Websites, use of particular services and interest in services, information or features of the Websites or other parties made available through or found at the Websites.  The Websites also utilize Google Analytics Demographics and Interest Reporting. Learn more about how you can manage what information Google collects [here](https://tools.google.com/dlpage/gaoptout/). **How Information is Used** :  Personally identifiable information - Personally identifiable information may be used to assist with marketing programs designed to identify broad market groups for specific promotional opportunities. By providing personally identifiable information for this purpose you agree to be placed on marketing lists and may receive promotional notices from us or our affiliates, from time to time.  We may also use your personally identifiable information for operational uses. Examples include using your information to complete transactions requested by you (such as your purchase of a product or service, including room reservations, through the Websites), to send you administrative communications either about your account with us, or to share your personal information with our telephone reservations center in order to allow our staff to respond more promptly to your questions or requests when you call.  Your personally identifiable information may be shared with reputable third parties, but only for use in advertising campaign delivery or to provide more relevant advertising. Your personally identifiable information may be combined with additional information provided by you or augmented from other data sources.  We will not sell or rent any personally identifiable information collected with any party not affiliated with us without your express written consent, except as provided below.  Non-personally identifiable information - Non-personally identifiable information is used to make the Websites more helpful, interesting and useful to our visitors.  Non-personally identifiable information may be used to provide anonymous statistical analysis of visitor traffic patterns, administer the Websites and servers, to allow for the auditing of our services by third parties and to improve our services. **Permission for Use** : We may collect and use personally identifiable information that you submit at the Websites in any manner consistent with uses in this Privacy Policy or disclosed elsewhere on the Websites at the point you submit such personal information.  **Privacy Statement Exceptions** : Special circumstances - We may monitor and, when we believe in good faith that disclosure is required, disclose personally identifiable information to protect the security, property, assets and/or rights of Kalahari Development LLC, LMN Development LLC and Kalahari Resorts LLC from unauthorized use, or misuse, of the Websites or anything found at the Websites.  We reserve the right to disclose personally identifiable information of the users of the Websites for any law enforcement purpose at the request of any law enforcement body or in response to subpoena or as otherwise required by court or administrative agency.  Sale of assets - No part of this Privacy Policy is intended to interfere with the ability of Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC to transfer all or part of its businesses or assets, including the Websites to an affiliate or independent third party at any time, for any purpose, without any limitation whatsoever. We specifically reserve the right to transfer personally identifiable information collected from the Websites to the buyer of that portion of our business relating to that information. You may opt out of continued use of your information by any buyer of the Websites.  **Links Provided to Other Internet Sites** : The Internet sites owned and operated by Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC may contain links to other Internet sites. These third party Internet sites may not follow the same privacy practices of Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC. Therefore, we are not responsible for the privacy practices or the actions of third parties, including without limitation, any Internet site owners whose Internet sites may be reached through any Internet site owned or operated by Kalahari Development LLC, LMN Development LLC and Kalahari Resorts LLC. For this reason, we strongly encourage you to view the privacy policies of these other sites prior to submitting any personally identifiable information to them.  **User Consent to This Privacy Policy** : Use of the Websites signifies your consent, as well as the consent of the company for whom you use the Websites and whose information you submit (if any), to this on-line Privacy Policy, including the collection and use of information by Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC, as described in this policy, and also signifies agreement to the Terms of Use for the Websites. Continued access and use of the Websites without acceptance of the terms of this Privacy Policy relieves us from responsibility to the user.  **Withdrawing Consent** : If, after permitting use of your personally identifiable information, you later decide that you no longer want us to include your information in our marketing database or otherwise contact you or to use your information in the manner disclosed in this Privacy Policy or at the Websites, simply tell us by contacting us using the resources listed at the bottom of this Privacy Policy. **Privacy Statement Modifications** : We reserve the right to change this Privacy Policy at any time; notice of changes will be published on this page. Changes will always be prospective, not retroactive.  **Contacting Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC** : If you have questions regarding this Privacy Policy, the practices of Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC or your dealings with Kalahari Development LLC, LMN Development LLC and/or Kalahari Resorts LLC, please [email](mailto:webmaster@kalahariresort.com) us or write us at:  Internet Marketing Kalahari Waterpark Resort Convention Center P. O. Box 590 Wisconsin Dells WI 53965 10/19/2017
C++
UTF-8
561
2.96875
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n,x,y,flag=1,i; cin >> n; int arr2[n]={0}; cin >> x; int arr[x]; for(i=0;i<x;i++) { cin >> arr[i]; arr2[arr[i]-1]++; } cin >> y; int arr1[y]; for(i=0;i<y;i++) { cin >> arr1[i]; arr2[arr1[i]-1]++; } sort(arr2,arr2+n); for(i=0;i<n;i++) { if(arr2[i]==0) { flag=0; break; } else { flag=1; } } if(flag==0) { cout << "Oh, my keyboard!"; } else { cout << "I become the guy."; } }
Python
UTF-8
313
2.796875
3
[]
no_license
from sklearn.neighbors import NearestNeighbors import numpy as np X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X) distances, indices = nbrs.kneighbors(X) indices=array([[0, 1], [1, 0], [2, 1], [3, 4], [4, 3], [5, 4]])
JavaScript
UTF-8
931
2.734375
3
[ "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function check(form)/*function to check userid & password*/ { /*the following code checkes whether the entered userid and password are matching*/ if (form.userid.value === "admin" && form.pswrd.value === "admin") { var uname = escape(form.userid.value) + ";"; document.cookie = "name=" + uname; window.location.href = "finalprivate.html"; } else { alert("Error Password or Username");/*displays error message*/ } } function login() { if (event.keyCode === 13) document.getElementById('loginbtn').click(); } function logout() { if (document.cookie.length !== 0) { document.cookie = "name=" + ""; window.location.href = "index.html"; } }
Markdown
UTF-8
7,008
2.828125
3
[]
no_license
--- layout: post title: "Android的ViewPager学习笔记!" date: 2014-07-30 07:30:00 categories: android type: android --- viewpager可以实现屏幕滑动的效果,用来做画廊,启动界面这些都不错,而且比Flipper,Gallery都快,顺畅。可以考虑把tongli的那个图片换成viewpager。 **官方的viewpager使用很简单:** 首先在布局设置viewpager控件,然后重写PagerAdapter,里面的data是List<View>即可,主要重载两个方法: {% highlight java %} @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager)container).removeView(data.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { ((ViewPager)container).addView(data.get(position)); return data.get(position); } {% endhighlight %} viewpager可以设置setOnPageChangeListener事件。 一般结合viewpager使用的是在顶部有一些tab,当滑动viewpager的时候,tab也跟着变化。 官方的有这两个控件,他们都是作为viewpager的子控件使用: PagerTabStrip: 交互式 PagerTitleStrip: 非交互式 PagerTabStrip: 1.点击上面的标题可以实现ViewPager的切换。 2.选中的文字下方包含指引线 3.显示全宽下划线(setDrawFullUnderline) PagerTitleStrip: 1.点击上面的标题无反应。 2.无上述描述。 代码上没多少区别,vviewpager和strip无需再绑定了,只要在上面的adapter里面再重写一个方法和设置title的data {% highlight java %} @Override public CharSequence getPageTitle(int position) { return Titles.get(position); } {% endhighlight %} 另外,strip有很多属性可以设置的。 **FragmentPagerAdapter** viewpager的adapter的另外一种写法,不是继承PagerAdapter,而是继承FragmentPagerAdapter,没什么难的,只是viewpager的每一个view都是fragment而已。而且,这个adapter还需要传FragmentManager进去。 **FragmentStatePagerAdapter** FragmentPagerAdapter更多的用于少量界面的ViewPager,比如Tab。划过的fragment会保存在内存中,尽管已经划过。而FragmentStatePagerAdapter和ListView有点类似,会保存当前界面,以及下一个界面和上一个界面(如果有),最多保存3个,其他会被销毁掉。 **FixedFragmentStatePagerAdapter** 可以google一下这个,说是修复被回收后重启时不能从fragmentstatepageradapter恢复的bug。但是我还是不太懂,先记录下来,也许以后遇到这个问题就懂了。 **setOffscreenPageLimit** 设置mPager.setOffscreenPageLimit(3);viewpager的适配器会预装在3个view,包含当前显示的view,一共4个,这是一个窗口,移动窗口时候,后面加载一个,前面销毁一个,最好能重写adapter的onDestoryItem方法。如果fragment缓存了的话,就不会去执行getItem方法,就会不去new Fragment了。 有一个开源的strip,那些tap是可以滑动的: pagerslidingtabstrip:http://blog.csdn.net/top_code/article/details/17438027 如果要用它的时候再认真去学,公司就是用这个的,然后再适当修改为自己需求的。 比较成熟和出名的是这个Android-ViewPagerIndicator:http://viewpagerindicator.com/ 网上还有人用actionbar来实现: http://blog.csdn.net/qinyuanpei/article/details/17837165 http://blog.csdn.net/eclipsexys/article/details/8688538 也有人自定义:http://blog.csdn.net/jdsjlzx/article/details/20937985 以上有机会再去学习。。。 **其他一些设置** viewpager去掉边缘滑动阴影(这些效果耗内存): android:overScrollMode="never" * **设置自动滑动的切换速度** 由于公司项目有需求,viewpager加一个按钮点击,然后滑动到下一个页面,直接去调用:mViewPager.setCurrentItem(mPos, true);发现切换得很快。调查发现,可以用反射修改viewpager的scroller属性。 Field sField = ViewPager.class.getDeclaredField("mScroller"); sField.setAccessible(true); mScroller = new FixedSpeedScroller(mViewPager.getContext(), mDuration); sField.set(mViewPager, mScroller); FixedSpeedScroller在我的github上有。。 给viewpager设置onTouch事件,如果返回true则可以屏蔽viewpager手动滑动。 * **滑动页面时对按钮进行渐变效果** 例子如下: {% highlight java %} //viewpager页面改变事件,主要做的是对开始按钮和下一步箭头按钮进行透明度处理 mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { //在第三页滑到第四页(最后页),马上体验按钮要逐渐进行显示,下一步按钮逐渐消失,通过设置Alpha值来改变透明度 //positionOffset变化是0-1,向后滑逐渐增大,向前逐渐变小。 if (position >= 2 && positionOffset != 0) { begin.setVisibility(View.VISIBLE); next.setVisibility(View.VISIBLE); if (positionOffset > 0.9) { //大于0.9以后则直接显示begin,消失next begin.getBackground().setAlpha(255); next.getBackground().setAlpha(0); } else if (positionOffset > 0) { //只要是大于0,那么就进行一个渐变效果 begin.getBackground().setAlpha((int) (255 * positionOffset)); next.getBackground().setAlpha(255 - (int) (255 * positionOffset)); } else if (positionOffset == 0) { //为0情况,则next消失 next.setVisibility(View.GONE); } } else if (position != 3) { //不是最后一页情况 begin.setVisibility(View.GONE); next.setVisibility(View.VISIBLE); } mPos = position; } @Override public void onPageSelected(int position) { //如果是最后一页,则进行显示 马上体验按钮,隐藏 下一步箭头按钮 //其他页相反处理 if (position == 3) { begin.setVisibility(View.VISIBLE); next.setVisibility(View.GONE); } else { begin.setVisibility(View.GONE); next.setVisibility(View.VISIBLE); } mPos = position; } @Override public void onPageScrollStateChanged(int state) { } }); {% endhighlight %} **要拿到viewpager的指定或者当前子view方法** 方法一: 创建子view的时候设置一个ID,然后可以根据这个id来find。 {% highlight java %} view.setId(index); mPager.findViewById(position); {% endhighlight %} 方法二: 在adapter里面设置。 {% highlight java %} private View mCurrentView; @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { mCurrentView = (View)object; } public View getPrimaryItem() { return mCurrentView; } {% endhighlight %} 方法一在viewpager的onpagechange事件里面使用很好,方法二就不行了,因为是会先处理onpagechange事件,再调用adapter里面的方法来设置。注意,mPager.childAt(mPager.getCurrentItem());这个方法不准确,viewpager超过三个就不行了。
Java
UTF-8
2,369
2.734375
3
[]
no_license
package model; import javafx.beans.property.IntegerProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; public class ScheduleDetails { private final StringProperty Team1; private final StringProperty Team2; private final IntegerProperty kolejka; private final StringProperty GoleGosp; private final StringProperty GoleGosc; private final StringProperty terminmeczu; private final StringProperty godzina; // Default constructor public ScheduleDetails(int kolejka, String terminmeczu, String godzina, String Team1, String GoleGosp, String Team2, String GoleGosc) { this.kolejka = new SimpleIntegerProperty(kolejka); this.terminmeczu = new SimpleStringProperty(terminmeczu); this.godzina = new SimpleStringProperty(godzina); this.Team1 = new SimpleStringProperty(Team1); this.GoleGosp = new SimpleStringProperty(GoleGosp); this.Team2 = new SimpleStringProperty(Team2); this.GoleGosc = new SimpleStringProperty(GoleGosc); } public String getTeam1() { return Team1.get(); } public String getterminmeczu() { return terminmeczu.get(); } public String getgodzina() { return godzina.get(); } public String getTeam2() { return Team2.get(); } public void setTeam1(String value) { Team1.set(value); } public void setterminmeczu(String value) { terminmeczu.set(value); } public void setgodzina(String value) { godzina.set(value); } public void setTeam2(String value) { Team2.set(value); } public StringProperty Team1Property() { return Team1; } public StringProperty Team2Property() { return Team2; } public StringProperty terminmeczuProperty() { return terminmeczu; } public StringProperty godzinaProperty() { return godzina; } public IntegerProperty kolejkaProperty() { return kolejka; } public Integer getKolejka() { return kolejka.get(); } public String getGoleGosp() { return GoleGosp.get(); } public String getGoleGosc() { return GoleGosc.get(); } public void setKolejka(Integer value) { kolejka.set(value); } public void setGoleGosp(String value) { GoleGosp.set(value); } public void setGoleGosc(String value) { GoleGosc.set(value); } }
Java
UTF-8
1,274
1.726563
2
[]
no_license
package com.dk.service; import com.dk.data.dto.SearchCommentDto; import com.dk.data.entity.Comment; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springframework.web.multipart.MultipartFile; import java.util.List; /** * 评论 Service * * @author ban * @date 2018/12/12 */ public interface CommentService { Comment add(Comment bean); Comment update(Comment bean); Comment findById(Long id); Comment findByUuid(String uuid); IPage<Comment> findAll(SearchCommentDto condition); int count(SearchCommentDto condition); int batchInsert(List<Comment> list); List<Comment> batchQueryByIds(List<Long> ids); List<Comment> batchQueryByUuids(List<String> uuids); int delete(Long id); int delete(String uuid); int delete(Comment bean); int batchDeleteById(List<Long> ids); int batchDeleteByUuid(List<String> uuids); String addImage(String route, MultipartFile[] imageFiles); int deleteByUserAndOrder(String user, String uuid); int countByUser(String user); Comment findByUserAndOrder(String user, String uuid); Boolean deleteImage(String route); IPage<Comment> getAll(SearchCommentDto condition); IPage<Comment> findByNurse(SearchCommentDto condition); }
Python
UTF-8
298
3.390625
3
[]
no_license
class MyError(Exception): def __init__(self,message=""): self.message=message def __str__(self): return "MyError" def fun(): raise MyError("My test error message") try: fun() except MyError as e: print("MyError",e.message) print("*"*100) raise MyError()
Markdown
UTF-8
781
2.671875
3
[]
no_license
# threejs-examples-dae-tools-sphere-normals-invert The idea here is to start a project in which I am [creating a sphere in blender with inverted normals so that when I load a DAE file export into a threejs project](https://dustinpfister.github.io/2022/05/31/threejs-examples-dae-tools-sphere-normals-invert/) the 'front side' of the sphere is the inside of the sphere. On top of having inverted normals I can also work out one or more textures to use with this as well with the end goal of just having a few options for something that will work as a kind of background for an over all scene. <div align="center"> <a href="https://www.youtube.com/watch?v=nznbbT525Mk"> <img src="https://img.youtube.com/vi/nznbbT525Mk/0.jpg" style="width:50%;"> </a> </div>
SQL
UTF-8
5,194
3.015625
3
[]
no_license
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; CREATE TABLE IF NOT EXISTS `waste_total` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT COMMENT '#db_NoDisplay', `year` enum('1960','1970','1980','1990','2000','2005','2007','2008','2009','2010') NOT NULL COMMENT '#db_Filter ', `type` enum('generated','recovered','discarded') DEFAULT NULL COMMENT '#db_Filter ', `paper` mediumint(8) unsigned DEFAULT NULL, `glass` mediumint(8) unsigned DEFAULT NULL, `ferrous_metals` mediumint(8) unsigned DEFAULT NULL, `aluminum` mediumint(8) unsigned DEFAULT NULL, `other_non_ferrous_metals` mediumint(8) unsigned DEFAULT NULL, `plastic` mediumint(8) unsigned DEFAULT NULL, `rubber_leather` mediumint(8) unsigned DEFAULT NULL, `textiles` mediumint(8) unsigned DEFAULT NULL, `wood` mediumint(8) unsigned DEFAULT NULL, `other` mediumint(8) unsigned DEFAULT NULL, `food` mediumint(8) unsigned DEFAULT NULL, `yard` mediumint(8) unsigned DEFAULT NULL, `misc_inorganic` mediumint(8) unsigned DEFAULT NULL, `total` mediumint(8) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `year` (`year`,`type`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=31 ; INSERT INTO `waste_total` (`id`, `year`, `type`, `paper`, `glass`, `ferrous_metals`, `aluminum`, `other_non_ferrous_metals`, `plastic`, `rubber_leather`, `textiles`, `wood`, `other`, `food`, `yard`, `misc_inorganic`, `total`) VALUES (1, '1960', 'generated', 29990, 6720, 10300, 340, 180, 390, 1840, 1760, 3030, 70, 12200, 20000, 1300, 88120), (2, '1970', 'generated', 44310, 12740, 12360, 800, 670, 2900, 2970, 2040, 3720, 770, 12800, 23200, 1780, 121060), (3, '1980', 'generated', 55160, 15130, 12620, 1730, 1160, 6830, 4200, 2530, 7010, 2520, 13000, 27500, 2250, 151640), (4, '1990', 'generated', 72730, 13100, 12640, 2810, 1100, 17130, 5790, 5810, 12210, 3190, 23860, 35000, 2900, 208270), (5, '2000', 'generated', 87740, 12770, 14150, 3190, 1600, 25530, 6670, 9480, 13570, 4000, 29810, 30530, 3500, 242540), (6, '2005', 'generated', 84840, 12540, 15210, 3330, 1860, 29250, 7290, 11510, 14790, 4290, 31990, 32070, 3690, 252660), (7, '2007', 'generated', 82530, 12520, 15940, 3360, 1890, 30740, 7500, 12170, 15190, 4550, 32610, 32630, 3750, 255380), (8, '2008', 'generated', 77420, 12150, 15960, 3410, 1960, 30070, 7590, 12710, 15400, 4670, 33340, 32900, 3780, 251360), (9, '2009', 'generated', 68430, 11780, 15940, 3440, 1970, 29830, 7630, 13020, 15590, 4710, 34290, 33200, 3820, 243650), (10, '2010', 'generated', 71310, 11530, 16900, 3410, 2100, 31040, 7780, 13120, 15880, 4790, 34760, 33400, 3840, 249860), (11, '1960', 'recovered', 5080, 100, 50, 0, 0, 0, 330, 50, 0, 0, 0, 0, 0, 5610), (12, '1970', 'recovered', 6770, 160, 150, 10, 320, 0, 250, 60, 0, 300, 0, 0, 0, 8020), (13, '1980', 'recovered', 11740, 750, 370, 310, 540, 20, 130, 160, 0, 500, 0, 0, 0, 14520), (14, '1990', 'recovered', 20230, 2630, 2230, 1010, 730, 370, 370, 660, 130, 680, 0, 4200, 0, 33240), (15, '2000', 'recovered', 37560, 2880, 4680, 860, 1060, 1480, 820, 1320, 1370, 980, 680, 15770, 0, 69460), (16, '2005', 'recovered', 41960, 2590, 5030, 690, 1280, 1780, 1090, 1840, 1830, 1210, 690, 19860, 0, 79850), (17, '2007', 'recovered', 44480, 2880, 5280, 730, 1300, 2110, 1140, 1920, 2020, 1240, 810, 20900, 0, 84810), (18, '2008', 'recovered', 42940, 2810, 5300, 720, 1360, 2140, 1130, 1910, 2110, 1300, 800, 21300, 0, 83820), (19, '2009', 'recovered', 42500, 3000, 5270, 690, 1370, 2140, 1140, 1910, 2200, 1310, 850, 19900, 0, 82280), (20, '2010', 'recovered', 44570, 3130, 5710, 680, 1480, 2550, 1170, 1970, 2300, 1410, 970, 19200, 0, 85140), (21, '1960', 'discarded', 24910, 6620, 10250, 340, 180, 390, 1510, 1710, 3030, 70, 12200, 20000, 1300, 82510), (22, '1970', 'discarded', 37540, 12580, 12210, 790, 350, 2900, 2720, 1980, 3720, 470, 12800, 23200, 1780, 113040), (23, '1980', 'discarded', 43420, 14380, 12250, 1420, 620, 6810, 4070, 2370, 7010, 2020, 13000, 27500, 2250, 137120), (24, '1990', 'discarded', 52500, 10470, 10410, 1800, 370, 16760, 5420, 5150, 12080, 2510, 23860, 30800, 2900, 175030), (25, '2000', 'discarded', 50180, 9890, 9470, 2330, 540, 24050, 5850, 8160, 12200, 3020, 29130, 14760, 3500, 173080), (26, '2005', 'discarded', 42880, 9950, 10180, 2640, 580, 27470, 6200, 9670, 12960, 3080, 31300, 12210, 3690, 172810), (27, '2007', 'discarded', 38050, 9640, 10660, 2630, 590, 28630, 6360, 10250, 13170, 3310, 31800, 11730, 3750, 170570), (28, '2008', 'discarded', 34480, 9340, 10660, 2690, 600, 27930, 6460, 10800, 13290, 3370, 32540, 11600, 3780, 167540), (29, '2009', 'discarded', 25930, 8780, 10670, 2750, 600, 27690, 6490, 11110, 13390, 3400, 33440, 13300, 3820, 161370), (30, '2010', 'discarded', 26740, 8400, 11190, 2730, 620, 28490, 6610, 11150, 13580, 3380, 33790, 14200, 3840, 164720); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
1,977
2.234375
2
[]
no_license
package com.dimple.project.blog.blog.service; import com.dimple.project.blog.blog.domain.Blog; import java.util.List; /** * @className: BlogService * @description: * @auther: Dimple * @Date: 2019/3/16 * @Version: 1.0 */ public interface BlogService { /** * 根据条件查询所有的blog * * @param blog 带有条件信息的blog * @return 博客集合 */ List<Blog> selectBlogList(Blog blog); /** * 新增博客 * * @param blog 需要新增的博客的实体 * @return 受影响的行数 */ int insertBlog(Blog blog); /** * 根据id修改blog * * @param blogId 需要修改的blog的id * @return blog实体 */ Blog selectBlogById(Integer blogId); /** * 修改blog信息 * * @param blog 需要修改的blog实体 * @return 受影响的行数 */ int updateBlog(Blog blog); /** * 切换support状态 * * @param blogId 需要切换状态的blog的id * @param support 需要切换的support状态 * @return 受影响的行数 */ int updateBlogSupportById(Integer blogId, String support); /** * 切换博客的状态 * * @param blogIds 博客的id * @param status 需要切换的博客的状态 * @return 受影响的行数 */ int updateBlogStatusById(String blogIds, String status); /** * 删除博客 * * @param ids 需要删除的blog的id * @return 受影响的行数 */ int deleteBlogById(Integer[] ids); /** * 根据Blog的状态统计数量 * * @param status 需要统计的blog的状态 * @return 该状态下的blog数量 */ int selectBlogCountByStatus(int status); /** * 根据Blog的id获取blog信息,包括tag * * @param blogId 需要获取信息的blog的id * @return Blog实体类 */ Blog selectBlogWithTextAndTagsById(Integer blogId); }
Ruby
UTF-8
129
2.953125
3
[]
no_license
puts "Hey, donne-moi un nombre" user_number = gets.chomp.to_i i = user_number i.times do puts "Salut, ça farte?" end
Java
UTF-8
3,758
2.3125
2
[]
no_license
package user.model.service; import static common.JDBCTemplate.*; import java.sql.Connection; import java.util.ArrayList; import petSitter.model.vo.PetSitter; import user.model.dao.MyMatchingDao; import matching.model.vo.Matching; public class MyMatchingService { MyMatchingDao mmd = new MyMatchingDao(); public MyMatchingService() { } //펫시터인지 검사하고 모든객체 가져오기 public PetSitter findSitter(String userId) { Connection conn= getConnection(); PetSitter ps = new MyMatchingDao().findSitter(conn,userId); close(conn); return ps; } public ArrayList<Matching> viewYetMatching(String userId) { Connection conn = getConnection(); ArrayList<Matching> yList1 = mmd.yetMatchingView(conn,userId); close(conn); return yList1; } public ArrayList<Matching> viewYetMatching2(String userId) { Connection conn = getConnection(); ArrayList<Matching> yList2 = mmd.yetMatchingView2(conn,userId); if(yList2 == null) { System.out.println("service null확인"); return yList2; } close(conn); return yList2; } public ArrayList<Matching> viewNowMatching(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList1 = mmd.nowMatchingView(conn, userId); close(conn); return nList1; } public ArrayList<Matching> viewNowMatching2(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList2 = mmd.nowMatchingView2(conn, userId); close(conn); return nList2; } public ArrayList<Matching> viewNowMatching3(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList3 = mmd.nowMatchingView3(conn, userId); close(conn); return nList3; } public ArrayList<Matching> viewNowMatching4(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList4 = mmd.nowMatchingView4(conn, userId); close(conn); return nList4; } public ArrayList<Matching> viewNowMatching5(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList5 = mmd.nowMatchingView5(conn, userId); close(conn); return nList5; } public ArrayList<Matching> viewNowMatching6(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList6 = mmd.nowMatchingView6(conn, userId); close(conn); return nList6; } public ArrayList<Matching> viewNowMatching7(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList7 = mmd.nowMatchingView7(conn, userId); close(conn); return nList7; } public ArrayList<Matching> viewNowMatching8(String userId) { Connection conn = getConnection(); ArrayList<Matching> nList8 = mmd.nowMatchingView8(conn, userId); close(conn); return nList8; } public ArrayList<Matching> viewEndMatching(String userId) { Connection conn = getConnection(); ArrayList<Matching> eList1 = mmd.endMatchingView1(conn, userId); close(conn); return eList1; } public ArrayList<Matching> viewEndMatching2(String userId) { Connection conn = getConnection(); ArrayList<Matching> eList2 = mmd.endMatchingView2(conn, userId); close(conn); return eList2; } public ArrayList<Matching> viewEndMatching3(String userId) { Connection conn = getConnection(); ArrayList<Matching> eList3 = mmd.endMatchingView3(conn, userId); close(conn); return eList3; } public ArrayList<Matching> viewEndMatching4(String userId) { Connection conn = getConnection(); ArrayList<Matching> eList4 = mmd.endMatchingView4(conn, userId); close(conn); return eList4; } }
Java
UTF-8
1,489
2.1875
2
[]
no_license
package com.quizwish.quiz.component; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import com.quizwish.quiz.services.QuizService; import com.quizwish.quiz.services.QuizgrupoService; import com.quizwish.quiz.entity.Grupo; import com.quizwish.quiz.entity.Quiz; import com.quizwish.quiz.entity.Quizgrupo; import com.quizwish.quiz.models.User; @Component("quizComponent") public class QuizComponent { @Autowired @Qualifier("quizService") QuizService quizService; @Autowired @Qualifier("quizgrupoService") QuizgrupoService quizgrupoService; public List<Quiz> quizWithStatusTrue(User user) { List<Quiz> quizList = quizService.getQuizByIduser(user); quizList.stream().filter(Quiz -> Quiz.isEstatus() == true).forEach(System.out::println); return quizList; } public List<User> StudentWithStatusTrue(List<User> listUser) { listUser.stream().filter(User -> User.isEnable() == true).forEach(System.out::println); return listUser; } public Quizgrupo getOnlyOneQuizgrupo(Grupo grupo, Quiz idquiz) { List<Quizgrupo> grupousuario = quizgrupoService.findAllByIdquiz(idquiz) .stream() .filter(grupu -> grupu.getIdgrupo().getIdgrupo().equals(grupo.getIdgrupo())) .collect(Collectors.toList()); return grupousuario.isEmpty() ? new Quizgrupo() : grupousuario.get(0); } }
PHP
UTF-8
2,268
2.875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: alonso * Date: 2019-05-18 * Time: 14:27 */ namespace Project\Posts; use Project\Utils\ProjectDao; use Firebase\JWT\JWT; class PostsDao { private $dbConnection; public function getAll() { $sql = "SELECT * FROM Posts ORDER BY ID DESC"; return $this->dbConnection->fetchAll($sql); } public function __construct(ProjectDao $dbConnection) { $this->dbConnection = $dbConnection; } public function getByUsername($username) { $sql = "SELECT * FROM Posts WHERE username = ? ORDER BY ID DESC"; return $this->dbConnection->fetchAll($sql, array($username)); } public function getById($id) { $sql = "SELECT * FROM Posts WHERE ID = ?"; return $this->dbConnection->fetchAll($sql, array($id)); } public function updatePost($id, $post) { $sql = "UPDATE Posts SET title = ?, description = ?, class = ? WHERE ID = ?"; $this->dbConnection->execute($sql, array($post['title'], $post['description'],$post['class'], $id)); return $this->getById($id); } public function getByClass($classe) { $sql = "SELECT * FROM Posts WHERE class = ? ORDER BY ID DESC"; return $this->dbConnection->fetchAll($sql, array($classe)); } public function getPhotosById($id) { $sql = "SELECT * FROM Imagenes WHERE ID = ?"; return $this->dbConnection->fetchAll($sql, array($id)); } public function createPost($post) { $sql = "INSERT INTO Posts (username, title, description, class) VALUES (?, ?, ?, ?)"; $id = $this->dbConnection->insert($sql, array($post['username'], $post['title'], $post['description'], $post['classe'])); $sql = "INSERT INTO Imagenes (ID, image) VALUES (?,?)"; for ($x = 0; $x < count($post['images']); $x++) { $this->dbConnection->insert($sql,array($id,$post['images'][$x])); } return $id; } public function delete($id) { $sql = "DELETE FROM Posts WHERE id = ?"; $this->dbConnection->execute($sql, array($id)); $sql = "DELETE FROM Imagenes WHERE ID = ?"; $this->dbConnection->execute($sql, array($id)); } }
Java
UTF-8
126
1.640625
2
[]
no_license
package ca.customer.dao.models; /** * Created by Vivek on 25-02-2017. */ public enum Status { DRAFT,ACTIVE,INACTIVE }
Rust
UTF-8
2,487
2.71875
3
[ "Apache-2.0", "MIT" ]
permissive
// Copyright 2019-2023 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use std::convert::TryFrom; use libipld::cid::{ multihash::{Code, MultihashDigest}, Version, }; use unsigned_varint::{decode as varint_decode, encode as varint_encode}; use crate::libp2p_bitswap::*; /// Prefix represents all metadata of a CID, without the actual content. #[derive(PartialEq, Eq, Clone, Debug)] pub struct Prefix { /// The version of `CID`. pub version: Version, /// The codec of `CID`. pub codec: u64, /// The `multihash` type of `CID`. pub mh_type: u64, /// The `multihash` length of `CID`. pub mh_len: usize, } impl Prefix { /// Create a new prefix from encoded bytes. pub fn new(data: &[u8]) -> anyhow::Result<Prefix> { let (raw_version, remain) = varint_decode::u64(data)?; let version = Version::try_from(raw_version)?; let (codec, remain) = varint_decode::u64(remain)?; let (mh_type, remain) = varint_decode::u64(remain)?; let (mh_len, _remain) = varint_decode::usize(remain)?; Ok(Prefix { version, codec, mh_type, mh_len, }) } /// Convert the prefix to encoded bytes. pub fn to_bytes(&self) -> Vec<u8> { let mut res = Vec::with_capacity(4); let mut buf = varint_encode::u64_buffer(); let version = varint_encode::u64(self.version.into(), &mut buf); res.extend_from_slice(version); let mut buf = varint_encode::u64_buffer(); let codec = varint_encode::u64(self.codec, &mut buf); res.extend_from_slice(codec); let mut buf = varint_encode::u64_buffer(); let mh_type = varint_encode::u64(self.mh_type, &mut buf); res.extend_from_slice(mh_type); let mut buf = varint_encode::u64_buffer(); let mh_len = varint_encode::u64(self.mh_len as u64, &mut buf); res.extend_from_slice(mh_len); res } /// Create a CID out of the prefix and some data that will be hashed pub fn to_cid(&self, data: &[u8]) -> anyhow::Result<Cid> { let mh = Code::try_from(self.mh_type)?.digest(data); Ok(Cid::new(self.version, self.codec, mh)?) } } impl From<&Cid> for Prefix { fn from(cid: &Cid) -> Self { Self { version: cid.version(), codec: cid.codec(), mh_type: cid.hash().code(), mh_len: cid.hash().digest().len(), } } }
C++
UTF-8
1,178
2.640625
3
[]
no_license
#pragma once #include <iostream> #include <windows.h> #include <vector> enum class AutoMovementDirection { UP, DOWN, LEFT, RIGHT, IDLE }; struct Coordinates { int x; int y; }; class Map { public: Map(); void GenerateMap() const; void Control(); void Bounderies(); void AutomaticMovement(); Coordinates RandomXandY(int maxHeight, int maxWidth) const; void CollectConsumables(); void TailBehaviour(); void LoseCondition(); int GetScore() const { return score; } void CleanStart(); bool GetGameStatus() const { return isGameRunning; } void SetGameStatus(bool gameStatus) { isGameRunning = gameStatus; } protected: int GetMapWidth() { return mapWidth; } int GetMapHeight() { return mapHeight; } private: //score int score = 0; //map dimensions int mapWidth = 20; int mapHeight = 20; //mc position int mcInitalPosX; int mcInitalPosY; //enum initialization AutoMovementDirection autoMovementDirectionVar; //consumable position int consumablePosX; int consumablePosY; // tail std::vector<int> tPosX; std::vector<int> tPosY; bool isGameRunning = true; };
PHP
UTF-8
1,372
2.609375
3
[]
no_license
<?php /** * 159339Assignment3 * XIN WANG 15397438 * Tianxiang Han 13064237 * Zhen Cheng 13040788 */ class BadTransException extends Exception { /** * BadTransException constructor. * @param null $message message to throw * @param int $code exception code */ public function __construct($message = null, $code = 0) { if (!$message) { throw new $this('Unknown '. get_class($this)); } parent::__construct($message, $code); } } /** * Class BadRegisterException */ class BadRegisterException extends Exception { /** * BadRegisterException constructor. * @param null $message message to throw * @param int $code exception code */ public function __construct($message = null, $code = 0) { if (!$message) { throw new $this('Unknown '. get_class($this)); } parent::__construct($message, $code); } } /** * Class BadAddAccountException */ class BadAddAccountException extends Exception { /** * BadAddAccountException constructor. * @param null $message message to throw * @param int $code exception code */ public function __construct($message = null, $code = 0) { if (!$message) { throw new $this('Unknown ' . get_class($this)); } parent::__construct($message, $code); } }
Markdown
UTF-8
2,104
3.5625
4
[]
no_license
## 题解:[20191209]#0056 Merge Intervals - **题干** 输入一组区间,合并有交叠的区间并返回。 示例: ``` // e.g.1 Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: [1,3]和[2,6]有交叠,合并区间为[1,6] // e.g.2 Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: 区间[1,4]和[4,5]可以看做是有重叠的 ``` - **第一思路** 对于两个区间[a,b],[c,d],可以进行合并的条件是`c>=b`,已知在区间中`b>=a`,则`c>=b>=a`。所以首先对区间进行排序,对于区间[a,b]/[c,d]比较规则如下: - a<c,则[a,b]位于[c,d]之前 - a>c,则[c,d]位于[a,b]之前 - a==c, 则比较b,d,如果b<=d则[a,b]位于前,否则[c,d]位于前 排序完成后对遍历一次数组,当`c>=b`时,则合并区间。时间复杂度O(nlogn)。 Runtime: 96 ms, faster than 13.36% of JavaScript online submissions for Merge Intervals. Memory Usage: 38 MB, less than 7.69% of JavaScript online submissions for Merge Intervals. - **优化思路** 这个时间复杂度不太满意,主要耗时操作是在排序上,目前感觉排序还是需要的,所以考虑优化一下排序比较规则。当a==c时的状况是可以不处理的,因为在后续合并区间的时候还是需要比较b和d。 Runtime: 76 ms, faster than 68.80% of JavaScript online submissions for Merge Intervals. Memory Usage: 37.7 MB, less than 15.38% of JavaScript online submissions for Merge Intervals. - **高票答案对比** 高票思路:https://leetcode.com/problems/merge-intervals/discuss/21222/A-simple-Java-solution 同第一思路,作者不在原数组操作,而是新建一个结果数组,最后合并时遍历区间数组,与结果数组中的最后一个区间比较,根据比较结果,修改最后区间的结束位置即可。 Runtime: 60 ms, faster than 99.62% of JavaScript online submissions for Merge Intervals. Memory Usage: 37 MB, less than 76.92% of JavaScript online submissions for Merge Intervals.
Python
UTF-8
113
2.734375
3
[]
no_license
input_file = 'ml-latest/movies.csv' with open(input_file, 'rb') as file: for row in file: print(row)
JavaScript
UTF-8
1,074
4.4375
4
[]
no_license
// Exercise 2.1 // ------------ // Create a Book class and then intantiate it 5 times with various books // include the following properties in the constructor // - title (string) // - genre (string) // - author (string) // - isRead (boolean - whether or not you've read the book) // // Declare the books as book1, book2, book3, book4, book5 // // If the book doesn't provide a value for `isRead`, it should default to // `false`. // // Console.log them to verify that all is working. class Book { constructor(title, genre, author, isRead) { this.title = title; this.genre = genre; this.author = author; this.isRead = isRead; } } const book1 = new Book('Harry Potter', 'Fantasy', 'J.K. Rowling', true); const book2 = new Book('The Murder of Roger Ackroyd', 'Mystery', 'Agatha Christie', true); const book3 = new Book('Death on the Nile', 'Mystery', 'Agatha Christie', false); const book4 = new Book('A Fine Balance', 'Fiction', 'Rohinton Mistry', true); const book5 = new Book('Cutting for Stone', 'Fiction', 'Abraham Verghese', false); console.log(book1, book2, book3, book4, book5);
Markdown
UTF-8
30,395
3.046875
3
[]
no_license
## 我在创意阶段所做的贡献 >我们小组的创意来源于我的一门期末作业,因此主要是我提出的。之后我们小组一起对功能进行完善。 我的贡献主要是:1,提出主题;2.对项目的模块和功能进行完善。 ## 针对人群 >ECNU作业评价小工具的针对人群 ,就是华东师范大学的学生和老师们,可以通过我们的小工具进行作业的发布、提交、评价和交流。 ## ECNU作业评价小工具的功能 >1.注册和登录功能。学生在注册页面填写信息之后,数据会记录到数据库中,之后学生在登陆的时候,学生所填写的身份信息会自动与数据库中的数据进行比对。 2.教师发布作业的功能。教师可以在对应科目发布作业,所有选修这门课的同学都能看到这项作业。 3.学生查看、提交作业的功能。学生看到教师发布的作业信息之后,可以提交作业,包括直接提交文本和提交附件两种形式。 4.教师查看、评价学生作业的功能。教师收到学生作业后,可以下载附件,并对作业进行评分和点评。学生的得分有一次修改机会。 5.教师与学生之间进行交流的功能。教师对学生的作业的点评,学生如有疑问,可以继续与老师进行交流。 ## 创意 > ECNU作业评价小工具的灵感来源 ,就是看到很多没有考试的科目,都是采用期末大作业的形式来评分。而期末的大作业,很多都是采用小组作业的形式。但是,往往都是小组把作业提交之后,等到假期里成绩出来。有的成绩与学生本人预期比较近,但是有的同学的成绩则与本人预期相差较远。而在我们学校,针对期末作业的提交情况,学生与老师之间并没有一个有效的沟通工具。学生的成绩较低,也不知道自己的作业为什么比别热差,更不清楚自己需要改进的地方在哪里。因此,我们组想设计一个作业评价小工具,针对作业的提交的问题,在学生和老师之间建立一个沟通的渠道,方便师、生之间就作业进行探讨,也方便学生查看自己的成绩,以及老师对学生的作品进行点评,包括学生作品的缺点和改进措施等。 ## 需求 >我们的小工具,使用简便,只有有一个浏览器就可以进行操作,无需另外下载APP; 功能强大,老师可以在这里发布作业,学生可以提交作业,师、生之间还可以就作业的问题进行交流。如果学生对老师的评分有疑问,师、生之间还可以进行商榷,得分有一次修改的机会。 界面简洁,能给用户带来美感。 ## 原型图片 ![new mockup 3](https://cloud.githubusercontent.com/assets/22018427/21747367/b01333d8-d59f-11e6-99d7-1ccd821ca8a5.png) ![teacher](https://cloud.githubusercontent.com/assets/22018427/21747365/afe4a568-d59f-11e6-91f8-f81f9ca3c154.png) ![judge](https://cloud.githubusercontent.com/assets/22018427/21747366/afe8b900-d59f-11e6-9835-9e34129c8b3b.png) ![new mockup 1 alternate 391r](https://cloud.githubusercontent.com/assets/22018427/21747368/b02c0a52-d59f-11e6-877d-be9a949d0572.png) ![new mockup 2](https://cloud.githubusercontent.com/assets/22018427/21747369/b0bcbebc-d59f-11e6-9985-2ff0f6968c5b.png) ## 设计的功能列表以及其完成情况 设计的功能|承担该功能的组员|任务完成度 --|--|-- 注册功能| 杜谦|20% 作业提交功能 | 杜谦|50% 从数据库中获取教师已发布的作业列表|李志伟|未完成 从数据中获取学生提交的作业信息|李志伟|未完成 router实现界面的切换|李志伟|100% 将教师的评分以及评价写入数据库|李志伟|未完成 登录|吴怡雯|10% 评论区|吴怡雯|80% # 产品技术方案 >ecnu作业评价工具包含登陆,注册,作业上传,老师查看作业列表和老师评价作业,以及师生互动交流讨论这6个界面。这是一个完整简单的作业评价系统,学生注册一个新账号,在登陆界面登陆,找到老师布置作业的界面,提交自己的作业,然后老师对提交的作业进行批改得出最终成绩,将成绩反馈给学生,学生可以提出问题或者评论,老师给予回答,从而形成一个交互的过程。首先,我们创建了一个数据库,包含学生老师的基本信息数据库,老师发布作业及评论的数据库还有学生上传作业文件的数据库。 > 我们的产品创意的技术思路:我们是希望能针对作业的提交问题,建立师、生之间的沟通平台。 1,我们的服务器:可以对客户端的操作进行监听,例如用户在客户端输入文字、点击某个按钮,服务器必须能够进行监听并做出反应。另外,服务器端需要及时对客户端发送的请求做出反应,进行处理,及时给出反馈。 2,我们的客户端:我们力求客户端能够做到界面简洁、操作简单。每个URL之间的跳转清晰、条理清楚。 3,我们的数据库:数据库能够及时接收服务器端发送过来的数据并进行存储,并且对于服务器请求的数据,能够及时做出反应。 # 我在小组中的分工 >我在小组中主要负责: 1.利用router实现各个页面的切换; 2.教师部分的页面,包括:从数据库中获取教师已发布的作业列表,从数据中获取学生提交的作业信息,将教师的评分以及评价写入数据库。 与小组其他成员相比,我利用router实现各个页面的切换部分完成的较好,从数据库中存取数据部分完成的不够好。我们组是实行平均分工,因此每位同学的工作量相差不多,相对而言,吴怡雯同学的工作量较大。 # 我的编程实践活动 ## 我的代码 ```index.html ///教师页面以及页面之间切换 <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="scaffolded-by" content="https://github.com/google/stagehand"> <title>ECNU作业评价系统</title> <link href="styles.css"rel="stylesheet" href="styles.css"> <script defer src="main.dart" type="application/dart"></script> <script defer src="packages/browser/dart.js"></script> </head> <body> <div id="warning">Dart is not running</div> <section id="hello"> <h1>ECNU作业评价小工具</h1> <div align="right" class="yhead"> <p>你好,XX!|<a id="logoutbu">注销 </a></p> </div> </section> <div id="mainbody"> <section id="loginpage"> </section> <section id="loguppage"><div id="register" align="center"> </section> <section id="teapage"> <div id="prolist"> <h3>科目:web编程</h3> <h3>作业列表</h3> <table> <tr> <td width="800px" height="30px"> <div id="linkthree1"><a href="#three" id="linkthree" title="project3">项目三:提交一个预定座位的小程序</a></div> </td> <td width="800px"> <div id="teatimethree">时间:2016年10月7日 15:00</div> </td> </tr> <tr> <td width="800px" height="30px"> <div id="linktwo1"><a href="#two" id="linktwo" title="project2">项目二:提交一个画图的小程序</a></div> </td> <td width="800px"> <div id="teatimetwo">时间:2016年10月7日 15:00</div> </td> </tr> <tr> <td width="800px" height="30px"> <div id="linkone1"><a href="#one" id="linkone" title="project1" >项目一:提交一个银行的服务器程序</a></div> </td> <td width="800px"> <div id="teatimeone">时间:2016年10月7日 15:00</div> </td> </tr> </table> </div> </section> <section id="three"> <a id="rebtnthree" href="#teacherpage" title="返回作业列表">返回作业列表</a> <h2>项目三:提交一个预定座位的小程序</h2> <div id="threedetail"> <table> <tr> <td width="800px" height="30px"> <div id="linkthreewu1"><a href="#threewu" id="linkthreewu" title="project3_wu" >吴怡雯提交了项目三的作业:图书馆预定座位小程序</a></div> </td> <td width="800px"> <div id="stutimethreewu">时间:2016年10月7日 15:00</div> </td> </tr> <tr> <td width="800px" height="30px"> <div id="linkthreeli1"><a href="#threeli" id="linkthreeli" title="project3_li">李志伟提交了项目三的作业:餐厅预定座位小程序</a></div> </td> <td width="800px"> <div id="stutimethreeli">时间:2016年10月7日 15:00</div> </td> </tr> <tr> <td width="800px" height="30px"> <div id="linkthreedu1"><a href="#threedu" id="linkthreedu" title="project3_du" >杜谦提交了项目三的作业:电影院预定座位小程序</a></div> </td> <td width="800px"> <div id="stutimethreedu">时间:2016年10月7日 15:00</div> </td> </tr> </table> <br> <br> </div> </section> <section id="threewu"> <h3>吴怡雯提交了项目三的作业:图书馆预定座位小程序</h3> <div><a href="#threewufile" title="附件" >附件:图书馆预定座位小程序</a> <form action="" method="get"> <p>详情</p> <textarea name="word" cols="100" rows="8" id="threewuword"></textarea></form> </div> <form action="" method="post"> <label for="reasonwu">评价</label><br> <textarea name="word" cols="100" rows="8" id="reasonwu"></textarea></form> <form action="" method="post" id="teajudgewu"> <label for="scorewu">分数</label> <input type="text" name="score" id="scorewu" size="2" MAXLENGTH="4"/> <button type="submit" value="提交"><a id="subbtnwu">提交</a></button> </form> </section> <section id="threeli"> <h3>李志伟提交了项目三的作业:餐厅预定座位小程序</h3> <div><a href="#threelifile" title="附件" >附件:餐厅预定座位小程序</a> <form action="" method="get"> <p>详情</p> <textarea name="word" cols="100" rows="8" id="threeliword"></textarea></form> </div> <form action="" method="post"> <label for="reasonli">评价</label><br> <textarea name="word" cols="100" rows="8" id="reasonli"></textarea></form> <form action="" method="post" id="teajudgeli"> <label for="scoreli">分数</label> <input type="text" name="score" id="scoreli" size="2" MAXLENGTH="4"/> <button type="submit" value="提交"><a id="subbtnli">提交</a></button> </form> </section> <section id="threedu"> <h3>杜谦提交了项目三的作业:电影院预定座位小程序</h3> <div><a href="#threelifile" title="附件" >附件:电影院预定座位小程序</a> <form action="" method="get"> <p>详情</p> <textarea name="word" cols="130" rows="8" id="threeduword"></textarea></form> </div> <form action="" method="post"> <label for="reasondu">评价</label><br> <textarea name="word" cols="130" rows="8" id="reasondu"></textarea></form> <form action="" method="post" id="teajudgedu"> <label for="scoredu">分数</label> <input type="text" name="score" id="scoredu" size="2" MAXLENGTH="4"/> <button type="submit" value="提交"><a id="subbtndu">提交</a></button> </form> </section> <section id="two"> <a id="rebtntwo" href="#teapage" title="返回作业列表">返回作业列表</a> <h2>项目二:提交一个画图的小程序</h2> <div id="linktwowu1"><a href="#twowu" id="linktwowu" title="project2_wu">吴怡雯提交了项目二的作业:勾画简单图形小程序</a></div><br> <div id="linktwoli1"><a href="#twoli" id="linktwoli" title="project2_li">李志伟提交了项目二的作业:简单服装勾画小程序</a></div><br> <div id="linktwodu1"><a href="#twodu" id="linktwodu" title="project2_du" >杜谦提交了项目二的作业:简单房屋勾画小程序</a></div> </section> <section id="one"> <a id="rebtnone" href="#teapage" title="返回作业列表">返回作业列表</a> <h2>项目一:提交一个银行的服务器程序</h2> <div id="linkonewu1"><a href="#onewu" id="linkonewu" title="project1_wu">吴怡雯提交了项目一的作业:一个银行的服务器程序</a></div><br> <div id="linkoneli1"><a href="#oneli" id="linkoneli" title="project1_li">李志伟提交了项目一的作业:一个银行的服务器程序</a></div><br> <div id="linkonedu1"><a href="#onedu" id="linkonedu" title="project1_du">杜谦提交了项目一的作业:一个银行的服务器程序</a></div> </section> <section id="stupage"> </section> <section id="posthomework"> </section> <section id="mygrade" class="container"> </section> </div> ``` ```style.css ///整体CSS定义以及教师页面、学生页面CSS定义 html, body { width: 100%; height: 100%; background-color: rgba(232, 232, 232, 0.98); } #mainbody{ width: 80%; height: 80%; background-color: #e3f1ff; margin-right: 10%; margin-left: 10%; } #hello{ height: auto; } #loginpage{ margin-bottom: 25%; } #prolist{ padding-top: 5px; padding-left: 5px; margin-left: 5% } #loginpage,#three,#two,#one,#threewu,#threeli,#threedu{ padding-top: 5px; padding-left: 5px; margin-right: 5%; margin-left: 5%; } #linkthree1,#linktwo1,#linkone1,#linkthreewu1,#linkthreeli1,#linkthreedu1,#linktwowu1,#linktwoli1,#linktwodu1,#linkonewu1,#linkoneli1,#linkonedu1{ margin-bottom: 5px; } #threewuword,#reasonwu,#threeliword,#reasonli,#threeduword,#reasondu{ margin-top: 5px; margin-bottom: 5px; margin-right: 2%; margin-left: 2%; } #teajudgewu,#teajudgeli,#teajudgedu{ margin-left: 30%; margin-right: 30%; } #rebtnthree,#rebtntwo,#rebtnone{ margin-left: 90%; } table{ font-family: "宋体"; font-size: 16px; } a:link { text-decoration: none; font-family: "宋体"; font-size: 16px; color: #000000; } a.hover{ text-decoration:underline; font-size: 18px; background-color: #ececec; } a:active { text-decoration:underline; font-size: 18px; background-color: #f0f0f0; } a:visited { text-decoration: none; font-family: "宋体"; font-size: 16px; color: #000000; } section { display: none; width: 90%; height: 20%; } section.selected { display: block; } .warning { color: red; } ``` ```main.dart ///主函数 main(){ querySelector('#warning').remove(); router.root ..addRoute(name: 'loginpage', defaultRoute: true, path: '/loginpage', enter: showloginpage) ..addRoute(name: 'loguppage',path: '/loguppage', enter: showloguppage) ..addRoute(name: 'teapage',path: '/teapage', enter: showteapage) ..addRoute(name: 'stupage',path: '/stupage', enter: showstupage) ..addRoute(name: 'posthomework',path: '/stupage/posthomework', enter: showposthomework) ..addRoute(name: 'mygrade',path: '/stupage/mygrade', enter: showmygrade) ..addRoute(name: 'three', path: '/three', enter: showthree) ..addRoute(name: 'two', path: '/two', enter: showtwo) ..addRoute(name: 'one', path: '/one', enter: showone) ..addRoute(name: 'threewu', path: '/threewu', enter: showthreewu) ..addRoute(name: 'threeli', path: '/threeli', enter: showthreeli) ..addRoute(name: 'threedu', path: '/threedu', enter: showthreedu); querySelector('#loginpage').attributes['href'] = router.url('loginpage'); querySelector('#logup').attributes['href'] = router.url('loguppage'); querySelector('#login1').attributes['href'] = router.url('teapage'); querySelector('#login2').attributes['href'] = router.url('stupage'); querySelector('#logoutbu').attributes['href'] = router.url('loginpage'); querySelector('#confirbu').attributes['href'] = router.url('loginpage'); querySelector('#combtn').attributes['href'] = router.url('stupage'); querySelector('#subbtnwu').attributes['href'] = router.url('three'); querySelector('#subbtnli').attributes['href'] = router.url('three'); querySelector('#subbtndu').attributes['href'] = router.url('three'); querySelector('#newhomework').attributes['href'] = router.url('posthomework'); querySelector('#myhomework').attributes['href'] = router.url('mygrade'); querySelector('#rebtnthree').attributes['href'] = router.url('teapage'); querySelector('#rebtntwo').attributes['href'] = router.url('teapage'); querySelector('#rebtnone').attributes['href'] = router.url('teapage'); querySelector('#linkthree').attributes['href'] = router.url('three'); querySelector('#linktwo').attributes['href'] = router.url('two'); querySelector('#linkone').attributes['href'] = router.url('one'); querySelector('#linkthreewu').attributes['href'] = router.url('threewu'); querySelector('#linkthreeli').attributes['href'] = router.url('threeli'); querySelector('#linkthreedu').attributes['href'] = router.url('threedu'); router.listen(); //评价页面 var comment = querySelector('#combtn'); querySelector("#combtn").onClick.listen(combtn);//教师对学生进行评价 querySelector('#comment').text = showcomment(); //学生姓名的数据 //提交作业界面 var projectlist = querySelector('#projectlist'); querySelector('#projectlist') ..text='信息技术课程作业' ..onClick.listen(projectlist); var homeworklist = querySelector('#homeworklist'); querySelector('#homeworklist') ..text='信息技术课程作业三' ..onClick.listen(homeworklist); var homeworkdetail = querySelector('#homeworkdetail'); querySelector('#homeworkdetail') ..text='信息技术课程作业三:吴同学' ..onClick.listen (homeworkdetail ); var stuhomeworklist = querySelector('#stuhomeworklist'); querySelector('#stuhomeworklist') ..text='信息技术课程作业三' ..onClick.listen(stuhomeworklist); var submitbutton = querySelector('#submitbutton'); querySelector('#submitbutton') ..text = '提交' ..onClick.listen(submitbutton); var judge = querySelector('#judge'); querySelector('#judge') ..text = '信息技术课程作业三:吴同学 图书馆预定座位小程序' ..onClick.listen(judge); } ///教师评价页面的评论部分,可以自动显示评论内容 void showcomment(MouseEvent event){ //to do 显示评论内容 } ///教师评价页面的评论部分,“提交”按钮,将教师的评价写入数据库 void reasonwu(MouseEvent event) { //to do 将评价的数据写入数据库 var router = new Router(useFragment: true); router.root ..addRoute( name: 'SnewTask', path: '/tea/newTask/success', enter:SnewTask); querySelector('#ConfirmWord_Confirm_Btn').attributes['href'] = router.url('SnewTask'); router.listen(); String jsonData = encode(newWordList); HttpRequest request = new HttpRequest(); request.onReadyStateChange.listen((_) { }); var url = "http://127.0.0.1:14080/teacher_writetask"; request.open("POST", url); request.send(jsonData); } ///登录页面,主页 void showloginpage(RouteEvent e) { querySelector('#hello').classes.remove('selected'); querySelector('#loginpage').classes.add('selected'); querySelector('#loguppage').classes.remove('selected'); querySelector('#stupage').classes.remove('selected'); querySelector('#posthomework').classes.remove('selected'); querySelector('#mygrade').classes.remove('selected'); querySelector('#teapage').classes.remove('selected'); querySelector('#one').classes.remove('selected'); querySelector('#two').classes.remove('selected'); querySelector('#three').classes.remove('selected'); querySelector('#threewu').classes.remove('selected'); querySelector('#threeli').classes.remove('selected'); querySelector('#threedu').classes.remove('selected'); } ///“注册”按钮,进入注册界面 void showloguppage(RouteEvent e) { querySelector('#hello').classes.remove('selected'); querySelector('#loginpage').classes.remove('selected'); querySelector('#loguppage').classes.add('selected'); } ///“学生登录”按钮,进入学生主界面 void showstupage(RouteEvent e) { querySelector('#hello').classes.add('selected'); querySelector('#loginpage').classes.remove('selected'); querySelector('#stupage').classes.add('selected'); querySelector('#posthomework').classes.remove('selected'); querySelector('#mygrade').classes.remove('selected'); } ///点击任意一个作业项目的链接,进入作业提交页面 void showposthomework(RouteEvent e) { querySelector('#stupage').classes.remove('selected'); querySelector('#posthomework').classes.add('selected'); querySelector('#mygrade').classes.remove('selected'); } ///点击已完成作业的链接,进入成绩查看页面 void showmygrade(RouteEvent e) { querySelector('#stupage').classes.remove('selected'); querySelector('#mygrade').classes.add('selected'); } ///“教师登录”按钮,进入教师主界面 void showteapage(RouteEvent e) { querySelector('#hello').classes.add('selected'); querySelector('#teapage').classes.add('selected'); querySelector('#loginpage').classes.remove('selected'); querySelector('#one').classes.remove('selected'); querySelector('#two').classes.remove('selected'); querySelector('#three').classes.remove('selected'); } ///进入项目三界面 void showthree(RouteEvent e) { querySelector('#teapage').classes.remove('selected'); querySelector('#three').classes.add('selected'); querySelector('#threewu').classes.remove('selected'); querySelector('#threeli').classes.remove('selected'); querySelector('#threedu').classes.remove('selected'); } ///进入项目二界面 void showtwo(RouteEvent e) { querySelector('#teapage').classes.remove('selected'); querySelector('#two').classes.add('selected'); } ///进入项目一界面 void showone(RouteEvent e) { querySelector('#teapage').classes.remove('selected'); querySelector('#one').classes.add('selected'); } ///进入项目三吴同学的作业界面 void showthreewu(RouteEvent e) { querySelector('#three').classes.remove('selected'); querySelector('#threewu').classes.add('selected'); } ///进入项目三李同学的作业界面 void showthreeli(RouteEvent e) { querySelector('#three').classes.remove('selected'); querySelector('#threeli').classes.add('selected'); } ///进入项目三杜同学的作业界面 void showthreedu(RouteEvent e) { querySelector('#three').classes.remove('selected'); querySelector('#threedu').classes.add('selected'); } ///自动获取教师发布的作业信息 void projectlist() { var url = 'http://localhost:3320/teapage'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ///自动获取某一项的作业信息 void homeworklist() { var url = 'http://localhost:3320/teapage/homeworklist'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ///自动获取学生提交的作业信息 void stuhomeworklist() { var url = 'http://localhost:3320/teapage/homeworklist/stuhomeworklist'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ///获取学生提交的作业详情 void homeworkdetail() { var url = 'http://localhost:3320/teapage/homeworklist/stuhomeworklist/homeworkdetail'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ///自动获取教师的评价信息 void judge() { var url = 'http://localhost:3320/teapage/judgepage'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ///提交按钮,转到教师的主页面 void submitbutton() { var url = 'http://localhost:3320/teapage/'; request = new HttpRequest(); request.onReadyStateChange.listen(onData); request.open('GET', url); request.send(" jsonstring"); } ``` ```dart ///主函数 main(){ ..get('/tea/gethprolist/{schnum}/',getprolist)//获取老师发布的作业列表 ..get('/tea/gethprolist/{schnum}/gethomeworklist',gethomeworklist)//获取老师收到的学生的作业列表 ..get('/tea/prolist/{schnum}/gethomeworklist/gethomeworkdetail',gethomeworkdetail)//获取学生提交的一份作业的具体信息 ..post('/tea/postjudge/{teaschoolnumber}/{stuschoolnumber}/{id}/',postjudge)//提交教师的评价 ..get('/{name}{?age}', myHandler); } ///自动获取老师发布的作业列表 getprolist(request){ //todo 取老师发布的作业列表 var pro=new Map<String,String>();//存放单个用户数据 var prolist=new List();//存放所有用户的数据 var endprolist=new Map<String,String>();//存放最终的用户数据 var pool=new ConnectionPool(host:'localhost',port:3306,user: 'test', password: '111111', db: 'evaltool',max:5); var data= await pool.query('select id,question from homework'); await data.forEach((row){ pro={'"id"':'"${row.id}"','"question"':'"${row.question}"'}; prolist.add(pro);//将该数据加入数组中 }); endprolist={'"prolist"':prolist}; return (new Response.ok(endprolist.toString(),headers: _headers)); } ///自动获取老师收到的作业列表 gethomeworklist(request){ //todo 获取老师收到的学生的作业列表 var pro=new Map<String,String>();//存放单个用户数据 var prolist=new List();//存放所有用户的数据 var endprolist=new Map<String,String>();//存放最终的用户数据 var pool=new ConnectionPool(host:'localhost',port:3306,user: 'test', password: '111111', db: 'evaltool',max:5); var data= await pool.query('select id,question from homework'); await data.forEach((row){ pro={'"id"':'"${row.id}"','"question"':'"${row.question}"'}; prolist.add(pro);//将该数据加入数组中 }); endprolist={'"prolist"':prolist}; return (new Response.ok(endprolist.toString(),headers: _headers)); } ///自动获取学生提交的作业 gethomeworkdetail(request){ //todo 获取学生提交的一份作业的具体信息 var homeworkdetail=new Map<String,String>(); var homeworkdetail1=new List(); var pool=new ConnectionPool(host:'localhost',port:3306,user: 'test', password: '111111', db: 'evaltool',max:5); var data= await pool.query('select id,question from homework'); await data.forEach((row){ homeworkdetail={'"answer"':'"${row.answer}"'}; homeworkdetail.add();//将该数据加入数组中 }); return (new Response.ok(homeworkdetail1.toString(),headers: _headers)); } ///获取老师的评价 postjudge(request){ //todo 提交教师的评价 var judge=new Map<String,String>(); var judge1=new List(); var pool=new ConnectionPool(host:'localhost',port:3306,user: 'test', password: '111111', db: 'evaltool',max:5); var data= await pool.query('select score,judge from homework'); await data.forEach((row){ judge={'"score"':'"${row.score}"','"judge"':'"${row.judge}"'}; judge1.add(judge);//将该数据加入数组中 }); return (new Response.ok(judge1.toString(),headers: _headers)); } ``` ## 我的活动量化 > 李志伟/10140340150/26 commits / 2023 ++ / 1378 --/0 issues/ ## 我的issue活动 # 我的自评 > 对自己的工作进行自评 我对编程是比较感兴趣的,我认为通过一些代码能够实现各个功能是一件很神奇的事情。 在web编程的课程学习的过程中,一方面我充分感受到了编程的神奇和奇妙之处,通过自己和小伙伴的努力一起做出了一个项目; 第二,我的自主学习的能力有所增强,用老师的话说,知道了该怎样进兴学习。不应该像以往一样,只是等着老师给与我们答案,应该自己学会去主动寻找解决办法。我在这次项目中,就是自己去寻找解决办法,不只是依赖老师给我讲解。例如,我利用router实现了页面的切换功能,这给我带来了极大的自信心。 第三,我更加认识到了坚持的重要性。web编程对我而言,是一门非常有挑战性的一门课。因为我的编程基础不是很好。但是我依然很努力的在研究,在这个过程中,坚持就显得至关重要。
C++
UTF-8
2,634
3.96875
4
[]
no_license
/* Branden Lee CIS 22B Fall 2017 Assignment B Problem B1 Used Microsoft Visual Studio 2017 Prompts user for the height and radius to return the volume of a cone. Demonstrates the use of data structures. */ #include <iostream> #include <iomanip> #include <string> #include <cmath> using namespace std; /************************************************** ** global structure, functions, and variables **************************************************/ struct Cone { double height; double radius; }; void input (double& height, double& radius); void setUp (double height, double radius, Cone* conePtr); double getVolume (Cone* conePtr); void output (Cone* conePtr); const double PI = 3.14159265358979323846; int main () { Cone* ptr = new Cone (); double height; double radius; input (height, radius); setUp (height, radius, ptr); output (ptr); delete ptr; //system("pause"); return 0; } /********************* input ********************** ** Reads the height and radius from the user as ** reference parameters **************************************************/ void input (double& height, double& radius) { cout << "Enter height of the cone and radius of the base " << endl << "with spaces between the two values. i.e. 6 2" << endl; cin >> height >> radius; } /********************* setUp ********************** ** Puts the data into the data structure ** height and radius into a pointer to the Cone **************************************************/ void setUp (double height, double radius, Cone* conePtr) { (*conePtr).height = height; (*conePtr).radius = radius; } /********************* getVolume ****************** ** Computes the volume from a pointer to the Cone ** Returns the volume V = Π r2 h / 3 **************************************************/ double getVolume (Cone* conePtr) { return PI * (*conePtr).radius*(*conePtr).radius * (*conePtr).height / 3.0; } /********************* output ********************* ** Calls the getVolume function to get the volume ** Prints the height, radius, and volume in a neat ** format **************************************************/ void output (Cone* conePtr) { cout << endl << "The values of the cone are: " << endl << "height: " << setw (8) << right << (*conePtr).height << endl << "radius: " << setw (8) << right << (*conePtr).radius << endl << "volume: " << setw (8) << right << fixed << setprecision (2) << getVolume (conePtr) << endl; } /* Execution results Enter height of the cone and radius of the base with spaces between the two values. i.e. 6 2 6 2 The values of the cone are: height: 6 radius: 2 volume: 8.89 */
Java
UTF-8
520
3.375
3
[]
no_license
package exception.throw_; public class ThrowEx01 { public static void main(String[] args) { try { System.out.println("결과: " + calc(10)); System.out.println("결과: " + calc(-10)); } catch (Exception e) { // TODO Auto-generated catch block System.out.println(e); System.out.println(e.getMessage()); } } public static int calc(int n) throws Exception{ if(n < 0) { throw new Exception("히히"); } int sum = 0; for(int i = 0; i <= n; i++) { sum += i; } return sum; } }
C++
UTF-8
468
2.625
3
[]
no_license
#include "SDLManager.h" SDLManager::SDLManager() { if (SDL_Init(SDL_INIT_EVERYTHING)) std::cout << "failed to init SDL" << std::endl << SDL_GetError() << std::endl; if (!IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG)) std::cout << "failed to init IMG" << std::endl << IMG_GetError() << std::endl; if (TTF_Init()) std::cout << "failed to init TTF" << std::endl << TTF_GetError() << std::endl; } SDLManager::~SDLManager() { TTF_Quit(); IMG_Quit(); SDL_Quit(); }
C++
UTF-8
3,498
2.640625
3
[]
no_license
#include "Client.h" #include "SingleBufferedConsole.h" #include <thread> static CClient Client{ "192.168.219.200", 9999, timeval{ 2, 0 } }; static BOOL ConsoleEventHandler(DWORD event) { switch (event) { case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: Client.Leave(); break; } return TRUE; } int main() { SetConsoleCtrlHandler(ConsoleEventHandler, TRUE); char Buffer[2048]{}; while (true) { std::cout << "Enter your Nickname: "; std::cin >> Buffer; if (strlen(Buffer) <= 31) { if (Client.IsTimedOut()) return 0; if (Client.Enter(Buffer)) { break; } } else { std::cout << "[SYSTEM] Nickname cannot be longer than 31 letters.\n"; } } static constexpr int KWidth{ 130 }; static constexpr int KHeight{ 30 }; CSingleBufferedConsole Console{ KWidth, KHeight, "StringWorld", ECommandLinePosition::Bottom }; Console.SetClearBackground(EBackgroundColor::Black); Console.SetDefaultForeground(EForegroundColor::LightYellow); std::thread ThrNetwork { [&]() { while (true) { if (Client.IsTerminating() || Client.IsTimedOut()) break; Client.Receive(); } } }; std::thread ThrInput { [&]() { while (true) { if (Client.IsTerminating() || Client.IsTimedOut()) break; if (Console.HitKey()) { if (Console.IsHitKey(EArrowKeys::Left)) { Client.Input(EInput::Left); } else if (Console.IsHitKey(EArrowKeys::Right)) { Client.Input(EInput::Right); } else if (Console.IsHitKey(EArrowKeys::Up)) { Client.Input(EInput::Up); } else if (Console.IsHitKey(EArrowKeys::Down)) { Client.Input(EInput::Down); } else if (Console.IsHitKey(VK_RETURN)) { if (Console.ReadCommand()) { if (Console.IsLastCommand("/quit")) { Client.Leave(); } else { Client.Chat(Console.GetLastCommand()); } } } } } } }; while (true) { if (Client.IsTerminating() || Client.IsTimedOut()) break; Console.Clear(); Console.PrintBox(0, 0, 70, KHeight - 1, ' ', EBackgroundColor::DarkGray, EForegroundColor::Black); Console.PrintBox(70, 0, 40, KHeight - 1, ' ', EBackgroundColor::DarkGray, EForegroundColor::Black); if (Client.HasChatLog()) { static constexpr int KMaxLines{ KHeight - 1 - 2 }; auto& vChatLog{ Client.GetChatLog() }; int ChatCount{ (int)vChatLog.size() }; int Offset{ (ChatCount > KMaxLines) ? ChatCount - KMaxLines : 0 }; for (int i = Offset; i < ChatCount; ++i) { if (vChatLog[i].bIsLocal) { Console.PrintHString(70 + 1, 1 + i - Offset, vChatLog[i].String, EForegroundColor::LightYellow, 40 - 2); } else { Console.PrintHString(70 + 1, 1 + i - Offset, vChatLog[i].String, EForegroundColor::Yellow, 40 - 2); } } } auto& vClientData{ Client.GetClientData() }; auto& MyData{ Client.GetMyDatum() }; for (auto& Client : vClientData) { if (Client.ID == KInvalidID) continue; Console.PrintChar(Client.X, Client.Y, '@', EForegroundColor::Yellow); } Console.PrintChar(MyData.X, MyData.Y, '@', EForegroundColor::LightYellow); Console.PrintHString(112, 1, "ID"); Console.PrintHString(115, 1, Client.GetMyStringID().String); Console.PrintHString(112, 3, " X"); Console.PrintHString(112, 4, " Y"); Console.PrintHString(115, 3, MyData.X); Console.PrintHString(115, 4, MyData.Y); Console.Render(); } ThrNetwork.join(); ThrInput.join(); return 0; }
C
UTF-8
5,145
2.515625
3
[ "BSD-3-Clause" ]
permissive
/************************************************************************ ** Pragmas *************************************************************************/ /************************************************************************ ** Includes *************************************************************************/ #include <string.h> #include "ea_app.h" #include "ea_cds_utils.h" /************************************************************************ ** Local Defines *************************************************************************/ /************************************************************************ ** Local Structure Declarations *************************************************************************/ /************************************************************************ ** External Global Variables *************************************************************************/ extern EA_AppData_t EA_AppData; /************************************************************************ ** Global Variables *************************************************************************/ /************************************************************************ ** Local Variables *************************************************************************/ /************************************************************************ ** Function Prototypes *************************************************************************/ /************************************************************************ ** Function Definitions *************************************************************************/ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Initialize CDS Tables */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ int32 EA_InitCdsTbl() { int32 iStatus=0; int32 iResetType=0; uint32 uiResetSubType=0; /* Only clear CDS table when it's a PowerOn reset, and not a Processor reset */ iResetType = CFE_ES_GetResetType(&uiResetSubType); if (iResetType == CFE_ES_POWERON_RESET) { memset((void*)&EA_AppData.CdsTbl, 0x00, sizeof(EA_CdsTbl_t)); } /* Register and manage CDS table */ iStatus = CFE_ES_RegisterCDS(&EA_AppData.CdsTblHdl, sizeof(EA_CdsTbl_t), EA_CDS_TABLENAME); if (iStatus == CFE_SUCCESS) { /* Setup initial content of CDS table */ iStatus = CFE_ES_CopyToCDS(EA_AppData.CdsTblHdl, &EA_AppData.CdsTbl); if (iStatus == CFE_SUCCESS) { (void) CFE_EVS_SendEvent(EA_CDS_INF_EID, CFE_EVS_INFORMATION, "Successfully setup CDS"); } else { (void) CFE_EVS_SendEvent(EA_INIT_ERR_EID, CFE_EVS_ERROR, "Failed to setup CDS"); } } else if (iStatus == CFE_ES_CDS_ALREADY_EXISTS) { /* If one already exists, get a copy of its current content */ memset((void*)&EA_AppData.CdsTbl, 0x00, sizeof(EA_CdsTbl_t)); iStatus = CFE_ES_RestoreFromCDS(&EA_AppData.CdsTbl, EA_AppData.CdsTblHdl); if (iStatus == CFE_SUCCESS) { (void) CFE_EVS_SendEvent(EA_CDS_INF_EID, CFE_EVS_INFORMATION, "Successfully restored data from CDS"); } else { (void) CFE_EVS_SendEvent(EA_INIT_ERR_EID, CFE_EVS_ERROR, "Failed to restore data from CDS"); memset((void*)&EA_AppData.CdsTbl, 0x00, sizeof(EA_CdsTbl_t)); } } else { (void) CFE_EVS_SendEvent(EA_INIT_ERR_EID, CFE_EVS_ERROR, "Failed to create CDS (0x%08X)", (unsigned int)iStatus); } return (iStatus); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Update CDS Tables */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void EA_UpdateCdsTbl() { /* TODO: Add code to update values in CDS table here */ } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Save CDS Tables */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ void EA_SaveCdsTbl() { /* TODO This return value is not checked. Developer should decide what to do here in case of failure or should add a return value for higher-level logic to handle. */ CFE_ES_CopyToCDS(EA_AppData.CdsTblHdl, &EA_AppData.CdsTbl); } /************************/ /* End of File Comment */ /************************/
Python
UTF-8
513
3.140625
3
[]
no_license
class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ for i in xrange(k): cur_max = 0 for j in xrange(1, len(nums) - i): if nums[j] > nums[cur_max]: cur_max = j tmp = nums[cur_max] nums[cur_max] = nums[-i-1] nums[-i-1] = tmp return nums[-k] s = Solution() print s.findKthLargest([3,2,1,5,6,4],2)
Java
UTF-8
345
2.078125
2
[]
no_license
package document; import document.documentItem.ItemsCollection.IDocumentItemCollection; import document.documentItem.image.IMutableImage; import document.documentItem.title.IDocumentTitle; import document.documentItem.title.IMutableDocumentTitle; public interface IDocument { IDocumentTitle Title(); IDocumentItemCollection Items(); }
C++
UTF-8
527
2.734375
3
[]
no_license
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { n = nums.size(); dfs(nums,0, vector<int>()); return set; } private: vector<vector<int>> set; int n; void dfs(vector<int>& nums, int step, vector<int> subset){ if (step==n){ set.push_back(subset); } else{ dfs(nums, step+1, subset); subset.push_back(nums[step]); dfs(nums, step+1, subset); } } }; //4ms 一次AK faster than 100%s
Python
UTF-8
258
3.421875
3
[]
no_license
def try_me(word1, word2): if len(word1) > len(word2): return f"{word1} is longer than {word2}" elif len(word1) < len(word2): return f"{word1} is longer than {word2}" else: return f"{word1} and {word2} have the same length"
Markdown
UTF-8
1,473
2.84375
3
[]
no_license
# Article R6212-83 Dans une société d'exercice libéral mentionnée à l'article R. 6212-72, la détention directe ou indirecte de parts ou d'actions représentant tout ou partie du capital social non détenu par des personnes mentionnées au premier alinéa ou aux 1° à 4° de l'article 5 de la loi n° 90-1258 du 31 décembre 1990 relative à l'exercice sous forme de sociétés des professions libérales soumises à un statut législatif ou réglementaire ou dont le titre est protégé et aux sociétés de participations financières de professions libérales est interdite à toute personne physique ou morale exerçant sous quelque forme que ce soit : - soit une autre profession de santé ; - soit une activité de fournisseur, distributeur ou fabricant de matériel ou de réactifs d'analyses de biologie médicale. Sont également exclus les entreprises d'assurance et de capitalisation, les organismes de prévoyance, de retraite et de protection sociale obligatoires ou facultatifs, ainsi que les établissements de santé, sociaux et médico-sociaux de droit privé. **Liens relatifs à cet article** _Cite_: - Loi n°90-1258 du 31 décembre 1990 - art. 5 - Code de la santé publique - art. R6212-72 _Anciens textes_: - Décret n°92-545 1992-06-17 art. 12 - Décret n°92-545 du 17 juin 1992 - art. 12 (V) _Codifié par_: - Décret n°2005-840 du 20 juillet 2005 _Abrogé par_: - Décret n°2016-44 du 26 janvier 2016 - art. 1
C++
UTF-8
12,177
2.609375
3
[]
no_license
#ifndef __GLFRAME__ #define __GLFRAME__ #ifdef WIN32 #undef APIENTRY // This is to stop Windows from complaining about APIENTRY already being defined. #endif // These are here to make GLFW expose the right functionality // #ifdef WIN32 #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL #elif defined(MACOSX) #define GLFW_EXPOSE_NATIVE_COCOA #define GLFW_EXPOSE_NATIVE_NSGL #elif defined(__unix) #define GLFW_EXPOSE_NATIVE_X11 #define GLFW_EXPOSE_NATIVE_GLX #endif //////////////////////////////////////////////////////////////// // Include GLEW // #include "glew/include/GL/glew.h" ////////////////// // Include standard headers needed by GLFrame // #include <stdio.h> #include <stdlib.h> #include <fstream> #include <string> #include <cstring> #include <iostream> //////////////////////////////////////////////// // Include GLFW // #include "glfw/include/GLFW/glfw3.h" #ifdef WIN32 #undef APIENTRY // This is to stop Windows from complaining about APIENTRY already being defined. #endif #include "glfw/include/GLFW/glfw3native.h" ////////////////// // Include GLM // #include "glm/glm.hpp" #include "glm/gtx/transform.hpp" #include "glm/gtc/matrix_transform.hpp" ///////////////// /** * An Enum which stores the current status of the GLFrame instance. * * NONE means that GLFrame is in its initial state and needs initialising. * GLFW means that GLFW has been started but not bound to yet. * BOUND means that GLFW has been started and bound to, but glew still needs to be loaded. * FULL means that GLFrame is fully initialised and ready to be used. */ enum GLFrameStatus { NONE, GLFW, BOUND, FULL }; // This is used to check the status of GLFrame. /** * @file * @author Jack Blower <jlgb4@kent.ac.uk> * @version 2.1 * * @section DESCRIPTION * GLFrame is a simple GLFW wrapper framework that provides a working environment for OpenGL * by using the GLFW Window Handler framework. */ /** * GLFrame tries to abstract away the raw window as much as possible which makes code slightly cleaner * than normal OpenGL code, it also provides shader loading code and a mouse function which can get the * mouse coördinates wherever your mouse is on the screen. * The mouse function that gets your coördinates outside the context has not been implemented for Mac. */ class GLFrame { public: /** * Initialises the GLFW Window handler and opens a window with OpenGL 3.3 and 4 samples. * * @param windowTitle The title of the window to be opened. */ void glfwInit(std::string windowTitle); /** * Makes the context the current context. Must be called after glfwInit and before glewInit. */ void glfwMakeContextCurrent(); /** * Asks GLFW if the window should close. * * @return True if the window should close. */ bool glfwWindowShouldClose() { return ::glfwWindowShouldClose(m_window) != 0; } /** * Destroys the window. */ void glfwDestroyWindow() { ::glfwDestroyWindow(m_window); } /** * Terminates GLFW */ void glfwTerminate() { ::glfwTerminate(); } /** * Tells GLFW if the window should close or not. * * @param value Whether the window should close or not. Should be GL_TRUE for close. */ void glfwSetWindowShouldClose(GLint value) { ::glfwSetWindowShouldClose(m_window, value); } /** * Sets the key callback to the function that should be defined in your main.cpp */ void glfwSetKeyCallback(); /** * Swaps the buffers over. GLFW is doubled buffered so this should be swapped once per iteration. */ void glfwSwapBuffers() { ::glfwSwapBuffers(m_window); } /** * Polls GLFW for any events. */ void glfwPollEvents() { ::glfwPollEvents(); } /** * Returns the context size. * * @param width A pointer to hold the width of the context in pixels. * @param height A pointer to hold the height of the context in pixels. */ void glfwGetFramebufferSize(int *width, int *height) { ::glfwGetFramebufferSize(m_window, width, height); } /** * Initialises glew to make sure the 3.3 functionality is available for use. */ void glewInit(); /** * Generates and binds to a Vertex Array Object for managing VBOs. * * @return The ID of the created VAO. */ GLuint generateVAO(); /** * Generates and binds to a Vertex Buffer Object. * * @return The ID of the created VBO */ GLuint generateVBO(); /** * Generates and binds to an index buffer array for the current VAO. * * @return The ID of the created index buffer array. */ GLuint generateIndexBuffer(); // These methods are located in GLFrameShader.cpp // /** * Opens a file and returns its contents. * Warning this method could add a \n to the returned file. * * @param filename The filename to open and return. (May contain a path) * * @return The contents of filename. */ char const * const getFileContents(char const *filename); /** * Loads two shaders from two filenames and returns the ID of the compiled programme if they compiled correctly. * The programme will exit without a Vertex Shader, to try an teach proper OpenGL 3.3 practises. * * @param vertexShaderFilename The file name (and possibly path) to open and load as a vertex shader. * @param fragmentShaderFilename The file name (and possibly path) to open and load as a fragment shader. * * @return The shader programme ID. */ GLuint loadShaders(char const * vertexShaderFilename, char const * fragmentShaderFilename); //////////////////////////////////////////////////// // The definition for getMouseRelPostition is located in GLFrameMouse.cpp // // These functions do NOT work on Mac. // /** * Gets the current mouse position relative to the overall display. * Note: This function can track the mouse anywhere on the screen, unlike the GLFW mouse function which is bound to the conext. * * @param xPos A pointer which will hold the current x position. * @param yPos A pointer which will hold the current y position. */ void getMouseDispRelPosition(int *xPos, int *yPos) const { getMouseRelPosition(xPos, yPos, false); } /** * Gets the current mouse position relative to the GLFW window. * Note: This function can track the mouse anywhere on the screen, unlike the GLFW mouse function which is bound to the conext. * * @param xPos A pointer which will hold the current x position. * @param yPos A pointer which will hold the current y position. */ void getMouseWindRelPosition(int *xPos, int *yPos) const { getMouseRelPosition(xPos, yPos, true); } //////////////////////////////////////////////////////////////////////////// /** * Prints an error message and exits the application with EXIT_FAILURE. * * @param errorString The error message to print before exiting. */ void printErrorAndExit( char const * const errorString ) const; /** * Returns the singleton instance of GLFrame * * @return The GLFrame singleton instance. */ static GLFrame &getInstance() { return *GLFrame::glFrame; } /** * Initialises the GLFW Window handler and opens a window with OpenGL 3.3 and 4 samples with the window title "GLFrame". */ void glfwInit() { glfwInit("GLFrame"); } /** * Gets the cursor position relative to the context boundaries with 0,0 being top left. * Note: This function *only* works while inside the context bounds. * * @param xPos A pointer which will contain the current x position of the mouse. * @param yPos A pointer which will contain the current y position of the mouse. */ void glfwGetCursorPos(double *xPos, double *yPos) const { ::glfwGetCursorPos(m_window, xPos, yPos); } /** * Sets the cursor position relative to the top left boundary of the context window. * Note: Only works if the cursor is inside the context bounds and * * @param xPos A reference to an x position for the cursor to be set to. * @param yPos A reference to an y position for the cursor to be set to. */ void glfwSetCursorPos(const double &xPos, const double &yPos) { ::glfwSetCursorPos(m_window, xPos, yPos); } /** * Returns the current X Mousewheel Offset. * * @return The current X Mousewheel Offset. */ const double getMouseWheelX() const { return m_xScrollOffset; } /** * Returns the current Y Mousewheel Offset. * * @return The current Y Mousewheel Offset. */ const double getMouseWheelY() const { return m_yScrollOffset; } /** * Returns the status of a key since the last time it was checked. * * @param key The key . Look at http://www.glfw.org/docs/latest/group__keys.html for all the keys. * * @return An int whether the key is pressed or released. */ int const glfwGetKey(int key) const { return ::glfwGetKey(m_window, key); } /** * Gets the current time offset according to GLFW. * This starts from 0 when GLFW is initialised. * * @return The current time according to GLFW as a double. */ double glfwGetTime() const { return ::glfwGetTime(); } /** * GLFrame destructor which makes sure GLFW destroys its window if open. */ ~GLFrame() { glfwDestroyWindow(); } private: /** * Constructor for GLFrame. */ GLFrame(); /** * Singleton GLFrame holder. */ static GLFrame * const glFrame; /** * The current status of GLFrame in the programme. */ GLFrameStatus m_glFrameStatus; /** * The GLFW callback for key presses. */ void static key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); /** * The GLFW Window which is abstracted from students. */ GLFWwindow *m_window; /** * The x scroll offset of the mouse. */ double m_xScrollOffset; /** * The y scroll offset of the mouse. */ double m_yScrollOffset; /** * This function is a callback for error events in GLFW. It prints the error to the stderr. */ void static error_callback(int error, char const * description) { fputs(description, stderr); } /** * This function is a callback for the scroll event in GLFW. It adjusts the current scroll offsets. * * @param window The GLFW window that caused the event. * @param xOffset The new X offset of the mousewheel. * @param yOffset The new Y offset of the mousewheel. */ void static scroll_callback(GLFWwindow* window, double xOffset, double yOffset) { GLFrame::getInstance().m_xScrollOffset += xOffset; GLFrame::getInstance().m_yScrollOffset += yOffset; } /** * This function checks that GLFrame is fully initialised and if not it prints an error. */ void requireFullInit() const; // This function is located in GLFrameShader.cpp // /** * Prints an error about shader compilation / loading and exits the application with EXIT_FAILURE. * * @param shaderType The type of shader, "Vertex" or "Fragment" * @param shaderFilename The filename/path of the shader */ void printShaderErrorAndExit( char const * const shaderType, char const * const shaderFilename); /////////////////////////////////////////////////// // This function is located in GLFrameMouse.cpp // /** * Gets the current mouse position, either based on the screen or based on the top left of the window. * Note: This function can track the mouse anywhere on the screen, unlike the GLFW mouse function which is bound to the context. * * @param xPos A pointer which will hold the current x position. * @param yPos A pointer which will hold the current y position. * @param winRel A boolean to decide whether the coördinates are based on window or the screen. * * This will NOT work on Mac. */ void getMouseRelPosition(int *xPos, int *yPos, bool winRel) const; /////////////////////////////////////////////////// }; #endif //__GLFRAME__
Markdown
UTF-8
8,410
3.078125
3
[]
no_license
--- layout: post title: "Embrangler: Moving to Jekyll" summary: The migration process of <a href="http://embrangler.com">this blog</a>, from Wordpress 2.9 to Jekyll 0.5.7 tags: [blog, migration, jekyll, wordpress] --- It took only three days to migrate my blog from [Wordpress](http://wordpress.org) to [Jekyll](http://wiki.github.com/mojombo/jekyll/). For anyone who plans to do this, I'm summarizing the whole process below. Table of contents: * [Why change?](#why_change) * [Why Jekyll?](#why_jekyll) * [Migration process](#migration_process) * [Conclusion](#conclusion) ## Why change? While I realize Wordpress the most popular blogging platform for a reason, I was bothered by the workflow involved with having a WP blog. Some of the (arguable) inconveniences I found were: * the WYSIWYG editor doesn't handle some of the markup I would like (headings, tables aren't great either), so I would constantly switch between the Visual and HTML tabs to format things the way I wanted to. While I realize this could be fixed by customizing the editor, why should I have to do that? Plus, I have long given up hope of the ideal WYSIWYG editor. Besides not handling markup very well, it would sometimes reformat some of my plain HTML and break it. * creating posts is pretty much the only thing I do. I don't use categories, tags, or any other features. Yet I had this admin area cluttered with features. * I'm not too fond of WP's version control. I would often see the message that "a more recent version of this post is available" erroneously, I'm still not sure why. While changing versions worked well enough, I find the idea of an actual version control system more appealing. * My blog could use a redesign. For a while, I was using the [Carrington Text](http://wordpress.org/extend/themes/carrington-text) theme, which was ok but not great. I wanted to make it feel more like _my_ blog -- no sidebar, larger font, a better home page to name a few. ## Why Jekyll? A few weeks before I decided to switch off of Wordpress, I found out about static site-generator engines alternatives that would use available version control software such as git or svn. After looking around I hesitated to switch to any of these because they were mostly Ruby-based, and I was unfamliar with how they work. However, all other alternatives seem to be heading towards full-fledged <abbr title="Content Management System">CMS</abbr>'s. A quick note on static sites: they have virtually no security holes (well, in theory), because there is no server-side handling of data submission. I'm using a <abbr title="Virtual Private Server">VPS</abbr> too, so I was fond of having less CPU usage on the server (due to not having to process, say, PHP scripts for Wordpress). Some of the alternatives to Jekyll that I considered are [Toto](http://www.cloudhead.io/toto), [StaceyApp](http://www.staceyapp.com/), [Chyrp](http://chyrp.net/), [Subtext](http://subtextproject.com/) and [Typo](http://typosphere.org/). I picked [Jekyll](http://wiki.github.com/mojombo/jekyll/) for two main reasons: * popularity -- looking at the [project's github](http://wiki.github.com/mojombo/jekyll/) watches/forks * documentation and examples -- there is actually a [Sites](http://wiki.github.com/mojombo/jekyll/sites) page, leading to other sites and their github hosted sources, immensely helpful when starting out ## Migration process I followed these instructions: * [Installation steps from the Jekyll documentation](http://wiki.github.com/mojombo/jekyll/install) * [Installing Jekyll on Ubuntu](http://blog.favrik.com/2009/03/02/installing-jekyll-on-ubuntu-8-10/) ... and started by looking at [Tom Preston-Werner's blog](http://tom.preston-werner.com/) and its [source on github](http://github.com/mojombo/mojombo.github.com). ### Migrating posts After I got the redesign to look good on Jekyll, the next step was migrating my Wordpress posts. Fortunately, [there is documentation for that too](http://wiki.github.com/mojombo/jekyll/blog-migrationsl). Unfortunately, the automatic migration did not convert some of the markup very well, such as LaTex, images with captions, most lists and links. Yet I had less than 15 posts, so I just went through them and checked everything. Because I'm using [LaTeX](http://www.latex-project.org/) in some of my posts, I used [maruku](http://maruku.rubyforge.org/maruku.html) (instead of [rdiscount](http://github.com/rtomayko/rdiscount)) to parse them. I couldn't find LaTeX support for rdiscount, which is a faster parser. I'm also using lsi for related posts, and [python-pygments](http://pygments.org/) for syntax highlighting. The latter is simply a wonderful tool, and I recommend it to anyone posting code on the web. Of course, all of these are documented in the Jekyll documentation, so it was easy to get it all working. The code for this site is up on github as well, so you can [check it out there](http://github.com/pcraciunoiu/embrangler/) to see how it works. ### Migrating comments This took me about 20 minutes :), following [these instructions](http://disqus.com/comments/wordpress/). ### Server setup and more I actually didn't want to install jekyll on my server, and preferred to do all the generating locally. My server only works with plain html this way. The one thing I did do, however, was use github's post-receive-hook service. I ended up having something [similar to this](http://forum.webfaction.com/viewtopic.php?id=964): 1. github posts data to a php file on my server 1. this file verifies the posted data, logs the commit, and runs a C script. 1. the C script runs `git pull` Here's the code for all of this: 1. php script __Update:__ [James](http://coffeeonthekeyboard.com/) pointed out that my security measures weren't good enough, so I updated the script. If you don't care much for security, you may prefer automated publishing. See my [second script](#second-script), below. {% highlight php %} <?php $check = auth(); if (!$check) die; echo '<pre>'; echo exec('/path/to/site/pull_script'); echo '</pre>'; function auth() { // do some parameter checking here // and return true when matches } {% endhighlight %} To make things even more awesome, I bookmarked this URL using [Firefox's keywords](http://lifehacker.com/196779/hack-attack-firefox-and-the-art-of-keyword-bookmarking), so I only need to type one character to publish ;) <span id="second-script"></span> Here is my second script, which does automatic publishing. {% highlight php %} <?php if (!$_POST['payload']) { header('HTTP/1.0 403 Forbidden'); exit; } define('HOOKLOG', '../logs/hooks.log'); $fh = fopen(HOOKLOG, 'w') or die("Can't open file"); $data = ''; $hook = json_decode($_POST['payload']); if ($hook->repository->owner->name != 'pcraciunoiu') { header('HTTP/1.0 403 Forbidden'); exit; } $cs = $hook->commits; foreach ($cs as $c) { $data .= $c->timestamp . "\n"; $data .= $c->author->name . ' (' . $c->author->email . ')' . ' pushed to ' . $hook->repository->url . "\n" . 'View commit at ' . $c->url . "\n" . "\n\nCommit message was:\n" . $c->message . "\n\n" ; } fwrite($fh, $data); fclose($fh); // set this to your path exec('/path/to/site/pull_script'); {% endhighlight %} There are two important security measures in the first script: * it not write to a file, so if it gets hit by someone trying to find the secret codes, my server's disk doesn't perform intensive <abbr title="input-output">IO</abbr> * it does not hint in any way at parameter names, number of parameters that must be submitted, or whether they should be submitted through GET or POST -- if you don't get the right values, you don't see anything 2. the c file {% highlight cpp %} #include <stddef.h> #include <stdlib.h> #include <unistd.h> int main(void) { execl("/usr/bin/git", "git", "pull", "origin", "master", (const char *) NULL); return EXIT_FAILURE; } {% endhighlight %} Compile this with {% highlight bash %} gcc pull_script.c -o pull_script {% endhighlight %} So now, every time I push to github, the server automatically updates. Really cool way of publishing! ## Conclusion I enjoy using git, and having a static site. My comments are offloaded to a separate server, and I write plain text files using the markdown syntax. My blog gets published when I visit a bookmarked URL. Goodbye Wordpress!
Markdown
UTF-8
944
2.6875
3
[]
no_license
# Bid or Bullsh!t ### A game of wit and deception for the iPad with a built-in ACT-R opponent. Created for the course Cognitive Modelling: Complex Behaviour (April 2017) together with Pim van der Meulen and Kim van Prooijen. ![bidorbullshit.png](https://bitbucket.org/repo/z8jxRpr/images/2598546214-bidorbullshit.png) This game is a pirate-themed adaptation of the dice game [Perudo/Dudo/Liar's Dice](http://www.perudo.com/) for one player with an AI opponent. The AI opponent is an [ACT-R](https://github.com/ntaatgen/ACT-R) model which can shift between a novice rule-based strategy (for inexperienced players), and a more advanced memory-based one (for players who want a bigger challenge). ## Screenshots ![](img/mainmenu.png) ![](img/characterselection.png) ![](img/gamescreen.png) ## Usage You can import the repository into XCode using `Source Control` -> `Check Out...` and entering the URL https://github.com/maartenvandervelde/bid-or-bullshit.git.
Rust
UTF-8
1,370
3.484375
3
[]
no_license
/* .. default-role:: math 计算H因子 H因子是一个衡量科学家影响力的东西,主要看这个科学家发的文章的被引数。如果一个科学家有至少 `h` 篇文章的被引数大于等于 `h` ,那么这个科学家的H因子就不小于 `h` 。 这样说还是很模糊、很难算。维基百科 <https://en.wikipedia.org/wiki/H-index> 上面有一张图非常清晰,下面就是用这张图算的 1. 先把所有的文章按被引数从高到低排序 2. 被引数最高的文章的下标从1开始,x轴是文章的下标,y轴是被引数,数有多少篇文章在 `y = x` 这条线上、或者左上方 */ struct Solution; use std::cmp::Reverse; impl Solution { pub fn h_index(citations: Vec<i32>) -> i32 { let mut citations = citations; citations.sort_by_key(|v| Reverse(*v)); // 先按被引数从高到低排序 return citations .into_iter() .enumerate() .filter(|(i, v)| *v as usize >= *i + 1) // 注意下标从1开始。可能还能用take_while,更快,因为只要遇见一篇文章在y = x右下方,之后的文章都不可能出现在目标区域了 .count() as i32; } } fn main() { dbg!(Solution::h_index(vec![3, 0, 6, 1, 5])); // 3 dbg!(Solution::h_index(vec![0])); // 0 dbg!(Solution::h_index(vec![1, 1])); // 1 }
Python
UTF-8
1,217
3.546875
4
[]
no_license
''' 基本的绘图: 平面直接坐标系 ''' import numpy as np import matplotlib.pyplot as plt #使用线性拆分 x = np.linspace(-np.pi, np.pi, 200) sinx = np.sin(x) cosx = np.cos(x) plt.plot(x, sinx, linestyle='--',linewidth=3,color='green',alpha=0.2) plt.plot(x, cosx, linestyle='-.',linewidth=6,color='red',alpha=0.8) # 设置刻度 plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi] , [r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$-\pi$'] , fontsize=25 ) plt.yticks([-1, -1 / 2, 0, 1 / 2, 1] , ['-1', r'$-\frac{1}{2}$', '0', r'$\frac{1}{2}$', '1'] , fontsize=25 ) ax = plt.gca() # 上 和 右 设置为没有颜色 top = ax.spines['top'].set_color('none') right = ax.spines['right'].set_color('none') #移动 左 和 下 的位置 left = ax.spines['left'].set_position(('data',0)) bottom = ax.spines['bottom'].set_position(('data',0)) #(因为移动了位置)重新设置一下字体大小 plt.xticks(fontsize=14) # 去掉y轴的0,两边重合了 plt.yticks([-1, -1 / 2, 1 / 2, 1]) plt.show() # 显示图片,阻塞方法
Python
UTF-8
222
2.921875
3
[]
no_license
import pygame from pygame.locals import * class ClockController(object): def __init__(self): self.clock = pygame.time.Clock() def tick(self, fps): self.clock.tick(fps) def dt(self): return self.clock.get_time()
Java
UTF-8
1,842
2.703125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package amm.milestone3; import java.util.ArrayList; /** * * @author medas */ public class VenditoreFactory { private static VenditoreFactory singleton; //lista venditori private ArrayList<VenditoreClass> listaVenditori; public static VenditoreFactory getInstance() { if (singleton == null) { singleton = new VenditoreFactory(); } return singleton; } private VenditoreFactory() { listaVenditori = new ArrayList(); VenditoreClass seller1 = new VenditoreClass(); seller1.setNome("Michele"); seller1.setCognome("Medas"); seller1.setUsername("mike"); seller1.setPassword("juventus"); seller1.setCodiceFiscale("MDSMHL90B24E281S"); seller1.saldo = 333.5; listaVenditori.add(seller1); VenditoreClass seller2 = new VenditoreClass(); seller2.setNome("Pavel"); seller2.setCognome("Nedved"); seller2.setUsername("pavel"); seller2.setPassword("furiaceca"); seller2.setCodiceFiscale("PVLNDV75C02B283V"); seller2.saldo = 9999.9; listaVenditori.add(seller2); VenditoreClass seller3 = new VenditoreClass(); seller3.setNome("David"); seller3.setCognome("Trezeguet"); seller3.setUsername("david"); seller3.setPassword("france"); seller3.setCodiceFiscale("DVDTZG88C22A283V"); seller3.saldo = 731.2; listaVenditori.add(seller3); } public ArrayList<VenditoreClass> getVenditoriList() { return listaVenditori; } }
Shell
UTF-8
1,647
3.1875
3
[]
no_license
#!/bin/bash # # COMAND LINE INTERFACE WIKI # # Criado por: Edegard Santos. # 06/10/2016 # # ## BASHCSS trap 'menu' 1 2 3 15 20 BLACK='\E[0;30m' # PRETO BOLD='\033[37;4;1m' # NEGRITO UND='\033[37;4m' # SUBLINHADO RED='\033[00;31m' # VERMELHO GREEN='\033[01;32m' # VERDE YELLOW='\033[01;33m' # AMARELO BLUE='\033[01;34m' # AZUL PURPLE='\033[00;35m' # ROXO CYAN='\033[00;36m' # CIANO LIGHTGRAY='\033[00;37m' # CINZA CLARO LRED='\033[01;31m' # VERMELHO CLARO LGREEN='\033[01;32m' # VERDE CLARO LYELLOW='\033[01;33m' # AMARELO CLARO LBLUE='\033[01;34m' # AZUL CLARO LPURPLE='\033[01;35m' # ROXO CLARO LCYAN='\033[01;36m' # CIANO CLARO WHITE='\033[01;37m' # BRANCO RESE=$(tput sgr0) # SEM COR # # Cabeçalho # cab() { clear printf "############################################## ${LCYAN}WEBHOSTING${RESE} ${LYELLOW}COMMAND ${LBLUE}LINE ${LYELLOW}INTERFACE ${LBLUE}WIKI ${GREEN}(H${YELLOW}G${BLUE}B${WHITE}R)${RESE} ##############################################\n" } menu() { cab printf "[ 1 ] E-mail [ 2 ] DNS [ 3 ] cPanel [ 4 ] Shell [ 5 ] TOS [ 6 ] Outro - Pesquisar\n" read -n 1 -p "Opcao: <Enter=Sair>" opc [ "x$opc" == "x" ] && clear && echo -e "\nWiki finalizada, valor inválido\n" && exit 1 case $opc in 1) echo -e "\nBotão 1 apertado" ;; 2) echo -e "\nBotão 2 Apertado" ;; 3) echo -e "\nBotão 3 Apertado" ;; 4) echo -e "\nBotão 4 Apertado" ;; 5) echo -e "\nBotão 5 Apertado" ;; 6) echo -e "\nBotão 6 Apertado" ;; esac } # Chamar Menu menu
C++
UTF-8
1,157
2.609375
3
[ "MIT" ]
permissive
#include "transform.h" #include <memory.h> #if defined(CXX_GNU) || defined(BUILD_ANDROID) #include <GLES/gl.h> #elif defined(CXX_MSVC) #include <Windows.h> #include <GL/gl.h> #endif namespace c4g{ namespace render { namespace gles { CTransform& CTransform::Instance(float* const& rpfVertexData) { static CTransform s_Instance; s_Instance.m_pVertexData = rpfVertexData; return s_Instance; } CTransform::CTransform() : m_pVertexData(NULL) { ; } CTransform::~CTransform() { ; } void CTransform::Translate(const float& rfX, const float& rfY, const float& rfZ /*= 0.0f*/) { //TODO: use matrix //NOTE: reverse the y axis glTranslatef(rfX, -rfY, rfZ); } void CTransform::Scale(const float& rfX, const float& rfY, const float& rfZ /*= 1.0f*/) { //TODO: use matrix glScalef(rfX, rfY, rfZ); } void CTransform::Rotate(const float& rfAngle, const float& rfX, const float& rfY, const float& rfZ) { //TODO: use matrix glRotatef(rfAngle, rfX, rfY, rfZ); } void CTransform::Free(float* const& rpfData) { if (NULL == rpfData || NULL == m_pVertexData) { return; } memcpy(m_pVertexData, rpfData, sizeof(GLfloat) * 12); } } } }
Java
UTF-8
1,657
3.125
3
[]
no_license
package test; import static org.junit.Assert.*; import org.junit.Test; import com.exceedvote.DatebaseManager; import com.exceedvote.Statement; import com.exceedvote.StatementList; /** * StatementSeparateTest tests for a Statment class and a StatementList class. * @author Tanachot Teachajarupan * @version 2012.10.23 */ public class StatementSeparateTest { @Test public void testStatement() { //Create state a Statement Statement state = new Statement(); //Set the description of state state.setDescription("Question1"); //Testcase1, Check after setting the description. assertEquals(state.getDescription(),"Question1"); } @Test public void testStatementList(){ //Create db a DatabaseManager DatebaseManager dm = new DatebaseManager(); //Create list a StatementList StatementList list = new StatementList(dm); //Add the first statement in list list.addStatement("The first question"); //Instance statements an array of Statement Statement [] statements = list.getAllStatement(); //Testcase1, The first statement should be the same one which was added firstly. assertTrue(statements[0].getDescription() == "The first question"); //Add another statement in list list.addStatement("The second question"); //Rechange the value of statement after adding statements = list.getAllStatement(); //Testcase2, The first statement should not be the same one which was added secondly. assertFalse(statements[0].getDescription() == "The second question"); //Testcase3, The second statement should be the same on which was added secondly. assertTrue(statements[1].getDescription() == "The second question"); } }